src/ApplicationBundle/Modules/Inventory/Controller/InventoryController.php line 11015

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Modules\Inventory\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\Modules\Authentication\Constants\UserConstants;
  9. use ApplicationBundle\Controller\GenericController;
  10. use ApplicationBundle\Entity\Carton;
  11. use ApplicationBundle\Entity\InvItemInOut;
  12. use ApplicationBundle\Entity\StockReceivedNote;
  13. use ApplicationBundle\Entity\ProductByCode;
  14. use ApplicationBundle\Entity\StockReceivedNoteItem;
  15. use ApplicationBundle\Entity\ConsumptionType;
  16. use ApplicationBundle\Entity\LabelFormat;
  17. use ApplicationBundle\Entity\UnitType;
  18. use ApplicationBundle\Entity\SpecType;
  19. use ApplicationBundle\Entity\EmployeeAttendance;
  20. use ApplicationBundle\Entity\EmployeeAttendanceLog;
  21. use ApplicationBundle\Modules\Project\ProjectM;
  22. use ApplicationBundle\Modules\Sales\Client;
  23. use ApplicationBundle\Modules\User\Users;
  24. use ApplicationBundle\Constants\ProjectConstant;
  25. use ApplicationBundle\Interfaces\SessionCheckInterface;
  26. use ApplicationBundle\Entity\InvProductCategories;
  27. use ApplicationBundle\Helper\Generic;
  28. use ApplicationBundle\Modules\Accounts\Accounts;
  29. use ApplicationBundle\Modules\Inventory\Inventory;
  30. use ApplicationBundle\Modules\Purchase\Purchase;
  31. use ApplicationBundle\Modules\Sales\SalesOrderM;
  32. use ApplicationBundle\Modules\Production\ProductionM;
  33. use ApplicationBundle\Modules\System\System;
  34. use ApplicationBundle\Modules\HumanResource\HumanResource;
  35. use ApplicationBundle\Modules\Purchase\Supplier;
  36. use ApplicationBundle\Modules\System\DeleteDocument;
  37. use ApplicationBundle\Modules\System\DocValidation;
  38. use ApplicationBundle\Modules\System\MiscActions;
  39. use ApplicationBundle\Modules\User\Company;
  40. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  41. use Symfony\Component\HttpFoundation\JsonResponse;
  42. use Symfony\Component\HttpFoundation\Request;
  43. use Symfony\Component\HttpFoundation\Response;
  44. use Symfony\Component\Routing\Generator\UrlGenerator;
  45. class InventoryController extends GenericController implements SessionCheckInterface
  46. {
  47.     public function GetInitialDataForProductSelectVendorAppAction(Request $request)
  48.     {
  49.         $em $this->getDoctrine()->getManager();
  50.         $em_goc $this->getDoctrine()->getManager('company_group');
  51.         $session $request->getSession();
  52.         $companyId $this->getLoggedUserCompanyId($request);
  53.         $userRestrictions = [];
  54.         $selectiveDocumentsFlag 0;
  55.         $allowedLoginIds = [];
  56. //        $salesPersonList = Client::SalesPersonList($this->getDoctrine()->getManager());
  57. //
  58. //        $clientList = SalesOrderM::GetClientList($em, [], $companyId);
  59.         $userType $session->get(UserConstants::USER_TYPE);
  60.         $userId $session->get(UserConstants::USER_ID);
  61.         $productListArray = [];
  62.         $subCategoryListArray = [];
  63.         $categoryListArray = [];
  64.         $igListArray = [];
  65.         $unitListArray = [];
  66.         $skipProductList $request->request->has('skipProductList') ? $request->request->get('skipProductList') : 0;
  67.         $productList = ($skipProductList == 1) ? [] : Inventory::ProductList($em$companyId);
  68.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  69.         $categoryList Inventory::ProductCategoryList($em$companyId);
  70.         $igList Inventory::ItemGroupList($em$companyId);
  71.         $unitList Inventory::UnitTypeList($em);
  72.         $brandList Inventory::GetBrandList($em$companyId);
  73.         $defaultSuffix 'lemon-o';
  74.         $pidsByCategory = [];
  75.         $pidsBySubCategory = [];
  76.         $pidsByIg = [];
  77.         $pidsByBrand = [];
  78.         foreach ($igList as $key => $product) {
  79.             if ($product['classSuffix'] == '') {
  80.                 $product['classSuffix'] = $defaultSuffix;
  81.                 $igList[$key]['classSuffix'] = $defaultSuffix;
  82.             }
  83.             $igListArray[] = $product;
  84.         }
  85.         foreach ($categoryList as $product) {
  86.             if ($product['classSuffix'] == '' && isset($igList[$product['igId']]))
  87.                 $product['classSuffix'] = $igList[$product['igId']]['classSuffix'];
  88.             $categoryListArray[] = $product;
  89.         }
  90.         foreach ($subCategoryList as $product) {
  91.             if ($product['classSuffix'] == '' && isset($igList[$product['igId']]))
  92.                 $product['classSuffix'] = $igList[$product['igId']]['classSuffix'];
  93.             $subCategoryListArray[] = $product;
  94.         }
  95.         foreach ($unitList as $product) {
  96.             $unitListArray[] = $product;
  97.         }
  98.         $brandListArray = [];
  99.         foreach ($brandList as $product) {
  100.             $brandListArray[] = $product;
  101.         }
  102.         foreach ($productList as $key => $product) {
  103. //            $productListArray[] = $product;
  104.             $product['igName'] = $igList[$product['igId']]['name'];
  105.             $product['categoryName'] = $categoryList[$product['categoryId']]['name'];
  106.             $product['subCategoryName'] = $subCategoryList[$product['subCategoryId']]['name'];
  107.             $product['brandName'] = $brandList[$product['brandCompany']]['name'];
  108.             $pidsByCategory[$product['categoryId']][] = $key;
  109.             $pidsBySubCategory[$product['subCategoryId']][] = $key;
  110.             $pidsIg[$product['igId']][] = $key;
  111.             $pidsByBrand[$product['brandCompany']][] = $key;
  112. //            $pidsBySubCategory=[];
  113. //            $pidsByIg=[];
  114.             $productListArray[] = $product;
  115.             $productList[$key] = $product;
  116.         }
  117.         $data = [
  118.             ''
  119.         ];
  120. //        if ($request->request->has('returnJson') || $request->query->has('returnJson'))
  121.         {
  122.             return new JsonResponse(
  123.                 array(
  124.                     'page_title' => ' ',
  125.                     'data' => $data,
  126.                     'productList' => $productList,
  127.                     'subCategoryList' => $subCategoryList,
  128.                     'categoryList' => $categoryList,
  129.                     'igList' => $igList,
  130.                     'unitList' => $unitList,
  131.                     'brandList' => $brandList,
  132.                     'productListArray' => $productListArray,
  133.                     'subCategoryListArray' => $subCategoryListArray,
  134.                     'categoryListArray' => $categoryListArray,
  135.                     'igListArray' => $igListArray,
  136.                     'unitListArray' => $unitListArray,
  137.                     'brandListArray' => $brandListArray,
  138.                     'pidsByCategory' => $pidsByCategory,
  139.                     'pidsBySubCategory' => $pidsBySubCategory,
  140.                     'pidsByBrand' => $pidsByBrand,
  141.                     'pidsByIg' => $pidsByIg,
  142.                     'success' => true
  143.                 )
  144.             );
  145.         }
  146.     }
  147.     public function GetRefreshedItemAction(Request $request$type 0)
  148.     {
  149.         $em $this->getDoctrine()->getManager();
  150.         $companyId $this->getLoggedUserCompanyId($request);
  151.         $productListArray = [];
  152.         $subCategoryListArray = [];
  153.         $categoryListArray = [];
  154.         $igListArray = [];
  155.         $unitListArray = [];
  156.         $skipProductList $request->request->has('skipProductList') ? $request->request->get('skipProductList') : 0;
  157.         $productList = ($skipProductList == 1) ? [] : Inventory::ProductList($em$companyId$type);
  158.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  159.         $categoryList Inventory::ProductCategoryList($em$companyId);
  160.         $igList Inventory::ItemGroupList($em$companyId);
  161.         $unitList Inventory::UnitTypeList($em);
  162.         $brandList Inventory::GetBrandList($em$companyId);
  163.         foreach ($productList as $product) {
  164.             $productListArray[] = $product;
  165.         }
  166.         foreach ($categoryList as $product) {
  167.             $categoryListArray[] = $product;
  168.         }
  169.         foreach ($subCategoryList as $product) {
  170.             $subCategoryListArray[] = $product;
  171.         }
  172.         foreach ($igList as $product) {
  173.             $igListArray[] = $product;
  174.         }
  175.         foreach ($unitList as $product) {
  176.             $unitListArray[] = $product;
  177.         }
  178.         $brandListArray = [];
  179.         foreach ($brandList as $product) {
  180.             $brandListArray[] = $product;
  181.         }
  182.         $qry $em->getRepository("ApplicationBundle:AccService")->findBy(array(
  183.             "status" => GeneralConstant::ACTIVE,
  184.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  185. //            'type'=>1//trade items
  186.         ));
  187.         $sl = [];
  188.         $sl_array = [];
  189.         foreach ($qry as $product) {
  190.             $sl[$product->getServiceId()] = array(
  191.                 'text' => $product->getServiceName(),
  192.                 'value' => $product->getServiceId(),
  193.                 'name' => $product->getServiceName(),
  194.                 'id' => $product->getServiceId(),
  195.             );
  196.             $sl_array[] = array(
  197.                 'text' => $product->getServiceName(),
  198.                 'value' => $product->getServiceId(),
  199.                 'name' => $product->getServiceName(),
  200.                 'id' => $product->getServiceId(),
  201.             );
  202.         }
  203.         $hl Accounts::HeadList($em);
  204.         $hl_array Accounts::getParentLedgerHeads($em"""", [], 1$this->getLoggedUserCompanyId($request));
  205.         return new JsonResponse(
  206.             array(
  207. //                'page_title'=>'BOM',
  208. //                'clients'=>SalesOrderM::GetClientList($em),
  209. //                'clients_by_ac_head'=>SalesOrderM::GetClientListByAcHead($em),
  210.                 'productList' => $productList,
  211.                 'subCategoryList' => $subCategoryList,
  212.                 'categoryList' => $categoryList,
  213.                 'igList' => $igList,
  214.                 'unitList' => $unitList,
  215.                 'brandList' => $brandList,
  216.                 'productListArray' => $productListArray,
  217.                 'subCategoryListArray' => $subCategoryListArray,
  218.                 'categoryListArray' => $categoryListArray,
  219.                 'igListArray' => $igListArray,
  220.                 'unitListArray' => $unitListArray,
  221.                 'brandListArray' => $brandListArray,
  222.                 "success" => true,
  223.                 'users' => Users::getUserListById($em),
  224.                 'stages' => ProjectConstant::$projectStages,
  225.                 'sl' => $sl,
  226.                 'hl' => $hl,
  227.                 'hl_array' => $hl_array,
  228.                 'sl_array' => $sl_array,
  229. //                'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
  230.             )
  231.         );
  232.     }
  233.     public function GetProductListForMisAction(Request $request)
  234.     {
  235.         $em $this->getDoctrine()->getManager();
  236.         $productIds $request->query->get('productId');
  237.         $fdmList = [];
  238.         $find_array = array('id' => $productIds);
  239.         if ($request->query->get('fdmList')) {
  240.             $find_array = array();
  241.             $fdmList $productIds $request->query->get('fdmList');
  242.         }
  243. //            $find_array=array('id' =>  $productIds);
  244.         $products $this->getDoctrine()
  245.             ->getRepository('ApplicationBundle:InvProducts')
  246.             ->findBy(
  247.                 $find_array
  248.             );
  249.         $productList = [];
  250.         $productListForShow = [];
  251.         foreach ($products as $entry) {
  252.             $productList[$entry->getId()] = array(
  253.                 'id' => $entry->getId(),
  254.                 'name' => $entry->getName(),
  255.                 'fdm' => $entry->getProductFdm(),
  256.             );
  257.         }
  258.         $products_in_stock $this->getDoctrine()
  259.             ->getRepository('ApplicationBundle:InventoryStorage')
  260.             ->findBy(
  261.                 $find_array
  262.             );
  263.         $warehouseList Inventory::WarehouseList($em);
  264.         if (!empty($fdmList)) {
  265.             foreach ($products_in_stock as $dt) {
  266. //            if()
  267.                 $matched_a_product 0;
  268.                 foreach ($fdmList as $fdm) {
  269.                     $matchFdm Inventory::MatchFdm($fdm$productList[$dt->getProductId()]['fdm']);
  270.                     if ($matchFdm['hasMatched'] == 1) {
  271.                         if ($matchFdm['isIdentical'] == || $matchFdm['FirstBelongsToSecond'] == 1) {
  272.                             $matched_a_product 1;
  273.                             if (isset($productListForShow[$dt->getProductId()])) {
  274.                             } else {
  275.                                 $productListForShow[$dt->getProductId()] = array(
  276.                                     'id' => $productList[$dt->getProductId()]['id'],
  277.                                     'name' => $productList[$dt->getProductId()]['name'],
  278.                                     'fdm' => $productList[$dt->getProductId()]['fdm'],
  279.                                 );
  280.                             }
  281.                             if (isset($productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  282.                                 $productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  283.                             else {
  284.                                 $productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  285.                             }
  286.                             break;
  287.                         }
  288.                     }
  289.                 }
  290.                 if ($matched_a_product == 0) {
  291.                     continue;
  292.                 }
  293.                 if (isset($productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  294.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  295.                 else
  296.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  297.             }
  298.         } else {
  299.             foreach ($products_in_stock as $dt) {
  300. //            if()
  301.                 if (isset($productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  302.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  303.                 else
  304.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  305.             }
  306.             $productListForShow $productList;
  307.         }
  308.         $engine $this->container->get("templating");
  309. //        $SD=Supplier::GetSupplierDetailsForMis($em,$supplier_id);
  310.         if ($productList) {
  311.             $Content $engine->render('@Inventory/pages/report/selected_item_stock.html.twig', array("productList" => $productListForShow'warehouseList' => $warehouseList));
  312.             return new JsonResponse(array("success" => true"content" => $Content'productListForShow' => $productListForShow));
  313.         }
  314.         return new JsonResponse(array("success" => false));
  315.     }
  316.     public function CreateProductAction(Request $request$id 0)
  317.     {
  318.         $ex_id 0;
  319.         $prod_det = [];
  320.         $product_duplicate 0;
  321.         $group_type 1;//item
  322.         $em $this->getDoctrine()->getManager();
  323.         $companyId $this->getLoggedUserCompanyId($request);
  324.         $route $request->get('_route');
  325.         if ($route == 'create_service')
  326.             $group_type 2;//service
  327.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  328.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  329. //                $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  330. //        file_put_contents($path, json_encode(array(
  331. //            'sessionDataString'=>$request->request->get('sessionDataString'),
  332. //            'sessionData'=>json_decode($request->request->get('sessionDataString')),
  333. ////            'invData'=>$data_searched,
  334. //
  335. //        )));//overwrite
  336.         if ($request->isMethod('POST')) {
  337.             if ($id == 0)
  338.                 $id $request->request->has('ex_id') ? $request->request->get('ex_id') : 0;
  339.             if ($id == 0) {
  340.                 if ($group_type == 2)
  341.                     $ext_pr $this->getDoctrine()
  342.                         ->getRepository('ApplicationBundle:AccService')
  343.                         ->findOneBy(
  344.                             array(
  345.                                 'serviceName' => $request->request->get('name'),
  346.                             )
  347.                         );
  348.                 else
  349.                     $ext_pr $this->getDoctrine()
  350.                         ->getRepository('ApplicationBundle:InvProducts')
  351.                         ->findOneBy(
  352.                             array(
  353.                                 'name' => $request->request->get('name'),
  354.                             )
  355.                         );
  356.                 if ($ext_pr)
  357.                     $product_duplicate 1;
  358.             }
  359.             if ($product_duplicate == 1) {
  360.                 $this->addFlash(
  361.                     'error',
  362.                     'Duplicate Entry Found'
  363.                 );
  364.             } else {
  365.                 $image_list = [];
  366.                 $defaultImage "";
  367.                 $defaultImageUploadedFile null;
  368.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  369. //
  370. //                if ($request->files->has('product_default_image')) {
  371. //
  372. //
  373. ////                    foreach ($request->files->get('product_default_image') as $uploadedFile)
  374. //                    $defaultImageUploadedFile = $request->files->get('product_default_image');
  375. //                    {
  376. //
  377. //                        $path = "";
  378. //
  379. //                        if ($defaultImageUploadedFile != null) {
  380. //
  381. //                            $fileName = 'p' . md5(uniqid()) . '.' . $defaultImageUploadedFile->guessExtension();
  382. //                            $path = $fileName;
  383. //
  384. //                            if (!file_exists($upl_dir)) {
  385. //                                mkdir($upl_dir, 0777, true);
  386. //                            }
  387. ////                            $file = $uploadedFile->move($upl_dir, $path);
  388. //
  389. //                        }
  390. //                        $file_list[] = $path;
  391. //                        $defaultImage = $path;
  392. //                    }
  393. //
  394. //
  395. //                }
  396. //                if ($request->files->has('product_images')) {
  397. //
  398. //
  399. //                    foreach ($request->files->get('product_default_image') as $ind=>$uploadedFile)
  400. //                    {
  401. //
  402. //                        $path = "";
  403. //
  404. //                        if ($uploadedFile != null) {
  405. //
  406. //                            $fileName = 'p_'.$ind . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
  407. //                            $path = $fileName;
  408. //
  409. //                            if (!file_exists($upl_dir)) {
  410. //                                mkdir($upl_dir, 0777, true);
  411. //                            }
  412. ////                            $file = $uploadedFile->move($upl_dir, $path);
  413. //
  414. //                        }
  415. //                        $image_list[] = $path;
  416. //                        if($defaultImage=='' && $ind==0) {
  417. //                            $defaultImage = $path;
  418. //                            $uploadedFile = $path;
  419. //                        }
  420. //
  421. //                    }
  422. //
  423. //
  424. //                }
  425.                 if ($group_type == 2) {
  426.                     $ig $this->getDoctrine()
  427.                         ->getRepository('ApplicationBundle:InvItemGroup')
  428.                         ->findOneBy(
  429.                             array(
  430.                                 'id' => $request->request->get('itemgroupId')
  431.                             )
  432.                         );
  433.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Service/';
  434.                     $defaultPurchaseActionTagId $request->request->get('defaultPurchaseActionTagId''');
  435.                     $ledgerHitAs $request->request->get('ledgerHitAs''');
  436.                     $defaultExpenseId $request->request->get('defaultExpenseId''');
  437.                     Inventory::CreateNewService(
  438.                         $this->getDoctrine()->getManager(),
  439.                         $request->request->get('ex_id'),
  440.                         $request->request->get('name'),
  441.                         $companyId,
  442.                         $request->request->get('typeId'),
  443.                         $request->request->get('categoryId'),
  444.                         $request->request->get('brandCompany'),
  445.                         $request->request->get('subCategoryId'),
  446.                         $request->request->get('itemgroupId'),
  447.                         $request->request->get('unitTypeId'),
  448.                         $request->request->get('note'),
  449.                         $request->request->get('alias'''),
  450.                         $request->files->get('dataSheets', []),
  451.                         $request->files->get('service_default_image'null),
  452.                         $upl_dir,
  453.                         $request->files->get('service_images', []),
  454.                         $request->request->get('categorization_1'''),
  455.                         $request->request->get('categorization_2'''),
  456.                         $request->request->get('categorization_3'''),
  457.                         $request->request->get('categorization_4'''),
  458.                         $request->request->get('purchasePrice'0),
  459.                         $request->request->get('salesPrice'0),
  460.                         $request->request->get('productFdm'''),
  461.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  462.                         ($ledgerHitAs != '') ? $ledgerHitAs $ig->getLedgerHitAs(),
  463.                         ($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId $ig->getDefaultPurchaseActionTagId(),
  464.                         ($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId $ig->getDefaultExpenseId(),
  465.                         $request->request->get('taxConfigIds', []),
  466.                         $request->request->get('defaultTaxConfigId'0),
  467.                         $request->request->get('purchaseTaxConfigIds', []),
  468.                         $request->request->get('defaultPurchaseTaxConfigId'0)
  469.                     );
  470.                     $this->addFlash(
  471.                         'success',
  472.                         'Service Have Been Added/Updated'
  473.                     );
  474.                 } else {
  475.                     $ig $this->getDoctrine()
  476.                         ->getRepository('ApplicationBundle:InvItemGroup')
  477.                         ->findOneBy(
  478.                             array(
  479.                                 'id' => $request->request->get('itemgroupId')
  480.                             )
  481.                         );
  482.                     $defaultPurchaseActionTagId $request->request->get('defaultPurchaseActionTagId''');
  483.                     $ledgerHitAs $request->request->get('ledgerHitAs''');
  484.                     $defaultExpenseId $request->request->get('defaultExpenseId''');
  485.                     $specData = [];
  486.                     $specData = [];
  487.                     foreach ($request->request->get('spec', []) as $specIndex => $specId) {
  488.                         $specData[] = array(
  489.                             'id' => $request->request->get('spec', [])[$specIndex],
  490.                             'value' => $request->request->get('spec_value', [])[$specIndex],
  491.                         );
  492.                     }
  493.                     $crateData = [];
  494.                     $crateData = [];
  495.                     foreach ($request->request->get('product_crate', []) as $crateIndex => $crateId) {
  496.                         $crateData[] = array(
  497.                             'id' => $crateId,
  498.                             'qty' => $request->request->get('product_qty', []),
  499.                         );
  500.                     }
  501.                     $sizesData = [];
  502.                     foreach ($request->request->get('product_crate', []) as $crateIndex => $crateId) {
  503.                         $sizesData[] = array(
  504.                             'size' => $request->request->get('product_size', []),
  505.                             'dimension' => $request->request->get('product_dimension', []),
  506.                             'dimensionUnitType' => $request->request->get('product_dimension_unit_type', []),
  507.                             'weight' => $request->request->get('product_weight', []),
  508.                             'weightUnitType' => $request->request->get('product_weight_unit_type', []),
  509.                         );
  510.                     }
  511.                     Inventory::CreateNewProduct(
  512.                         $this->getDoctrine()->getManager(),
  513.                         $request->request->get('ex_id'0),
  514.                         $request->request->get('name'''),
  515.                         $request->request->get('model_no'''),
  516.                         $this->getLoggedUserCompanyId($request),
  517.                         $request->request->get('typeId'1),
  518.                         $request->request->get('categoryId'null),
  519.                         $request->request->get('hasSerial'null),
  520.                         $ig->getDraccountsHeadId(),
  521.                         $ig->getCraccountsHeadId(),
  522.                         ($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId $ig->getDefaultPurchaseActionTagId(),
  523.                         $ig->getVatAsExpenseFlag(),
  524.                         $request->request->get('brandCompany'null),
  525.                         $request->request->get('subCategoryId'null),
  526.                         $request->request->get('yearlyDepreciation'0),
  527.                         $request->request->get('purchaseWarrantyMonths'0),
  528.                         $request->request->get('salesWarrantyMonths'0),
  529.                         $request->request->get('startingBalanceUnit'0),
  530.                         $request->request->get('reorderLevel'0),
  531.                         $request->request->get('note'''),
  532.                         $request->request->get('alias'''),
  533.                         $request->request->get('itemgroupId'null),
  534.                         $request->request->get('unitTypeId'null),
  535.                         $request->request->get('hsCode'''),
  536.                         $request->request->get('skuCode'''),
  537.                         $request->files->get('dataSheets', []),
  538.                         $request->request->get('partId'''),
  539.                         $request->request->get('productCode'''),
  540.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  541.                         $request->request->get('purchasePrice'0),
  542.                         $request->request->get('salesPrice'0),
  543.                         $request->files->get('product_default_image'null),
  544.                         $upl_dir,
  545.                         $request->files->get('product_images', []),
  546.                         $request->request->get('expiryDays'0),
  547.                         $request->request->get('dimension'''),
  548.                         $request->request->get('dimensionUnitTypeId'0),
  549.                         $request->request->get('productFdm'''),
  550.                         $request->request->get('weight'''),
  551.                         $request->request->get('weightUnitTypeId'0),
  552.                         $request->request->get('specification'null),
  553.                         $request->request->get('ingredient'null),
  554.                         $request->request->get('nutrition'null),
  555.                         $request->request->get('segregatePriceByColorsFlag'null),
  556.                         $request->request->get('segregatePriceBySizesFlag'null),
  557.                         $request->request->get('categorization_1'''),
  558.                         $request->request->get('categorization_2'''),
  559.                         $request->request->get('categorization_3'''),
  560.                         $request->request->get('categorization_4'''),
  561.                         $request->request->get('weightVarianceValue'0),
  562.                         $request->request->get('weightVarianceType'0),
  563.                         $request->request->get('singleWeight'''),
  564.                         $request->request->get('singleWeightUnitTypeId'0),
  565.                         $request->request->get('singleWeightVarianceValue'0),
  566.                         $request->request->get('singleWeightVarianceType'0),
  567.                         $request->request->get('cartonWeightVarianceValue'0),
  568.                         $request->request->get('cartonWeightVarianceType'0),
  569.                         $request->request->get('cartonCapacityCount'0),
  570.                         $request->request->get('tac'''),
  571.                         $request->request->get('sellable'0),
  572.                         $request->request->get('abstract'0),
  573.                         $request->request->get('tags'''),
  574.                         $request->request->get('markerFlags'''),
  575.                         $request->request->get('defaultColorId'0),
  576.                         $request->request->get('product_color', []),
  577.                         $request->request->get('product_size', []),
  578.                         ($ledgerHitAs != '') ? $ledgerHitAs $ig->getLedgerHitAs(),
  579.                         ($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId $ig->getDefaultExpenseId(),
  580.                         $crateData,
  581.                         $sizesData,
  582.                         $specData,
  583.                         $request->request->get('taxConfigIds', []),
  584.                         $request->request->get('defaultTaxConfigId'0)  ,
  585.                         $request->request->get('purchaseTaxConfigIds', []),
  586.                         $request->request->get('defaultPurchaseTaxConfigId'0)
  587.                     );
  588.                     $this->addFlash(
  589.                         'success',
  590.                         'Product Have Been Added/Updated'
  591.                     );
  592.                 }
  593.             }
  594.             if ($request->request->has('returnJson')) {
  595.                 return new JsonResponse(array(
  596.                     'success' => true
  597.                 ));
  598.             }
  599.             if ($group_type == 2)
  600.                 return $this->redirectToRoute("create_service");
  601.             else
  602.                 return $this->redirectToRoute("create_product");
  603.         }
  604.         if ($id != 0) {
  605.             $ex_id $id;
  606.             if ($group_type == 2)
  607.                 $prod_det $this->getDoctrine()->getRepository('ApplicationBundle:AccService')->findOneBy(array(
  608.                     'serviceId' => $id//for now for stock of goods
  609. //                    'opening_locked'=>0
  610.                 ));
  611.             else
  612.                 $prod_det $this->getDoctrine()->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
  613.                     'id' => $id//for now for stock of goods
  614. //                    'opening_locked'=>0
  615.                 ));
  616.         }
  617. //        dump($prod_det);
  618.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  619.             'name' => 'warehouse_action_1'//for now for stock of goods
  620.         ));
  621.         return $this->render('@Inventory/pages/input_forms/create_product.html.twig',
  622.             array(
  623.                 'page_title' => $group_type == 'Service Entry' 'Product Entry',
  624.                 'group_type' => $group_type,
  625.                 'inv_head' => $inv_head $inv_head->getData() : '',
  626. //                'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  627.                 'services' => Inventory::ServiceList($this->getDoctrine()->getManager()),
  628.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  629.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  630.                 'itemgroup' => Inventory::ItemGroupList($em$companyId$group_type),
  631.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  632.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  633.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager(), 1),
  634.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  635.                 'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  636.                 'ex_id' => $ex_id,
  637.                 'warehouse_action_list' => $warehouse_action_list,
  638.                 'warehouse_action_list_array' => $warehouse_action_list_array,
  639.                 'markerFlags' => InventoryConstant::$SPECIAL_MARKER_ARRAY,
  640. //                'isUpdate' => true,
  641.                 'ex_prod_det' => $prod_det
  642.             )
  643.         );
  644.     }
  645.     public function ProductListAction(Request $request)
  646.     {
  647.         $em $this->getDoctrine()->getManager();
  648.         $companyId $this->getLoggedUserCompanyId($request);
  649.         $listData Inventory::GetProductListForProductListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  650.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  651.             if ($request->query->has('dataTableQry')) {
  652.                 return new JsonResponse(
  653.                     $listData
  654.                 );
  655.             }
  656.         }
  657.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  658.             'name' => 'warehouse_action_1'//for now for stock of goods
  659.         ));
  660.         return $this->render('@Inventory/pages/list/product_list.html.twig',
  661.             array(
  662.                 'page_title' => 'Product List',
  663.                 'inv_head' => $inv_head $inv_head->getData() : '',
  664. //                'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  665.                 'products' => [],
  666.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  667.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  668.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  669.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  670.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  671. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  672.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  673.                 'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  674.             )
  675.         );
  676.     }
  677.     public function SalesVsDeliveryListAction(Request $request)
  678.     {
  679.         $em $this->getDoctrine()->getManager();
  680.         $session $request->getSession();
  681.         $userType $session->get(UserConstants::USER_TYPE);
  682.         $userId $session->get(UserConstants::USER_ID);
  683.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  684.             'approved' => GeneralConstant::APPROVED,
  685. //            'stage' => GeneralConstant::STAGE_PENDING
  686.         );
  687.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  688.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  689.         }
  690. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  691. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  692. //            $selectiveDocumentsFlag=1; //by default will show only selective
  693. //            if(isset($userRestrictions['canSeeAllSo'])) {
  694. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  695. //                    $selectiveDocumentsFlag = 0;
  696. //                }
  697. //            }
  698. //
  699. //            if($selectiveDocumentsFlag==1)
  700. //            {
  701. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  702. //            }
  703. //        }
  704.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  705.             'name' => 'warehouse_action_1'//for now for stock of goods
  706.         ));
  707.         if ($request->query->has('queryDate')) {
  708.             $date = new \DateTime($request->query->get('queryDate'));
  709.         } else {
  710.             $today = new \DateTime();
  711.             $todayStr $today->format('Y-m-d');
  712.             $date = new \DateTime($todayStr);
  713.         }
  714.         $orderQryArray['salesOrderDate'] = $date;
  715.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrder')->findBy($orderQryArray);
  716.         $so_ids = [];
  717.         $so_data = [];
  718.         $so_item_ids = [];
  719.         $so_item_data = [];
  720.         foreach ($salesOrders as $salesOrder) {
  721.             if ($salesOrder->getSalesOrderDate() > $date)
  722.                 continue;
  723.             $so_ids[] = $salesOrder->getSalesOrderId();
  724.             $so_data[$salesOrder->getSalesOrderId()] = array(
  725.                 "id" => $salesOrder->getSalesOrderId(),
  726.                 "documentHash" => $salesOrder->getDocumentHash(),
  727.                 "clientId" => $salesOrder->getClientId(),
  728.             );
  729.         }
  730.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrderItem')->findBy(array(
  731.             'salesOrderId' => $so_ids,
  732.         ));
  733.         foreach ($salesOrderItems as $salesOrderItem) {
  734.             $so_item_ids[] = $salesOrderItem->getId();
  735.             $so_item_data[$salesOrderItem->getId()] = array(
  736.                 "id" => $salesOrderItem->getId(),
  737.                 "productId" => $salesOrderItem->getProductId(),
  738.                 "productName" => $salesOrderItem->getProductNameFdm(),
  739.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  740.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  741.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  742. //                "documentHash"=>$salesOrder->getDocumentHash(),
  743.                 "qty" => $salesOrderItem->getQty(),
  744.                 "transitQty" => $salesOrderItem->getTransitQty(),
  745.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  746.             );
  747.         }
  748.         return $this->render('@Inventory/pages/views/sales_vs_delivery_status.html.twig',
  749.             array(
  750.                 'page_title' => 'Order Vs. Disperse',
  751.                 'inv_head' => $inv_head $inv_head->getData() : '',
  752.                 'so_data' => $so_data,
  753.                 'queryDate' => $date,
  754.                 'so_item_data' => $so_item_data,
  755.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  756.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  757.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  758.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  759.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  760.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  761.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  762. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  763.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  764.             )
  765.         );
  766.     }
  767.     public function DeliveryPendingOrderListAction(Request $request)
  768.     {
  769.         $em $this->getDoctrine()->getManager();
  770.         $session $request->getSession();
  771.         $userType $session->get(UserConstants::USER_TYPE);
  772.         $userId $session->get(UserConstants::USER_ID);
  773.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  774.             'approved' => GeneralConstant::APPROVED,
  775.             'stage' => GeneralConstant::STAGE_PENDING
  776.         );
  777.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  778.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  779.         }
  780. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  781. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  782. //            $selectiveDocumentsFlag=1; //by default will show only selective
  783. //            if(isset($userRestrictions['canSeeAllSo'])) {
  784. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  785. //                    $selectiveDocumentsFlag = 0;
  786. //                }
  787. //            }
  788. //
  789. //            if($selectiveDocumentsFlag==1)
  790. //            {
  791. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  792. //            }
  793. //        }
  794.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  795.             'name' => 'warehouse_action_1'//for now for stock of goods
  796.         ));
  797.         if ($request->query->has('queryDate')) {
  798.             $date = new \DateTime($request->query->get('queryDate'));
  799.         } else {
  800.             $today = new \DateTime();
  801.             $todayStr $today->format('Y-m-d');
  802.             $date = new \DateTime($todayStr);
  803.         }
  804. //        $orderQryArray['salesOrderDate'] = $date;
  805.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrder')->findBy($orderQryArray);
  806.         $so_ids = [];
  807.         $so_data = [];
  808.         $so_item_ids = [];
  809.         $so_item_data = [];
  810.         foreach ($salesOrders as $salesOrder) {
  811.             if ($salesOrder->getSalesOrderDate() > $date)
  812.                 continue;
  813.             $so_ids[] = $salesOrder->getSalesOrderId();
  814.             $so_data[$salesOrder->getSalesOrderId()] = array(
  815.                 "id" => $salesOrder->getSalesOrderId(),
  816.                 "documentHash" => $salesOrder->getDocumentHash(),
  817.                 "clientId" => $salesOrder->getClientId(),
  818.             );
  819.         }
  820.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrderItem')->findBy(array(
  821.             'salesOrderId' => $so_ids,
  822.         ));
  823.         foreach ($salesOrderItems as $salesOrderItem) {
  824.             $so_item_ids[] = $salesOrderItem->getId();
  825.             $so_item_data[$salesOrderItem->getId()] = array(
  826.                 "id" => $salesOrderItem->getId(),
  827.                 "productId" => $salesOrderItem->getProductId(),
  828.                 "productName" => $salesOrderItem->getProductNameFdm(),
  829.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  830.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  831.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  832. //                "documentHash"=>$salesOrder->getDocumentHash(),
  833.                 "qty" => $salesOrderItem->getQty(),
  834.                 "transitQty" => $salesOrderItem->getTransitQty(),
  835.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  836.             );
  837.         }
  838.         return $this->render('@Inventory/pages/views/delivery_pending_order_list.html.twig',
  839.             array(
  840.                 'page_title' => 'Pending Delivery',
  841.                 'inv_head' => $inv_head $inv_head->getData() : '',
  842.                 'so_data' => $so_data,
  843.                 'queryDate' => $date,
  844.                 'so_item_data' => $so_item_data,
  845.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  846.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  847.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  848.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  849.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  850.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  851.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  852. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  853.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  854.             )
  855.         );
  856.     }
  857.     public function AddSpecTypeAction(Request $request$id 0)
  858.     {
  859.         $ex_id 0;
  860.         $det = [];
  861.         $em $this->getDoctrine()->getManager();
  862.         $companyId $this->getLoggedUserCompanyId($request);
  863.         if ($request->isMethod('POST')) {
  864. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  865. //            $request->request->get('ex_id');
  866. //
  867. //
  868. //            $this->addFlash(
  869. //                'success',
  870. //                'Spec Type Added'
  871. //            );
  872.             Inventory::CreateSpecType(
  873.                 $this->getDoctrine()->getManager(),
  874.                 $request->request->get('ex_id'),
  875.                 $request->request,
  876.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  877.               );
  878.         }
  879.         if ($id != 0) {
  880.             $ex_id $id;
  881.             $det $this->getDoctrine()->getRepository('ApplicationBundle:SpecType')->findOneBy(array(
  882.                 'id' => $id
  883.             ));
  884.         }
  885.         $specTypeDetails $em->getRepository(SpecType::class)->findAll();
  886.         return $this->render('@Inventory/pages/input_forms/addSpecType.html.twig',
  887.             array(
  888.                 'page_title' => 'Add Spec Type',
  889.                 'ex_id' => $ex_id,
  890.                 'ex_det' => $det,
  891.                 'specTypeDetails' => $specTypeDetails,
  892.             )
  893.         );
  894.     }
  895.     public function ItemGroupAction(Request $request$id 0)
  896.     {
  897.         $ex_id 0;
  898.         $det = [];
  899.         $em $this->getDoctrine()->getManager();
  900.         $companyId $this->getLoggedUserCompanyId($request);
  901.         $group_type 1;//item
  902.         $route $request->get('_route');
  903.         if ($route == 'service_group')
  904.             $group_type 2;//service
  905.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');
  906.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');
  907.         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ItemGroup/';
  908.         if ($request->isMethod('POST')) {
  909.             Inventory::CreateItemGroup(
  910.                 $this->getDoctrine()->getManager(),
  911.                 $request->request->get('ex_id'),
  912.                 $this->getLoggedUserCompanyId($request),
  913.                 $request->request,
  914.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  915.                 $request->files->get('dataSheets', []),
  916.                 $request->files->get('item_group_icon'),
  917.                 $request->files->get('item_group_banner_image'),
  918.                 $request->files->get('item_group_default_image'),
  919.                 $upl_dir,
  920.                 $request->files->get('item_group_images', []));
  921.         }
  922.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  923.             'name' => 'warehouse_action_1',
  924.         ));
  925.         if($group_type == 1){
  926.             if ($id != 0) {
  927.                 $ex_id $id;
  928.                 $det $this->getDoctrine()->getRepository('ApplicationBundle:InvItemGroup')->findOneBy(array(
  929.                     'id' => $id//for now for stock of goods
  930. //                    'opening_locked'=>0
  931.                 ));
  932.             }
  933.         }
  934.         else{
  935.             if ($id != 0) {
  936.                 $ex_id $id;
  937.                 $det $this->getDoctrine()->getRepository('ApplicationBundle:AccService')->findOneBy(array(
  938.                     'serviceId' => $id
  939.                 ));
  940.             }
  941.         }
  942. //        dump($det);
  943.         return $this->render('@Inventory/pages/input_forms/item_group.html.twig',
  944.             array(
  945.                 'page_title' => $group_type == "Item Groups" "Service Groups",
  946.                 'inv_head' => $inv_head $inv_head->getData() : '',
  947.                 'group_type' => $group_type,
  948.                 'igList' => Inventory::ItemGroupList($em$companyId$group_type),
  949.                 'warehouse_action_list' => $warehouse_action_list,
  950. //                'data'=>Inventory::ItemGroupFormRelatedData($this->getDoctrine()->getManager()),
  951.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  952.                 'spec_type_list' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  953.                 'ex_id' => $ex_id,
  954.                 'ex_det' => $det,
  955.                 'upl_dir' => $upl_dir,
  956.             )
  957.         );
  958.     }
  959.     public function addStartingOpeningInOutAction(Request $request$refreshed_opening 0)
  960.     {
  961.         //be very careful!!
  962.         $em $this->getDoctrine()->getManager();
  963. //        $last_refresh_date="";
  964.         //steps
  965.         //1. set all inventory to their opening position
  966.         $assign_list = array();
  967.         $data = array();
  968.         if ($refreshed_opening == 0) {
  969.             $new_cc $em
  970.                 ->getRepository('ApplicationBundle:AccSettings')
  971.                 ->findOneBy(
  972.                     array(
  973.                         'name' => 'accounting_year_start',
  974.                     )
  975.                 );
  976.             $date_start = new \DateTime($new_cc->getData());
  977.             $date_start_str $date_start->format('Y-m-d');
  978.             $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  979. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  980.             $stmt $em->getConnection()->prepare($closingQuery);
  981.             $stmt->execute();
  982.             $iniClosing $stmt->fetchAll();
  983. //                $stmt = $em->getConnection()->prepare($transQuery);
  984. //                $stmt->execute();
  985. //                $iniTrans = $stmt->fetchAll();
  986.             $singleClosing_byProductId = array();
  987.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  988.             foreach ($iniClosing as $item) {
  989.                 if (!isset($singleClosing_byProductId[$item['product_id']])) {
  990.                     $singleClosing_byProductId[$item['product_id']] = array(
  991.                         'date' => $item['date'],
  992.                         'qtyAdd' => $item['qty_addition'],
  993.                         'qtySub' => '0',
  994.                         'valueAdd' => $item['addition'],
  995.                         'valueSub' => '0',
  996.                         'fromWarehouse' => 0,
  997.                         'toWarehouse' => $item['warehouse_id'],
  998.                         'fromWarehouseSub' => 0,
  999.                         'toWarehouseSub' => $item['action_tag_id'],
  1000.                         'price' => ($item['addition'] / $item['qty_addition'])
  1001.                     );
  1002.                 }
  1003.             }
  1004.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1005. //                foreach ($iniTrans as $item) {
  1006. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  1007. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  1008. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  1009. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  1010. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  1011. //                    }
  1012. //                }
  1013.             foreach ($singleClosing_byProductId as $key => $item) {
  1014.                 if (!isset($data[$key])) {
  1015.                     $data[$key][] = $item;
  1016.                 }
  1017.             }
  1018.             //now that we go the data we can empty the closing table
  1019. //                $get_kids_sql ='UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  1020. //    truncate `inv_closing_balance`;
  1021. //    truncate `inventory_storage`;
  1022. //    truncate `inv_item_transaction`;';
  1023. //                $stmt = $em->getConnection()->prepare($get_kids_sql);
  1024. //                $stmt->execute();
  1025. //                $stmt->closeCursor();
  1026. //                $stmt->fetchAll();
  1027.             $total_inv_value_in 0;
  1028.             foreach ($data as $key => $item) {
  1029.                 if (!empty($item)) {
  1030.                     foreach ($item as $entry) {
  1031.                         $transDate = new \DateTime($entry['date']);
  1032.                         $new = new InvItemInOut();
  1033.                         $new->setProductId($key);
  1034.                         $new->setWarehouseId($entry['toWarehouse']);
  1035.                         $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  1036.                         $new->setActionTagId($entry['toWarehouseSub']);
  1037.                         $new->setTransactionDate($transDate);
  1038.                         $new->setQty($entry['qtyAdd']);
  1039.                         $new->setPrice($entry['price']);
  1040.                         $new->setAmount($entry['qtyAdd'] * $entry['price']);
  1041.                         $new->setEntity(0);// opening =0
  1042.                         $new->setEntityId(0);// opening =0
  1043.                         $new->setDebitCreditHeadId(0);// opening =0
  1044.                         $new->setVoucherIds(null);// opening =0
  1045.                         $em->persist($new);
  1046.                         $em->flush();
  1047.                         $total_inv_value_in += $entry['qtyAdd'] * $entry['price'];
  1048.                     }
  1049.                 }
  1050.             }
  1051.             $refreshed_opening 1;
  1052. //                $terminate=1;
  1053. //                $last_refresh_date=$last_refresh_date_obj->format('Y-m-d');
  1054.             return new JsonResponse(array(
  1055.                 "success" => true,
  1056.             ));
  1057.             //now call the function which will add the 1st ever entry or opening entry
  1058.         }
  1059.         //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  1060.         return new JsonResponse(array(
  1061.             "success" => false,
  1062.         ));
  1063.     }
  1064.     public function RefreshInventoryAction(Request $request$refreshed_opening 0)
  1065.     {
  1066.         //be very careful!!
  1067.         $em $this->getDoctrine()->getManager();
  1068.         $refreshed_opening 0;
  1069.         $last_refresh_date "";
  1070.         $last_refresh_date_obj "";
  1071.         $terminate 0;
  1072.         $companyId $this->getLoggedUserCompanyId($request);
  1073.         $modifyAccTransaction $request->request->has('modify_acc_trans_flag') ? $request->request->get('modify_acc_trans_flag') : 0;
  1074.         $modifyProductionPrice $request->request->has('modify_production_price') ? $request->request->get('modify_production_price') : 0;
  1075. //        $last_refresh_date="";
  1076.         if ($request->isMethod('POST')) {
  1077.             //steps
  1078.             //1. set all inventory to their opening position
  1079.             $assign_list = array();
  1080.             $data = array();
  1081.             if ($request->request->has('inventory_refreshed'))
  1082.                 $refreshed_opening $request->request->get('inventory_refreshed');
  1083.             if ($request->request->has('last_refresh_date'))
  1084.                 $last_refresh_date $request->request->get('last_refresh_date');
  1085.             if ($refreshed_opening == 0) {
  1086. //                System::log_it($this->container->getParameter('kernel.root_dir'), "",
  1087. //                    'inventory_refresh_debug', 0); //last er 1 is append
  1088.                 $new_cc $em
  1089.                     ->getRepository('ApplicationBundle:AccSettings')
  1090.                     ->findOneBy(
  1091.                         array(
  1092.                             'name' => 'accounting_year_start',
  1093.                         )
  1094.                     );
  1095.                 $date_start = new \DateTime($new_cc->getData());
  1096.                 $date_start_str $date_start->format('Y-m-d');
  1097.                 $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  1098. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  1099.                 $stmt $em->getConnection()->prepare($closingQuery);
  1100.                 $stmt->execute();
  1101.                 $iniClosing $stmt->fetchAll();
  1102. //                $stmt = $em->getConnection()->prepare($transQuery);
  1103. //                $stmt->execute();
  1104. //                $iniTrans = $stmt->fetchAll();
  1105.                 $singleClosing_byProductId = array();
  1106.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1107.                 foreach ($iniClosing as $item) {
  1108.                     if (!isset($singleClosing_byProductId[$item['product_id']])) {
  1109.                         $singleClosing_byProductId[$item['product_id']] = array(
  1110.                             'date' => $item['date'],
  1111.                             'qtyAdd' => $item['qty_addition'],
  1112.                             'qtySub' => '0',
  1113.                             'valueAdd' => $item['addition'],
  1114.                             'valueSub' => '0',
  1115.                             'fromWarehouse' => 0,
  1116.                             'toWarehouse' => $item['warehouse_id'],
  1117.                             'fromWarehouseSub' => 0,
  1118.                             'toWarehouseSub' => $item['action_tag_id'],
  1119.                             'price' => $item['qty_addition'] != ? ($item['addition'] / $item['qty_addition']) : $item['addition']
  1120.                         );
  1121.                     }
  1122.                 }
  1123.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1124. //                foreach ($iniTrans as $item) {
  1125. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  1126. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  1127. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  1128. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  1129. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  1130. //                    }
  1131. //                }
  1132.                 foreach ($singleClosing_byProductId as $key => $item) {
  1133.                     if (!isset($data[$key])) {
  1134.                         $data[$key][] = $item;
  1135.                     }
  1136.                 }
  1137.                 //new one
  1138.                 //chekc if ultra opening stock received note exists if not create it
  1139.                 $mo $em
  1140.                     ->getRepository('ApplicationBundle:StockReceivedNote')
  1141.                     ->findOneBy(
  1142.                         array(
  1143.                             'documentHash' => '_MASTER_OPENING_',
  1144.                             'typeHash' => 'SR',
  1145.                             'prefixHash' => 4,
  1146.                             'assocHash' => '_MASTER_OPENING_',
  1147.                             'numberHash' => 1,
  1148.                         )
  1149.                     );
  1150.                 if (!$mo) {
  1151.                     //doensot exist to add :)
  1152. //                    $products = $post_data->get('products');
  1153. //                    $qty = $post_data->get('qty');
  1154. //                    $note = $post_data->get('note');
  1155.                     $new = new StockReceivedNote();
  1156.                     $new->setStockReceivedNoteDate(new \DateTime($date_start_str));
  1157.                     $new->setCompanyId($companyId);
  1158.                     $new->setDocumentHash('_MASTER_OPENING_');
  1159.                     $new->setTypeHash('SR');
  1160.                     $new->setPrefixHash(4);
  1161.                     $new->setAssocHash('_MASTER_OPENING_');
  1162.                     $new->setNumberHash(1);
  1163.                     $new->setCreditHeadId(0);
  1164.                     $new->setStockTransferId(0);
  1165.                     $new->setSalesOrderId(0);
  1166.                     $new->setType(4);
  1167.                     $new->setStatus(GeneralConstant::ACTIVE);
  1168.                     $new->setWarehouseId(0);
  1169.                     $new->setNote('');
  1170.                     $new->setAutoCreated(1);
  1171.                     $new->setApproved(GeneralConstant::APPROVED);
  1172. //        $new->setIndentTagged(0);
  1173.                     $new->setStage(GeneralConstant::STAGE_COMPLETE);
  1174.                     $new->setCreatedLoginId(0);
  1175.                     $new->setEditedLoginId(0);
  1176.                     $em->persist($new);
  1177.                     $em->flush();
  1178.                     $SRID $new->getStockReceivedNoteId();
  1179.                     $last_refresh_date_obj $new->getStockReceivedNoteDate();
  1180.                     //now add items to details
  1181.                     foreach ($data as $key => $item) {
  1182.                         if (!empty($item)) {
  1183.                             foreach ($item as $entry) {
  1184.                                 $transDate = new \DateTime($entry['date']);
  1185.                                 if ($last_refresh_date_obj == '') {
  1186.                                     $last_refresh_date_obj $transDate;
  1187.                                 } else if ($transDate $last_refresh_date_obj) {
  1188.                                     $last_refresh_date_obj $transDate;
  1189.                                 }
  1190.                                 $new = new StockReceivedNoteItem();
  1191.                                 $new->setStockReceivedNoteId($SRID);
  1192.                                 $new->setStockTransferItemId(0);
  1193.                                 $salesCodeRange = [];
  1194.                                 $salesCodeRangeStr '';
  1195.                                 $new->setSalesCodeRange("[" $salesCodeRangeStr "]");
  1196.                                 $new->setQty($entry['qtyAdd']);
  1197.                                 $new->setPrice($entry['price']);
  1198.                                 $new->setBalance($entry['qtyAdd']);
  1199.                                 $new->setProductId($key);
  1200.                                 $new->setWarrantyMon(0);
  1201.                                 $new->setWarehouseId($entry['toWarehouse']);
  1202.                                 $new->setWarehouseActionId($entry['toWarehouseSub']);
  1203.                                 $em->persist($new);
  1204.                                 $em->flush();
  1205.                             }
  1206.                         }
  1207.                     }
  1208. //                    for ($i = 0; $i < count($products); $i++) {
  1209. //
  1210. //
  1211. //                        $srItem = self::CreateNewStockReceivedNoteItem($em, $post_data, $i, $new->getStockReceivedNoteId(), $LoginID);
  1212. //                    }
  1213.                 }
  1214.                 if ($mo)
  1215.                     $last_refresh_date_obj $mo->getStockReceivedNoteDate();
  1216.                 $last_refresh_date_obj->modify('-1 day');///new so that it willstart form this day on next call
  1217.                 //new ends
  1218.                 //now that we go the data we can empty the closing table
  1219.                 $get_kids_sql "UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  1220. UPDATE `purchase_order` SET expense_amount=0, expense_pending_balance_amount=0, grn_tag_pending_expense_invoice_ids='[]' WHERE 1;
  1221.     truncate `inv_closing_balance`;
  1222.     truncate `inventory_storage`;
  1223.     truncate `inv_item_transaction`;";
  1224.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  1225.                 $stmt->execute();
  1226.                 $stmt->closeCursor();
  1227. //                $stmt->fetchAll();
  1228. //                foreach ($data as $key => $item) {
  1229. //                    if (!empty($item)) {
  1230. //                        foreach ($item as $entry) {
  1231. //                            $transDate = new \DateTime($entry['date']);
  1232. //                            Inventory::addItemToInventoryCompact($em,
  1233. //                                $key,
  1234. //                                $entry['fromWarehouse'],
  1235. //                                $entry['toWarehouse'],
  1236. //                                $entry['fromWarehouseSub'],
  1237. //                                $entry['toWarehouseSub'],
  1238. //                                $transDate,
  1239. //                                $entry['qtyAdd'],
  1240. //                                $entry['qtySub'],
  1241. //                                $entry['valueAdd'],
  1242. //                                $entry['valueSub'],
  1243. //                                $entry['price'],
  1244. //                                $this->getLoggedUserCompanyId($request));
  1245. //                            if ($last_refresh_date_obj == '') {
  1246. //                                $last_refresh_date_obj = $transDate;
  1247. //                            } else if ($transDate < $last_refresh_date_obj) {
  1248. //                                $last_refresh_date_obj = $transDate;
  1249. //                            }
  1250. //                        }
  1251. //                    }
  1252. //                }
  1253.                 $refreshed_opening 1;
  1254. //                $terminate=1;
  1255.                 if ($last_refresh_date_obj == "") {
  1256.                     $last_refresh_date $date_start_str;
  1257.                 } else {
  1258.                     $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1259.                 }
  1260.                 return new JsonResponse(array(
  1261.                     "success" => true,
  1262.                     "last_refresh_date" => $last_refresh_date,
  1263.                     "inventory_refreshed" => $refreshed_opening
  1264.                 ));
  1265.                 //now call the function which will add the 1st ever entry or opening entry
  1266.             }
  1267.             //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  1268.             if ($last_refresh_date != '')
  1269.                 $last_refresh_date_obj = new \DateTime($last_refresh_date);
  1270.             else {
  1271.                 $new_cc $em
  1272.                     ->getRepository('ApplicationBundle:AccSettings')
  1273.                     ->findOneBy(
  1274.                         array(
  1275.                             'name' => 'accounting_year_start',
  1276.                         )
  1277.                     );
  1278.                 $last_refresh_date_obj = new \DateTime($new_cc->getData());
  1279.                 $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1280.             }
  1281.             $last_refresh_date_obj->modify('+1 day');
  1282.             $today = new \DateTime();
  1283.             if ($last_refresh_date_obj $today) {
  1284.                 $terminate 1;
  1285.             }
  1286.             $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1287.             //ok now we got the date so get grn item on this date
  1288.             //GRN
  1289.             $query "SELECT grn_item.*, grn.grn_date, grn.document_hash from  grn_item
  1290.               join grn on grn.grn_id=grn_item.grn_id
  1291.             where grn.grn_date ='" $last_refresh_date " 00:00:00' and grn.approved=1";
  1292.             $stmt $em->getConnection()->prepare($query);
  1293.             $stmt->execute();
  1294.             $queryData $stmt->fetchAll();
  1295.             $grn_ids = [];
  1296.             foreach ($queryData as $item) {
  1297.                 $data[$item['product_id']][] = array(
  1298.                     'date' => $last_refresh_date,
  1299.                     'entity' => array_flip(GeneralConstant::$Entity_list)['Grn'],
  1300.                     'entityId' => $item['grn_id'],
  1301.                     'colorId' => $item['color_id'],
  1302.                     'sizeId' => $item['size_id'],
  1303.                     'entityDocHash' => $item['document_hash'],
  1304.                     'qtyAdd' => $item['qty'],
  1305.                     'qtySub' => 0,
  1306.                     'valueAdd' => ($item['qty'] * $item['price_with_expense']),
  1307.                     'valueSub' => 0,
  1308.                     'price' => $item['price_with_expense'],
  1309.                     'fromWarehouse' => 0,
  1310.                     'toWarehouse' => $item['warehouse_id'],
  1311.                     'fromWarehouseSub' => 0,
  1312. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1313.                     'toWarehouseSub' => $item['warehouse_action_id']
  1314.                 );
  1315.                 if (!in_array($item['grn_id'], $grn_ids))
  1316.                     $grn_ids[] = $item['grn_id'];
  1317.             }
  1318.             //now add grns
  1319.             foreach ($data as $key => $item) {
  1320.                 if (!empty($item)) {
  1321.                     foreach ($item as $entry) {
  1322.                         $transDate = new \DateTime($entry['date']);
  1323.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1324.                             $key,
  1325.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1326.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1327.                             $entry['fromWarehouse'],
  1328.                             $entry['toWarehouse'],
  1329.                             $entry['fromWarehouseSub'],
  1330.                             $entry['toWarehouseSub'],
  1331.                             $transDate,
  1332.                             $entry['qtyAdd'],
  1333.                             $entry['qtySub'],
  1334.                             $entry['valueAdd'],
  1335.                             $entry['valueSub'],
  1336.                             $entry['price'],
  1337.                             $this->getLoggedUserCompanyId($request),
  1338.                             0,
  1339.                             $entry['entity'],
  1340.                             $entry['entityId'],
  1341.                             $entry['entityDocHash'],
  1342.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_SUPPLER
  1343.                         );
  1344.                         if ($last_refresh_date_obj == '') {
  1345.                             $last_refresh_date_obj $transDate;
  1346.                         } else if ($transDate $last_refresh_date_obj) {
  1347.                             $last_refresh_date_obj $transDate;
  1348.                         }
  1349.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1350.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1351.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1352.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1353.                             "",
  1354.                             'inventory_refresh_debug'1); //last er 1 is append
  1355.                     }
  1356.                 }
  1357.             }
  1358.             ///adding grn vouhcer mod here too incase it wasnot in the distributed IG for heads
  1359. //            $grn=$em->getRepository('ApplicationBundle:Grn')->findBy(array(
  1360. //                'grnId'=>$grn_ids,
  1361. //                'modifyVoucherFlag'=>1 //have to add this flag
  1362. //            ));
  1363.             foreach ($grn_ids as $grn_id) {
  1364.                 if ($modifyAccTransaction == 1)
  1365.                     Inventory::ModifyGrnTransactions($em$grn_id1);
  1366.                 else
  1367.                     Inventory::ModifyGrnTransactions($em$grn_id);
  1368.             }
  1369.             //adding voucher ends
  1370.             $inv_head_list_by_wa = [];
  1371.             $inv_head_list = [];
  1372.             $cogs_head 0;
  1373.             $cogs_head 0;
  1374.             $internal_proj 0;
  1375. //            if ($project) {
  1376. //                if ($project->getProjectType() == 2) {
  1377. //                    $cogs_head = $project->getInternalProjectAssetHeadId();
  1378. //                    $internal_proj = 1;
  1379. //                } else {
  1380. //                    $cogs_head_qry = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1381. //                        'name' => 'cogs'
  1382. //                    ));
  1383. //                    $cogs_head = $cogs_head_qry->getData();
  1384. //                }
  1385. //            } else {
  1386.             $cogs_head_qry $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1387.                 'name' => 'cogs'
  1388.             ));
  1389.             $cogs_head $cogs_head_qry->getData();
  1390. //            }
  1391.             $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');
  1392.             foreach ($warehouse_action_list as $wa) {
  1393.                 $inv_head_data $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1394.                         'name' => 'warehouse_action_' $wa['id'])
  1395.                 );
  1396.                 if ($inv_head_data) {
  1397.                     $inv_head_list_by_wa[$wa['id']] = $inv_head_data->getData();
  1398.                     $inv_head_list[] = $inv_head_data->getData();
  1399.                 }
  1400.             }
  1401.             $data = [];
  1402.             //____________STOCK_RECEIVED___________________
  1403.             $docEntity "StockReceivedNote";
  1404.             $docEntityIdField "stockReceivedNoteId";
  1405.             $accTransactionDataByDocId = [];
  1406.             $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
  1407.               join stock_received_note on stock_received_note.stock_received_note_id=stock_received_note_item.stock_received_note_id
  1408.             where stock_received_note.stock_received_note_date ='" $last_refresh_date " 00:00:00' and stock_received_note.approved=1";
  1409.             $stmt $em->getConnection()->prepare($query);
  1410.             $stmt->execute();
  1411.             $queryData $stmt->fetchAll();
  1412.             $grn_ids = [];
  1413.             foreach ($queryData as $item) {
  1414.                 $data[$item['product_id']][] = array(
  1415.                     'date' => $last_refresh_date,
  1416.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  1417.                     'entityId' => $item['stock_received_note_id'],
  1418.                     'colorId' => $item['color_id'],
  1419.                     'sizeId' => $item['size_id'],
  1420.                     'type' => $item['type'],
  1421.                     'entityDocHash' => $item['document_hash'],
  1422.                     'qtyAdd' => $item['qty'],
  1423.                     'qtySub' => 0,
  1424.                     'valueAdd' => ($item['qty'] * $item['price']),
  1425.                     'valueSub' => 0,
  1426.                     'price' => $item['price'],
  1427.                     'fromWarehouse' => 0,
  1428.                     'toWarehouse' => $item['warehouse_id'],
  1429.                     'fromWarehouseSub' => 0,
  1430. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1431.                     'toWarehouseSub' => $item['warehouse_action_id']
  1432.                 );
  1433. //                if (!in_array($item['grn_id'], $grn_ids))
  1434. //                    $grn_ids[] = $item['grn_id'];
  1435.             }
  1436.             foreach ($data as $key => $item) {
  1437.                 if (!empty($item)) {
  1438.                     foreach ($item as $entry) {
  1439.                         $transDate = new \DateTime($entry['date']);
  1440.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1441.                             $key,
  1442.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1443.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1444.                             $entry['fromWarehouse'],
  1445.                             $entry['toWarehouse'],
  1446.                             $entry['fromWarehouseSub'],
  1447.                             $entry['toWarehouseSub'],
  1448.                             $transDate,
  1449.                             $entry['qtyAdd'],
  1450.                             $entry['qtySub'],
  1451.                             $entry['valueAdd'],
  1452.                             $entry['valueSub'],
  1453.                             $entry['price'],
  1454.                             $this->getLoggedUserCompanyId($request),
  1455.                             0,
  1456.                             $entry['entity'],
  1457.                             $entry['entityId'],
  1458.                             $entry['entityDocHash'],
  1459.                             $entry['type'] == ?
  1460.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_OPENING :
  1461.                                 ($entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_STOCK_IN :
  1462.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT)
  1463.                         );
  1464.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1465.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1466.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1467.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1468.                             "",
  1469.                             'inventory_refresh_debug'1); //last er 1 is append
  1470.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1471.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1472.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  1473.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  1474.                         else
  1475.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  1476.                         if ($last_refresh_date_obj == '') {
  1477.                             $last_refresh_date_obj $transDate;
  1478.                         } else if ($transDate $last_refresh_date_obj) {
  1479.                             $last_refresh_date_obj $transDate;
  1480.                         }
  1481.                     }
  1482.                 }
  1483.             }
  1484.             if ($modifyAccTransaction == 1) {
  1485.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1486.                     $docHere $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  1487.                         $docEntityIdField => $docId,
  1488.                     ));;
  1489.                     if ($docHere) {
  1490.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1491.                         if ($curr_v_ids == null)
  1492.                             $curr_v_ids = [];
  1493.                         $skipVids = [];
  1494.                         $toChangeVid 0;
  1495.                         $voucher null;
  1496.                         foreach ($curr_v_ids as $vid) {
  1497.                             if (in_array($vid$skipVids))
  1498.                                 continue;
  1499.                             $skipVids[] = $vid//to prevent duplicate query
  1500.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1501.                                 'transactionId' => $vid,
  1502.                             ));;
  1503.                             if ($voucher) {
  1504.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1505.                                     $toChangeVid $vid;
  1506.                                 } else {
  1507.                                     continue;
  1508.                                 }
  1509.                             }
  1510.                         }
  1511.                         if ($toChangeVid == 0) {
  1512.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1513.                                 $em,
  1514.                                 $docHere->getStockReceivedNoteDate()->format('Y-m-d'),
  1515.                                 0,
  1516.                                 AccountsConstant::VOUCHER_JOURNAL,
  1517.                                 'Journal For Stock Received Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  1518.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1519.                                 'JV',
  1520.                                 'GN',
  1521.                                 0,
  1522.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1523.                                 0,
  1524.                                 $docHere->getCreatedLoginId(),
  1525.                                 $docHere->getCompanyId(),
  1526.                                 '',
  1527.                                 0,
  1528.                                 1
  1529.                             );
  1530.                             $em->flush();
  1531.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1532.                                 'transactionId' => $toChangeVid,
  1533.                             ));;
  1534.                         }
  1535.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  1536.                         $tot_inv_amount 0;
  1537.                         foreach ($transData as $k => $v) {
  1538.                             $tot_inv_amount += ($v);
  1539.                             Accounts::CreateNewTransactionDetails($em,
  1540.                                 '',
  1541.                                 $toChangeVid,
  1542.                                 Generic::CurrToInt($v),
  1543.                                 $k,
  1544.                                 'Inventory Inward For - ' $docHere->getDocumentHash(),
  1545.                                 AccountsConstant::DEBIT,
  1546.                                 0,
  1547.                                 [],
  1548.                                 [],
  1549.                                 $docHere->getCreatedLoginId()
  1550.                             );
  1551.                         }
  1552.                         $stockReceivedType $docHere->getType();
  1553.                         $to_balance_head 0;
  1554.                         if (in_array($stockReceivedType, [23]))
  1555.                             $to_balance_head $docHere->getCreditHeadId();
  1556.                         else {
  1557.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1558.                                     'name' => 'inv_on_transit_head')
  1559.                             );
  1560.                             if ($inv_transit_head)
  1561.                                 $to_balance_head $inv_transit_head->getData();
  1562.                         }
  1563.                         Accounts::CreateNewTransactionDetails($em,
  1564.                             '',
  1565.                             $toChangeVid,
  1566.                             Generic::CurrToInt($tot_inv_amount),
  1567.                             $to_balance_head,
  1568.                             in_array($stockReceivedType, [23]) ? 'Balancing of Stock in Items for -' $docHere->getDocumentHash() : 'In Transit Items for -' $docHere->getDocumentHash(),
  1569.                             AccountsConstant::CREDIT,
  1570.                             0,
  1571.                             [],
  1572.                             [],
  1573.                             $docHere->getCreatedLoginId()
  1574.                         );
  1575.                         if ($voucher)
  1576.                             $voucher->setTransactionAmount($tot_inv_amount);
  1577.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1578.                         if ($curr_v_ids != null)
  1579.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1580.                         else
  1581.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1582.                         $em->flush();
  1583. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  1584.                     }
  1585.                 }
  1586.             }
  1587.             $data = [];
  1588.             $query "SELECT purchase_invoice.* from  purchase_invoice
  1589. where purchase_invoice.purchase_invoice_date ='" $last_refresh_date " 00:00:00' and purchase_invoice.approved=1
  1590.             ";
  1591.             $stmt $em->getConnection()->prepare($query);
  1592.             $stmt->execute();
  1593.             $queryData $stmt->fetchAll();
  1594.             foreach ($queryData as $pi) {
  1595.                 $transDate = new \DateTime($pi['purchase_invoice_date']);
  1596.                 if ($last_refresh_date_obj == '') {
  1597.                     $last_refresh_date_obj $transDate;
  1598.                 } else if ($transDate $last_refresh_date_obj) {
  1599.                     $last_refresh_date_obj $transDate;
  1600.                 }
  1601.                 Accounts::CalibrateProductPriceWithPi($em$pi['purchase_invoice_id'], 1);
  1602.             }
  1603.             $data = [];
  1604.             $query "SELECT expense_invoice.* from  expense_invoice
  1605. where expense_invoice.expense_invoice_date ='" $last_refresh_date " 00:00:00' and expense_invoice.approved=1 and
  1606.             expense_invoice_type_id=1";
  1607.             $stmt $em->getConnection()->prepare($query);
  1608.             $stmt->execute();
  1609.             $queryData $stmt->fetchAll();
  1610.             foreach ($queryData as $ei) {
  1611.                 $transDate = new \DateTime($ei['expense_invoice_date']);
  1612.                 if ($last_refresh_date_obj == '') {
  1613.                     $last_refresh_date_obj $transDate;
  1614.                 } else if ($transDate $last_refresh_date_obj) {
  1615.                     $last_refresh_date_obj $transDate;
  1616.                 }
  1617.                 $grn_ids json_decode($ei['grn_id_list'], true);
  1618.                 if ($grn_ids == null)
  1619.                     $grn_ids = [];
  1620. //                if (!empty($grn_ids)) {
  1621. //
  1622. //
  1623. //                        if ($ei->getExpenseInvocationStrategyOnGrn() != 2) {
  1624. //                            $grn = $em->getRepository('ApplicationBundle:Grn')->findBy(array(
  1625. //                                'purchaseOrderId' => $ei->getPurchaseOrderId()
  1626. //                            ));
  1627. //
  1628. //                        }
  1629. //                        else
  1630. //                        {
  1631. //                            $po = $em->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(array(
  1632. //                                'purchaseOrderId' => $ei['purchase_order_id']
  1633. //                            ));
  1634. //
  1635. //                            if ($po) {
  1636. //                                $po->setExpenseAmount($po->getExpenseAmount() + $ei['invoice_amount']);
  1637. //                            }
  1638. //                            continue; //grn expense will be there anyway
  1639. //                        }
  1640. //
  1641. //
  1642. //
  1643. //                }
  1644.                 Accounts::CalibrateProductPriceWithExpense($em$ei['expense_invoice_id']);
  1645. //                $po = $em->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(array(
  1646. //                    'purchaseOrderId' => $ei['purchase_order_id']
  1647. //                ));
  1648. //
  1649. //
  1650. //                //first get the total valuation
  1651. //                if ($po) {
  1652. //                    $total_product_value = 0;
  1653. //                    $total_pending_expense = 0;
  1654. //                    $po_item_data = $em->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(array(
  1655. ////                'productId' => $item->getProductId(),
  1656. //                        'purchaseOrderId' => $ei['purchase_order_id']
  1657. //                    ));
  1658. //
  1659. //
  1660. //                    foreach ($po_item_data as $it) {
  1661. ////                    $product = $em->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
  1662. ////                        'id' => $item->getProductId()
  1663. ////                    ));
  1664. //
  1665. //                        $poqty = $it->getReceived();
  1666. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);
  1667. //                        $total_product_value += (1 * $po_price);
  1668. //
  1669. //
  1670. //                    }
  1671. //
  1672. //
  1673. //                    //now we know the total grn price value. lets get the fraction increase
  1674. //                    $total_pending_expense = $ei['invoice_amount'];
  1675. //                    if ($total_product_value != 0)
  1676. //                        $fraction_increase = ($total_pending_expense) / ($total_product_value);
  1677. //                    else
  1678. //                        $fraction_increase = 0;
  1679. //
  1680. //                    foreach ($po_item_data as $it) {
  1681. //                        $item = $it;
  1682. //                        $product = $em->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
  1683. //                            'id' => $it->getProductId()
  1684. //                        ));
  1685. //                        if (!$product)
  1686. //                            continue;
  1687. //
  1688. ////                    $items_in_inventory=$em->getRepository('ApplicationBundle:InventoryStorage')->findBy(array(
  1689. ////                        'productId'=>$item->getProductId()
  1690. ////                    ));
  1691. //
  1692. //                        $poqty = $it->getReceived();
  1693. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);;
  1694. //
  1695. //                        $existing_qty = $product->getQty();;
  1696. //
  1697. //
  1698. //                        $increased_po_price = ($po_price * $fraction_increase);
  1699. //
  1700. //                        //now lets see homuch is the total price
  1701. //                        $new_purchase_price = $product->getPurchasePrice();
  1702. //
  1703. //                        if ($increased_po_price != 0) {
  1704. //                            $last_grn_item = $em->getRepository('ApplicationBundle:GrnItem')->findOneBy(array(
  1705. //                                'purchaseOrderItemId' => $item->getId()
  1706. //                            ));
  1707. //                            if ($last_grn_item) {
  1708. //
  1709. //                                $data[$last_grn_item->getProductId()][] = array(
  1710. //                                    'date' => $last_refresh_date,
  1711. //
  1712. //                                    'entity' => array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  1713. //                                    'entityId' => $ei['expense_invoice_id'],
  1714. //                                    'colorId' => $last_grn_item->getColorId(),
  1715. //                                    'sizeId' => $last_grn_item->getSizeId(),
  1716. //                                    'entityDocHash' => $ei['document_hash'],
  1717. //                                    'qtyAdd' => 0,
  1718. //                                    'qtySub' => 0,
  1719. //                                    'valueAdd' => $increased_po_price,
  1720. ////                                    'valueAdd' => $increased_po_price>=0?$increased_po_price:0,
  1721. ////                    'valueSub' => ($item['qty'] * $item['price']),
  1722. ////                                    'valueSub' => $increased_po_price<0?((-1)*$increased_po_price):0,
  1723. //                                    'valueSub' => 0,
  1724. //                                    'price' => '_UNSET_',
  1725. //                                    'fromWarehouse' => 0,
  1726. //                                    'toWarehouse' => $last_grn_item->getWarehouseId(),
  1727. //                                    'fromWarehouseSub' => 0,
  1728. ////                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1729. //                                    'toWarehouseSub' => $last_grn_item->getWarehouseActionId()
  1730. //                                );
  1731. //
  1732. ////                                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);
  1733. ////
  1734. ////                                $total_item_price = $increased_po_price + ($product->getPurchasePrice() * ($existing_qty));
  1735. ////                                if ($existing_qty != 0)
  1736. ////                                    $new_purchase_price = $total_item_price / $existing_qty;
  1737. //
  1738. //
  1739. //                                $total_pending_expense -= $increased_po_price;
  1740. //                            }
  1741. //                        }
  1742. //                    }
  1743. //
  1744. //
  1745. //
  1746. //
  1747. //
  1748. //
  1749. //                } else {
  1750. //                    continue;
  1751. //                }
  1752.             }
  1753.             $data = [];
  1754.             //____________STOCK_TRANSFER___________________
  1755.             $docEntity "StockTransfer";
  1756.             $docEntityIdField "stockTransferId";
  1757.             $accTransactionDataByDocId = [];
  1758.             $query "SELECT stock_transfer_item.*,  stock_transfer.stock_transfer_date, stock_transfer.document_hash, stock_transfer.transfer_action_type from  stock_transfer_item
  1759.               join stock_transfer on stock_transfer.stock_transfer_id=stock_transfer_item.stock_transfer_id
  1760.             where stock_transfer.stock_transfer_date ='" $last_refresh_date " 00:00:00' and stock_transfer.approved=1";
  1761.             $stmt $em->getConnection()->prepare($query);
  1762.             $stmt->execute();
  1763.             $queryData $stmt->fetchAll();
  1764.             $grn_ids = [];
  1765.             foreach ($queryData as $item) {
  1766.                 $data[$item['product_id']][] = array(
  1767.                     'date' => $last_refresh_date,
  1768.                     'transfer_action_type' => $item['transfer_action_type'],
  1769.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  1770.                     'entityId' => $item['stock_transfer_id'],
  1771.                     'colorId' => $item['color_id'],
  1772.                     'sizeId' => $item['size_id'],
  1773.                     'entityDocHash' => $item['document_hash'],
  1774.                     'qtyAdd' => $item['transfer_action_type'] == $item['qty'] : 0,
  1775.                     'qtySub' => $item['qty'],
  1776.                     'valueAdd' => 0,
  1777. //                    'valueSub' => ($item['qty'] * $item['price']),
  1778.                     'valueSub' => '_AUTO_',
  1779.                     'price' => $item['price'],
  1780.                     'fromWarehouse' => $item['warehouse_id'],
  1781.                     'toWarehouse' => $item['transfer_action_type'] == $item['to_warehouse_id'] : 0,
  1782.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  1783. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1784.                     'toWarehouseSub' => $item['transfer_action_type'] == $item['to_warehouse_action_id'] : 0
  1785.                 );
  1786. //                if (!in_array($item['grn_id'], $grn_ids))
  1787. //                    $grn_ids[] = $item['grn_id'];
  1788.             }
  1789.             //now add grns
  1790.             foreach ($data as $key => $item) {
  1791.                 if (!empty($item)) {
  1792.                     foreach ($item as $entry) {
  1793.                         $transDate = new \DateTime($entry['date']);
  1794.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1795.                             $key,
  1796.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1797.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1798.                             $entry['fromWarehouse'],
  1799.                             $entry['toWarehouse'],
  1800.                             $entry['fromWarehouseSub'],
  1801.                             $entry['toWarehouseSub'],
  1802.                             $transDate,
  1803.                             $entry['qtyAdd'],
  1804.                             $entry['qtySub'],
  1805.                             $entry['valueAdd'],
  1806.                             $entry['valueSub'],
  1807.                             $entry['price'],
  1808.                             $this->getLoggedUserCompanyId($request),
  1809.                             0,
  1810.                             $entry['entity'],
  1811.                             $entry['entityId'],
  1812.                             $entry['entityDocHash'],
  1813.                             $entry['transfer_action_type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_INTER_WAREHOUSE GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT
  1814.                         );
  1815.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1816.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1817.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1818.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1819.                             "",
  1820.                             'inventory_refresh_debug'1); //last er 1 is append
  1821.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1822.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1823.                         if ($entry['transfer_action_type'] == 4) {
  1824.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  1825.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtySub'] * $modifiedData['slot_cost_price'];
  1826.                             else
  1827.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  1828.                         }
  1829.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  1830.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  1831.                         else
  1832.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  1833.                         if ($last_refresh_date_obj == '') {
  1834.                             $last_refresh_date_obj $transDate;
  1835.                         } else if ($transDate $last_refresh_date_obj) {
  1836.                             $last_refresh_date_obj $transDate;
  1837.                         }
  1838.                     }
  1839.                 }
  1840.             }
  1841.             if ($modifyAccTransaction == 1) {
  1842.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1843.                     $docHere $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  1844.                         $docEntityIdField => $docId,
  1845.                     ));;
  1846.                     if ($docHere) {
  1847.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1848.                         if ($curr_v_ids == null)
  1849.                             $curr_v_ids = [];
  1850.                         $skipVids = [];
  1851.                         $toChangeVid 0;
  1852.                         $voucher null;
  1853.                         foreach ($curr_v_ids as $vid) {
  1854.                             if (in_array($vid$skipVids))
  1855.                                 continue;
  1856.                             $skipVids[] = $vid//to prevent duplicate query
  1857.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1858.                                 'transactionId' => $vid,
  1859.                             ));;
  1860.                             if ($voucher) {
  1861.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1862.                                     $toChangeVid $vid;
  1863.                                 } else {
  1864.                                     continue;
  1865.                                 }
  1866.                             }
  1867.                         }
  1868.                         if ($toChangeVid == 0) {
  1869.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1870.                                 $em,
  1871.                                 $docHere->getStockTransferDate()->format('Y-m-d'),
  1872.                                 0,
  1873.                                 AccountsConstant::VOUCHER_JOURNAL,
  1874.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  1875.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1876.                                 'JV',
  1877.                                 'GN',
  1878.                                 0,
  1879.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1880.                                 0,
  1881.                                 $docHere->getCreatedLoginId(),
  1882.                                 $docHere->getCompanyId(),
  1883.                                 '',
  1884.                                 0,
  1885.                                 1
  1886.                             );
  1887.                             $em->flush();
  1888.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1889.                                 'transactionId' => $toChangeVid,
  1890.                             ));;
  1891.                         }
  1892.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  1893.                         $tot_inv_amount 0;
  1894.                         foreach ($transData as $k => $v) {
  1895.                             $tot_inv_amount += ($v);
  1896.                             Accounts::CreateNewTransactionDetails($em,
  1897.                                 '',
  1898.                                 $toChangeVid,
  1899.                                 Generic::CurrToInt($v),
  1900.                                 $k,
  1901.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  1902.                                 $v >= AccountsConstant::DEBIT AccountsConstant::CREDIT,
  1903.                                 0,
  1904.                                 [],
  1905.                                 [],
  1906.                                 $docHere->getCreatedLoginId()
  1907.                             );
  1908.                         }
  1909. //                        $stockReceivedType = $docHere->getType();
  1910.                         $to_balance_head 0;
  1911.                         if ($docHere->getTransferActionType() == 4) {
  1912.                         } else {
  1913.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1914.                                     'name' => 'inv_on_transit_head')
  1915.                             );
  1916.                             if ($inv_transit_head)
  1917.                                 $to_balance_head $inv_transit_head->getData();
  1918.                         }
  1919.                         if ($to_balance_head != 0) {
  1920.                             Accounts::CreateNewTransactionDetails($em,
  1921.                                 '',
  1922.                                 $toChangeVid,
  1923.                                 Generic::CurrToInt($tot_inv_amount),
  1924.                                 $to_balance_head,
  1925.                                 'In Transit Items for -' $docHere->getDocumentHash(),
  1926.                                 $tot_inv_amount >= AccountsConstant::CREDIT AccountsConstant::DEBIT,
  1927.                                 0,
  1928.                                 [],
  1929.                                 [],
  1930.                                 $docHere->getCreatedLoginId()
  1931.                             );
  1932.                         }
  1933.                         if ($voucher)
  1934.                             $voucher->setTransactionAmount($tot_inv_amount);
  1935.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1936.                         if ($curr_v_ids != null)
  1937.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1938.                         else
  1939.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1940.                         $em->flush();
  1941. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  1942.                     }
  1943.                 }
  1944.             }
  1945.             $data = [];
  1946.             //____________IRR___________________
  1947.             $docEntity "ItemReceivedAndReplacement";
  1948.             $docEntityIdField "itemReceivedAndReplacementId";
  1949.             $accTransactionDataByDocId = [];
  1950.             $query "SELECT irr_item.*,  item_received_replacement.irr_date, item_received_replacement.document_hash from  irr_item
  1951.               join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  1952.             where item_received_replacement.irr_date ='" $last_refresh_date " 00:00:00' and item_received_replacement.approved=1";
  1953.             $stmt $em->getConnection()->prepare($query);
  1954.             $stmt->execute();
  1955.             $queryData $stmt->fetchAll();
  1956.             $irr_add_data = [];
  1957.             $irr_replace_data = [];
  1958.             $irr_dispose_data = [];
  1959.             foreach ($queryData as $item) {
  1960.                 $irr_add_data[$item['received_product_id']][] = array(
  1961.                     'date' => $last_refresh_date,
  1962.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1963.                     'entityId' => $item['irr_id'],
  1964.                     'colorId' => $item['received_product_color_id'],
  1965.                     'sizeId' => $item['received_product_color_id'],
  1966.                     'entityDocHash' => $item['document_hash'],
  1967.                     'qtyAdd' => $item['received_qty'],
  1968.                     'qtySub' => 0,
  1969.                     'valueAdd' => ($item['received_qty'] * $item['received_unit_purchase_price']),
  1970.                     'valueSub' => 0,
  1971.                     'price' => $item['received_unit_purchase_price'],
  1972.                     'fromWarehouse' => 0,
  1973.                     'toWarehouse' => $item['received_warehouse_id'],
  1974.                     'fromWarehouseSub' => 0,
  1975.                     'toWarehouseSub' => $item['received_warehouse_action_id']
  1976.                 );
  1977.                 $irr_replace_data[$item['replaced_product_id']][] = array(
  1978.                     'date' => $last_refresh_date,
  1979.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1980.                     'entityId' => $item['irr_id'],
  1981.                     'colorId' => $item['replaced_product_color_id'],
  1982.                     'sizeId' => $item['replaced_product_color_id'],
  1983.                     'entityDocHash' => $item['document_hash'],
  1984.                     'qtyAdd' => 0,
  1985.                     'qtySub' => $item['replaced_qty'],
  1986.                     'valueAdd' => 0,
  1987.                     'valueSub' => ($item['replaced_qty'] * $item['replaced_unit_purchase_price']),
  1988.                     'price' => $item['replaced_unit_purchase_price'],
  1989.                     'fromWarehouse' => $item['replaced_warehouse_id'],
  1990.                     'toWarehouse' => 0,
  1991.                     'fromWarehouseSub' => $item['replaced_warehouse_action_id'],
  1992.                     'toWarehouseSub' => 0
  1993.                 );
  1994.                 $irr_dispose_data[$item['received_product_id']][] = array(
  1995.                     'date' => $last_refresh_date,
  1996.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1997.                     'entityId' => $item['irr_id'],
  1998.                     'colorId' => $item['received_product_color_id'],
  1999.                     'sizeId' => $item['received_product_size_id'],
  2000.                     'entityDocHash' => $item['document_hash'],
  2001.                     'qtyAdd' => 0,
  2002.                     'qtySub' => $item['dispose_qty'],
  2003.                     'valueAdd' => 0,
  2004.                     'valueSub' => ($item['dispose_qty'] * $item['received_unit_purchase_price']),
  2005.                     'price' => $item['received_unit_purchase_price'],
  2006.                     'fromWarehouse' => $item['received_warehouse_id'],
  2007.                     'toWarehouse' => 0,
  2008.                     'fromWarehouseSub' => $item['received_warehouse_id'],
  2009.                     'toWarehouseSub' => 0
  2010.                 );
  2011.             }
  2012.             //now add irrs
  2013.             foreach ($irr_add_data as $key => $item) {
  2014.                 if (!empty($item)) {
  2015.                     foreach ($item as $entry) {
  2016.                         $transDate = new \DateTime($entry['date']);
  2017.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2018.                             $key,
  2019.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2020.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2021.                             $entry['fromWarehouse'],
  2022.                             $entry['toWarehouse'],
  2023.                             $entry['fromWarehouseSub'],
  2024.                             $entry['toWarehouseSub'],
  2025.                             $transDate,
  2026.                             $entry['qtyAdd'],
  2027.                             $entry['qtySub'],
  2028.                             $entry['valueAdd'],
  2029.                             $entry['valueSub'],
  2030.                             $entry['price'],
  2031.                             $this->getLoggedUserCompanyId($request),
  2032.                             0,
  2033.                             $entry['entity'],
  2034.                             $entry['entityId'],
  2035.                             $entry['entityDocHash'],
  2036.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2037.                         );
  2038.                         if ($modifiedData)
  2039.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2040.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2041.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2042.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2043.                                 "",
  2044.                                 'inventory_refresh_debug'1); //last er 1 is append
  2045.                         if ($last_refresh_date_obj == '') {
  2046.                             $last_refresh_date_obj $transDate;
  2047.                         } else if ($transDate $last_refresh_date_obj) {
  2048.                             $last_refresh_date_obj $transDate;
  2049.                         }
  2050.                     }
  2051.                 }
  2052.             }
  2053.             foreach ($irr_replace_data as $key => $item) {
  2054.                 if (!empty($item)) {
  2055.                     foreach ($item as $entry) {
  2056.                         $transDate = new \DateTime($entry['date']);
  2057.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2058.                             $key,
  2059.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2060.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2061.                             $entry['fromWarehouse'],
  2062.                             $entry['toWarehouse'],
  2063.                             $entry['fromWarehouseSub'],
  2064.                             $entry['toWarehouseSub'],
  2065.                             $transDate,
  2066.                             $entry['qtyAdd'],
  2067.                             $entry['qtySub'],
  2068.                             $entry['valueAdd'],
  2069.                             $entry['valueSub'],
  2070.                             $entry['price'],
  2071.                             $this->getLoggedUserCompanyId($request),
  2072.                             0,
  2073.                             $entry['entity'],
  2074.                             $entry['entityId'],
  2075.                             $entry['entityDocHash']);
  2076.                         if ($modifiedData)
  2077.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2078.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2079.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2080.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2081.                                 "",
  2082.                                 'inventory_refresh_debug'1); //last er 1 is append
  2083.                         if ($last_refresh_date_obj == '') {
  2084.                             $last_refresh_date_obj $transDate;
  2085.                         } else if ($transDate $last_refresh_date_obj) {
  2086.                             $last_refresh_date_obj $transDate;
  2087.                         }
  2088.                     }
  2089.                 }
  2090.             }
  2091.             foreach ($irr_dispose_data as $key => $item) {
  2092.                 if (!empty($item)) {
  2093.                     foreach ($item as $entry) {
  2094.                         $transDate = new \DateTime($entry['date']);
  2095.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2096.                             $key,
  2097.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2098.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2099.                             $entry['fromWarehouse'],
  2100.                             $entry['toWarehouse'],
  2101.                             $entry['fromWarehouseSub'],
  2102.                             $entry['toWarehouseSub'],
  2103.                             $transDate,
  2104.                             $entry['qtyAdd'],
  2105.                             $entry['qtySub'],
  2106.                             $entry['valueAdd'],
  2107.                             $entry['valueSub'],
  2108.                             $entry['price'],
  2109.                             $this->getLoggedUserCompanyId($request),
  2110.                             0,
  2111.                             $entry['entity'],
  2112.                             $entry['entityId'],
  2113.                             $entry['entityDocHash'],
  2114.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2115.                         );
  2116.                         if ($modifiedData)
  2117.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2118.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2119.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2120.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2121.                                 "",
  2122.                                 'inventory_refresh_debug'1); //last er 1 is append
  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.             $data = [];
  2132.             //____________DELIVERY_RECEIPT___________________
  2133.             $docEntity "DeliveryReceipt";
  2134.             $docEntityIdField "deliveryReceiptId";
  2135.             $accTransactionDataByDocId = [];
  2136.             $query "SELECT delivery_receipt_item.*, delivery_receipt.delivery_receipt_date, delivery_receipt.document_hash, delivery_receipt.skip_inventory_hit from  delivery_receipt_item
  2137.               join delivery_receipt on delivery_receipt.delivery_receipt_id=delivery_receipt_item.delivery_receipt_id
  2138.             where delivery_receipt.delivery_receipt_date ='" $last_refresh_date " 00:00:00' and delivery_receipt.approved=1";
  2139.             $stmt $em->getConnection()->prepare($query);
  2140.             $stmt->execute();
  2141.             $queryData $stmt->fetchAll();
  2142.             foreach ($queryData as $item) {
  2143.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  2144.                     ->findOneBy(
  2145.                         array(
  2146.                             'id' => $item['product_id']
  2147.                         )
  2148.                     );
  2149.                 $curr_purchase_price $product->getPurchasePrice();
  2150.                 if ($item['skip_inventory_hit'] != 1) {
  2151.                     $data[$item['product_id']][] = array(
  2152.                         'date' => $last_refresh_date,
  2153.                         'entity' => array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  2154.                         'entityId' => $item['delivery_receipt_id'],
  2155.                         'colorId' => $item['color_id'],
  2156.                         'sizeId' => $item['size_id'],
  2157.                         'entityDocHash' => $item['document_hash'],
  2158.                         'qtyAdd' => 0,
  2159.                         'qtySub' => ($item['qty'] * $item['unit_multiplier']),
  2160.                         'valueAdd' => 0,
  2161.                         'valueSub' => '_AUTO_',
  2162.                         'price' => $curr_purchase_price,
  2163.                         'fromWarehouse' => $item['warehouse_id'],
  2164.                         'toWarehouse' => 0,
  2165.                         'fromWarehouseSub' => $item['warehouse_action_id'] != null $item['warehouse_action_id'] : GeneralConstant::WAREHOUSE_ACTION_GOODS,
  2166.                         'toWarehouseSub' => 0
  2167.                     );
  2168.                 }
  2169.                 $get_kids_sql "UPDATE `delivery_receipt_item` SET current_purchase_price='" $curr_purchase_price "' WHERE id=" $item['id'] . ";";
  2170.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  2171.                 $stmt->execute();
  2172.             }
  2173.             foreach ($data as $key => $item) {
  2174.                 if (!empty($item)) {
  2175.                     foreach ($item as $entry) {
  2176.                         $transDate = new \DateTime($entry['date']);
  2177.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2178.                             $key,
  2179.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2180.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2181.                             $entry['fromWarehouse'],
  2182.                             $entry['toWarehouse'],
  2183.                             $entry['fromWarehouseSub'],
  2184.                             $entry['toWarehouseSub'],
  2185.                             $transDate,
  2186.                             $entry['qtyAdd'],
  2187.                             $entry['qtySub'],
  2188.                             $entry['valueAdd'],
  2189.                             $entry['valueSub'],
  2190.                             $entry['price'],
  2191.                             $this->getLoggedUserCompanyId($request),
  2192.                             0,
  2193.                             $entry['entity'],
  2194.                             $entry['entityId'],
  2195.                             $entry['entityDocHash'],
  2196.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2197.                         );
  2198.                         if ($modifiedData)
  2199.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2200.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2201.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2202.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2203.                                 "",
  2204.                                 'inventory_refresh_debug'1); //last er 1 is append
  2205.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2206.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  2207.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2208.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2209.                         else
  2210.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2211.                         if ($last_refresh_date_obj == '') {
  2212.                             $last_refresh_date_obj $transDate;
  2213.                         } else if ($transDate $last_refresh_date_obj) {
  2214.                             $last_refresh_date_obj $transDate;
  2215.                         }
  2216.                     }
  2217.                 }
  2218.             }
  2219.             if ($modifyAccTransaction == 1) {
  2220.                 //for now we are suuming there is only receipt without confirmation needed
  2221.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2222.                     $docHereDr $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  2223.                         $docEntityIdField => $docId,
  2224.                     ));;
  2225.                     $so $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
  2226.                         array(
  2227.                             'salesOrderId' => $docHereDr->getSalesOrderId()
  2228.                         )
  2229.                     );
  2230.                     $query $em->getRepository('ApplicationBundle:SalesInvoice')
  2231.                         ->createQueryBuilder('p');
  2232.                     $query->where('p.salesOrderId = :soID')
  2233.                         ->setParameter('soID'$docHereDr->getSalesOrderId());
  2234.                     $query->andWhere("p.deliveryReceiptIds LIKE '%" $docId "%' ");
  2235.                     $query->setMaxResults(1);
  2236.                     $results $query->getQuery()->getResult();
  2237.                     $docHere null;
  2238.                     if (!empty($results))
  2239.                         $docHere $results[0];
  2240.                     if ($docHere) {
  2241.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2242.                         if ($curr_v_ids == null)
  2243.                             $curr_v_ids = [];
  2244.                         $skipVids = [];
  2245.                         $toChangeVid 0;
  2246.                         $voucher null;
  2247.                         foreach ($curr_v_ids as $vid) {
  2248.                             if (in_array($vid$skipVids))
  2249.                                 continue;
  2250.                             $skipVids[] = $vid//to prevent duplicate query
  2251.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2252.                                 'transactionId' => $vid,
  2253.                             ));;
  2254.                             if ($voucher) {
  2255.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2256.                                     $toChangeVid $vid;
  2257.                                 } else {
  2258.                                     continue;
  2259.                                 }
  2260.                                 if (strpos($voucher->getDescription(), 'Inventory') !== false) {
  2261. //                                    echo "Word Found!";
  2262.                                     $toChangeVid $vid;
  2263.                                 } else {
  2264.                                     continue;
  2265.                                 }
  2266.                             }
  2267.                         }
  2268.                         if ($toChangeVid == 0) {
  2269.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2270.                                 $em,
  2271.                                 $docHere->getSalesInvoiceDate()->format('Y-m-d'),
  2272.                                 0,
  2273.                                 AccountsConstant::VOUCHER_JOURNAL,
  2274.                                 'Journal For Inventory balance for Sales Invoice ' $docHere->getDocumentHash(),
  2275.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2276.                                 'JV',
  2277.                                 'GN',
  2278.                                 0,
  2279.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2280.                                 0,
  2281.                                 $docHere->getCreatedLoginId(),
  2282.                                 $docHere->getCompanyId(),
  2283.                                 '',
  2284.                                 0,
  2285.                                 1,
  2286.                                 0''$so->getBranchId(),
  2287.                                 AccountsConstant::INVOICE_REVENUE_JOURNAL,
  2288.                                 array_flip(GeneralConstant::$Entity_list)['SalesInvoice'], $docHere->getSalesInvoiceId(), $docHere->getDocumentHash()
  2289.                             );
  2290.                             $em->flush();
  2291.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2292.                                 'transactionId' => $toChangeVid,
  2293.                             ));;
  2294.                         }
  2295. //                        DeleteDocument::AccTransactions($em, $toChangeVid, 0);
  2296.                         //now remove cogs or inventory related transactions
  2297.                         $voucherDetails $em->getRepository('ApplicationBundle:AccTransactionDetails')->findBy(array(
  2298.                             'transactionId' => $toChangeVid,
  2299.                         ));;
  2300.                         foreach ($voucherDetails as $vdtls) {
  2301.                             if (in_array($vdtls->getAccountsHeadId(), $inv_head_list)) {
  2302.                                 $em->remove($vdtls);
  2303.                                 $em->flush();
  2304.                             }
  2305.                             if ($cogs_head == $vdtls->getAccountsHeadId()) {
  2306.                                 $em->remove($vdtls);
  2307.                                 $em->flush();
  2308.                             }
  2309.                         }
  2310.                         $tot_inv_amount 0;
  2311.                         foreach ($transData as $k => $v) {
  2312.                             $tot_inv_amount += ($v);
  2313.                             Accounts::CreateNewTransactionDetails($em,
  2314.                                 '',
  2315.                                 $toChangeVid,
  2316.                                 Generic::CurrToInt($v),
  2317.                                 $k,
  2318.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2319.                                 AccountsConstant::DEBIT,
  2320.                                 0,
  2321.                                 [],
  2322.                                 [],
  2323.                                 $docHere->getCreatedLoginId()
  2324.                             );
  2325.                         }
  2326. //                        $stockReceivedType = $docHere->getType();
  2327.                         $to_balance_head 0;
  2328. //                        if ($docHere->getTransferActionType() == 4)
  2329.                         if (1) {
  2330.                         } else {
  2331.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  2332.                                     'name' => 'inv_on_transit_head')
  2333.                             );
  2334.                             if ($inv_transit_head)
  2335.                                 $to_balance_head $inv_transit_head->getData();
  2336.                         }
  2337.                         if ($to_balance_head != 0) {
  2338.                             Accounts::CreateNewTransactionDetails($em,
  2339.                                 '',
  2340.                                 $toChangeVid,
  2341.                                 Generic::CurrToInt($tot_inv_amount),
  2342.                                 $to_balance_head,
  2343.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  2344.                                 AccountsConstant::CREDIT,
  2345.                                 0,
  2346.                                 [],
  2347.                                 [],
  2348.                                 $docHere->getCreatedLoginId()
  2349.                             );
  2350.                         }
  2351.                         if ($voucher)
  2352.                             $voucher->setTransactionAmount($tot_inv_amount);
  2353.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2354.                         if ($curr_v_ids != null)
  2355.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2356.                         else
  2357.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2358.                         $em->flush();
  2359. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2360.                     }
  2361.                 }
  2362.             }
  2363.             $data = [];
  2364.             //____________STOCK_CONSUMPTION___________________
  2365.             $docEntity "StockConsumptionNote";
  2366.             $docEntityIdField "stockConsumptionNoteId";
  2367.             $accTransactionDataByDocId = [];
  2368.             $query "SELECT stock_consumption_note_item.*,  stock_consumption_note.stock_consumption_note_date, stock_consumption_note.document_hash, stock_consumption_note.data
  2369.               from  stock_consumption_note_item
  2370.               join stock_consumption_note on stock_consumption_note.stock_consumption_note_id=stock_consumption_note_item.stock_consumption_note_id
  2371.             where stock_consumption_note.stock_consumption_note_date ='" $last_refresh_date " 00:00:00' and stock_consumption_note.approved=1";
  2372.             $stmt $em->getConnection()->prepare($query);
  2373.             $stmt->execute();
  2374.             $queryData $stmt->fetchAll();
  2375.             $consumption_data = [];
  2376.             $produced_data = [];
  2377.             $checked_stcm_ids = [];
  2378.             foreach ($queryData as $item) {
  2379. //                $product=$em->getRepository('ApplicationBundle:InvProducts')
  2380. //                    ->findOneBy(
  2381. //                        array(
  2382. //                            'id'=>$item['product_id']
  2383. //                        )
  2384. //                    );
  2385. //
  2386. //                $curr_purchase_price=$product->getPurchasePrice();
  2387.                 if (!in_array($item['stock_consumption_note_id'], $checked_stcm_ids)) {
  2388.                     $conversion_data json_decode($item['data'], true);
  2389.                     if ($conversion_data == null)
  2390.                         $conversion_data = [];
  2391.                     if (isset($conversion_data['conversionData'])) {
  2392.                         if (isset($conversion_data['conversionData']['converted_products'])) {
  2393.                             $curr_spec_data $conversion_data['conversionData'];
  2394.                             foreach ($curr_spec_data['converted_products'] as $pika_key => $val) {
  2395.                                 $consumption_data[$val][] = array(
  2396.                                     'date' => $last_refresh_date,
  2397.                                     'type' => 2,
  2398.                                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2399.                                     'entityId' => $item['stock_consumption_note_id'],
  2400.                                     'colorId' => isset($curr_spec_data['converted_product_colors'][$pika_key]) ? ($curr_spec_data['converted_product_colors'][$pika_key]) : 0,
  2401.                                     'sizeId' => isset($curr_spec_data['converted_product_sizes'][$pika_key]) ? ($curr_spec_data['converted_product_sizes'][$pika_key]) : 0,
  2402.                                     'entityDocHash' => $item['document_hash'],
  2403.                                     'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_units'][$pika_key]) : 0,
  2404.                                     'qtySub' => 0,
  2405.                                     '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,
  2406.                                     'valueSub' => 0,
  2407.                                     'price' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_unit_price'][$pika_key]) : 0,
  2408.                                     'fromWarehouse' => 0,
  2409.                                     'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key]) ? ($curr_spec_data['converted_warehouseId'][$pika_key]) : 0,
  2410.                                     'fromWarehouseSub' => 0,
  2411.                                     'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key]) ? ($curr_spec_data['converted_warehouseActionId'][$pika_key]) : 0
  2412.                                 );
  2413.                             }
  2414.                         }
  2415.                     }
  2416. //                    if(isset($conversion_data['expenseCost'] ))
  2417. //                    if(isset($conversion_data['expenseCost']['expense_heads'] ))
  2418. //                    {
  2419. //                        $curr_spec_data=$conversion_data['expenseCost'];
  2420. //                        foreach($curr_spec_data['expense_heads'] as $pika_key=>$val)
  2421. //                        {
  2422. //
  2423. //                            $consumption_data[$val][] = array(
  2424. //                                'date' => $last_refresh_date,
  2425. //                                'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2426. //                                'entityId' => $item['stock_consumption_note_id'],
  2427. //                                'entityDocHash' => $item['document_hash'],
  2428. //                                'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_units'][$pika_key]):0,
  2429. //                                'qtySub' => 0,
  2430. //                                '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,
  2431. //                                'valueSub' => 0,
  2432. //                                'price' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_unit_price'][$pika_key]):0,
  2433. //                                'fromWarehouse' => 0,
  2434. //                                'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key])?(1*$curr_spec_data['converted_warehouseId'][$pika_key]):0,
  2435. //                                'fromWarehouseSub' => 0,
  2436. //                                'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key])?(1*$curr_spec_data['converted_warehouseActionId'][$pika_key]):0
  2437. //                            );
  2438. //                        }
  2439. //                    }
  2440.                     $checked_stcm_ids[] = $item['stock_consumption_note_id'];
  2441.                 }
  2442.                 $consumption_data[$item['product_id']][] = array(
  2443.                     'date' => $last_refresh_date,
  2444.                     'type' => 1,
  2445.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2446.                     'entityId' => $item['stock_consumption_note_id'],
  2447.                     'colorId' => $item['color_id'],
  2448.                     'sizeId' => $item['size_id'],
  2449.                     'entityDocHash' => $item['document_hash'],
  2450.                     'qtyAdd' => 0,
  2451.                     'qtySub' => ($item['qty'] * 1),
  2452.                     'valueAdd' => 0,
  2453.                     'valueSub' => (($item['qty']) * ($item['price'])),
  2454.                     'price' => $item['price'],
  2455.                     'fromWarehouse' => $item['warehouse_id'],
  2456.                     'toWarehouse' => 0,
  2457.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  2458.                     'toWarehouseSub' => 0
  2459.                 );
  2460. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2461. //                $stmt = $em->getConnection()->prepare($get_kids_sql);
  2462. //                $stmt->execute();
  2463.             }
  2464.             foreach ($consumption_data as $key => $item) {
  2465.                 if (!empty($item)) {
  2466.                     foreach ($item as $entry) {
  2467.                         $transDate = new \DateTime($entry['date']);
  2468.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2469.                             $key,
  2470.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2471.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2472.                             $entry['fromWarehouse'],
  2473.                             $entry['toWarehouse'],
  2474.                             $entry['fromWarehouseSub'],
  2475.                             $entry['toWarehouseSub'],
  2476.                             $transDate,
  2477.                             $entry['qtyAdd'],
  2478.                             $entry['qtySub'],
  2479.                             $entry['valueAdd'],
  2480.                             $entry['valueSub'],
  2481.                             $entry['price'],
  2482.                             $this->getLoggedUserCompanyId($request),
  2483.                             0,
  2484.                             $entry['entity'],
  2485.                             $entry['entityId'],
  2486.                             $entry['entityDocHash'],
  2487.                             $entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION
  2488.                         );
  2489.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2490.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2491.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2492.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2493.                             "",
  2494.                             'inventory_refresh_debug'1); //last er 1 is append
  2495.                         if ($last_refresh_date_obj == '') {
  2496.                             $last_refresh_date_obj $transDate;
  2497.                         } else if ($transDate $last_refresh_date_obj) {
  2498.                             $last_refresh_date_obj $transDate;
  2499.                         }
  2500.                     }
  2501.                 }
  2502.             }
  2503.             $data = [];
  2504.             //____________PRODUCTION___________________
  2505.             $docEntity "Production";
  2506.             $docEntityIdField "productionId";
  2507.             $accTransactionDataByDocId = [];
  2508.             $consumedAmountByProductionId = [];
  2509.             $query "SELECT * from production_process_settings
  2510.             where approved=1 order by production_process_settings_id asc  ";
  2511.             $stmt $em->getConnection()->prepare($query);
  2512.             $stmt->execute();
  2513.             $processList $stmt->fetchAll();
  2514. //            $processList=[];
  2515.             foreach ($processList as $process) {
  2516.                 $query "SELECT production_entry_item.*,  production.production_date, production.document_hash
  2517.               from  production_entry_item
  2518.               join production on production_entry_item.production_id=production.production_id
  2519.             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  ";
  2520.                 $stmt $em->getConnection()->prepare($query);
  2521.                 $stmt->execute();
  2522.                 $queryData $stmt->fetchAll();
  2523.                 $produced_data = [];
  2524.                 $rejected_data = [];
  2525.                 $consumed_data = [];
  2526.                 foreach ($queryData as $item) {
  2527. //                $product=$em->getRepository('ApplicationBundle:InvProducts')
  2528. //                    ->findOneBy(
  2529. //                        array(
  2530. //                            'id'=>$item['product_id']
  2531. //                        )
  2532. //                    );
  2533. //
  2534. //                $curr_purchase_price=$product->getPurchasePrice();
  2535.                     if ($item['price'] == '')
  2536.                         $item['price'] = 0;
  2537.                     if ($item['price'] < 0)
  2538.                         $item['price'] = 0;
  2539.                     $item['production_nature_id'];
  2540.                     $consumed_data[$item['product_id']][] = array(
  2541.                         'date' => $last_refresh_date,
  2542.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2543.                         'entityId' => $item['production_id'],
  2544.                         'colorId' => $item['color_id'],
  2545.                         'sizeId' => $item['size_id'],
  2546.                         'entityDocHash' => $item['document_hash'],
  2547.                         'qtyAdd' => 0,
  2548.                         'qtySub' => ($item['additional_consumed_qty'] * 1) + ($item['consumed_qty']),
  2549.                         'valueAdd' => 0,
  2550.                         'valueSub' => '_AUTO_',
  2551.                         'price' => $item['price'],
  2552.                         'fromWarehouse' => $item['warehouse_id'],
  2553.                         'toWarehouse' => 0,
  2554.                         'fromWarehouseSub' => $item['consumed_item_action_tag_id'],
  2555.                         'toWarehouseSub' => 0,
  2556.                         'production_nature_id' => $item['production_nature_id'],
  2557.                     );
  2558.                     $produced_data[$item['product_id']][] = array(
  2559.                         'date' => $last_refresh_date,
  2560.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2561.                         'entityId' => $item['production_id'],
  2562.                         'colorId' => $item['color_id'],
  2563.                         'sizeId' => $item['size_id'],
  2564.                         'entityDocHash' => $item['document_hash'],
  2565.                         'qtyAdd' => ($item['accepted_qty'] * 1),
  2566.                         'qtySub' => 0,
  2567.                         'valueAdd' => (($item['accepted_qty'] * 1) * ($item['price'])),
  2568.                         'valueSub' => 0,
  2569.                         'price' => $item['price'],
  2570.                         'fromWarehouse' => 0,
  2571.                         'toWarehouse' => $item['warehouse_id'],
  2572.                         'fromWarehouseSub' => 0,
  2573.                         'toWarehouseSub' => $item['produced_item_action_tag_id'],
  2574.                         'production_nature_id' => $item['production_nature_id'],
  2575.                     );
  2576.                     $rejected_data[$item['product_id']][] = array(
  2577.                         'date' => $last_refresh_date,
  2578.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2579.                         'entityId' => $item['production_id'],
  2580.                         'colorId' => $item['color_id'],
  2581.                         'sizeId' => $item['size_id'],
  2582.                         'entityDocHash' => $item['document_hash'],
  2583.                         'qtyAdd' => ($item['rejected_qty'] * 1),
  2584.                         'qtySub' => 0,
  2585.                         'valueAdd' => (($item['rejected_qty'] * 1) * ($item['price'])),
  2586.                         'valueSub' => 0,
  2587.                         'price' => $item['price'],
  2588.                         'fromWarehouse' => 0,
  2589.                         'toWarehouse' => $item['warehouse_id'],
  2590.                         'fromWarehouseSub' => 0,
  2591.                         'toWarehouseSub' => $item['rejected_item_action_tag_id'],
  2592.                         'production_nature_id' => $item['production_nature_id'],
  2593.                     );
  2594. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2595. //                $stmt = $em->getConnection()->prepare($get_kids_sql);
  2596. //                $stmt->execute();
  2597.                 }
  2598.                 foreach ($consumed_data as $key => $item) {
  2599.                     if (!empty($item)) {
  2600.                         foreach ($item as $entry) {
  2601.                             $transDate = new \DateTime($entry['date']);
  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.                                 $entry['qtyAdd'],
  2612.                                 $entry['qtySub'],
  2613.                                 $entry['valueAdd'],
  2614.                                 $entry['valueSub'],
  2615.                                 $entry['price'],
  2616.                                 $this->getLoggedUserCompanyId($request),
  2617.                                 0,
  2618.                                 $entry['entity'],
  2619.                                 $entry['entityId'],
  2620.                                 $entry['entityDocHash'],
  2621.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION);
  2622.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2623.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2624.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2625.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2626.                                 "",
  2627.                                 'inventory_refresh_debug'1); //last er 1 is append
  2628.                             if (!isset($consumedAmountByProductionId[$entry['entityId']]))
  2629.                                 $consumedAmountByProductionId[$entry['entityId']] = ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2630.                             else
  2631.                                 $consumedAmountByProductionId[$entry['entityId']] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2632.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2633.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  2634.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2635.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2636.                             else
  2637.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2638.                             if ($last_refresh_date_obj == '') {
  2639.                                 $last_refresh_date_obj $transDate;
  2640.                             } else if ($transDate $last_refresh_date_obj) {
  2641.                                 $last_refresh_date_obj $transDate;
  2642.                             }
  2643.                         }
  2644.                     }
  2645.                 }
  2646.                 foreach ($produced_data as $key => $item) {
  2647.                     if (!empty($item)) {
  2648.                         foreach ($item as $entry) {
  2649.                             $transDate = new \DateTime($entry['date']);
  2650.                             $productionNature $entry['production_nature_id'];
  2651.                             if (in_array($productionNature, [12])) {
  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.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2665.                                     $entry['valueSub'],
  2666.                                     $entry['price'],
  2667.                                     $this->getLoggedUserCompanyId($request),
  2668.                                     0,
  2669.                                     $entry['entity'],
  2670.                                     $entry['entityId'],
  2671.                                     $entry['entityDocHash'],
  2672.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2673.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2674.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2675.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2676.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2677.                                     "",
  2678.                                     'inventory_refresh_debug'1); //last er 1 is append
  2679.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2680.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2681.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2682.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2683.                                 else
  2684.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2685. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2686. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2687. //                            else
  2688. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2689.                             } else {
  2690.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2691.                                     $key,
  2692.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2693.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2694.                                     $entry['fromWarehouse'],
  2695.                                     $entry['toWarehouse'],
  2696.                                     $entry['fromWarehouseSub'],
  2697.                                     $entry['toWarehouseSub'],
  2698.                                     $transDate,
  2699.                                     0,
  2700.                                     0,
  2701. //                                $entry['valueAdd'],
  2702.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2703.                                     0,
  2704.                                     $entry['price'],
  2705.                                     $this->getLoggedUserCompanyId($request),
  2706.                                     0,
  2707.                                     $entry['entity'],
  2708.                                     $entry['entityId'],
  2709.                                     $entry['entityDocHash'],
  2710.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2711.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2712.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2713.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2714.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2715.                                     "",
  2716.                                     'inventory_refresh_debug'1); //last er 1 is append
  2717.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2718.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2719.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2720.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2721.                                 else
  2722.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2723. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2724. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2725. //                            else
  2726. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2727.                             }
  2728.                             if ($last_refresh_date_obj == '') {
  2729.                                 $last_refresh_date_obj $transDate;
  2730.                             } else if ($transDate $last_refresh_date_obj) {
  2731.                                 $last_refresh_date_obj $transDate;
  2732.                             }
  2733.                         }
  2734.                     }
  2735.                 }
  2736.                 foreach ($rejected_data as $key => $item) {
  2737.                     if (!empty($item)) {
  2738.                         foreach ($item as $entry) {
  2739.                             $transDate = new \DateTime($entry['date']);
  2740.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2741.                                 $key,
  2742.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2743.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2744.                                 $entry['fromWarehouse'],
  2745.                                 $entry['toWarehouse'],
  2746.                                 $entry['fromWarehouseSub'],
  2747.                                 $entry['toWarehouseSub'],
  2748.                                 $transDate,
  2749.                                 $entry['qtyAdd'],
  2750.                                 $entry['qtySub'],
  2751.                                 $entry['valueAdd'],
  2752.                                 $entry['valueSub'],
  2753.                                 $entry['price'],
  2754.                                 $this->getLoggedUserCompanyId($request),
  2755.                                 0,
  2756.                                 $entry['entity'],
  2757.                                 $entry['entityId'],
  2758.                                 $entry['entityDocHash'],
  2759.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2760.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2761.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2762.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2763.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2764.                                 "",
  2765.                                 'inventory_refresh_debug'1); //last er 1 is append
  2766.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2767.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  2768.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2769.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = (-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2770.                             else
  2771.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ((-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2772.                             if ($last_refresh_date_obj == '') {
  2773.                                 $last_refresh_date_obj $transDate;
  2774.                             } else if ($transDate $last_refresh_date_obj) {
  2775.                                 $last_refresh_date_obj $transDate;
  2776.                             }
  2777.                         }
  2778.                     }
  2779.                 }
  2780.             }
  2781.             if ($modifyAccTransaction == 1) {
  2782.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2783.                     $docHere $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  2784.                         $docEntityIdField => $docId,
  2785.                     ));;
  2786.                     if ($docHere) {
  2787.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2788.                         if ($curr_v_ids == null)
  2789.                             $curr_v_ids = [];
  2790.                         $skipVids = [];
  2791.                         $toChangeVid 0;
  2792.                         $voucher null;
  2793.                         foreach ($curr_v_ids as $vid) {
  2794.                             if (in_array($vid$skipVids))
  2795.                                 continue;
  2796.                             $skipVids[] = $vid//to prevent duplicate query
  2797.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2798.                                 'transactionId' => $vid,
  2799.                             ));;
  2800.                             if ($voucher) {
  2801.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2802.                                     $toChangeVid $vid;
  2803.                                 } else {
  2804.                                     continue;
  2805.                                 }
  2806.                             }
  2807.                         }
  2808.                         if ($toChangeVid == 0) {
  2809.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2810.                                 $em,
  2811.                                 $docHere->getProductionDate()->format('Y-m-d'),
  2812.                                 0,
  2813.                                 AccountsConstant::VOUCHER_JOURNAL,
  2814.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  2815.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2816.                                 'JV',
  2817.                                 'GN',
  2818.                                 0,
  2819.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2820.                                 0,
  2821.                                 $docHere->getCreatedLoginId(),
  2822.                                 $docHere->getCompanyId(),
  2823.                                 '',
  2824.                                 0,
  2825.                                 1
  2826.                             );
  2827.                             $em->flush();
  2828.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2829.                                 'transactionId' => $toChangeVid,
  2830.                             ));;
  2831.                         }
  2832.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  2833.                         $tot_inv_amount 0;
  2834.                         foreach ($transData as $k => $v) {
  2835.                             $tot_inv_amount += ($v);
  2836.                             Accounts::CreateNewTransactionDetails($em,
  2837.                                 '',
  2838.                                 $toChangeVid,
  2839.                                 Generic::CurrToInt($v),
  2840.                                 $k,
  2841.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2842.                                 AccountsConstant::DEBIT,
  2843.                                 0,
  2844.                                 [],
  2845.                                 [],
  2846.                                 $docHere->getCreatedLoginId()
  2847.                             );
  2848.                         }
  2849. //                        $stockReceivedType = $docHere->getType();
  2850.                         $to_balance_head 0;
  2851. //                        if ($docHere->getTransferActionType() == 4)
  2852.                         if (1) {
  2853.                         } else {
  2854.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  2855.                                     'name' => 'inv_on_transit_head')
  2856.                             );
  2857.                             if ($inv_transit_head)
  2858.                                 $to_balance_head $inv_transit_head->getData();
  2859.                         }
  2860.                         if ($to_balance_head != 0) {
  2861.                             Accounts::CreateNewTransactionDetails($em,
  2862.                                 '',
  2863.                                 $toChangeVid,
  2864.                                 Generic::CurrToInt($tot_inv_amount),
  2865.                                 $to_balance_head,
  2866.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  2867.                                 AccountsConstant::CREDIT,
  2868.                                 0,
  2869.                                 [],
  2870.                                 [],
  2871.                                 $docHere->getCreatedLoginId()
  2872.                             );
  2873.                         }
  2874.                         if ($voucher)
  2875.                             $voucher->setTransactionAmount($tot_inv_amount);
  2876.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2877.                         if ($curr_v_ids != null)
  2878.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2879.                         else
  2880.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2881.                         $em->flush();
  2882. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2883.                     }
  2884.                 }
  2885.             }
  2886.             if ($terminate == 0) {
  2887.                 return new JsonResponse(array(
  2888.                     "success" => true,
  2889.                     "last_refresh_date" => $last_refresh_date,
  2890.                     "inventory_refreshed" => $refreshed_opening
  2891.                 ));
  2892.             } else {
  2893.                 return new JsonResponse(array(
  2894.                     "success" => false,
  2895.                     "last_refresh_date" => $last_refresh_date,
  2896.                     "inventory_refreshed" => $refreshed_opening
  2897.                 ));
  2898.             }
  2899.         }
  2900.         return new JsonResponse(array(
  2901.             "success" => false,
  2902.             "last_refresh_date" => $last_refresh_date,
  2903.             "inventory_refreshed" => $refreshed_opening
  2904.         ));
  2905.         //2 .now make an array with necessary data based on challan and grn for now willl need consumption later
  2906.         //broken into transactions not closing
  2907.         //structure---> $data['productId']=array(
  2908.         //'date'=>'2017-09-02 00:00:00'
  2909.         //'qtyAdd'=>'2'
  2910.         //'qtySub'=>'0'
  2911.         //'valueAdd'=>'2000'
  2912.         //'valueSub'=>'0'
  2913.         //'fromWarehouse'=>'0'
  2914.         //'toWarehouse'=>'0'
  2915.         //'fromWarehouseSub'=>'0'
  2916.         //'toWarehouseSub'=>'0'
  2917.         //)
  2918.         //
  2919.     }
  2920.     public function OpeningItemAction(Request $request)
  2921.     {
  2922.         $em $this->getDoctrine()->getManager();
  2923.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  2924.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  2925.         if ($request->isMethod('POST')) {
  2926.             $pp trim($request->request->get('purchasePrice'));
  2927. //replace comma with space
  2928.             $pp str_replace(","""$pp);
  2929.             if ($request->request->get('productId') != '') {
  2930.                 foreach ($request->request->get('warehouseId') as $key => $value) {
  2931.                     $data = array(
  2932.                         'productId' => $request->request->get('productId'),
  2933.                         'warehouseId' => $request->request->get('warehouseId')[$key],
  2934.                         'warehouseActionId' => $request->request->get('warehouseActionId')[$key],
  2935.                         'purchasePrice' => $pp,
  2936.                         'date' => new \DateTime($request->request->get('date')),
  2937.                         'qty' => $request->request->get('qty')[$key],
  2938.                     );
  2939.                     $transDate = new \DateTime($request->request->get('date'));
  2940.                     $new = new InvItemInOut();
  2941.                     $new->setProductId($request->request->get('productId'));
  2942.                     $new->setWarehouseId($request->request->get('warehouseId')[$key]);
  2943.                     $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  2944.                     $new->setActionTagId($request->request->get('warehouseActionId')[$key]);
  2945.                     $new->setTransactionDate($transDate);
  2946.                     $new->setQty($request->request->get('qty')[$key]);
  2947.                     $new->setPrice($pp);
  2948.                     $new->setAmount($request->request->get('qty')[$key] * $pp);
  2949.                     $new->setEntity(0);// opening =0
  2950.                     $new->setEntityId(0);// opening =0
  2951.                     $new->setDebitCreditHeadId(0);// opening =0
  2952.                     $new->setVoucherIds(null);// opening =0
  2953.                     $em->persist($new);
  2954.                     $em->flush();
  2955. //                    $total_inv_value_in_by_id += $request->request->get('qty')[$key] * $pp;
  2956.                     Inventory::AddOpeningInventoryStock($em$data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2957.                 }
  2958.             }
  2959.         }
  2960.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  2961.             'name' => 'warehouse_action_1'//for now for stock of goods
  2962.         ));
  2963.         return $this->render('@Inventory/pages/input_forms/opening_item_assign.html.twig',
  2964.             array(
  2965.                 'page_title' => "Opening Items",
  2966.                 'inv_head' => $inv_head $inv_head->getData() : '',
  2967.                 'products' => $this->getDoctrine()->getRepository('ApplicationBundle:InvProducts')->findBy(array(
  2968.                     'status' => GeneralConstant::ACTIVE//for now for stock of goods
  2969. //                    'opening_locked'=>0
  2970.                 )),
  2971.                 'warehouseList' => Inventory::WarehouseList($em),
  2972.                 'warehouseActionList' => $warehouse_action_list
  2973.             )
  2974.         );
  2975.     }
  2976.     public function CreateProductCategoryAction(Request $request)
  2977.     {
  2978.         if ($request->isMethod('POST')) {
  2979.             $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));
  2980.             if ($cat_data['id'] != '')
  2981.                 return new JsonResponse(array("success" => true'cat_data' => $cat_data));
  2982.         }
  2983.         return new JsonResponse(array("success" => false,));
  2984. //        return $this->redirectToRoute("create_product");
  2985.     }
  2986.     public function CreateProductSubCategoryAction(Request $request)
  2987.     {
  2988.         if ($request->isMethod('POST')) {
  2989.             $spec_data Inventory::CreateSubCategory($this->getDoctrine()->getManager(),
  2990.                 $this->getLoggedUserCompanyId($request), $request->request->get('spec_name'),
  2991.                 $request->request->get('level'0),
  2992.                 $request->request->get('parentId'0),
  2993.                 $request->request->get('itemgroupId'),
  2994.                 $request->request->get('categoryId'),
  2995.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2996.             if ($spec_data['id'] != '')
  2997.                 return new JsonResponse(array("success" => true'spec_data' => $spec_data));
  2998.         }
  2999.         return new JsonResponse(array("success" => false,));
  3000. //        return $this->redirectToRoute("create_product");
  3001.     }
  3002.     public function CreateProductBrandAction(Request $request)
  3003.     {
  3004.         if ($request->isMethod('POST')) {
  3005.             $data Inventory::CreateBrand($this->getDoctrine()->getManager(),
  3006.                 $this->getLoggedUserCompanyId($request), $request->request->get('brand_name'),
  3007.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3008.             if ($data['id'] != '')
  3009.                 return new JsonResponse(array("success" => true'data' => $data));
  3010.         }
  3011.         return new JsonResponse(array("success" => false,));
  3012. //        return $this->redirectToRoute("create_product");
  3013.     }
  3014.     public function CreateIssueNoteAction(Request $request)
  3015.     {
  3016.         return $this->render('@Inventory/pages/input_forms/issue_note.html.twig',
  3017.             array(
  3018.                 'page_title' => 'Issue Note'
  3019.             )
  3020.         );
  3021.     }
  3022.     public function ProcessDraftDeliveryReceiptAction(Request $request$id 0)
  3023.     {
  3024.         $em $this->getDoctrine()->getManager();
  3025.         $companyId $this->getLoggedUserCompanyId($request);
  3026.         $extId $id;
  3027.         $receiptId $id;
  3028.         $allowed 0;
  3029.         if ($request->isMethod('POST')) {
  3030.             $receiptId $request->request->get('deliveryReceiptId');
  3031.             $QD $this->getDoctrine()
  3032.                 ->getRepository('ApplicationBundle:DeliveryReceipt')
  3033.                 ->findOneBy(
  3034.                     array(
  3035.                         'deliveryReceiptId' => $receiptId
  3036.                     ),
  3037.                     array()
  3038.                 );
  3039.             $soId $QD->getSalesOrderId();
  3040.             $drData = [];
  3041.             $dr_item_data $em->getRepository('ApplicationBundle:DeliveryReceiptItem')->findBy(
  3042.                 array(
  3043.                     'deliveryReceiptId' => $receiptId,
  3044.                 )
  3045.             );
  3046.             foreach ($dr_item_data as $dr_item) {
  3047.                 $drData[] = array(
  3048.                     'soItemId' => $dr_item->getSalesorderItemId(),
  3049.                     'qty' => $dr_item->getQty()
  3050.                 );
  3051.             }
  3052. //            $drData=[
  3053. //                ['soItemId'=>9,'qty'=>9],
  3054. //                ['soItemId'=>9,'qty'=>9],
  3055. //                ['soItemId'=>9,'qty'=>9],
  3056. //            ];
  3057.             $toGetSoItemsId = [];
  3058.             $toGetDoItemsId = [];
  3059.             $drDataBySoItemId = [];
  3060.             $drDataByDoItemId = [];
  3061.             $so $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(array(
  3062.                 'salesOrderId' => $soId   //$id is soId
  3063.             ));
  3064.             if ($so->getDeliveryOrderSkipFlag() == 1) {
  3065.                 foreach ($drData as $pp) {
  3066.                     $toGetSoItemsId[] = $pp['soItemId'];
  3067.                     $drDataBySoItemId[$pp['soItemId']] = $pp;
  3068.                 }
  3069.             } else {
  3070.                 foreach ($drData as $pp) {
  3071.                     $toGetDoItemsId[] = $pp['soItemId'];
  3072.                     $drDataByDoItemId[$pp['soItemId']] = $pp;
  3073.                 }
  3074.                 $do_item_data $em->getRepository('ApplicationBundle:DeliveryOrderItem')->findBy(
  3075.                     array(
  3076.                         'salesorderId' => $id,
  3077.                         'id' => $toGetDoItemsId
  3078.                     )
  3079.                 );
  3080.                 foreach ($do_item_data as $dd) {
  3081.                     $toGetSoItemsId[] = $dd->getSalesorderItemId();
  3082.                     $drDataBySoItemId[$dd->getSalesorderItemId()] = $drDataByDoItemId[$dd->getId()];
  3083.                 }
  3084. //                $do_item_data = $em->getRepository('ApplicationBundle:SalesOrderItem')->findOneBy(
  3085. //                    array(
  3086. ////                'salesOrderId'=>$post_data->get('soId', null),
  3087. //                        'id' => $post_data->get('do_details_id')[$key]
  3088. //                    )
  3089. //                );
  3090.             }
  3091.             $so_item_data $em->getRepository('ApplicationBundle:SalesOrderItem')->findBy(
  3092.                 array(
  3093.                     'salesOrderId' => $soId,
  3094.                     'id' => $toGetSoItemsId
  3095.                 )
  3096.             );
  3097.             $prev_so_amount $so->getSoAmount();
  3098.             $total_discounted_amount 0;
  3099.             $total_product_amount 0;
  3100.             $total_discount 0;
  3101.             $total_special_discount $so->getSpecialDiscountAmount();
  3102.             $total_special_discount_rate $so->getSpecialDiscountRate();
  3103.             foreach ($so_item_data as $item) {
  3104.                 $qty $drDataBySoItemId[$item->getId()]['qty'];
  3105.                 $price $item->getPrice();
  3106.                 $amount $qty $price;
  3107.                 $discountAmount $amount * ($item->getDiscountRate() / 100);
  3108.                 $discountedAmount $amount $discountAmount;
  3109.                 $total_discounted_amount += $discountedAmount;
  3110.                 $total_discount += $discountAmount;
  3111.                 $total_product_amount += $amount;
  3112.             }
  3113.             $aitRate $so->getAitRate();
  3114.             $vatRate $so->getVatRate();
  3115.             if ($aitRate == '' || $aitRate == null$aitRate 0;
  3116.             if ($vatRate == '' || $vatRate == null$vatRate 0;
  3117. //        $so->setVatRate($post->get('vat_rate', null));
  3118.             $vatAmount $total_discounted_amount * ($vatRate 100);
  3119.             $aitAmount $total_discounted_amount * ($aitRate 100);
  3120.             $total_sales_amount $total_discounted_amount $vatAmount $aitAmount $total_special_discount;
  3121.             //now get client
  3122.             $client $em->getRepository('ApplicationBundle:AccClients')->findOneBy(array(
  3123.                 'clientId' => $so->getClientId(),
  3124.             ));
  3125.             if ($client->getCreditLimitEnabled() != 1) {
  3126.                 $allowed 1;
  3127.             } else {
  3128.                 $creditLimit $client->getCreditLimit();
  3129.                 $due $client->getClientDue();
  3130.                 if ($creditLimit >= ($due $total_sales_amount))
  3131.                     $allowed 1;
  3132.             }
  3133.             //now package data
  3134.             if ($allowed == 0) {
  3135.                 return new JsonResponse(array(
  3136.                     'success' => false,
  3137. //                        'documentHash' => $order->getDocumentHash(),
  3138.                     'documentId' => $receiptId,
  3139.                     'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3140.                     'viewUrl' => '',
  3141.                 ));
  3142.             }
  3143.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  3144.             $dochash $request->request->get('docHash'); //change
  3145.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3146.             $approveRole 1;  //created
  3147.             $approveHash $request->request->get('approvalHash');
  3148.             $receiptId $request->request->get('deliveryReceiptId');
  3149.             $sig DocValidation::isSignatureOk($em$loginId$approveHash);
  3150. //            $this->addFlash(
  3151. //                'success',
  3152. //                'New Transaction Added.'
  3153. //            );
  3154.             $success $sig == false true;
  3155.             if ($success == true) {
  3156.                 $QD $this->getDoctrine()
  3157.                     ->getRepository('ApplicationBundle:DeliveryReceipt')
  3158.                     ->findOneBy(
  3159.                         array(
  3160.                             'deliveryReceiptId' => $receiptId
  3161.                         ),
  3162.                         array()
  3163.                     );
  3164.                 $draftFlag $QD->getDraftFlag();
  3165.                 if ($draftFlag == 1) {
  3166.                     //now add Approval info
  3167.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3168.                     $approveRole 1;  //created
  3169.                     System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3170.                         $receiptId,
  3171.                         $loginId,
  3172.                         $approveRole,
  3173.                         $request->request->get('approvalHash'));
  3174.                     $options = array(
  3175.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3176.                         'notification_server' => $this->container->getParameter('notification_server'),
  3177.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3178.                         'url' => $this->generateUrl(
  3179.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  3180.                             ['entity_view_route_path_name']
  3181.                         )
  3182.                     );
  3183.                     System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3184.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3185.                         $receiptId,
  3186.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3187.                     );
  3188.                     $QD->setDraftFlag(0);
  3189.                     $em->flush();
  3190.                 }
  3191.                 $url $this->generateUrl(
  3192.                     'view_delivery_receipt'
  3193.                 );
  3194.                 if ($request->request->has('returnJson')) {
  3195. //                    $dr = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  3196. //                        array(
  3197. //                            'salesOrderId' => $orderId, ///material
  3198. //
  3199. //                        )
  3200. //                    );
  3201.                     return new JsonResponse(array(
  3202.                         'success' => true,
  3203. //                        'documentHash' => $order->getDocumentHash(),
  3204.                         'documentId' => $receiptId,
  3205.                         'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3206.                         'viewUrl' => $url "/" $receiptId,
  3207.                     ));
  3208.                 } else {
  3209.                     $this->addFlash(
  3210.                         'success',
  3211.                         'Action Successful'
  3212.                     );
  3213.                     return $this->redirect($url "/" $receiptId);
  3214.                 }
  3215.             }
  3216.         }
  3217.         return new JsonResponse(array(
  3218.             'success' => false,
  3219. //                        'documentHash' => $order->getDocumentHash(),
  3220.             'documentId' => $receiptId,
  3221.             'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3222.             'viewUrl' => '',
  3223.         ));
  3224.     }
  3225.     public function CreateServiceChallanAction(Request $request)
  3226.     {
  3227.         $em $this->getDoctrine()->getManager();
  3228.         if ($request->isMethod('POST')) {
  3229.             $entity_id array_flip(GeneralConstant::$Entity_list)['ServiceChallan']; //change
  3230.             $dochash $request->request->get('docHash'); //change
  3231.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3232.             $approveRole $request->request->get('approvalRole');
  3233.             $approveHash $request->request->get('approvalHash');
  3234.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  3235.                 $loginId$approveRole$approveHash)
  3236.             ) {
  3237.                 $this->addFlash(
  3238.                     'error',
  3239.                     'Sorry Could not insert Data.'
  3240.                 );
  3241.             } else {
  3242.                 $receiptId SalesOrderM::CreateNewServiceChallan($this->getDoctrine()->getManager(), $request->request,
  3243.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  3244.                     $this->getLoggedUserCompanyId($request));
  3245.                 //now add Approval info
  3246.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3247. //                $approveRole = 1;  //created
  3248.                 $options = array(
  3249.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3250.                     'notification_server' => $this->container->getParameter('notification_server'),
  3251.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3252.                     'url' => $this->generateUrl(
  3253.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ServiceChallan']]
  3254.                         ['entity_view_route_path_name']
  3255.                     )
  3256.                 );
  3257.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3258.                     array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3259.                     $receiptId,
  3260.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3261.                 );
  3262.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3263.                     $receiptId,
  3264.                     $loginId,
  3265.                     $approveRole,
  3266.                     $request->request->get('approvalHash'));
  3267.                 $this->addFlash(
  3268.                     'success',
  3269.                     'New Service Challan Created'
  3270.                 );
  3271.                 $url $this->generateUrl(
  3272.                     'view_service_challan'
  3273.                 );
  3274.                 return $this->redirect($url "/" $receiptId);
  3275.             }
  3276.         }
  3277.         return $this->render('@Inventory/pages/input_forms/create_service_challan.html.twig',
  3278.             array(
  3279.                 'page_title' => 'New Service Challan',
  3280.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  3281.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  3282.                 'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  3283.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  3284.                 'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
  3285.                 'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
  3286.                 'deliveryOrders' => SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
  3287.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
  3288.                 'serviceList' => Inventory::ServiceList($em$this->getLoggedUserCompanyId($request))
  3289.             )
  3290.         );
  3291.     }
  3292.     public function GetItemListForDrAction(Request $request)
  3293.     {
  3294.         $em $this->getDoctrine()->getManager();
  3295.         $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3296.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3297.         if ($request->isMethod('POST')) {
  3298.             $em $this->getDoctrine();
  3299.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3300.             );
  3301.             $Content = [];
  3302.             $Transport_data = [];
  3303.             $Lul_data = [];
  3304.             if ($request->request->get('doId') != '')
  3305.                 $find_array['deliveryOrderId'] = $request->request->get('doId');
  3306. //            if($request->request->get('warehouseId')!='')
  3307. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3308.             $QD $this->getDoctrine()
  3309.                 ->getRepository('ApplicationBundle:DeliveryOrderItem')
  3310.                 ->findBy(
  3311.                     $find_array,
  3312.                     array()
  3313.                 );
  3314. //            if($request->request->get('wareHouseId')!='')
  3315.             $DO $this->getDoctrine()
  3316.                 ->getRepository('ApplicationBundle:DeliveryOrder')
  3317.                 ->findOneBy(
  3318.                     $find_array,
  3319.                     array()
  3320.                 );
  3321.             $sendData = array(
  3322. //                'salesType'=>$SO->getSalesType(),
  3323. //                'packageData'=>[],
  3324.                 'productList' => [],
  3325. //                'productListByPackage'=>[],
  3326.             );
  3327.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3328.             $pckg_item_cross_match_data = [];
  3329.             $unitList Inventory::UnitTypeList($em);
  3330.             $colorList Inventory::GetColorList($em);
  3331.             foreach ($QD as $product) {
  3332. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  3333.                 if (($product->getBalance()) <= 0)
  3334.                     continue;
  3335.                 $fdm $product->getProductFdm();
  3336.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3337.                 $find_query = array();
  3338.                 $soItem $this->getDoctrine()
  3339.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  3340.                     ->findOneBy(
  3341.                         array(
  3342.                             'id' => $product->getSalesorderItemId()
  3343.                         )
  3344.                     );
  3345.                 if (!$soItem)
  3346.                     continue;
  3347. //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3348. //                $soBalance = $soItem->getBalance();
  3349.                 $soBalance $soItem->getQty();
  3350. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3351. //                $doBalance = $product->getBalance();
  3352.                 $doBalance $product->getQty();
  3353.                 //now check if any so ir do item id there that is at
  3354.                 //least pending
  3355.                 $approvalPendingDrs $this->getDoctrine()
  3356.                     ->getRepository('ApplicationBundle:DeliveryReceipt')
  3357.                     ->findBy(
  3358.                         array(
  3359.                             'deliveryOrderId' => $DO->getDeliveryOrderId(),
  3360.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3361.                         )
  3362.                     );
  3363.                 foreach ($approvalPendingDrs as $appPendDr) {
  3364.                     $appPendDrItem $this->getDoctrine()
  3365.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3366.                         ->findOneBy(
  3367.                             array(
  3368.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3369.                                 'salesorderItemId' => $product->getSalesorderItemId()
  3370.                             )
  3371.                         );
  3372.                     if ($appPendDrItem) {
  3373.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3374.                             $soBalance $soBalance $appPendDrItem->getQty();
  3375.                             $doBalance $doBalance $appPendDrItem->getQty();
  3376.                         }
  3377.                     }
  3378.                 }
  3379.                 $colorId $product->getColorId();
  3380.                 $size $product->getSizeId();
  3381. //                $find_query['colorId']=
  3382.                 if ($productData['productId'] != 0) {
  3383.                     $find_query['productId'] = $productData['productId'];
  3384.                     if ($colorId == '' || $colorId == || $colorId == null)
  3385.                         $colorId $productData['defaultColorId'];
  3386.                     if ($size == '' || $size == || $size == null)
  3387.                         $size $productData['defaultSize'];
  3388.                     $find_query['productId'] = $productData['productId'];
  3389.                 } else {
  3390.                     if ($productData['igId'] != 0) {
  3391.                         $find_query['igId'] = $productData['igId'];
  3392.                     }
  3393.                     if ($productData['categoryId'] != 0) {
  3394.                         $find_query['categoryId'] = $productData['categoryId'];
  3395.                     }
  3396.                     if ($productData['subCategoryId'] != 0) {
  3397.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3398.                     }
  3399.                     if ($productData['brandId'] != 0) {
  3400.                         $find_query['brandId'] = $productData['brandId'];
  3401.                     }
  3402.                 }
  3403.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3404.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3405.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3406. //                    $find_query['color'] = $colorId;
  3407.                 } else
  3408.                     $find_query['color'] = $colorId;
  3409.                 if ($size == '' || $size == || $size == null) {
  3410. //                    $find_query['size'] = $size;
  3411.                 } else
  3412.                     $find_query['size'] = 0;
  3413.                 $inventory_by_warehouse_list $this->getDoctrine()
  3414.                     ->getRepository('ApplicationBundle:InventoryStorage')
  3415.                     ->findBy(
  3416.                         $find_query,
  3417.                         array()
  3418.                     );
  3419.                 $new_pid $productData['productId'];
  3420.                 $p_data = array(
  3421.                     'details_id' => $product->getId(),
  3422. //                        'productId'=>$new_pid,
  3423.                     'productIdList' => [],
  3424.                     'multList' => [],
  3425.                     'drItemIds' => [],
  3426.                     'drItemQty' => [],
  3427.                     'drItemCodeIds' => [],
  3428.                     'drItemCartonIds' => [],
  3429.                     'colorIds' => [],
  3430.                     'colorNames' => [],
  3431.                     'sizeIds' => [],
  3432.                     'productNameList' => [],
  3433.                     'availableInventoryList' => [],
  3434.                     'warehouseActionId' => [],
  3435.                     'warehouseActionName' => [],
  3436.                     'availableBarcodes' => [],
  3437.                     'availableBarcodesStr' => [],
  3438. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3439. //                        'available_inventory'=>0,
  3440. //                        'package_id'=>$product->getPackageId(),
  3441.                     'qty' => $product->getQty(),
  3442.                     'delivered' => $product->getDelivered(),
  3443. //                    'deliverable' => $product->getDeliverable() - $product->getTransitQty(),
  3444.                     'deliverable' => min($soBalance$doBalance),
  3445. //                    'balance' => $product->getBalance(),
  3446.                     'balance' => min($soBalance$doBalance),
  3447.                     'productNameFdm' => $product->getProductNameFdm(),
  3448.                     'productFdm' => $product->getProductFdm(),
  3449. //                        'delivered'=>$product->getDelivered(),
  3450.                 );
  3451.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  3452.                     if ($inventory_by_warehouse->getQty() <= 0)
  3453.                         continue;
  3454.                     $unitType $product->getUnitTypeId();
  3455.                     $mult_unit 1;
  3456.                     if ($drId != 0) {
  3457.                         $drItem $this->getDoctrine()
  3458.                             ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3459.                             ->findOneBy(
  3460.                                 array(
  3461.                                     'deliveryReceiptId' => $drId,
  3462.                                     'productId' => $inventory_by_warehouse->getProductId(),
  3463.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  3464.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  3465.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  3466.                                 )
  3467.                             );
  3468.                         if ($drItem) {
  3469.                             $p_data['drItemIds'][] = $drItem->getId();
  3470.                             $p_data['drItemQty'][] = $drItem->getQty();
  3471.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  3472.                             if ($codes == null)
  3473.                                 $codes = [];
  3474.                             $p_data['drItemCodeIds'][] = $codes;
  3475.                             $codes json_decode($drItem->getCartonIds(), true);
  3476.                             if ($codes == null)
  3477.                                 $codes = [];
  3478.                             $p_data['drItemCartonIds'][] = $codes;
  3479.                         } else {
  3480.                             $p_data['drItemIds'][] = 0;
  3481.                             $p_data['drItemQty'][] = 0;
  3482.                             $p_data['drItemCodeIds'][] = 0;
  3483.                             $p_data['drItemCartonIds'][] = 0;
  3484.                         }
  3485.                     } else {
  3486.                         $p_data['drItemIds'][] = 0;
  3487.                         $p_data['drItemQty'][] = 0;
  3488.                         $p_data['drItemCodeIds'][] = 0;
  3489.                         $p_data['drItemCartonIds'][] = 0;
  3490.                     }
  3491.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  3492.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  3493.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  3494.                         }
  3495.                     };
  3496.                     if ($mult_unit == 0)
  3497.                         $mult_unit 1;
  3498.                     $inv_product_id $inventory_by_warehouse->getProductId();
  3499.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  3500.                     $p_data['multList'][] = $mult_unit;
  3501.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  3502.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  3503.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  3504.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  3505.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  3506. //                        $p_data['availableInventoryList'][]=$inventory_by_warehouse?(($inventory_by_warehouse->getQty())*$mult_unit):0;
  3507.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  3508.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  3509.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  3510.                 }
  3511.                 $sendData['productList'][] = $p_data;
  3512.             }
  3513.             //now package data
  3514.             if ($sendData) {
  3515.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3516.             }
  3517.             return new JsonResponse(array("success" => false));
  3518.         }
  3519.         return new JsonResponse(array("success" => false));
  3520.     }
  3521.     public function GetItemListForDrBySoAction(Request $request)
  3522.     {
  3523.         $em $this->getDoctrine()->getManager();
  3524.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3525.         if ($request->isMethod('POST')) {
  3526.             $em $this->getDoctrine();
  3527.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3528. //                'type'=>1//product only
  3529.             );
  3530.             $find_item_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3531.                 'type' => 1//product only
  3532.             );
  3533.             $Content = [];
  3534.             $Transport_data = [];
  3535.             $Lul_data = [];
  3536.             $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3537.             if ($request->request->get('soId') != '') {
  3538.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3539.                 $find_item_array['salesOrderId'] = $request->request->get('soId');
  3540.             }
  3541. //            if($request->request->get('warehouseId')!='')
  3542. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3543.             $QD $this->getDoctrine()
  3544.                 ->getRepository('ApplicationBundle:SalesOrderItem')
  3545.                 ->findBy(
  3546.                     $find_item_array,
  3547.                     array()
  3548.                 );
  3549. //            if($request->request->get('wareHouseId')!='')
  3550.             $DO $this->getDoctrine()
  3551.                 ->getRepository('ApplicationBundle:SalesOrder')
  3552.                 ->findOneBy(
  3553.                     $find_array,
  3554.                     array()
  3555.                 );
  3556.             $sendData = array(
  3557. //                'salesType'=>$SO->getSalesType(),
  3558. //                'packageData'=>[],
  3559.                 'productList' => [],
  3560. //                'productListByPackage'=>[],
  3561.             );
  3562.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3563.             $pckg_item_cross_match_data = [];
  3564.             $unitList Inventory::UnitTypeList($em);
  3565.             $colorList Inventory::GetColorList($em);
  3566.             foreach ($QD as $product) {
  3567.                 if (($product->getBalance() - $product->getTransitQty()) <= 0)
  3568.                     continue;
  3569.                 //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3570. //                $soBalance = $soItem->getBalance();
  3571.                 $soBalance $product->getQty();
  3572. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3573. //                $doBalance = $product->getBalance();
  3574. //                $doBalance = 0;
  3575.                 //now check if any so ir do item id there that is at
  3576.                 //least pending
  3577.                 $approvalPendingDrs $this->getDoctrine()
  3578.                     ->getRepository('ApplicationBundle:DeliveryReceipt')
  3579.                     ->findBy(
  3580.                         array(
  3581.                             'salesOrderId' => $DO->getSalesOrderId(),
  3582.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3583.                         )
  3584.                     );
  3585.                 foreach ($approvalPendingDrs as $appPendDr) {
  3586.                     $appPendDrItem $this->getDoctrine()
  3587.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3588.                         ->findOneBy(
  3589.                             array(
  3590.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3591. //                                'salesorderItemId' => $product->getId(),
  3592.                                 'salesorderItemId' => $product->getId()
  3593.                             )
  3594.                         );
  3595.                     if ($appPendDrItem) {
  3596.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3597.                             $soBalance $soBalance $appPendDrItem->getQty();
  3598.                         }
  3599. //                        $doBalance=$doBalance-$appPendDrItem->getQty();
  3600.                     }
  3601.                 }
  3602.                 $fdm $product->getProductFdm();
  3603.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3604.                 $find_query = array();
  3605.                 $colorId $product->getColorId();
  3606.                 $size $product->getSizeId();
  3607. //                $find_query['colorId']=
  3608.                 if ($productData['productId'] != 0) {
  3609.                     $find_query['productId'] = $productData['productId'];
  3610.                     if ($colorId == '' || $colorId == || $colorId == null)
  3611.                         $colorId $productData['defaultColorId'];
  3612.                     if ($size == '' || $size == || $size == null)
  3613.                         $size $productData['defaultSize'];
  3614.                 } else {
  3615.                     if ($productData['igId'] != 0) {
  3616.                         $find_query['igId'] = $productData['igId'];
  3617.                     }
  3618.                     if ($productData['categoryId'] != 0) {
  3619.                         $find_query['categoryId'] = $productData['categoryId'];
  3620.                     }
  3621.                     if ($productData['subCategoryId'] != 0) {
  3622.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3623.                     }
  3624.                     if ($productData['brandId'] != 0) {
  3625.                         $find_query['brandId'] = $productData['brandId'];
  3626.                     }
  3627.                 }
  3628.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3629.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3630.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3631. //                    $find_query['color'] = $colorId;
  3632.                 } else
  3633.                     $find_query['color'] = $colorId;
  3634.                 if ($size == '' || $size == || $size == null) {
  3635. //                    $find_query['size'] = $size;
  3636.                 } else
  3637.                     $find_query['size'] = 0;
  3638.                 $inventory_by_warehouse_list $this->getDoctrine()
  3639.                     ->getRepository('ApplicationBundle:InventoryStorage')
  3640.                     ->findBy(
  3641.                         $find_query,
  3642.                         array()
  3643.                     );
  3644.                 $new_pid $productData['productId'];
  3645.                 $unitType $product->getUnitTypeId();
  3646.                 $p_data = array(
  3647.                     'details_id' => $product->getId(),
  3648.                     'unitType' => $unitType,
  3649.                     'productIdList' => [],
  3650.                     'multList' => [],
  3651.                     'drItemIds' => [],
  3652.                     'drItemQty' => [],
  3653.                     'drItemCodeIds' => [],
  3654.                     'drItemCartonIds' => [],
  3655.                     'colorIds' => [],
  3656.                     'colorNames' => [],
  3657.                     'sizeIds' => [],
  3658.                     'productNameList' => [],
  3659.                     'availableInventoryList' => [],
  3660.                     'warehouseActionId' => [],
  3661.                     'warehouseActionName' => [],
  3662.                     'availableBarcodes' => [],
  3663.                     'availableBarcodesStr' => [],
  3664. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3665. //                        'available_inventory'=>0,
  3666. //                        'package_id'=>$product->getPackageId(),
  3667.                     'qty' => $product->getQty(),
  3668.                     'delivered' => $product->getDelivered(),
  3669. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  3670. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  3671.                     'deliverable' => $soBalance,
  3672. //                    'deliverable' => $product->getBalance(),
  3673.                     'balance' => $soBalance,
  3674. //                    'balance' => $product->getBalance(),
  3675.                     'productNameFdm' => $product->getProductNameFdm(),
  3676.                     'productFdm' => $product->getProductFdm(),
  3677. //                        'delivered'=>$product->getDelivered(),
  3678.                 );
  3679.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  3680.                     if ($inventory_by_warehouse->getQty() <= 0)
  3681.                         continue;
  3682.                     $mult_unit 1;
  3683.                     if ($drId != 0) {
  3684.                         $drItem $this->getDoctrine()
  3685.                             ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3686.                             ->findOneBy(
  3687.                                 array(
  3688.                                     'deliveryReceiptId' => $drId,
  3689.                                     'productId' => $inventory_by_warehouse->getProductId(),
  3690.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  3691.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  3692.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  3693.                                 )
  3694.                             );
  3695.                         if ($drItem) {
  3696.                             $p_data['drItemIds'][] = $drItem->getId();
  3697.                             $p_data['drItemQty'][] = $drItem->getQty();
  3698.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  3699.                             if ($codes == null)
  3700.                                 $codes = [];
  3701.                             $p_data['drItemCodeIds'][] = $codes;
  3702.                             $codes json_decode($drItem->getCartonIds(), true);
  3703.                             if ($codes == null)
  3704.                                 $codes = [];
  3705.                             $p_data['drItemCartonIds'][] = $codes;
  3706.                         } else {
  3707.                             $p_data['drItemIds'][] = 0;
  3708.                             $p_data['drItemQty'][] = 0;
  3709.                             $p_data['drItemCodeIds'][] = 0;
  3710.                             $p_data['drItemCartonIds'][] = 0;
  3711.                         }
  3712.                     } else {
  3713.                         $p_data['drItemIds'][] = 0;
  3714.                         $p_data['drItemQty'][] = 0;
  3715.                         $p_data['drItemCodeIds'][] = 0;
  3716.                         $p_data['drItemCartonIds'][] = 0;
  3717.                     }
  3718.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  3719.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  3720.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  3721.                         }
  3722.                     };
  3723.                     if ($mult_unit == 0)
  3724.                         $mult_unit 1;
  3725.                     $inv_product_id $inventory_by_warehouse->getProductId();
  3726.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  3727.                     $p_data['multList'][] = $mult_unit;
  3728.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  3729.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  3730.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  3731.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  3732.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  3733.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  3734.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  3735.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  3736.                 }
  3737.                 $sendData['productList'][] = $p_data;
  3738.             }
  3739.             //now package data
  3740.             if ($sendData) {
  3741.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3742.             }
  3743.             return new JsonResponse(array("success" => false));
  3744.         }
  3745.         return new JsonResponse(array("success" => false));
  3746.     }
  3747.     public function GetItemListForStockReqBySoAction(Request $request)
  3748.     {
  3749.         $em $this->getDoctrine()->getManager();
  3750.         if ($request->isMethod('POST')) {
  3751.             $em $this->getDoctrine();
  3752.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3753.             );
  3754.             $Content = [];
  3755.             $Transport_data = [];
  3756.             $Lul_data = [];
  3757.             $find_array['serviceId'] = [0null];
  3758.             $sendData = array(
  3759. //                'salesType'=>$SO->getSalesType(),
  3760. //                'packageData'=>[],
  3761.                 'productList' => [],
  3762. //                'productListByPackage'=>[],
  3763.             );
  3764.             if ($request->request->get('soId') != '') {
  3765.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3766. //            if($request->request->get('warehouseId')!='')
  3767. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3768.                 $QD $this->getDoctrine()
  3769.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  3770.                     ->findBy(
  3771.                         $find_array,
  3772.                         array()
  3773.                     );
  3774. //            if($request->request->get('wareHouseId')!='')
  3775. //            $DO = $this->getDoctrine()
  3776. //                ->getRepository('ApplicationBundle:SalesOrder')
  3777. //                ->findOneBy(
  3778. //                    $find_array,
  3779. //                    array()
  3780. //                );
  3781.                 $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3782.                 $pckg_item_cross_match_data = [];
  3783.                 $unitList Inventory::UnitTypeList($em);
  3784.                 foreach ($QD as $product) {
  3785. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  3786. //                    continue;
  3787.                     $fdm $product->getProductFdm();
  3788.                     $unitType $product->getUnitTypeId();
  3789.                     $p_data = array(
  3790.                         'details_id' => $product->getId(),
  3791.                         'unitType' => $unitType,
  3792.                         'productIdList' => [],
  3793.                         'multList' => [],
  3794.                         'productNameList' => [],
  3795.                         'availableInventoryList' => [],
  3796.                         'warehouseActionId' => [],
  3797.                         'warehouseActionName' => [],
  3798.                         'availableBarcodes' => [],
  3799.                         'availableBarcodesStr' => [],
  3800. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3801. //                        'available_inventory'=>0,
  3802. //                        'package_id'=>$product->getPackageId(),
  3803.                         'qty' => $product->getQty(),
  3804.                         'delivered' => $product->getDelivered(),
  3805. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  3806. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  3807.                         'deliverable' => $product->getBalance(),
  3808.                         'balance' => $product->getBalance(),
  3809.                         'productNameFdm' => $product->getProductNameFdm(),
  3810.                         'productFdm' => $product->getProductFdm(),
  3811. //                        'delivered'=>$product->getDelivered(),
  3812.                     );
  3813.                     $sendData['productList'][] = $p_data;
  3814.                 }
  3815.             }
  3816.             //now package data
  3817.             if ($sendData) {
  3818.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3819.             }
  3820.             return new JsonResponse(array("success" => false));
  3821.         }
  3822.         return new JsonResponse(array("success" => false));
  3823.     }
  3824.     public function GetBarcodesListForStAction(Request $request)
  3825.     {
  3826.         $em $this->getDoctrine()->getManager();
  3827.         $sendData = [];
  3828.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3829.         if ($request->isMethod('POST')) {
  3830.             $em $this->getDoctrine();
  3831.             $find_query = array();
  3832.             $find_query['warehouseId'] = $request->request->get('warehouseId');
  3833.             $find_query['actionTagId'] = $request->request->get('warehouseActionId');
  3834.             $find_query['productId'] = $request->request->get('productId');
  3835.             $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3836.             $inventory_by_warehouse_list $this->getDoctrine()
  3837.                 ->getRepository('ApplicationBundle:InventoryStorage')
  3838.                 ->findBy(
  3839.                     $find_query,
  3840.                     array()
  3841.                 );
  3842.             $new_pid $request->request->get('productId');
  3843.             $p_data = array();
  3844.             //now get bacodes if available
  3845. //                    $query = "SELECT product_by_code_id, GROUP_CONCAT(DISTINCT sales_code SEPARATOR ',') sales_code_list_str
  3846. //FROM product_by_code
  3847. //where company_id=" . $this->getLoggedUserCompanyId($request).
  3848. //                        " and product_id=".$inv_product_id.
  3849. //                        " and warehouse_id=".$inventory_by_warehouse->getWarehouseId().
  3850. //                        " and warehouse_action_id=".$inventory_by_warehouse->getActionTagId();
  3851. //                        " GROUP BY product_by_code_id" ;
  3852.             $query "SELECT product_by_code_id, sales_code
  3853. FROM product_by_code
  3854. where company_id=" $this->getLoggedUserCompanyId($request) .
  3855.                 " and product_id=" $request->request->get('productId') .
  3856.                 " and warehouse_id=" $request->request->get('warehouseId') .
  3857.                 " and warehouse_action_id=" $request->request->get('warehouseActionId');
  3858.             $stmt $em->getConnection()->prepare($query);
  3859.             $stmt->execute();
  3860.             $results $stmt->fetchAll();
  3861.             $sales_code_list_str '';
  3862.             foreach ($results as $pika => $result) {
  3863.                 if ($pika != 0)
  3864.                     $sales_code_list_str .= ',';
  3865.                 $sales_code_list_str .= str_pad($result['sales_code'], 13'0'STR_PAD_LEFT);
  3866.             }
  3867.             if ($results) {
  3868.                 $p_data['availableBarcodes'] = $sales_code_list_str != '' || $sales_code_list_str != null
  3869.                     explode(','$sales_code_list_str) : [];
  3870.                 $p_data['availableBarcodesStr'] = $sales_code_list_str != '' || $sales_code_list_str != null
  3871.                     $sales_code_list_str "";
  3872. //
  3873.             } else {
  3874.                 $p_data['availableBarcodes'] = [];
  3875.                 $p_data['availableBarcodesStr'] = "";
  3876. //
  3877.             }
  3878.             $sendData $p_data;
  3879.         }
  3880.         //now package data
  3881.         if (!empty($sendData['availableBarcodes'])) {
  3882.             return new JsonResponse(array("success" => true"content" => $sendData));
  3883.         }
  3884.         return new JsonResponse(array("success" => false));
  3885.     }
  3886.     public function GetItemListForSalesReturnAction(Request $request)
  3887.     {
  3888.         if ($request->isMethod('POST')) {
  3889.             $em $this->getDoctrine();
  3890.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3891.             );
  3892.             $Content = [];
  3893.             $Transport_data = [];
  3894.             $Lul_data = [];
  3895.             if ($request->request->get('drId') != '')
  3896.                 $find_array['deliveryReceiptId'] = $request->request->get('drId');
  3897. //            if($request->request->get('warehouseId')!='')
  3898. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3899.             $QD $this->getDoctrine()
  3900.                 ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3901.                 ->findBy(
  3902.                     $find_array,
  3903.                     array()
  3904.                 );
  3905. //            if($request->request->get('wareHouseId')!='')
  3906.             $DR $this->getDoctrine()
  3907.                 ->getRepository('ApplicationBundle:DeliveryReceipt')
  3908.                 ->findOneBy(
  3909.                     $find_array,
  3910.                     array()
  3911.                 );
  3912.             $sendData = array(
  3913.                 'productList' => [],
  3914.             );
  3915.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3916.             $pckg_item_cross_match_data = [];
  3917.             $unitList Inventory::UnitTypeList($em);
  3918.             foreach ($QD as $product) {
  3919.                 if (($product->getQty()) <= 0)
  3920.                     continue;
  3921.                 $new_pid $product->getProductId();
  3922.                 $sales_code_range = [];
  3923.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  3924.                     $sales_code_range json_decode($product->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  3925.                 } else {
  3926.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  3927.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getSalesCodeRange());
  3928.                     $sales_code_range json_decode($json_without_bigintstrue);
  3929.                 }
  3930.                 $p_data = array(
  3931.                     'details_id' => $product->getId(),
  3932.                     'dr_id' => $product->getDeliveryReceiptId(),
  3933.                     'productId' => $new_pid,
  3934.                     'product_name' => isset($productList[$new_pid]) ? $productList[$new_pid]['name'] : '',
  3935.                     'qty' => $product->getQty(),
  3936.                     'delivered' => $product->getDelivered(),
  3937.                     'unitTypeId' => $product->getUnitTypeId(),
  3938.                     'deliverable' => $product->getDeliverable(),
  3939.                     'balance' => $product->getBalance(),
  3940.                     'salesCodeRangeStr' => $product->getSalesCodeRange(),
  3941.                     'salesCodeRange' => $sales_code_range,
  3942.                     'sales_codes' => $sales_code_range,
  3943.                     'sales_price' => $product->getPrice(),
  3944.                     'purchase_price' => $product->getCurrentPurchasePrice()
  3945. //                        'delivered'=>$product->getDelivered(),
  3946.                 );
  3947.                 $sendData['productList'][] = $p_data;
  3948.             }
  3949.             //now package data
  3950.             if ($sendData) {
  3951.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3952.             }
  3953.             return new JsonResponse(array("success" => false));
  3954.         }
  3955.         return new JsonResponse(array("success" => false));
  3956.     }
  3957.     public function GetItemListForIrrAction(Request $request)
  3958.     {
  3959.         if ($request->isMethod('POST')) {
  3960.             $em $this->getDoctrine();
  3961.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3962.             );
  3963.             $Content = [];
  3964.             $Transport_data = [];
  3965.             $Lul_data = [];
  3966.             if ($request->request->get('srId') != '')
  3967.                 $find_array['salesReturnId'] = $request->request->get('srId');
  3968. //            if($request->request->get('warehouseId')!='')
  3969. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3970.             $QD $this->getDoctrine()
  3971.                 ->getRepository('ApplicationBundle:SalesReturnItem')
  3972.                 ->findBy(
  3973.                     $find_array,
  3974.                     array()
  3975.                 );
  3976. //            if($request->request->get('wareHouseId')!='')
  3977.             $sendData = array(
  3978.                 'productList' => [],
  3979.             );
  3980.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3981.             $pckg_item_cross_match_data = [];
  3982.             $unitList Inventory::UnitTypeList($em);
  3983.             foreach ($QD as $product) {
  3984.                 if (($product->getReceivedBalance()) <= && ($product->getReplacedBalance()) <= 0)
  3985.                     continue;
  3986.                 $DR_ITEM null;
  3987.                 $DR_TAGGED_CODES = [];
  3988.                 $DR_TAGGED_CODES_FOR_SELECTIZE = [];
  3989.                 $RESTRICT_RECEIVED_CODES_FLAG 0;
  3990.                 $sales_code_range = [];
  3991.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  3992.                     $sales_code_range json_decode($product->getReceivedCodeRange(), true512JSON_BIGINT_AS_STRING);
  3993.                 } else {
  3994.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  3995.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getReceivedCodeRange());
  3996.                     $sales_code_range json_decode($json_without_bigintstrue);
  3997.                 }
  3998.                 $DR_TAGGED_CODES $sales_code_range;
  3999.                 if (!empty($DR_TAGGED_CODES)) {
  4000.                     $RESTRICT_RECEIVED_CODES_FLAG 1;
  4001.                     foreach ($DR_TAGGED_CODES as $DTC) {
  4002.                         $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  4003.                             'value' => $DTC
  4004.                         );
  4005.                     }
  4006.                 }
  4007. //                if ($product->getTaggedDetailsId() != 0 && $product->getTaggedDetailsId() != null) {
  4008. //
  4009. //                    $DR_ITEM = $this->getDoctrine()
  4010. //                        ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  4011. //                        ->findOneBy(
  4012. //                            array(
  4013. //                                'id' => $product->getTaggedDetailsId()
  4014. //                            ),
  4015. //                            array()
  4016. //                        );
  4017. //                    if ($DR_ITEM) {
  4018. //                        if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  4019. //
  4020. //                            $DR_TAGGED_CODES = json_decode($DR_ITEM->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  4021. //                        } else {
  4022. //
  4023. //                            $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  4024. //                            $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $DR_ITEM->getSalesCodeRange());
  4025. //                            $DR_TAGGED_CODES = json_decode($json_without_bigints, true);
  4026. //                        }
  4027. //
  4028. //                        if ($DR_TAGGED_CODES == null)
  4029. //                            $DR_TAGGED_CODES = [];
  4030. //                        if (!empty($DR_TAGGED_CODES)) {
  4031. //                            $RESTRICT_RECEIVED_CODES_FLAG = 1;
  4032. //                            foreach ($DR_TAGGED_CODES as $DTC) {
  4033. //                                $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  4034. //                                    'value' => $DTC
  4035. //                                );
  4036. //                            }
  4037. //                        }
  4038. //                    }
  4039. //                }
  4040.                 $p_data = array(
  4041.                     'details_id' => $product->getId(),
  4042.                     'receivedDrTaggedCodes' => $DR_TAGGED_CODES,
  4043.                     'receivedDrTaggedCodesStr' => implode(','$DR_TAGGED_CODES),
  4044.                     'receivedDrTaggedCodesForSel' => $DR_TAGGED_CODES_FOR_SELECTIZE,
  4045.                     'receivedRestrictCodesFlag' => $RESTRICT_RECEIVED_CODES_FLAG,
  4046.                     'receivedProductId' => $product->getReceivedProductId(),
  4047.                     'receivedBalance' => $product->getReceivedBalance(),
  4048.                     'receivedUnitSalesPrice' => $product->getReceivedUnitSalesPrice(),
  4049.                     'receivedUnitPurchasePrice' => $product->getReceivedUnitPurchasePrice(),
  4050.                     'receivedProductName' => isset($productList[$product->getReceivedProductId()]) ? $productList[$product->getReceivedProductId()]['name'] : '',
  4051.                     'replacedProductId' => $product->getReplacedProductId(),
  4052.                     'replacedBalance' => $product->getReplacedBalance(),
  4053.                     'replacedUnitSalesPrice' => $product->getReplacedUnitSalesPrice(),
  4054.                     'replacedUnitPurchasePrice' => $product->getReplacedUnitPurchasePrice(),
  4055.                     'replacedProductName' => isset($productList[$product->getReplacedProductId()]) ? $productList[$product->getReplacedProductId()]['name'] : '',
  4056.                     'disposeBalance' => $product->getDisposeBalance(),
  4057.                     'unusedBalance' => $product->getUnusedBalance(),
  4058.                     'disposeTag' => $product->getDisposeTag(),
  4059.                     'unitTypeId' => $product->getUnitTypeId(),
  4060. //                        'delivered'=>$product->getDelivered(),
  4061.                 );
  4062.                 $sendData['productList'][] = $p_data;
  4063.             }
  4064.             //now package data
  4065.             if ($sendData) {
  4066.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4067.             }
  4068.             return new JsonResponse(array("success" => false));
  4069.         }
  4070.         return new JsonResponse(array("success" => false));
  4071.     }
  4072.     public function LabelFormatAction(Request $request$id 0)
  4073.     {
  4074.         $data = array(
  4075.             'formatId' => '',
  4076.             'formatCode' => '',
  4077.             'name' => '',
  4078.             'labelType' => 0,
  4079.             'width' => 60,
  4080.             'pageWidth' => 6,
  4081.             'height' => 39,
  4082.             'pageHeight' => 2,
  4083.             'formatData' => '',
  4084.         );
  4085.         if ($request->isMethod('POST')) {
  4086.             $post $request->request;
  4087.             $exists_already 0;
  4088.             if ($request->request->get('formatId') != '') {
  4089.                 $query_here $this->getDoctrine()
  4090.                     ->getRepository('ApplicationBundle:LabelFormat')
  4091.                     ->findOneBy(
  4092.                         array(
  4093.                             'formatId' => $request->request->get('formatId')
  4094.                         )
  4095.                     );
  4096.                 if (!empty($query_here)) {
  4097.                     $exists_already 1;
  4098.                     $new $query_here;
  4099.                 } else
  4100.                     $new = new LabelFormat();
  4101.             } else
  4102.                 $new = new LabelFormat();
  4103.             $new->setName($request->request->get('name'));
  4104.             $new->setLabelType($request->request->get('labelType'));
  4105.             $new->setWidth($request->request->get('width'));
  4106.             $new->setHeight($request->request->get('height'));
  4107.             $new->setFormatCode($request->request->get('formatCode'));
  4108.             $new->setActive(GeneralConstant::ACTIVE);
  4109.             $new->setPageHeight($request->request->get('pageHeight'));
  4110.             $new->setPageWidth($request->request->get('pageWidth'));
  4111.             $new->setFormatData($request->request->get('formatData'));
  4112.             if ($exists_already == 0)
  4113.                 $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4114.             $new->setEditLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4115.             $new->setCompanyId($request->getSession()->get(UserConstants::USER_COMPANY_ID));
  4116.             $em $this->getDoctrine()->getManager();
  4117.             $em->persist($new);
  4118.             $em->flush();
  4119.         }
  4120.         if ($id != 0) {
  4121.             $query_here $this->getDoctrine()
  4122.                 ->getRepository('ApplicationBundle:LabelFormat')
  4123.                 ->findOneBy(
  4124.                     array(
  4125.                         'formatId' => $id
  4126.                     )
  4127.                 );
  4128.             if ($query_here)
  4129.                 $data $query_here;
  4130.         } else if ($request->query->has('formatId')) {
  4131.             $query_here $this->getDoctrine()
  4132.                 ->getRepository('ApplicationBundle:LabelFormat')
  4133.                 ->findOneBy(
  4134.                     array(
  4135.                         'formatId' => $request->query->get('formatId')
  4136.                     )
  4137.                 );
  4138.             if ($query_here)
  4139.                 $data $query_here;
  4140.         }
  4141.         return $this->render(
  4142.             '@Inventory/pages/input_forms/label_format.html.twig',
  4143.             array(
  4144.                 'page_title' => 'Label Format',
  4145.                 'data' => $data,
  4146.                 'labelTypeList' => LabelConstant::$label_type_list,
  4147.                 'labelFieldsList' => LabelConstant::$label_fields_list,
  4148.                 'formatList' => $this->getDoctrine()
  4149.                     ->getRepository('ApplicationBundle:LabelFormat')
  4150.                     ->findBy(
  4151.                         array( //                            'formatId' => $request->query->get('formatId')
  4152.                         )
  4153.                     )
  4154.                 //                'incomeLedgerHeads'=>Accounts::getChildLedgerHeads($this->getDoctrine()->getManager(),AccountsConstant::INCOME)
  4155.             )
  4156.         );
  4157.     }
  4158.     public function GetServiceListForScAction(Request $request)
  4159.     {
  4160.         if ($request->isMethod('POST')) {
  4161.             $em $this->getDoctrine();
  4162.             $find_array = array(
  4163.                 'type' => 2//service
  4164.             );
  4165.             $Content = [];
  4166.             $Transport_data = [];
  4167.             $Lul_data = [];
  4168.             if ($request->request->get('soId') != '')
  4169.                 $find_array['salesOrderId'] = $request->request->get('soId');
  4170. //            if($request->request->get('warehouseId')!='')
  4171. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4172.             $QD $this->getDoctrine()
  4173.                 ->getRepository('ApplicationBundle:SalesOrderItem')
  4174.                 ->findBy(
  4175.                     $find_array,
  4176.                     array()
  4177.                 );
  4178. //            if($request->request->get('wareHouseId')!='')
  4179.             $SO $this->getDoctrine()
  4180.                 ->getRepository('ApplicationBundle:SalesOrder')
  4181.                 ->findOneBy(
  4182.                     array(
  4183.                         'salesOrderId' => $request->request->get('soId')
  4184.                     ),
  4185.                     array()
  4186.                 );
  4187.             $sendData = array(
  4188. //                'salesType'=>$SO->getSalesType(),
  4189. //                'packageData'=>[],
  4190.                 'productList' => [],
  4191. //                'productListByPackage'=>[],
  4192.             );
  4193.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager(), $SO->getCompanyId());
  4194.             $pckg_item_cross_match_data = [];
  4195.             foreach ($QD as $product) {
  4196.                 $p_data = array(
  4197.                     'details_id' => $product->getId(),
  4198.                     'service_id' => $product->getServiceId(),
  4199.                     'service_name' => $serviceList[$product->getServiceId()]['name'],
  4200.                     'available_inventory' => $product->getBalance(),
  4201. //                        'package_id'=>$product->getPackageId(),
  4202.                     'qty' => $product->getQty(),
  4203.                     'delivered' => $product->getDelivered(),
  4204. //                    'deliverable'=>$product->getDeliverable(),
  4205.                     'balance' => $product->getBalance(),
  4206. //                        'delivered'=>$product->getDelivered(),
  4207.                 );
  4208.                 $sendData['serviceList'][] = $p_data;
  4209.             }
  4210.             //now package data
  4211.             if ($sendData) {
  4212.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4213.             }
  4214.             return new JsonResponse(array("success" => false));
  4215.         }
  4216.         return new JsonResponse(array("success" => false));
  4217.     }
  4218.     public function CreateReceivedNoteAction(Request $request)
  4219.     {
  4220.         if ($request->isMethod('POST')) {
  4221.             $em $this->getDoctrine()->getManager();
  4222.             $entity_id array_flip(GeneralConstant::$Entity_list)['Grn']; //change
  4223.             $dochash $request->request->get('docHash'); //change
  4224.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4225.             $approveRole 1;  //created
  4226.             $approveHash $request->request->get('approvalHash');
  4227.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4228.                 $loginId$approveRole$approveHash)
  4229.             ) {
  4230.                 $this->addFlash(
  4231.                     'error',
  4232.                     'Sorry Couldnot insert Data.'
  4233.                 );
  4234.             } else {
  4235.                 $data $request->request;
  4236.                 $grnId Inventory::CreateGrn($this->getDoctrine()->getManager(), $data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4237.                 //now add Approval info
  4238.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4239.                 $approveRole 1;  //created
  4240.                 $options = array(
  4241.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4242.                     'notification_server' => $this->container->getParameter('notification_server'),
  4243.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4244.                     'url' => $this->generateUrl(
  4245.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['Grn']]
  4246.                         ['entity_view_route_path_name']
  4247.                     )
  4248.                 );
  4249.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4250.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  4251.                     $grnId,
  4252.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4253.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['Grn'], $grnId,
  4254.                     $loginId,
  4255.                     $approveRole,
  4256.                     $request->request->get('approvalHash'));
  4257.                 $this->addFlash(
  4258.                     'success',
  4259.                     'New GRN Added.'
  4260.                 );
  4261.                 $url $this->generateUrl(
  4262.                     'view_grn'
  4263.                 );
  4264.                 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),
  4265.                     "Good Received Note : " $dochash " Has Been Created And is Under Processing",
  4266.                     'pos',
  4267.                     System::getPositionIdsByDepartment($em, [GeneralConstant::SALES_DEPARTMENTGeneralConstant::PURCHASE_DEPARTMENTGeneralConstant::ACCOUNTS_DEPARTMENTGeneralConstant::INVENTORY_DEPARTMENT]),
  4268.                     'success',
  4269.                     $url "/" $grnId,
  4270.                     "GRN"
  4271.                 );
  4272.                 return $this->redirect($url "/" $grnId);
  4273.             }
  4274.         }
  4275.         return $this->render('@Inventory/pages/input_forms/received_note.html.twig',
  4276.             array(
  4277.                 'page_title' => 'GRN',
  4278.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  4279.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  4280.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  4281.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  4282.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  4283.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  4284.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  4285.                 'material_inward' => $this->getDoctrine()
  4286.                     ->getRepository('ApplicationBundle:MaterialInward')
  4287.                     ->findBy(
  4288.                         array(
  4289.                             'stage' => GeneralConstant::STAGE_PENDING_TAG
  4290.                         )
  4291.                     )
  4292. //                'po'=>Inventory::getPurchaseOrderList
  4293.             )
  4294.         );
  4295.     }
  4296.     public function GetQcListForGrnAction(Request $request)
  4297.     {
  4298.         if ($request->isMethod('POST')) {
  4299.             $find_array = array(
  4300.                 'stage' => GeneralConstant::STAGE_PENDING_TAG
  4301.             );
  4302.             $Content = [];
  4303.             $ContentByProductId = [];
  4304.             $Transport_data = [];
  4305.             $Lul_data = [];
  4306.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4307.             if ($request->request->get('poId') != '')
  4308.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4309.             if ($request->request->get('warehouseId') != '')
  4310.                 $find_array['warehouseId'] = $request->request->get('warehouseId');
  4311.             $QD $this->getDoctrine()
  4312.                 ->getRepository('ApplicationBundle:MaterialInward')
  4313.                 ->findBy(
  4314.                     $find_array,
  4315.                     array(
  4316.                         'inwardDate' => 'ASC',
  4317.                         'qcDate' => 'ASC'
  4318.                     )
  4319.                 );
  4320.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4321.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4322.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4323.             $lotNumArray = [];
  4324.             foreach ($QD as $entry) {
  4325. //                $inwardDate=strtotime($entry->getInwardDate());
  4326. //                $qcDate=strtotime($entry->getQcDate());
  4327.                 $inwardDate = ($entry->getInwardDate() instanceof \DateTime) ? $entry->getInwardDate()->format('m/d/Y') : '';
  4328.                 $qcDate = ($entry->getQcDate() instanceof \DateTime) ? $entry->getQcDate()->format('m/d/Y') : '';
  4329.                 if (!in_array($entry->getLotNumber(), $lotNumArray))
  4330.                     $lotNumArray[] = $entry->getLotNumber();
  4331.                 if (isset($ContentByProductId[$entry->getPurchaseOrderItemId()])) {
  4332.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['inwardDateList'][] = $inwardDate;
  4333.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcDateList'][] = $inwardDate;
  4334.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcIdList'][] = $entry->getQcId();
  4335.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['appQtyList'][] = $entry->getApprovedQty();
  4336.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['totQty'] += ($entry->getApprovedQty());
  4337.                 } else {
  4338.                     $ContentByProductId[$entry->getPurchaseOrderItemId()] = array(
  4339.                         'productName' => $productList[$entry->getProductId()]['name'],
  4340.                         'productUnitName' => $unitList[$productList[$entry->getProductId()]['unit_type']]['name'],
  4341.                         'qcHash' => $entry->getDocumentHash(),
  4342.                         'warehouseName' => $warehouse[$entry->getWarehouseId()]['name'],
  4343.                         'inwardDate' => $inwardDate,
  4344.                         'inwardDateList' => [$inwardDate],
  4345.                         'qcDateList' => [$qcDate],
  4346.                         'qcIdList' => [$entry->getQcId()],
  4347.                         'qcDate' => $qcDate,
  4348.                         'poQty' => $entry->getPoQty(),
  4349.                         'poPrevbalance' => $entry->getPoBalance(),
  4350.                         'appQty' => $entry->getApprovedQty(),
  4351.                         'appQtyList' => [$entry->getApprovedQty()],
  4352.                         'totQty' => $entry->getApprovedQty(),
  4353.                         'poBalance' => $entry->getPoBalance() - $entry->getApprovedQty(),
  4354.                         'qcId' => $entry->getQcId(),
  4355.                         'productId' => $entry->getProductId()
  4356.                     );
  4357.                 }
  4358.                 $Expense_Cost[$entry->getQcId()] = json_decode($entry->getExpenseCost());
  4359.                 $Expense_Id[$entry->getQcId()] = json_decode($entry->getExpenseId());
  4360.             }
  4361.             foreach ($ContentByProductId as $c) {
  4362.                 $Content[] = $c;
  4363.             }
  4364.             if ($QD) {
  4365.                 return new JsonResponse(array("success" => true"content" => $Content"lotNumber" => implode(', '$lotNumArray), 'Expense_Cost' => $Expense_Cost'Expense_Id' => $Expense_Id));
  4366.             }
  4367.             return new JsonResponse(array("success" => false));
  4368.         }
  4369.         return new JsonResponse(array("success" => false));
  4370.     }
  4371.     public function GetSrListForIrAction(Request $request)
  4372.     {
  4373.         if ($request->isMethod('POST')) {
  4374.             $find_array = array();
  4375.             $Content = [];
  4376.             if ($request->request->get('srId') != '')
  4377.                 $find_array['stockRequisitionId'] = $request->request->get('srId');
  4378.             $find_array['forceSkipTag'] = [0null];
  4379.             $QD $this->getDoctrine()
  4380.                 ->getRepository('ApplicationBundle:StockRequisitionItem')
  4381.                 ->findBy(
  4382.                     $find_array
  4383.                 );
  4384.             $itemList Inventory::ItemGroupList($this->getDoctrine()->getManager());
  4385.             $catgoryList Inventory::ProductCategoryList($this->getDoctrine()->getManager());
  4386.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4387.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4388.             $fdmData = array();
  4389.             $em $this->getDoctrine()->getManager();
  4390.             $matchType 'MAXIMUM';
  4391.             if ($request->request->has('matchType') != '') {
  4392.                 $matchType $request->request->get('matchType');
  4393.             }
  4394.             if ($matchType == 'MINIMUM') {
  4395.                 foreach ($QD as $entry) {
  4396.                     if ($entry->getTagPendingAmount() <= 0)
  4397.                         continue;
  4398.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4399.                     $combined_id $entry->getProductFdm();
  4400.                     if (isset($fdmData[$combined_id])) {
  4401.                         $fdmData[$combined_id]['unit'] += $entry->getTagPendingAmount();
  4402.                         $fdmData[$combined_id]['specific_unit'][] = $entry->getTagPendingAmount();
  4403.                         $fdmData[$combined_id]['detailsIds'][] = $entry->getId();
  4404.                         $fdmData[$combined_id]['docIds'][] = $entry->getStockRequisitionId();
  4405.                     } else {
  4406.                         $fdmData[$combined_id] = array(
  4407.                             'id' => 0,
  4408.                             'alias' => $entry->getNote(),
  4409.                             'unit' => $entry->getTagPendingAmount(),
  4410.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4411.                             'warranty' => 0,
  4412.                             'unitTypeId' => 0,
  4413.                             'unit_price' => 0,
  4414.                             'fdm' => $combined_id,
  4415.                             'extDetailsId' => 0,
  4416.                             'product_name' => $productData['productName'],
  4417.                             'total_price' => 0,
  4418.                             'detailsIds' => [$entry->getId()],
  4419.                             'docIds' => [$entry->getStockRequisitionId()],
  4420.                         );
  4421.                     }
  4422.                 }
  4423.             }
  4424.             if ($matchType == 'MAXIMUM') {
  4425.                 foreach ($QD as $entry) {
  4426.                     if ($entry->getTagPendingAmount() <= 0)
  4427.                         continue;
  4428.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4429.                     $combined_id $entry->getProductFdm();
  4430.                     $assigned 0;
  4431.                     foreach ($fdmData as $key_ind => $rel_val) {
  4432.                         $matchFdm Inventory::MatchFdm($key_ind$combined_id);
  4433.                         if ($matchFdm['hasMatched'] == 1) {
  4434.                             if ($matchFdm['isIdentical'] == 1) {
  4435.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4436.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4437.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4438.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4439.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4440.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4441.                                 $assigned 1;
  4442.                             } elseif ($matchFdm['SecondBelongsToFirst'] == 1) {
  4443.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4444.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4445.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4446.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4447.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4448.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4449.                                 $assigned 1;
  4450.                             } elseif ($matchFdm['FirstBelongsToSecond'] == 1) {
  4451.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4452.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4453.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4454.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4455.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4456.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4457.                                 $fdmData[$combined_id] = $fdmData[$key_ind];
  4458.                                 unset($fdmData[$key_ind]);
  4459.                                 $assigned 1;
  4460.                             }
  4461.                         } else {
  4462.                         }
  4463.                         if ($assigned == 1)
  4464.                             break;
  4465.                     }
  4466.                     if ($assigned == 0) {
  4467.                         $fdmData[$combined_id] = array(
  4468.                             'id' => 0,
  4469.                             'alias' => $entry->getNote(),
  4470.                             'unit' => $entry->getTagPendingAmount(),
  4471.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4472.                             'specific_unit_type_id' => [$entry->getUnitTypeId()],
  4473.                             'warranty' => 0,
  4474.                             'unitTypeId' => $productData['unitTypeId'],
  4475. //                            'unitTypeId' => $productData['unitTypeId'],
  4476.                             'unit_price' => 0,
  4477.                             'fdm' => $combined_id,
  4478.                             'extDetailsId' => 0,
  4479.                             'product_name' => htmlspecialchars($productData['productName']),
  4480.                             'total_price' => 0,
  4481.                             'detailsIds' => [$entry->getId()],
  4482.                             'docIds' => [$entry->getStockRequisitionId()],
  4483.                         );
  4484.                     }
  4485.                     if (isset($fdmData[$combined_id])) {
  4486.                     } else {
  4487.                     }
  4488.                 }
  4489.             }
  4490.             $QD $this->getDoctrine()
  4491.                 ->getRepository('ApplicationBundle:StockRequisition')
  4492.                 ->findBy(
  4493.                     array('stockRequisitionId' => $request->request->get('srId'))
  4494.                 );
  4495.             $contentNote "";
  4496.             foreach ($QD as $r) {
  4497.                 $contentNote .= $r->getNote();
  4498.                 $contentNote .= " , ";
  4499.             }
  4500.             foreach ($fdmData as $dt) {
  4501.                 $Content[] = $dt;
  4502.             }
  4503.             if ($Content) {
  4504.                 return new JsonResponse(array("success" => true"content" => $Content"contentNote" => $contentNote));
  4505.             }
  4506.             return new JsonResponse(array("success" => false));
  4507.         }
  4508.         return new JsonResponse(array("success" => false));
  4509.     }
  4510.     public function GetGrnListForEiAction(Request $request)
  4511.     {
  4512.         if ($request->isMethod('POST')) {
  4513.             $find_array = array(
  4514.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  4515.                 'approved' => GeneralConstant::APPROVED,
  4516.                 'invoiceTagged' => 1
  4517.             );
  4518.             $Content = [];
  4519.             $Content_obj = [];
  4520.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4521.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4522.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4523.             if ($request->request->get('poId') != '')
  4524.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4525.             if ($request->request->get('grnId') != '')
  4526.                 $find_array['grnId'] = $request->request->get('grnId');
  4527.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4528.             $QD_GRN $this->getDoctrine()
  4529.                 ->getRepository('ApplicationBundle:Grn')
  4530.                 ->findBy(
  4531.                     $find_array,
  4532.                     array(
  4533.                         'grnDate' => 'ASC'
  4534.                     )
  4535.                 );
  4536.             $poId 0;
  4537. //
  4538. //            $expense_id=$QD_GRN->getExpenseId()!=''?json_decode($QD_GRN->getExpenseId()):[];
  4539. //                $expense_list=$QD_GRN->getExpenseCost()!=''?json_decode($QD_GRN->getExpenseCost()):[];
  4540. //                $expense_tagged=$QD_GRN->getExpenseTagged()!=''?json_decode($QD_GRN->getExpenseTagged()):[];
  4541.             $partyId $request->request->get('partyId');
  4542.             $bill_details = [];
  4543.             $bill_details_data = [];
  4544.             $bill_details_for_grn = [];
  4545.             $exp_list InventoryConstant::$Expense_list_details;
  4546.             $supp_list Inventory::ProductSupplierList($this->getDoctrine()->getManager());
  4547.             $head_qry $this->getDoctrine()
  4548.                 ->getRepository('ApplicationBundle:AccAccountsHead')
  4549.                 ->findAll();
  4550.             $head_list = [];
  4551.             $head_list_by_advance = [];
  4552.             foreach ($head_qry as $data) {
  4553.                 $head_list[$data->getAccountsHeadId()] = array(
  4554.                     'id' => $data->getAccountsHeadId(),
  4555.                     'name' => $data->getName(),
  4556.                     'advanceTagged' => $data->getAdvanceTagged(),
  4557.                     'advanceOf' => $data->getAdvanceOf(),
  4558.                     'balance' => $data->getCurrentBalance()
  4559.                 );
  4560.                 if ($data->getAdvanceOf() != null && $data->getAdvanceOf() != && $data->getAdvanceOf() != '')
  4561.                     $head_list_by_advance[$data->getAdvanceOf()] = array(
  4562.                         'id' => $data->getAccountsHeadId(),
  4563.                         'name' => $data->getName(),
  4564.                         'advanceTagged' => $data->getAdvanceTagged(),
  4565.                         'advanceOf' => $data->getAdvanceOf(),
  4566.                         'balance' => $data->getCurrentBalance()
  4567.                     );
  4568.             }
  4569.             $exp_def_head = [];
  4570.             foreach ($exp_list as $key => $item) {
  4571.                 $def_settings $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  4572.                     'name' => $item['name'] . '_onsite_head'
  4573.                 ));
  4574.                 if ($def_settings)
  4575.                     $exp_def_head[$item['id']] = $def_settings->getData();
  4576.                 else
  4577.                     $exp_def_head[$item['id']] = '';
  4578.             }
  4579.             $bill_details_by_party = [];
  4580. //            System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($QD_GRN),'debug_data');
  4581. //            System::log_it($this->container->getParameter('kernel.root_dir'),$partyId,'debug_data');
  4582. //            System::log_it($this->container->getParameter('kernel.root_dir'),"\nexp list here".json_encode($exp_list),'debug_data');
  4583. //
  4584.             foreach ($QD_GRN as $key => $value) {
  4585.                 $expense_id $value->getExpenseId() != '' json_decode($value->getExpenseId(), true) : [];
  4586.                 $expense_list $value->getExpenseCost() != '' json_decode($value->getExpenseCost(), true) : [];
  4587.                 $expense_tagged $value->getExpenseTagged() != '' json_decode($value->getExpenseTagged(), true) : [];
  4588. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_id),'debug_data');
  4589. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_list),'debug_data');
  4590.                 foreach ($exp_list as $chabi => $entry) {
  4591. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nChabi ".$chabi,'debug_data');
  4592. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nkeys are ".array_keys($expense_id),'debug_data');
  4593.                     if (array_key_exists($chabi$expense_id)) {
  4594. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nFOUND KEY!! ",'debug_data');
  4595.                         if ($partyId == ''//all
  4596.                         {
  4597.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  4598.                                 $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  4599.                                 $advance_balance 0;
  4600.                                 if ($partyHeadId != 0) {
  4601.                                     $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  4602.                                     $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  4603.                                     $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  4604.                                 }
  4605.                                 $bill_details_by_party[$my_val][] = array(
  4606.                                     'partyId' => $my_val,
  4607.                                     'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  4608.                                     'partyHeadId' => $partyHeadId,
  4609.                                     'expTypeId' => $chabi,
  4610.                                     'expTypeName' => $exp_list[$chabi]['name'],
  4611.                                     'expTypeAlias' => $exp_list[$chabi]['alias'],
  4612.                                     'expAmount' => $expense_list[$chabi][$index],
  4613.                                     'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  4614.                                     'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  4615.                                     'AdvanceBalance' => $advance_balance,
  4616.                                     'grnId' => $value->getGrnId(),
  4617.                                     'grnName' => $value->getDocumentHash(),
  4618.                                 );
  4619.                             }
  4620.                         } else {
  4621.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  4622.                                 if (in_array($my_val$partyId)) {
  4623.                                     $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  4624.                                     $advance_balance 0;
  4625.                                     if ($partyHeadId != 0) {
  4626.                                         $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  4627.                                         $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  4628.                                         $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  4629.                                     }
  4630.                                     $bill_details_by_party[$my_val][] = array(
  4631.                                         'partyId' => $my_val,
  4632.                                         'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  4633.                                         'partyHeadId' => $partyHeadId,
  4634.                                         'expTypeId' => $chabi,
  4635.                                         'expTypeName' => $exp_list[$chabi]['name'],
  4636.                                         'expTypeAlias' => $exp_list[$chabi]['alias'],
  4637.                                         'expAmount' => $expense_list[$chabi][$index],
  4638.                                         'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  4639.                                         'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  4640.                                         'AdvanceBalance' => $advance_balance,
  4641.                                         'grnId' => $value->getGrnId(),
  4642.                                         'grnName' => $value->getDocumentHash(),
  4643.                                     );
  4644.                                 }
  4645.                             }
  4646.                         }
  4647.                     }
  4648.                 }
  4649.             }
  4650. //            $Content_obj=
  4651. //
  4652. //            foreach($Content_obj as $item)
  4653. //            {
  4654. //                $Content[]=$item;
  4655. //
  4656. //            }
  4657.             $list_of_keys array_keys($bill_details_by_party);
  4658.             if ($bill_details_by_party) {
  4659.                 return new JsonResponse(array("success" => true"content" => $bill_details_by_party'index' => $list_of_keys'h_l_b_a' => $head_list_by_advance));
  4660.             }
  4661.             return new JsonResponse(array("success" => false));
  4662.         }
  4663.         return new JsonResponse(array("success" => false));
  4664.     }
  4665.     public function GetServiceListForPiAction(Request $request)
  4666.     {
  4667.         if ($request->isMethod('POST')) {
  4668. //            $find_array=array(
  4669. //                'stage' =>  GeneralConstant::STAGE_PENDING_TAG,
  4670. //                'approved'=>GeneralConstant::APPROVED
  4671. //            );
  4672.             $Content = [];
  4673.             $Content_obj = [];
  4674.             $ContentService = [];
  4675.             $Content_service_obj = [];
  4676. //            $warehouse=Inventory::WarehouseList($this->getDoctrine()->getManager());
  4677. //            $poList=Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4678. //            $productList=Inventory::ProductList($this->getDoctrine()->getManager());
  4679.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  4680.             if ($request->request->get('poId') != '')
  4681.                 $poId $request->request->get('poId');
  4682.             if ($request->request->get('grnId') != '')
  4683.                 $find_array['grnId'] = $request->request->get('grnId');
  4684.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4685.             //adding service data temporarily
  4686.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(
  4687.                 array('purchaseOrderId' => $poId));
  4688.             $multiply_type $po->getCurrencyMultiply();
  4689.             $multiply_rate $po->getCurrencyMultiplyRate();
  4690.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  4691.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  4692.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4693.                 array('purchaseOrderId' => $poId));
  4694.             foreach ($po_items as $item) {
  4695. //                $po_item_list[$item->getProductId()]=$item;
  4696.                 //temporary service add
  4697.                 if ($item->getType() == 2)
  4698.                     $Content_service_obj[$item->getId()] = array(
  4699.                         'serviceId' => $item->getServiceId(),
  4700.                         'poItemId' => $item->getId(),
  4701.                         'colorId' => 0,
  4702.                         'sizeId' => 0,
  4703.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  4704.                         'qty' => $item->getQty(),
  4705.                         'balance' => $item->getBalance(),
  4706.                         'unit_name' => '',
  4707.                         'unit_price' => $item->getPrice() * $multiplier,
  4708.                         'grn_id' => 0,
  4709.                     );
  4710.                 //temprary service add end
  4711.             }
  4712.             //temporary service data adding done
  4713.             $po_data = [];
  4714.             $po_data = array(
  4715.                 'docHash' => $po->getDocumentHash(),
  4716.                 'docDate' => $po->getPurchaseOrderDate(),
  4717.                 'supplierId' => $po->getSupplierId(),
  4718.                 'supplierName' => $po->getSupplierId(),
  4719.                 'vatRate' => $po->getVatRate(),
  4720.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  4721.                 'aitRate' => $po->getAitRate(),
  4722.                 'aitAmount' => $po->getAitAmount(),
  4723.                 'tdsRate' => $po->getTdsRate(),
  4724.                 'tdsAmount' => $po->getTdsAmount(),
  4725.                 'vdsRate' => $po->getVdsRate(),
  4726.                 'vdsAmount' => $po->getVdsAmount(),
  4727.                 'discountRate' => $po->getDiscountRate(),
  4728.                 'discountAmount' => $po->getVatAmount(),
  4729.             );
  4730.             foreach ($Content_obj as $item) {
  4731.                 $Content[] = $item;
  4732.             }
  4733.             foreach ($Content_service_obj as $item) {
  4734.                 $ContentService[] = $item;
  4735.             }
  4736.             if ($Content || $ContentService) {
  4737.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  4738.             }
  4739.             return new JsonResponse(array("success" => false));
  4740.         }
  4741.         return new JsonResponse(array("success" => false));
  4742.     }
  4743.     public function GetGrnListForPiAction(Request $request)
  4744.     {
  4745.         if ($request->isMethod('POST')) {
  4746.             $find_array = array(
  4747.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  4748.                 'approved' => GeneralConstant::APPROVED
  4749.             );
  4750.             $Content = [];
  4751.             $Content_obj = [];
  4752.             $ContentService = [];
  4753.             $Content_service_obj = [];
  4754.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4755.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4756.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4757.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  4758.             if ($request->request->get('poId') != '')
  4759.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4760.             if ($request->request->get('grnId') != '')
  4761.                 $find_array['grnId'] = $request->request->get('grnId');
  4762.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4763.             $QD_GRN $this->getDoctrine()
  4764.                 ->getRepository('ApplicationBundle:Grn')
  4765.                 ->findBy(
  4766.                     $find_array,
  4767.                     array(
  4768.                         'grnDate' => 'ASC'
  4769.                     )
  4770.                 );
  4771.             $poId 0;
  4772.             foreach ($QD_GRN as $value) {
  4773.                 $grn_items $this->getDoctrine()->getRepository('ApplicationBundle:GrnItem')->findBy(
  4774.                     array('grnId' => $value->getGrnId()));
  4775.                 $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4776.                     array('purchaseOrderId' => $value->getPurchaseOrderId()));
  4777.                 $poId $value->getPurchaseOrderId();
  4778.                 $po_item_list = [];
  4779.                 foreach ($po_items as $item) {
  4780.                     $po_item_list[$item->getProductId()] = $item;
  4781.                 }
  4782.                 foreach ($grn_items as $entry) {
  4783.                     //adding transaction
  4784. //                    System::log_it($this->container->getParameter('kernel.root_dir'),$entry->getProductId(),'debug_data');
  4785.                     $Content_obj[$entry->getId()] = array(
  4786.                         'productId' => $entry->getProductId(),
  4787.                         'poItemId' => $entry->getPurchaseOrderItemId(),
  4788.                         'productName' => $productList[$entry->getProductId()]['name'],
  4789.                         'colorId' => $entry->getColorId(),
  4790.                         'sizeId' => $entry->getSizeId(),
  4791.                         'qty' => isset($Content_obj[$entry->getId()]) ? $Content_obj[$entry->getId()]['qty'] + $entry->getQty() : $entry->getQty(),
  4792.                         'unit_name' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  4793. //                            'unit_price'=>$po_item_list[$entry->getProductId()]->getPrice(),
  4794.                         'unit_price' => $entry->getPrice(),
  4795.                         'grn_id' => $entry->getId(),
  4796.                     );
  4797.                 }
  4798. //            for
  4799.             }
  4800.             //adding service data temporarily
  4801.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(
  4802.                 array('purchaseOrderId' => $poId));
  4803.             $multiply_type $po->getCurrencyMultiply();
  4804.             $multiply_rate $po->getCurrencyMultiplyRate();
  4805.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  4806.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  4807.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4808.                 array('purchaseOrderId' => $poId));
  4809.             foreach ($po_items as $item) {
  4810. //                $po_item_list[$item->getProductId()]=$item;
  4811.                 //temporary service add
  4812.                 if ($item->getType() == 2)
  4813.                     $Content_service_obj[$item->getId()] = array(
  4814.                         'serviceId' => $item->getServiceId(),
  4815.                         'poItemId' => $item->getId(),
  4816.                         'colorId' => 0,
  4817.                         'sizeId' => 0,
  4818.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  4819.                         'qty' => $item->getQty(),
  4820.                         'balance' => $item->getBalance(),
  4821.                         'unit_name' => '',
  4822.                         'unit_price' => $item->getPrice() * $multiplier,
  4823.                         'grn_id' => 0,
  4824.                     );
  4825.                 //temprary service add end
  4826.             }
  4827.             //temporary service data adding done
  4828.             $po_data = [];
  4829.             $vatAmount 1*$po->getVatAmount();
  4830.             $priceAfterDiscount $po->getSupplierPayableAmount() - $po->getVatAmount();
  4831.             $vatRate = ($vatAmount/$priceAfterDiscount)*100;
  4832.             $po_data = array(
  4833.                 'docHash' => $po->getDocumentHash(),
  4834.                 'docDate' => $po->getPurchaseOrderDate(),
  4835.                 'supplierId' => $po->getSupplierId(),
  4836.                 'supplierName' => $po->getSupplierId(),
  4837.                 'vatRate' => $vatRate,
  4838.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  4839.                 'aitRate' => $po->getAitRate(),
  4840.                 'aitAmount' => $po->getAitAmount(),
  4841.                 'tdsRate' => $po->getTdsRate(),
  4842.                 'tdsAmount' => $po->getTdsAmount(),
  4843.                 'vdsRate' => $po->getVdsRate(),
  4844.                 'vdsAmount' => $po->getVdsAmount(),
  4845.                 'discountRate' => $po->getDiscountRate(),
  4846. //                'discountAmount' => $po->getVatAmount(),
  4847.                 'vatAmount' => $vatAmount,
  4848.                 'discountAmount' => $po->getDiscountAmount(),
  4849.                 'supplierPayableAmount'=> $po->getSupplierPayableAmount(),
  4850.                 'priceAfterDiscount' =>  $priceAfterDiscount
  4851.             );
  4852.             foreach ($Content_obj as $item) {
  4853.                 $Content[] = $item;
  4854.             }
  4855.             foreach ($Content_service_obj as $item) {
  4856.                 $ContentService[] = $item;
  4857.             }
  4858.             if ($Content) {
  4859.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  4860.             }
  4861.             return new JsonResponse(array("success" => false));
  4862.         }
  4863.         return new JsonResponse(array("success" => false));
  4864.     }
  4865.     public function GetPoDetailsForPiAction(Request $request$poId)
  4866.     {
  4867.     }
  4868.     public function GetPoDetailsAction(Request $request$poId)
  4869.     {
  4870.         if ($request->isMethod('POST')) {
  4871.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findBy(
  4872.                 array('purchaseOrderId' => $poId));
  4873.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4874.                 array('purchaseOrderId' => $poId));
  4875.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4876.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4877.             $spec_type Inventory::SpecTypeList($this->getDoctrine()->getManager());
  4878.             $Content = [];
  4879.             $po_items_list = [];
  4880.             foreach ($po_items as $entry) {
  4881.                 $po_items_list[] = array(
  4882.                     'productId' => $entry->getProductId(),
  4883.                     'productName' => $productList[$entry->getProductId()]['name'],
  4884.                     'price' => $entry->getPrice(),
  4885.                     'unit' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  4886.                     'spec' => $spec_type[$productList[$entry->getProductId()]['spec_type']]['name'],
  4887.                     'received' => $entry->getReceived(),
  4888.                     'qty' => $entry->getQty(),
  4889.                     'balance' => $entry->getBalance()
  4890.                 );
  4891.             }
  4892.             $po_data = [];
  4893.             $po_data = array(
  4894.                 'docHash' => $po->getDocumentHash(),
  4895.                 'docDate' => $po->getPurchaseOrderDate(),
  4896.                 'supplierId' => $po->getSupplierId(),
  4897.                 'supplierName' => $po->getSupplierId(),
  4898.             );
  4899.             if ($po_data) {
  4900.                 return new JsonResponse(array("success" => true"content" => $po_data));
  4901.             }
  4902.             return new JsonResponse(array("success" => false));
  4903.         }
  4904.         return new JsonResponse(array("success" => false));
  4905.     }
  4906.     public function CreateSalesReplacementAction(Request $request)
  4907.     {
  4908.         $em $this->getDoctrine()->getManager();
  4909.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4910.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4911.         if ($request->isMethod('POST')) {
  4912.             $em $this->getDoctrine()->getManager();
  4913.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesReplacement']; //change
  4914.             $dochash $request->request->get('voucherNumber'); //change
  4915.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4916.             $approveRole $request->request->get('approvalRole');
  4917.             $approveHash $request->request->get('approvalHash');
  4918.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4919.                 $loginId$approveRole$approveHash)
  4920.             ) {
  4921.                 $this->addFlash(
  4922.                     'error',
  4923.                     'Sorry Couldnot insert Data.'
  4924.                 );
  4925.             } else {
  4926.                 if ($request->request->has('check_allowed'))
  4927.                     $check_allowed 1;
  4928.                 $StID Inventory::CreateNewSalesReplacement(
  4929.                     $this->getDoctrine()->getManager(),
  4930.                     $request->request,
  4931.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  4932.                     $this->getLoggedUserCompanyId($request)
  4933.                 );
  4934.                 //now add Approval info
  4935.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4936.                 $approveRole 1;  //created
  4937.                 $options = array(
  4938.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4939.                     'notification_server' => $this->container->getParameter('notification_server'),
  4940.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4941.                     'url' => $this->generateUrl(
  4942.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesReplacement']]
  4943.                         ['entity_view_route_path_name']
  4944.                     )
  4945.                 );
  4946.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4947.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4948.                     $StID,
  4949.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  4950.                 );
  4951.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesReplacement'], $StID,
  4952.                     $loginId,
  4953.                     $approveRole,
  4954.                     $request->request->get('approvalHash'));
  4955.                 $this->addFlash(
  4956.                     'success',
  4957.                     'Stock Transfer Added.'
  4958.                 );
  4959.                 $url $this->generateUrl(
  4960.                     'view_st'
  4961.                 );
  4962.                 return $this->redirect($url "/" $StID);
  4963.             }
  4964.         }
  4965.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  4966.             array(
  4967.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  4968.             )
  4969.         );
  4970.         $INVLIST = [];
  4971.         foreach ($slotList as $slot) {
  4972.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  4973.         }
  4974.         return $this->render('@Inventory/pages/input_forms/sales_replacement.html.twig',
  4975.             array(
  4976.                 'page_title' => 'Sales Replacement Note',
  4977.                 'warehouseList' => Inventory::WarehouseList($em),
  4978.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  4979.                 'warehouseActionList' => $warehouse_action_list,
  4980.                 'warehouseActionListArray' => $warehouse_action_list_array,
  4981.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  4982.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  4983.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  4984.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  4985.                 'prefix_list' => array(
  4986.                     [
  4987.                         'id' => 1,
  4988.                         'value' => 'GN',
  4989.                         'text' => 'GN'
  4990.                     ]
  4991.                 ),
  4992.                 'assoc_list' => array(
  4993.                     [
  4994.                         'id' => 1,
  4995.                         'value' => 1,
  4996.                         'text' => 'GN'
  4997.                     ]
  4998.                 ),
  4999.                 'INVLIST' => $INVLIST
  5000.             )
  5001.         );
  5002.     }
  5003.     public function SalesReplacementListAction(Request $request)
  5004.     {
  5005.         $q $this->getDoctrine()
  5006.             ->getRepository('ApplicationBundle:SalesReplacement')
  5007.             ->findBy(
  5008.                 array(
  5009.                     'status' => GeneralConstant::ACTIVE,
  5010.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5011. //                    'approved' =>  GeneralConstant::APPROVED,
  5012.                 )
  5013.             );
  5014.         $stage_list = array(
  5015.             => 'Pending',
  5016.             => 'Pending',
  5017.             => 'Complete',
  5018.             => 'Partial',
  5019.         );
  5020.         $data = [];
  5021.         foreach ($q as $entry) {
  5022.             $data[] = array(
  5023.                 'doc_date' => $entry->getSalesReplacementDate(),
  5024.                 'id' => $entry->getSalesReplacementId(),
  5025.                 'doc_hash' => $entry->getDocumentHash(),
  5026.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5027.                 'stage' => $stage_list[$entry->getStage()]
  5028.             );
  5029.         }
  5030.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5031.             array(
  5032.                 'page_title' => 'Stock Transfer List',
  5033.                 'data' => $data
  5034.             )
  5035.         );
  5036.     }
  5037.     public function ViewSalesReplacementAction(Request $request$id)
  5038.     {
  5039.         $em $this->getDoctrine()->getManager();
  5040.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5041.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  5042.             array(
  5043.                 'page_title' => 'Stock Transfer',
  5044.                 'data' => $dt,
  5045.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5046.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5047.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5048.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5049.                     $id,
  5050.                     $dt['created_by'],
  5051.                     $dt['edited_by'])
  5052.             )
  5053.         );
  5054.     }
  5055.     public function PrintSalesReplacementAction(Request $request$id)
  5056.     {
  5057.         $em $this->getDoctrine()->getManager();
  5058.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5059.         $company_data Company::getCompanyData($em1);
  5060.         $document_mark = array(
  5061.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5062.             'copy' => ''
  5063.         );
  5064.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5065.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5066.                 array(
  5067.                     //full array here
  5068.                     'pdf' => true,
  5069.                     'page_title' => 'Stock Transfer',
  5070.                     'export' => 'pdf,print',
  5071.                     'data' => $dt,
  5072.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5073.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5074.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5075.                         array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5076.                         $id,
  5077.                         $dt['created_by'],
  5078.                         $dt['edited_by']),
  5079.                     'document_mark_image' => $document_mark['original'],
  5080.                     'company_name' => $company_data->getName(),
  5081.                     'company_data' => $company_data,
  5082.                     'company_address' => $company_data->getAddress(),
  5083.                     'company_image' => $company_data->getImage(),
  5084.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5085.                     'red' => 0
  5086.                 )
  5087.             );
  5088.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5089. //                'orientation' => 'landscape',
  5090. //                'enable-javascript' => true,
  5091. //                'javascript-delay' => 1000,
  5092.                 'no-stop-slow-scripts' => false,
  5093.                 'no-background' => false,
  5094.                 'lowquality' => false,
  5095.                 'encoding' => 'utf-8',
  5096. //            'images' => true,
  5097. //            'cookie' => array(),
  5098.                 'dpi' => 300,
  5099.                 'image-dpi' => 300,
  5100. //                'enable-external-links' => true,
  5101. //                'enable-internal-links' => true
  5102.             ));
  5103.             return new Response(
  5104.                 $pdf_response,
  5105.                 200,
  5106.                 array(
  5107.                     'Content-Type' => 'application/pdf',
  5108.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5109.                 )
  5110.             );
  5111.         }
  5112.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5113.             array(
  5114.                 'page_title' => 'Stock Transfer',
  5115.                 'export' => 'pdf,print',
  5116.                 'data' => $dt,
  5117.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5118.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5119.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5120.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5121.                     $id,
  5122.                     $dt['created_by'],
  5123.                     $dt['edited_by']),
  5124.                 'document_mark_image' => $document_mark['original'],
  5125.                 'company_name' => $company_data->getName(),
  5126.                 'company_data' => $company_data,
  5127.                 'company_address' => $company_data->getAddress(),
  5128.                 'company_image' => $company_data->getImage(),
  5129.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5130.                 'red' => 0
  5131.             )
  5132.         );
  5133.     }
  5134.     public function CreateStockTransferAction(Request $request)
  5135.     {
  5136.         $em $this->getDoctrine()->getManager();
  5137.         $companyId $this->getLoggedUserCompanyId($request);
  5138.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5139.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5140.         if ($request->isMethod('POST')) {
  5141.             $em $this->getDoctrine()->getManager();
  5142.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  5143.             $dochash $request->request->get('docHash'); //change
  5144.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5145.             $approveRole $request->request->get('approvalRole');
  5146.             $approveHash $request->request->get('approvalHash');
  5147.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5148.                 $loginId$approveRole$approveHash)
  5149.             ) {
  5150.                 $this->addFlash(
  5151.                     'error',
  5152.                     'Sorry Couldnot insert Data.'
  5153.                 );
  5154.             } else {
  5155.                 if ($request->request->has('check_allowed'))
  5156.                     $check_allowed 1;
  5157.                 $StID Inventory::CreateNewStockTransfer(
  5158.                     $this->getDoctrine()->getManager(),
  5159.                     $request->request,
  5160.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5161.                     $this->getLoggedUserCompanyId($request)
  5162.                 );
  5163.                 //now add Approval info
  5164.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5165.                 $approveRole 1;  //created
  5166.                 $options = array(
  5167.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5168.                     'notification_server' => $this->container->getParameter('notification_server'),
  5169.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5170.                     'url' => $this->generateUrl(
  5171.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  5172.                         ['entity_view_route_path_name']
  5173.                     )
  5174.                 );
  5175.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5176.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5177.                     $StID,
  5178.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  5179.                 );
  5180.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  5181.                     $loginId,
  5182.                     $approveRole,
  5183.                     $request->request->get('approvalHash'));
  5184.                 $this->addFlash(
  5185.                     'success',
  5186.                     'Stock Transfer Added.'
  5187.                 );
  5188.                 $url $this->generateUrl(
  5189.                     'view_st'
  5190.                 );
  5191.                 return $this->redirect($url "/" $StID);
  5192.             }
  5193.         }
  5194. //        $slotList = $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5195. //            array(
  5196. //                'CompanyId' => $this->getLoggedUserCompanyId($request),
  5197. //
  5198. //            )
  5199. //        );
  5200.         $INVLIST = [];
  5201. //        foreach ($slotList as $slot) {
  5202. //            $INVLIST[$slot->getWarehouseId() . '_' . $slot->getActionTagId() . '_' . $slot->getproductId()] = $slot->getQty();
  5203. //        }
  5204.         return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  5205.             array(
  5206.                 'page_title' => 'Stock Transfer Note',
  5207.                 'warehouseList' => Inventory::WarehouseList($em),
  5208.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5209.                 'colorList' => Inventory::GetColorList($em),
  5210.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  5211.                 'srList' => [],
  5212.                 'warehouseActionList' => $warehouse_action_list,
  5213.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5214.                 'item_list' => Inventory::ItemGroupList($em),
  5215.                 'item_list_array' => Inventory::ItemGroupListArray($em),
  5216.                 'category_list_array' => Inventory::ProductCategoryListArray($em),
  5217.                 'product_list_array' => Inventory::ProductListDetailedArray($em),
  5218. //                'product_list_array' => [],
  5219.                 'product_list' => Inventory::ProductList($em$companyId),
  5220. //                'product_list' => [],
  5221.                 'prefix_list' => array(
  5222.                     [
  5223.                         'id' => 1,
  5224.                         'value' => 'GN',
  5225.                         'text' => 'GN'
  5226.                     ]
  5227.                 ),
  5228.                 'assoc_list' => array(
  5229.                     [
  5230.                         'id' => 1,
  5231.                         'value' => 1,
  5232.                         'text' => 'GN'
  5233.                     ]
  5234.                 ),
  5235.                 'INVLIST' => $INVLIST
  5236.             )
  5237.         );
  5238.     }
  5239.     public function GetSrItemForTransferAction(Request $request)
  5240.     {
  5241.         $em $this->getDoctrine()->getManager();
  5242.         $search_query = [];
  5243.         $res_data_by_so_item_id = [];
  5244.         $Content = [];
  5245.         $productionProcessSettings = array(
  5246.             'id' => 0
  5247.         );
  5248.         if ($request->query->has('srId'))
  5249.             $search_query['stockRequisitionId'] = $request->query->get('srId');
  5250.         $DT $this->getDoctrine()
  5251.             ->getRepository('ApplicationBundle:StockRequisitionItem')
  5252.             ->findBy(
  5253.                 $search_query
  5254.             );
  5255.         $Content = array(
  5256.             'requisitioned_product_item_id' => [],
  5257.             'requisitioned_products' => [],
  5258.             'requisitioned_product_fdm' => [],
  5259.             'requisitioned_product_name' => [],
  5260.             'requisitioned_product_units' => [],
  5261.             'requisitioned_product_unit_type' => [],
  5262.             'requisitioned_product_balance' => [],
  5263.         );
  5264.         foreach ($DT as $dt) {
  5265. //            $data=json_decode($DT->getData(),true);
  5266.             $Content['requisitioned_products'][] = $dt->getProductId();
  5267.             $Content['requisitioned_product_item_id'][] = $dt->getId();
  5268.             $Content['requisitioned_product_fdm'][] = $dt->getProductFdm();
  5269.             $Content['requisitioned_product_name'][] = $dt->getProductNameFdm();
  5270.             $Content['requisitioned_product_units'][] = $dt->getQty();
  5271.             $Content['requisitioned_product_balance'][] = $dt->getAlottmentPendingAmount();
  5272.         }
  5273.         $INVLIST = [];
  5274.         if (!empty($Content)) {
  5275.             return new JsonResponse(array("success" => true"content" => $Content"INVLIST" => $INVLIST));
  5276.         } else {
  5277.             return new JsonResponse(array("success" => false"content" => $Content"INVLIST" => $INVLIST));
  5278.         }
  5279.     }
  5280.     public function StockTransferListAction(Request $request)
  5281.     {
  5282.         $q $this->getDoctrine()
  5283.             ->getRepository('ApplicationBundle:StockTransfer')
  5284.             ->findBy(
  5285.                 array(
  5286.                     'status' => GeneralConstant::ACTIVE,
  5287.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5288. //                    'approved' =>  GeneralConstant::APPROVED,
  5289.                 )
  5290.             );
  5291.         $stage_list = array(
  5292.             => 'Pending',
  5293.             => 'Pending',
  5294.             => 'Complete',
  5295.             => 'Partial',
  5296.         );
  5297.         $data = [];
  5298.         foreach ($q as $entry) {
  5299.             $data[] = array(
  5300.                 'doc_date' => $entry->getStockTransferDate(),
  5301.                 'id' => $entry->getStockTransferId(),
  5302.                 'doc_hash' => $entry->getDocumentHash(),
  5303.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5304.                 'stage' => $stage_list[$entry->getStage()]
  5305.             );
  5306.         }
  5307.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5308.             array(
  5309.                 'page_title' => 'Stock Transfer List',
  5310.                 'data' => $data
  5311.             )
  5312.         );
  5313.     }
  5314.     public function ViewStockTransferAction(Request $request$id)
  5315.     {
  5316.         $em $this->getDoctrine()->getManager();
  5317.         $dt Inventory::GetStockTransferDetails($em$id);
  5318.         return $this->render(
  5319.             '@Inventory/pages/views/view_stock_transfer.html.twig',
  5320.             array(
  5321.                 'page_title' => 'Stock Transfer',
  5322.                 'data' => $dt,
  5323.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5324.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5325.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5326.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5327.                     $id,
  5328.                     $dt['created_by'],
  5329.                     $dt['edited_by'])
  5330.             )
  5331.         );
  5332.     }
  5333.     public function PrintStockTransferAction(Request $request$id)
  5334.     {
  5335.         $em $this->getDoctrine()->getManager();
  5336.         $dt Inventory::GetStockTransferDetails($em$id);
  5337.         $company_data Company::getCompanyData($em1);
  5338.         $document_mark = array(
  5339.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5340.             'copy' => ''
  5341.         );
  5342.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5343.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5344.                 array(
  5345.                     //full array here
  5346.                     'pdf' => true,
  5347.                     'page_title' => 'Stock Transfer',
  5348.                     'export' => 'pdf,print',
  5349.                     'data' => $dt,
  5350.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5351.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5352.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5353.                         array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5354.                         $id,
  5355.                         $dt['created_by'],
  5356.                         $dt['edited_by']),
  5357.                     'document_mark_image' => $document_mark['original'],
  5358.                     'company_name' => $company_data->getName(),
  5359.                     'company_data' => $company_data,
  5360.                     'company_address' => $company_data->getAddress(),
  5361.                     'company_image' => $company_data->getImage(),
  5362.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5363.                     'red' => 0
  5364.                 )
  5365.             );
  5366.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5367. //                'orientation' => 'landscape',
  5368. //                'enable-javascript' => true,
  5369. //                'javascript-delay' => 1000,
  5370.                 'no-stop-slow-scripts' => false,
  5371.                 'no-background' => false,
  5372.                 'lowquality' => false,
  5373.                 'encoding' => 'utf-8',
  5374. //            'images' => true,
  5375. //            'cookie' => array(),
  5376.                 'dpi' => 300,
  5377.                 'image-dpi' => 300,
  5378. //                'enable-external-links' => true,
  5379. //                'enable-internal-links' => true
  5380.             ));
  5381.             return new Response(
  5382.                 $pdf_response,
  5383.                 200,
  5384.                 array(
  5385.                     'Content-Type' => 'application/pdf',
  5386.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5387.                 )
  5388.             );
  5389.         }
  5390.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5391.             array(
  5392.                 'page_title' => 'Stock Transfer',
  5393.                 'export' => 'pdf,print',
  5394.                 'data' => $dt,
  5395.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5396.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5397.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5398.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5399.                     $id,
  5400.                     $dt['created_by'],
  5401.                     $dt['edited_by']),
  5402.                 'document_mark_image' => $document_mark['original'],
  5403.                 'company_name' => $company_data->getName(),
  5404.                 'company_data' => $company_data,
  5405.                 'company_address' => $company_data->getAddress(),
  5406.                 'company_image' => $company_data->getImage(),
  5407.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5408.                 'red' => 0
  5409.             )
  5410.         );
  5411.     }
  5412.     public function CreateStockConsumptionNoteAction(Request $request)
  5413.     {
  5414.         $em $this->getDoctrine()->getManager();
  5415.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5416.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5417.         if ($request->isMethod('POST')) {
  5418.             $em $this->getDoctrine()->getManager();
  5419.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']; //change
  5420.             $dochash $request->request->get('voucherNumber'); //change
  5421.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5422.             $approveRole $request->request->get('approvalRole');
  5423.             $approveHash $request->request->get('approvalHash');
  5424.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5425.                 $loginId$approveRole$approveHash)
  5426.             ) {
  5427.                 $this->addFlash(
  5428.                     'error',
  5429.                     'Sorry Could not insert Data.'
  5430.                 );
  5431.             } else {
  5432.                 if ($request->request->has('check_allowed'))
  5433.                     $check_allowed 1;
  5434.                 $StID Inventory::CreateNewStockConsumptionNote(
  5435.                     $this->getDoctrine()->getManager(),
  5436.                     $request->request,
  5437.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5438.                     $this->getLoggedUserCompanyId($request)
  5439.                 );
  5440.                 //now add Approval info
  5441.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5442.                 $approveRole 1;  //created
  5443.                 $options = array(
  5444.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5445.                     'notification_server' => $this->container->getParameter('notification_server'),
  5446.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5447.                     'url' => $this->generateUrl(
  5448.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']]
  5449.                         ['entity_view_route_path_name']
  5450.                     )
  5451.                 );
  5452.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5453.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5454.                     $StID,
  5455.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5456.                 );
  5457.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'], $StID,
  5458.                     $loginId,
  5459.                     $approveRole,
  5460.                     $request->request->get('approvalHash'));
  5461.                 $this->addFlash(
  5462.                     'success',
  5463.                     'Stock Consumption Added.'
  5464.                 );
  5465.                 $url $this->generateUrl(
  5466.                     'view_stock_consumption_note'
  5467.                 );
  5468.                 return $this->redirect($url "/" $StID);
  5469.             }
  5470.         }
  5471.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5472.             array(
  5473.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5474.             )
  5475.         );
  5476.         $INVLIST = [];
  5477.         foreach ($slotList as $slot) {
  5478.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5479.         }
  5480.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5481.             array(
  5482.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5483.             )
  5484.         );
  5485.         $consumptionTypeList = [];
  5486.         $consumptionTypeListArray = [];
  5487.         foreach ($consumptionTypeQry as $entry) {
  5488.             $p = array(
  5489.                 'name' => $entry->getName(),
  5490.                 'id' => $entry->getConsumptionTypeId(),
  5491.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5492.                 'cost_center_id' => $entry->getCostCenterId(),
  5493.             );
  5494.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5495.             $consumptionTypeListArray[] = $p;
  5496.         }
  5497.         //add bill list
  5498.         $service_purchase_bill_query $this->getDoctrine()
  5499.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5500.             ->findBy(
  5501.                 array(
  5502.                     'typeHash' => 'SPB',
  5503.                     'approved' => GeneralConstant::APPROVED
  5504.                 )
  5505.             );
  5506.         $service_purchase_bill_list = [];
  5507.         $service_purchase_bill_list_array = [];
  5508.         $bill = array(
  5509.             'id' => 0,
  5510.             'type' => 'SPB',
  5511.             'name' => 'New Expense',
  5512.             'text' => 'New Expense',
  5513.             'amount' => 0,
  5514.         );
  5515.         $service_purchase_bill_list[0] = $bill;
  5516.         $service_purchase_bill_list_array[] = $bill;
  5517.         foreach ($service_purchase_bill_query as $d) {
  5518.             $bill = array(
  5519.                 'id' => $d->getPurchaseInvoiceId(),
  5520.                 'type' => 'SPB',
  5521.                 'name' => $d->getDocumentHash(),
  5522.                 'text' => $d->getDocumentHash(),
  5523.                 'amount' => $d->getInvoiceAmount(),
  5524.             );
  5525.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5526.             $service_purchase_bill_list_array[] = $bill;
  5527.         }
  5528.         return $this->render('@Inventory/pages/input_forms/stock_consumption_note.html.twig',
  5529.             array(
  5530.                 'page_title' => 'Stock Consumption Note',
  5531.                 'warehouseList' => Inventory::WarehouseList($em),
  5532.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5533.                 'consumptionTypeList' => $consumptionTypeList,
  5534.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5535.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5536.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5537.                 'warehouseActionList' => $warehouse_action_list,
  5538.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5539.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5540.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5541.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5542.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5543.                 'product_list' => Inventory::ProductListDetailed($this->getDoctrine()->getManager()),
  5544.                 'prefix_list' => array(
  5545.                     [
  5546.                         'id' => 1,
  5547.                         'value' => 'GN',
  5548.                         'text' => 'GN'
  5549.                     ]
  5550.                 ),
  5551.                 'assoc_list' => array(
  5552.                     [
  5553.                         'id' => 1,
  5554.                         'value' => 1,
  5555.                         'text' => 'GN'
  5556.                     ]
  5557.                 ),
  5558.                 'INVLIST' => $INVLIST
  5559.             )
  5560.         );
  5561.     }
  5562.     public function StockConsumptionNoteListAction(Request $request)
  5563.     {
  5564.         $q $this->getDoctrine()
  5565.             ->getRepository('ApplicationBundle:StockConsumptionNote')
  5566.             ->findBy(
  5567.                 array(
  5568.                     'status' => GeneralConstant::ACTIVE,
  5569.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5570. //                    'approved' =>  GeneralConstant::APPROVED,
  5571.                 )
  5572.             );
  5573.         $stage_list = array(
  5574.             => 'Pending',
  5575.             => 'Pending',
  5576.             => 'Complete',
  5577.             => 'Partial',
  5578.         );
  5579.         $data = [];
  5580.         foreach ($q as $entry) {
  5581.             $data[] = array(
  5582.                 'doc_date' => $entry->getStockConsumptionNoteDate(),
  5583.                 'id' => $entry->getStockConsumptionNoteId(),
  5584.                 'doc_hash' => $entry->getDocumentHash(),
  5585.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5586.                 'stage' => $stage_list[$entry->getStage()]
  5587.             );
  5588.         }
  5589.         return $this->render('@Inventory/pages/views/stock_consumption_note_list.html.twig',
  5590.             array(
  5591.                 'page_title' => 'Stock Consumption Note List',
  5592.                 'data' => $data
  5593.             )
  5594.         );
  5595.     }
  5596.     public function ViewStockConsumptionNoteAction(Request $request$id)
  5597.     {
  5598.         $em $this->getDoctrine()->getManager();
  5599.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5600.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5601.             array(
  5602.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5603.             )
  5604.         );
  5605.         $consumptionTypeList = [];
  5606.         $consumptionTypeListArray = [];
  5607.         foreach ($consumptionTypeQry as $entry) {
  5608.             $p = array(
  5609.                 'name' => $entry->getName(),
  5610.                 'id' => $entry->getConsumptionTypeId(),
  5611.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5612.                 'cost_center_id' => $entry->getCostCenterId(),
  5613.             );
  5614.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5615.             $consumptionTypeListArray[] = $p;
  5616.         }
  5617.         //add bill list
  5618.         $service_purchase_bill_query $this->getDoctrine()
  5619.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5620.             ->findBy(
  5621.                 array(
  5622.                     'typeHash' => 'SPB',
  5623.                     'approved' => GeneralConstant::APPROVED
  5624.                 )
  5625.             );
  5626.         $service_purchase_bill_list = [];
  5627.         $service_purchase_bill_list_array = [];
  5628.         $bill = array(
  5629.             'id' => 0,
  5630.             'type' => 'SPB',
  5631.             'name' => 'New Expense',
  5632.             'text' => 'New Expense',
  5633.             'amount' => 0,
  5634.         );
  5635.         $service_purchase_bill_list[0] = $bill;
  5636.         $service_purchase_bill_list_array[] = $bill;
  5637.         foreach ($service_purchase_bill_query as $d) {
  5638.             $bill = array(
  5639.                 'id' => $d->getPurchaseInvoiceId(),
  5640.                 'type' => 'SPB',
  5641.                 'name' => $d->getDocumentHash(),
  5642.                 'text' => $d->getDocumentHash(),
  5643.                 'amount' => $d->getInvoiceAmount(),
  5644.             );
  5645.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5646.             $service_purchase_bill_list_array[] = $bill;
  5647.         }
  5648.         return $this->render(
  5649.             '@Inventory/pages/views/view_stock_consumption_note.html.twig',
  5650.             array(
  5651.                 'page_title' => 'Stock Transfer',
  5652.                 'data' => $dt,
  5653.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5654.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5655.                 'consumptionTypeList' => $consumptionTypeList,
  5656.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5657.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5658.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5659.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5660.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5661.                     $id,
  5662.                     $dt['created_by'],
  5663.                     $dt['edited_by'])
  5664.             )
  5665.         );
  5666.     }
  5667.     public function PrintStockConsumptionNoteAction(Request $request$id)
  5668.     {
  5669.         $em $this->getDoctrine()->getManager();
  5670.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5671.         $company_data Company::getCompanyData($em1);
  5672.         $document_mark = array(
  5673.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5674.             'copy' => ''
  5675.         );
  5676.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5677.             array(
  5678.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5679.             )
  5680.         );
  5681.         $consumptionTypeList = [];
  5682.         $consumptionTypeListArray = [];
  5683.         foreach ($consumptionTypeQry as $entry) {
  5684.             $p = array(
  5685.                 'name' => $entry->getName(),
  5686.                 'id' => $entry->getConsumptionTypeId(),
  5687.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5688.                 'cost_center_id' => $entry->getCostCenterId(),
  5689.             );
  5690.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5691.             $consumptionTypeListArray[] = $p;
  5692.         }
  5693.         //add bill list
  5694.         $service_purchase_bill_query $this->getDoctrine()
  5695.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5696.             ->findBy(
  5697.                 array(
  5698.                     'typeHash' => 'SPB',
  5699.                     'approved' => GeneralConstant::APPROVED
  5700.                 )
  5701.             );
  5702.         $service_purchase_bill_list = [];
  5703.         $service_purchase_bill_list_array = [];
  5704.         $bill = array(
  5705.             'id' => 0,
  5706.             'type' => 'SPB',
  5707.             'name' => 'New Expense',
  5708.             'text' => 'New Expense',
  5709.             'amount' => 0,
  5710.         );
  5711.         $service_purchase_bill_list[0] = $bill;
  5712.         $service_purchase_bill_list_array[] = $bill;
  5713.         foreach ($service_purchase_bill_query as $d) {
  5714.             $bill = array(
  5715.                 'id' => $d->getPurchaseInvoiceId(),
  5716.                 'type' => 'SPB',
  5717.                 'name' => $d->getDocumentHash(),
  5718.                 'text' => $d->getDocumentHash(),
  5719.                 'amount' => $d->getInvoiceAmount(),
  5720.             );
  5721.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5722.             $service_purchase_bill_list_array[] = $bill;
  5723.         }
  5724.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5725.             $html $this->renderView('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  5726.                 array(
  5727.                     //full array here
  5728.                     'pdf' => true,
  5729.                     'page_title' => 'Stock Consumption',
  5730.                     'export' => 'pdf,print',
  5731.                     'data' => $dt,
  5732.                     'service_purchase_bill_list' => $service_purchase_bill_list,
  5733.                     'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5734.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5735.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5736.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5737.                         array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5738.                         $id,
  5739.                         $dt['created_by'],
  5740.                         $dt['edited_by']),
  5741.                     'document_mark_image' => $document_mark['original'],
  5742.                     'consumptionTypeList' => $consumptionTypeList,
  5743.                     'consumptionTypeListArray' => $consumptionTypeListArray,
  5744.                     'company_name' => $company_data->getName(),
  5745.                     'company_data' => $company_data,
  5746.                     'company_address' => $company_data->getAddress(),
  5747.                     'company_image' => $company_data->getImage(),
  5748.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5749.                     'red' => 0
  5750.                 )
  5751.             );
  5752.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5753. //                'orientation' => 'landscape',
  5754. //                'enable-javascript' => true,
  5755. //                'javascript-delay' => 1000,
  5756.                 'no-stop-slow-scripts' => false,
  5757.                 'no-background' => false,
  5758.                 'lowquality' => false,
  5759.                 'encoding' => 'utf-8',
  5760. //            'images' => true,
  5761. //            'cookie' => array(),
  5762.                 'dpi' => 300,
  5763.                 'image-dpi' => 300,
  5764. //                'enable-external-links' => true,
  5765. //                'enable-internal-links' => true
  5766.             ));
  5767.             return new Response(
  5768.                 $pdf_response,
  5769.                 200,
  5770.                 array(
  5771.                     'Content-Type' => 'application/pdf',
  5772.                     'Content-Disposition' => 'attachment; filename="stock_consumption_note_' $id '.pdf"'
  5773.                 )
  5774.             );
  5775.         }
  5776.         return $this->render('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  5777.             array(
  5778.                 'page_title' => 'Stock Consumption',
  5779.                 'export' => 'pdf,print',
  5780.                 'data' => $dt,
  5781.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5782.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5783.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5784.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5785.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5786.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5787.                     $id,
  5788.                     $dt['created_by'],
  5789.                     $dt['edited_by']),
  5790.                 'document_mark_image' => $document_mark['original'],
  5791.                 'consumptionTypeList' => $consumptionTypeList,
  5792.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5793.                 'company_name' => $company_data->getName(),
  5794.                 'company_data' => $company_data,
  5795.                 'company_address' => $company_data->getAddress(),
  5796.                 'company_image' => $company_data->getImage(),
  5797.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5798.                 'red' => 0
  5799.             )
  5800.         );
  5801.     }
  5802.     public function CreateStockReceivedNoteAction(Request $request$id 0)
  5803.     {
  5804.         $em $this->getDoctrine()->getManager();
  5805.         $companyId $this->getLoggedUserCompanyId($request);
  5806.         $extDocData = [];
  5807.         $userId $request->getSession()->get(UserConstants::USER_ID);
  5808.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  5809.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  5810. //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  5811.         $userBranchIdList $request->getSession()->get('branchIdList');
  5812.         if ($userBranchIdList == null$userBranchIdList = [];
  5813.         $userBranchId $request->getSession()->get('branchId');
  5814.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  5815.             $em $this->getDoctrine()->getManager();
  5816.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //change
  5817.             $dochash $request->request->get('docHash'); //change
  5818.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5819.             $approveRole $request->request->get('approvalRole');
  5820.             $approveHash $request->request->get('approvalHash');
  5821.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5822.                 $loginId$approveRole$approveHash$id)
  5823.             ) {
  5824.                 if ($request->request->has('returnJson')) {
  5825.                     return new JsonResponse(array(
  5826.                         'success' => false,
  5827.                         'documentHash' => 0,
  5828.                         'documentId' => 0,
  5829.                         'billIds' => [],
  5830.                         'drIds' => [],
  5831.                         'pmntTransIds' => [],
  5832.                         'viewUrl' => '',
  5833.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  5834.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  5835.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  5836.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  5837.                     ));
  5838.                 } else
  5839.                     $this->addFlash(
  5840.                         'error',
  5841.                         'Sorry Could not insert Data.'
  5842.                     );
  5843.             } else {
  5844.                 if ($request->request->has('check_allowed'))
  5845.                     $check_allowed 1;
  5846.                 $StID Inventory::CreateNewStockReceivedNote(
  5847.                     $this->getDoctrine()->getManager(),
  5848.                     $request->request,
  5849.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5850.                     $this->getLoggedUserCompanyId($request)
  5851.                 );
  5852.                 //now add Approval info
  5853.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5854.                 $approveRole 1;  //created
  5855.                 $options = array(
  5856.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5857.                     'notification_server' => $this->container->getParameter('notification_server'),
  5858.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5859.                     'url' => $this->generateUrl(
  5860.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  5861.                         ['entity_view_route_path_name']
  5862.                     )
  5863.                 );
  5864.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5865.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5866.                     $StID,
  5867.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5868.                 );
  5869.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  5870.                     $loginId,
  5871.                     $approveRole,
  5872.                     $request->request->get('approvalHash'));
  5873.                 $url $this->generateUrl(
  5874.                     'view_srcv'
  5875.                 );
  5876.                 if ($request->request->has('returnJson')) {
  5877.                     return new JsonResponse(array(
  5878.                         'success' => true,
  5879.                         'documentHash' => $dochash,
  5880.                         'documentId' => $StID,
  5881.                         'viewUrl' => $url "/" $StID,
  5882.                     ));
  5883.                 } else {
  5884.                     $this->addFlash(
  5885.                         'success',
  5886.                         'Stock Received Note Added.'
  5887.                     );
  5888.                     return $this->redirect($url "/" $StID);
  5889.                 }
  5890.             }
  5891.         }
  5892.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5893.             array(
  5894.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5895.             )
  5896.         );
  5897.         if ($id == 0) {
  5898.         } else {
  5899.             $extDoc $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  5900.                 array(
  5901.                     'salesOrderId' => $id///material
  5902.                 )
  5903.             );
  5904.             //now if its not editable, redirect to view
  5905.             if ($extDoc) {
  5906.                 if ($extDoc->getEditFlag() != 1) {
  5907.                     $url $this->generateUrl(
  5908.                         'view_srcv'
  5909.                     );
  5910.                     return $this->redirect($url "/" $id);
  5911.                 } else {
  5912.                     $extDocData $extDoc;
  5913.                     $extDocDataDetails $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findOneBy(
  5914.                         array(
  5915.                             'stockReceivedNoteId' => $id///material
  5916.                         )
  5917.                     );
  5918.                 }
  5919.             } else {
  5920.             }
  5921.         }
  5922.         $INVLIST = [];
  5923.         foreach ($slotList as $slot) {
  5924.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5925.         }
  5926.         $dataArray = array(
  5927.             'page_title' => 'Stock Received Note',
  5928. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  5929.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  5930.             'users' => Users::getUserListById($em),
  5931.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  5932.             'warehouseList' => Inventory::WarehouseList($em),
  5933.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  5934.             'warehouseActionList' => $warehouse_action_list,
  5935.             'warehouseActionListArray' => $warehouse_action_list_array,
  5936.             'extDocData' => $extDocData,
  5937.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  5938.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5939.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5940.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5941. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5942. //            'product_list' => Inventory::ProductList($em, $companyId),
  5943.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  5944.             'prefix_list' => array(
  5945.                 [
  5946.                     'id' => 1,
  5947.                     'value' => 'GN',
  5948.                     'text' => 'GN'
  5949.                 ]
  5950.             ),
  5951.             'assoc_list' => array(
  5952.                 [
  5953.                     'id' => 1,
  5954.                     'value' => 1,
  5955.                     'text' => 'GN'
  5956.                 ]
  5957.             ),
  5958.             'INVLIST' => $INVLIST,
  5959.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  5960.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  5961.             'userBranchIdList' => $userBranchIdList,
  5962.             'userBranchId' => $userBranchId,
  5963. //            'headList' => Accounts::HeadList($em),
  5964.         );
  5965.         //json
  5966.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  5967.         {
  5968.             $dataArray['success'] = true;
  5969.             return new JsonResponse(
  5970.                 $dataArray
  5971.             );
  5972.         }
  5973.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  5974.             $dataArray
  5975.         );
  5976.     }
  5977.     public function GetItemListForStockReceivedAction(Request $request)
  5978.     {
  5979.         if ($request->isMethod('POST')) {
  5980.             $em $this->getDoctrine();
  5981.             $receiveType 1;//transfer
  5982.             if ($request->request->has('receiveType'))
  5983.                 $receiveType $request->request->get('receiveType');
  5984.             $QD = [];
  5985.             if ($receiveType == 1)
  5986.                 $QD $this->getDoctrine()
  5987.                     ->getRepository('ApplicationBundle:StockTransferItem')
  5988.                     ->findBy(
  5989.                         array(
  5990. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  5991.                             'stockTransferId' => $request->request->get('stId')
  5992.                         ),
  5993.                         array()
  5994.                     );
  5995.             if ($receiveType == 2)
  5996.                 $QD $this->getDoctrine()
  5997.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  5998.                     ->findBy(
  5999.                         array(
  6000. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  6001.                             'salesOrderId' => $request->request->get('soId')
  6002.                         ),
  6003.                         array()
  6004.                     );
  6005. //            if($request->request->get('wareHouseId')!='')
  6006. //
  6007. //            $DO=$this->getDoctrine()
  6008. //                ->getRepository('ApplicationBundle:DeliveryOrder')
  6009. //                ->findOneBy(
  6010. //                    $find_array,
  6011. //                    array(
  6012. //
  6013. //                    )
  6014. //                );
  6015.             $sendData = array(
  6016. //                'salesType'=>$SO->getSalesType(),
  6017. //                'packageData'=>[],
  6018.                 'productList' => [],
  6019. //                'productListByPackage'=>[],
  6020.             );
  6021.             $productList Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request));
  6022.             $pckg_item_cross_match_data = [];
  6023.             foreach ($QD as $product) {
  6024. //                $b_code=json_decode($product->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  6025.                 $b_code = [];
  6026.                 $newProductId $product->getProductId();
  6027.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  6028.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6029.                     if ($to_analyze_codes_str != null)
  6030.                         $b_code json_decode($to_analyze_codes_strtrue512JSON_BIGINT_AS_STRING);
  6031.                     else
  6032.                         $b_code = [];
  6033.                 } else {
  6034.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6035.                     if ($to_analyze_codes_str != null) {
  6036.                         $max_int_length strlen((string)PHP_INT_MAX) - 1;
  6037.                         $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$to_analyze_codes_str);
  6038.                         $b_code json_decode($json_without_bigintstrue);
  6039.                     } else {
  6040.                         $b_code = [];
  6041.                     }
  6042.                 }
  6043.                 $b_code_data = [];
  6044.                 foreach ($b_code as $d) {
  6045.                     $b_code_data[] = array(
  6046.                         'id' => $d,
  6047.                         'name' => str_pad($d13'0'STR_PAD_LEFT),
  6048.                     );
  6049.                 }
  6050.                 $p_data = array(
  6051.                     'details_id' => $product->getId(),
  6052.                     'productId' => $product->getProductId(),
  6053.                     'product_name' => isset($productList[$product->getProductId()]) ? $productList[$product->getProductId()]['name'] : 'Unknown Product',
  6054.                     'product_barcodes' => $b_code_data,
  6055. //                    'available_inventory'=>$inventory_by_warehouse?$inventory_by_warehouse->getQty():0,
  6056. //                        'package_id'=>$product->getPackageId(),
  6057.                     'qty' => $receiveType == $product->getQty() : $product->getToBeReceived(),
  6058.                     'unit_price' => $receiveType == $product->getPrice() : $productList[$product->getProductId()]['purchase_price'],
  6059.                     'balance' => $receiveType == $product->getBalance() : ($product->getToBeReceived() - $product->getReceived()),
  6060. //                        'delivered'=>$product->getDelivered(),
  6061.                 );
  6062.                 $sendData['productList'][] = $p_data;
  6063.             }
  6064.             //now package data
  6065.             if ($sendData) {
  6066.                 return new JsonResponse(array("success" => true"content" => $sendData));
  6067.             }
  6068.             return new JsonResponse(array("success" => false));
  6069.         }
  6070.         return new JsonResponse(array("success" => false));
  6071.     }
  6072.     public function StockReceivedNoteListAction(Request $request)
  6073.     {
  6074.         $q $this->getDoctrine()
  6075.             ->getRepository('ApplicationBundle:StockReceivedNote')
  6076.             ->findBy(
  6077.                 array(
  6078.                     'status' => GeneralConstant::ACTIVE,
  6079.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  6080. //                    'approved' =>  GeneralConstant::APPROVED,
  6081.                 )
  6082.             );
  6083.         $stage_list = array(
  6084.             => 'Pending',
  6085.             => 'Pending',
  6086.             => 'Complete',
  6087.             => 'Partial',
  6088.         );
  6089.         $data = [];
  6090.         foreach ($q as $entry) {
  6091.             $data[] = array(
  6092.                 'doc_date' => $entry->getStockReceivedNoteDate(),
  6093.                 'id' => $entry->getStockReceivedNoteId(),
  6094.                 'doc_hash' => $entry->getDocumentHash(),
  6095.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  6096.                 'stage' => $stage_list[$entry->getStage()]
  6097.             );
  6098.         }
  6099.         return $this->render('@Inventory/pages/views/stock_received_note_list.html.twig',
  6100.             array(
  6101.                 'page_title' => 'Stock Received List',
  6102.                 'data' => $data
  6103.             )
  6104.         );
  6105.     }
  6106.     public function ViewStockReceivedNoteAction(Request $request$id)
  6107.     {
  6108.         $em $this->getDoctrine()->getManager();
  6109.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6110.         return $this->render(
  6111.             '@Inventory/pages/views/view_stock_received_note.html.twig',
  6112.             array(
  6113.                 'page_title' => 'Stock Received Note',
  6114.                 'data' => $dt,
  6115.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  6116.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6117.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6118.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6119.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6120.                     $id,
  6121.                     $dt['created_by'],
  6122.                     $dt['edited_by'])
  6123.             )
  6124.         );
  6125.     }
  6126.     public function PrintStockReceivedNoteAction(Request $request$id)
  6127.     {
  6128.         $em $this->getDoctrine()->getManager();
  6129.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6130.         $company_data Company::getCompanyData($em1);
  6131.         $document_mark = array(
  6132.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6133.             'copy' => ''
  6134.         );
  6135.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6136.             $html $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
  6137.                 array(
  6138.                     //full array here
  6139.                     'pdf' => true,
  6140.                     'page_title' => 'Stock Received Note',
  6141.                     'export' => 'pdf,print',
  6142.                     'data' => $dt,
  6143.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6144.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6145.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6146.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6147.                         $id,
  6148.                         $dt['created_by'],
  6149.                         $dt['edited_by']),
  6150.                     'document_mark_image' => $document_mark['original'],
  6151.                     'company_name' => $company_data->getName(),
  6152.                     'company_data' => $company_data,
  6153.                     'company_address' => $company_data->getAddress(),
  6154.                     'company_image' => $company_data->getImage(),
  6155.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6156.                     'red' => 0
  6157.                 )
  6158.             );
  6159.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6160. //                'orientation' => 'landscape',
  6161. //                'enable-javascript' => true,
  6162. //                'javascript-delay' => 1000,
  6163.                 'no-stop-slow-scripts' => false,
  6164.                 'no-background' => false,
  6165.                 'lowquality' => false,
  6166.                 'encoding' => 'utf-8',
  6167. //            'images' => true,
  6168. //            'cookie' => array(),
  6169.                 'dpi' => 300,
  6170.                 'image-dpi' => 300,
  6171. //                'enable-external-links' => true,
  6172. //                'enable-internal-links' => true
  6173.             ));
  6174.             return new Response(
  6175.                 $pdf_response,
  6176.                 200,
  6177.                 array(
  6178.                     'Content-Type' => 'application/pdf',
  6179.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  6180.                 )
  6181.             );
  6182.         }
  6183.         return $this->render('@Inventory/pages/print/print_stock_received_note.html.twig',
  6184.             array(
  6185.                 'page_title' => 'Stock Received Note',
  6186.                 'export' => 'pdf,print',
  6187.                 'data' => $dt,
  6188.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6189.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6190.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6191.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6192.                     $id,
  6193.                     $dt['created_by'],
  6194.                     $dt['edited_by']),
  6195.                 'document_mark_image' => $document_mark['original'],
  6196.                 'company_name' => $company_data->getName(),
  6197.                 'company_data' => $company_data,
  6198.                 'company_address' => $company_data->getAddress(),
  6199.                 'company_image' => $company_data->getImage(),
  6200.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6201.                 'red' => 0
  6202.             )
  6203.         );
  6204.     }
  6205.     public function CreateStoreRequisitionSlipAction(Request $request$id 0)
  6206.     {
  6207.         $em $this->getDoctrine()->getManager();
  6208. //        $id;
  6209.         if ($request->isMethod('POST')) {
  6210.             $em $this->getDoctrine()->getManager();
  6211.             $entity_id array_flip(GeneralConstant::$Entity_list)['StoreRequisition']; //change
  6212.             $dochash $request->request->get('voucherNumber'); //change
  6213.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6214.             $approveRole $request->request->get('approvalRole');
  6215.             $approveHash $request->request->get('approvalHash');
  6216.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6217.                 $loginId$approveRole$approveHash$id)
  6218.             ) {
  6219.                 $this->addFlash(
  6220.                     'error',
  6221.                     'Sorry, could not insert Data.'
  6222.                 );
  6223.             } else {
  6224.                 if ($request->request->has('check_allowed'))
  6225.                     $check_allowed 1;
  6226.                 $IrID Inventory::CreateNewStoreRequisition($id,
  6227.                     $this->getDoctrine()->getManager(),
  6228.                     $request->request,
  6229.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6230.                     $this->getLoggedUserCompanyId($request)
  6231.                 );
  6232.                 //now add Approval info
  6233.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6234.                 $approveRole $request->request->get('approvalRole');
  6235.                 $options = array(
  6236.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6237.                     'notification_server' => $this->container->getParameter('notification_server'),
  6238.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6239.                     'url' => $this->generateUrl(
  6240.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StoreRequisition']]
  6241.                         ['entity_view_route_path_name']
  6242.                     )
  6243.                 );
  6244.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6245.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  6246.                     $IrID,
  6247.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6248.                 );
  6249.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StoreRequisition'], $IrID,
  6250.                     $loginId,
  6251.                     $approveRole,
  6252.                     $request->request->get('approvalHash'));
  6253.                 $this->addFlash(
  6254.                     'success',
  6255.                     'New Indent Added.'
  6256.                 );
  6257.                 $url $this->generateUrl(
  6258.                     'view_ir'
  6259.                 );
  6260.                 return $this->redirect($url "/" $IrID);
  6261.             }
  6262.         }
  6263.         $extDocData = [];
  6264.         $extDocDetailsData = [];
  6265.         if ($id == 0) {
  6266.         } else {
  6267.             $extDoc $em->getRepository('ApplicationBundle:StoreRequisition')->findOneBy(
  6268.                 array(
  6269.                     'storeRequisitionId' => $id///material
  6270.                 )
  6271.             );
  6272.             //now if its not editable, redirect to view
  6273.             if ($extDoc) {
  6274.                 if ($extDoc->getEditFlag() != 1) {
  6275.                     $url $this->generateUrl(
  6276.                         'view_ir'
  6277.                     );
  6278.                     return $this->redirect($url "/" $id);
  6279.                 } else {
  6280.                     $extDocData $extDoc;
  6281.                     $extDocDetailsData $em->getRepository('ApplicationBundle:StoreRequisitionItem')->findBy(
  6282.                         array(
  6283.                             'storeRequisitionId' => $id///material
  6284.                         )
  6285.                     );;
  6286.                 }
  6287.             } else {
  6288.             }
  6289.         }
  6290.         $companyId $this->getLoggedUserCompanyId($request);
  6291.         $productListArray = [];
  6292.         $subCategoryListArray = [];
  6293.         $categoryListArray = [];
  6294.         $igListArray = [];
  6295.         $unitListArray = [];
  6296.         $brandListArray = [];
  6297.         $productList Inventory::ProductList($em$companyId);
  6298.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6299.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6300.         $igList Inventory::ItemGroupList($em$companyId);
  6301.         $unitList Inventory::UnitTypeList($em);
  6302.         $brandList Inventory::GetBrandList($em$companyId);
  6303.         foreach ($productList as $product$productListArray[] = $product;
  6304.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6305.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6306.         foreach ($igList as $product$igListArray[] = $product;
  6307.         foreach ($unitList as $product$unitListArray[] = $product;
  6308.         foreach ($brandList as $product$brandListArray[] = $product;
  6309.         $sr_list = [];
  6310.         $QD $this->getDoctrine()
  6311.             ->getRepository('ApplicationBundle:StockRequisition')
  6312.             ->findBy(
  6313.                 array(
  6314.                     'indentTagged' => 0,
  6315.                     'approved' => 1
  6316.                 )
  6317.             );
  6318.         foreach ($QD as $dt) {
  6319.             $sr_list[$dt->getStockRequisitionId()] = array(
  6320.                 'id' => $dt->getStockRequisitionId(),
  6321.                 'name' => $dt->getDocumentHash(),
  6322.                 'text' => $dt->getDocumentHash(),
  6323.             );
  6324.         }
  6325.         return $this->render('@Inventory/pages/input_forms/store_requisition.html.twig',
  6326.             array(
  6327.                 'page_title' => 'Indent Requisition Slip',
  6328.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6329.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6330.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6331.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6332.                 'sr_list' => $sr_list,
  6333.                 'productList' => $productList,
  6334.                 'subCategoryList' => $subCategoryList,
  6335.                 'categoryList' => $categoryList,
  6336.                 'igList' => $igList,
  6337.                 'extId' => $id,
  6338.                 'extDocDetailsData' => $extDocDetailsData,
  6339.                 'extDocData' => $extDocData,
  6340.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6341.                 'unitList' => $unitList,
  6342.                 'brandList' => $brandList,
  6343.                 'brandListArray' => $brandListArray,
  6344.                 'productListArray' => $productListArray,
  6345.                 'subCategoryListArray' => $subCategoryListArray,
  6346.                 'categoryListArray' => $categoryListArray,
  6347.                 'igListArray' => $igListArray,
  6348.                 'unitListArray' => $unitListArray,
  6349.                 'prefix_list' => array(
  6350.                     [
  6351.                         'id' => 1,
  6352.                         'value' => 'GN',
  6353.                         'text' => 'General'
  6354.                     ],
  6355.                     [
  6356.                         'id' => 1,
  6357.                         'value' => 'SD',
  6358.                         'text' => 'For Sales Demand'
  6359.                     ]
  6360.                 ),
  6361.                 'assoc_list' => array(
  6362.                     [
  6363.                         'id' => 1,
  6364.                         'value' => 1,
  6365.                         'text' => 'GN'
  6366.                     ]
  6367.                 )
  6368.             )
  6369.         );
  6370.     }
  6371.     public function CreateStockRequisitionSlipAction(Request $request$id 0)
  6372.     {
  6373.         $em $this->getDoctrine()->getManager();
  6374.         if ($request->isMethod('POST')) {
  6375.             $em $this->getDoctrine()->getManager();
  6376.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockRequisition']; //change
  6377.             $dochash $request->request->get('voucherNumber'); //change
  6378.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6379.             $approveRole $request->request->get('approvalRole');
  6380.             $approveHash $request->request->get('approvalHash');
  6381.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6382.                 $loginId$approveRole$approveHash$id)
  6383.             ) {
  6384.                 $this->addFlash(
  6385.                     'error',
  6386.                     'Sorry, could not insert Data.'
  6387.                 );
  6388.             } else {
  6389.                 if ($request->request->has('check_allowed'))
  6390.                     $check_allowed 1;
  6391.                 $SrID Inventory::CreateNewStockRequisition($id,
  6392.                     $this->getDoctrine()->getManager(),
  6393.                     $request->request,
  6394.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6395.                     $this->getLoggedUserCompanyId($request)
  6396.                 );
  6397.                 //now add Approval info
  6398.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6399.                 $approveRole $request->request->get('approvalRole');
  6400.                 $options = array(
  6401.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6402.                     'notification_server' => $this->container->getParameter('notification_server'),
  6403.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6404.                     'url' => $this->generateUrl(
  6405.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockRequisition']]
  6406.                         ['entity_view_route_path_name']
  6407.                     )
  6408.                 );
  6409.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6410.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  6411.                     $SrID,
  6412.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6413.                 );
  6414.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockRequisition'], $SrID,
  6415.                     $loginId,
  6416.                     $approveRole,
  6417.                     $request->request->get('approvalHash'));
  6418.                 $this->addFlash(
  6419.                     'success',
  6420.                     'New Requisition Added.'
  6421.                 );
  6422.                 $url $this->generateUrl(
  6423.                     'view_sr'
  6424.                 );
  6425. //                return $this->redirect($url . "/" . $SrID);
  6426.             }
  6427.         }
  6428.         $extDocData = [];
  6429.         $extDocDetailsData = [];
  6430.         if ($id == 0) {
  6431.         } else {
  6432.             $extDoc $em->getRepository('ApplicationBundle:StockRequisition')->findOneBy(
  6433.                 array(
  6434.                     'stockRequisitionId' => $id///material
  6435.                 )
  6436.             );
  6437.             //now if its not editable, redirect to view
  6438.             if ($extDoc) {
  6439.                 if ($extDoc->getEditFlag() != 1) {
  6440.                     $url $this->generateUrl(
  6441.                         'view_sr'
  6442.                     );
  6443.                     return $this->redirect($url "/" $id);
  6444.                 } else {
  6445.                     $extDocData $extDoc;
  6446.                     $extDocDetailsData $em->getRepository('ApplicationBundle:StockRequisitionItem')->findBy(
  6447.                         array(
  6448.                             'stockRequisitionId' => $id///material
  6449.                         )
  6450.                     );;
  6451.                 }
  6452.             } else {
  6453.             }
  6454.         }
  6455.         $companyId $this->getLoggedUserCompanyId($request);
  6456.         $productListArray = [];
  6457.         $subCategoryListArray = [];
  6458.         $categoryListArray = [];
  6459.         $igListArray = [];
  6460.         $unitListArray = [];
  6461.         $brandListArray = [];
  6462.         $productList Inventory::ProductList($em$companyId);
  6463.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6464.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6465.         $igList Inventory::ItemGroupList($em$companyId);
  6466.         $unitList Inventory::UnitTypeList($em);
  6467.         $brandList Inventory::GetBrandList($em$companyId);
  6468.         foreach ($productList as $product$productListArray[] = $product;
  6469.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6470.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6471.         foreach ($igList as $product$igListArray[] = $product;
  6472.         foreach ($unitList as $product$unitListArray[] = $product;
  6473.         foreach ($brandList as $product$brandListArray[] = $product;
  6474.         return $this->render('@Inventory/pages/input_forms/stock_requisition_slip.html.twig',
  6475.             array(
  6476.                 'page_title' => 'Stock Requisition Slip',
  6477.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6478.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6479.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6480.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6481.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  6482.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6483.                 'productList' => $productList,
  6484.                 'extId' => $id,
  6485.                 'extDocDetailsData' => $extDocDetailsData,
  6486.                 'extDocData' => $extDocData,
  6487.                 'subCategoryList' => $subCategoryList,
  6488.                 'categoryList' => $categoryList,
  6489.                 'igList' => $igList,
  6490.                 'unitList' => $unitList,
  6491.                 'brandList' => $brandList,
  6492.                 'brandListArray' => $brandListArray,
  6493.                 'productListArray' => $productListArray,
  6494.                 'subCategoryListArray' => $subCategoryListArray,
  6495.                 'categoryListArray' => $categoryListArray,
  6496.                 'igListArray' => $igListArray,
  6497.                 'unitListArray' => $unitListArray,
  6498.                 'productionBomList' => ProductionM::ProductionBomList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6499.                 'productionScheduleList' => ProductionM::ProductionScheduleList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6500.                 'prefix_list' => array(
  6501.                     [
  6502.                         'id' => 1,
  6503.                         'value' => 'GN',
  6504.                         'text' => 'General'
  6505.                     ],
  6506.                     [
  6507.                         'id' => 1,
  6508.                         'value' => 'SD',
  6509.                         'text' => 'For Sales Demand'
  6510.                     ]
  6511.                 ),
  6512.                 'projectList' => $em->getRepository('ApplicationBundle:Project')->findBy(
  6513.                     array(
  6514.                         'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  6515.                     ), array('projectDate' => 'desc')
  6516.                 ),
  6517.                 'salesOrderList' => SalesOrderM::SalesOrderListPendingDelivery($em),
  6518.                 'assoc_list' => array(
  6519.                     [
  6520.                         'id' => 1,
  6521.                         'value' => 'GN',
  6522.                         'text' => 'General'
  6523.                     ]
  6524.                 )
  6525.             )
  6526.         );
  6527.     }
  6528.     public function CreateStockReturnAction(Request $request)
  6529.     {
  6530.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  6531.             array(
  6532.                 'page_title' => 'Stock Return',
  6533. //                'dataList'=>$dta_list
  6534.             )
  6535.         );
  6536.     }
  6537.     public function MaterialInwardAction(Request $request)
  6538.     {
  6539.         $data = [];
  6540.         if ($request->isMethod('POST')) {
  6541.             //first of all resolve the transport costs
  6542.             $total_price_value 0;
  6543.             $data_list $dt $this->getDoctrine()
  6544.                 ->getRepository('ApplicationBundle:PurchaseOrderItem')
  6545.                 ->findBy(
  6546.                     array(
  6547.                         'purchaseOrderId' => $request->request->get('poId'),
  6548.                         'productId' => $request->request->get('products')
  6549.                     )
  6550.                 );
  6551.             $purchase_items = [];
  6552.             foreach ($data_list as $key => $value) {
  6553.                 $purchase_items[$value->getProductId()] = $value;
  6554.             }
  6555.             foreach ($request->request->get('products') as $key => $entry) {
  6556.                 $total_price_value $total_price_value + ($request->request->get('receivedQty')[$key]) * ($purchase_items[$entry]->getPrice());
  6557.             }
  6558.             $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$request->request->get('poId')];
  6559.             $supplier_id $po_data['supplier_id'];
  6560.             $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6561.             foreach ($request->request->get('products') as $key => $entry) {
  6562.                 if ($request->request->get('receivedQty')[$key] > 0)
  6563.                     Inventory::NewMaterialInward($this->getDoctrine()->getManager(),
  6564.                         $request->request,
  6565.                         $key,
  6566.                         $request->request->get('poId'),
  6567.                         $request->request->get('purchaseOrderItemId'),
  6568.                         $supplier_id,
  6569.                         $request->request->get('warehouseId'),
  6570.                         $request->request->get('lotNumber'),
  6571.                         $request->request->get('type_hash'),
  6572.                         $request->request->get('prefix_hash'),
  6573.                         $request->request->get('assoc_hash'),
  6574.                         $request->request->get('number_hash'),
  6575.                         $request->request->get('docHash'),
  6576.                         $request->request->get('docDate'),
  6577.                         $purchase_items[$entry],
  6578.                         $total_price_value,
  6579.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6580.             }
  6581.             $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$request->request->get('warehouseId')]['name'];
  6582. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6583.             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),
  6584.                 "A stack of material Has Arrived at The " $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6585.                 'all',
  6586.                 "",
  6587.                 'information',
  6588.                 "",
  6589.                 "Inbound Material"
  6590.             );
  6591. //                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);
  6592.         }
  6593.         return $this->render('@Inventory/pages/input_forms/material_inward.html.twig',
  6594.             array(
  6595.                 'page_title' => 'Material Inward',
  6596.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6597.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  6598.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  6599.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  6600.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  6601.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  6602.                 "unitList" => Inventory::UnitTypeList($this->getDoctrine()->getManager())
  6603. //                'po'=>Inventory::getPurchaseOrderList
  6604.             )
  6605.         );
  6606.     }
  6607.     public function QualityControlAction(Request $request)
  6608.     {
  6609.         $checked_qc_list_flag 0;
  6610.         if ($request->query->has('checked_qc_list_flag'))
  6611.             $checked_qc_list_flag $request->query->has('checked_qc_list_flag');
  6612.         if ($request->isMethod('POST')) {
  6613.             foreach ($request->request->get('qc_checked', []) as $key => $entry) {
  6614.                 $em $this->getDoctrine()->getManager();
  6615.                 $data $this->getDoctrine()
  6616.                     ->getRepository('ApplicationBundle:MaterialInward')
  6617.                     ->findOneBy(
  6618.                         array(
  6619.                             'qcId' => $entry
  6620.                         )
  6621.                     );
  6622.                 if ($request->request->get('approvedQty')[$entry] <= 0) {
  6623.                     $em->remove($data);
  6624.                     $em->flush();
  6625.                 } else {
  6626.                     $data->setApprovedQty($request->request->get('approvedQty')[$entry]);
  6627.                     $data->setRejectedQty($data->getInwardQty() - $request->request->get('approvedQty')[$entry]);
  6628.                     $data->setQcDate(new \DateTime($request->request->get('qcDate')));
  6629.                     $data->setStage(GeneralConstant::STAGE_PENDING_TAG);
  6630.                     $em->flush();
  6631.                 }
  6632.                 //notification
  6633.                 $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$data->getPurchaseOrderId()];
  6634.                 $supplier_id $po_data['supplier_id'];
  6635.                 $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6636.                 $product_name Inventory::ProductList($this->getDoctrine()->getManager())[$data->getProductId()]['name'];
  6637.                 $qty $request->request->get('approvedQty')[$entry];
  6638.                 $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$data->getWarehouseId()]['name'];
  6639. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6640.                 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),
  6641.                     $qty " among " $data->getInwardQty() . " units of " $product_name " has passed the Quality Control in " .
  6642.                     $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6643.                     'all',
  6644.                     "",
  6645.                     'success',
  6646.                     "",
  6647.                     "Quality Control"
  6648.                 );
  6649.             }
  6650.         }
  6651.         return $this->render('@Inventory/pages/input_forms/qc.html.twig',
  6652.             array(
  6653.                 'page_title' => 'Quality Control',
  6654.                 'checked_qc_list_flag' => $checked_qc_list_flag,
  6655.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6656.                 'warehouse_indexed' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6657.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  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.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6662.                 'material_inward' => $this->getDoctrine()
  6663.                     ->getRepository('ApplicationBundle:MaterialInward')
  6664.                     ->findBy(
  6665.                         array(
  6666.                             'stage' => $checked_qc_list_flag == GeneralConstant::STAGE_PENDING GeneralConstant::STAGE_PENDING_TAG
  6667.                         )
  6668.                     )
  6669. //                'po'=>Inventory::getPurchaseOrderList
  6670.             )
  6671.         );
  6672.     }
  6673.     public function InventoryTransactionViewAction(Request $request)
  6674.     {
  6675.         $em $this->getDoctrine()->getManager();
  6676.         $qry_data = array(
  6677.             'warehouseId' => [0],
  6678.             'igId' => [0],
  6679.             'brandId' => [0],
  6680.             'categoryId' => [0],
  6681.             'actionTagId' => [0],
  6682.         );
  6683.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6684.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6685.         $data_searched = [];
  6686.         $em $this->getDoctrine()->getManager();
  6687.         $companyId $this->getLoggedUserCompanyId($request);
  6688.         $company_data Company::getCompanyData($em$companyId);
  6689.         $data = [];
  6690.         $print_title "Inventory Report";
  6691.         $document_mark = array(
  6692.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6693.             'copy' => ''
  6694.         );
  6695.         if ($request->isMethod('POST'))
  6696.             $method 'POST';
  6697.         else
  6698.             $method 'GET';
  6699.         {
  6700.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  6701.                 $request->request$method,
  6702.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6703.                 $companyId);
  6704.             if ($request->query->has('returnJson') || $request->request->has('returnJson')) {
  6705.                 return new JsonResponse(
  6706.                     array(
  6707.                         'success' => true,
  6708. //                    'page_title' => 'Product Details',
  6709. //                    'company_data' => $company_data,
  6710.                         'page_title' => 'Inventory Transactions',
  6711.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6712.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6713.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6714.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6715.                         'data_products' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6716.                         'action_tag' => $warehouse_action_list,
  6717.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6718.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6719.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6720.                         'data_searched' => $data_searched
  6721.                     )
  6722.                 );
  6723.             } else if ($request->request->get('print_data_enabled') == 1) {
  6724.                 $print_sub_title "";
  6725.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  6726.                     array(
  6727.                         'page_title' => 'Inventory Report',
  6728.                         'page_header' => 'Report',
  6729.                         'print_title' => $print_title,
  6730.                         'document_type' => 'Journal voucher',
  6731.                         'document_mark_image' => $document_mark['original'],
  6732.                         'page_header_sub' => 'Add',
  6733.                         'item_data' => [],
  6734.                         'received' => 2,
  6735.                         'return' => 1,
  6736.                         'total_w_vat' => 1,
  6737.                         'total_vat' => 1,
  6738.                         'total_wo_vat' => 1,
  6739.                         'invoice_id' => 'abcd1234',
  6740.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6741.                         'created_by' => 'created by',
  6742.                         'created_at' => '',
  6743.                         'red' => 0,
  6744.                         'company_name' => $company_data->getName(),
  6745.                         'company_data' => $company_data,
  6746.                         'company_address' => $company_data->getAddress(),
  6747.                         'company_image' => $company_data->getImage(),
  6748.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6749.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6750.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6751.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6752.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6753.                         'action_tag' => $warehouse_action_list,
  6754.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6755.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6756.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6757.                         'data_searched' => $data_searched
  6758.                     )
  6759.                 );
  6760.             }
  6761.         }
  6762.         return $this->render('@Inventory/pages/report/inventory_transaction_view.html.twig',
  6763.             array(
  6764.                 'page_title' => 'Inventory Transactions',
  6765.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6766.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6767.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6768.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6769.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6770.                 'action_tag' => $warehouse_action_list,
  6771.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6772.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6773.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6774.                 'data_searched' => $data_searched
  6775.             )
  6776.         );
  6777.     }
  6778.     public function StockConsumptionViewAction(Request $request)
  6779.     {
  6780.         $em $this->getDoctrine()->getManager();
  6781.         $start_date $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
  6782.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : new \DateTime();
  6783.         $qry_data = array(
  6784.             'warehouseId' => [0],
  6785.             'igId' => [0],
  6786.             'brandId' => [0],
  6787.             'categoryId' => [0],
  6788.             'actionTagId' => [0],
  6789.         );
  6790.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6791.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6792.         $data_searched = [];
  6793.         $em $this->getDoctrine()->getManager();
  6794.         $company_data Company::getCompanyData($em1);
  6795.         $data = [];
  6796.         $print_title "Inventory Report";
  6797.         $document_mark = array(
  6798.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6799.             'copy' => ''
  6800.         );
  6801.         if ($request->isMethod('POST'))
  6802.             $method 'POST';
  6803.         else
  6804.             $method 'GET';
  6805.         $post_data $method == 'POST' $request->request $request->query;
  6806.         $data_searched Inventory::GetStockConsumptionData($this->getDoctrine()->getManager(),
  6807.             $post_data,
  6808.             $method,
  6809.             $start_date,
  6810.             $end_date,
  6811.             $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6812.         if ($post_data->get('print_data_enabled') == 1) {
  6813.             $print_sub_title "";
  6814.             if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6815.                 $html $this->renderView('@Inventory/pages/print/print_stock_consumption.html.twig',
  6816.                     array(
  6817.                         'pdf' => 'true',
  6818.                         'page_title' => 'Inventory Report',
  6819.                         'page_header' => 'Report',
  6820.                         'print_title' => $print_title,
  6821.                         'document_type' => 'Journal voucher',
  6822.                         'document_mark_image' => $document_mark['original'],
  6823.                         'page_header_sub' => 'Add',
  6824.                         'item_data' => [],
  6825.                         'received' => 2,
  6826.                         'return' => 1,
  6827.                         'total_w_vat' => 1,
  6828.                         'total_vat' => 1,
  6829.                         'total_wo_vat' => 1,
  6830.                         'invoice_id' => 'abcd1234',
  6831.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6832.                         'created_by' => 'created by',
  6833.                         'created_at' => '',
  6834.                         'red' => 0,
  6835.                         'start_date' => $start_date,
  6836.                         'end_date' => $end_date,
  6837.                         'openFilter' => empty($post_data->keys()) ? 0,
  6838.                         'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6839.                         'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6840.                         'company_name' => $company_data->getName(),
  6841.                         'company_data' => $company_data,
  6842.                         'company_address' => $company_data->getAddress(),
  6843.                         'company_image' => $company_data->getImage(),
  6844.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6845.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6846.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6847.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6848.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6849.                         'action_tag' => $warehouse_action_list,
  6850.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6851.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6852.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6853.                         'data_searched' => $data_searched,
  6854.                         'export' => 'all'
  6855.                     )
  6856.                 );
  6857.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6858.                     'orientation' => count($data_searched['query_columns_filter']) > 'landscape' 'portrait',
  6859.                     'no-stop-slow-scripts' => true,
  6860.                     'no-background' => false,
  6861.                     'lowquality' => false,
  6862.                     'encoding' => 'utf-8',
  6863.                     'dpi' => 300,
  6864.                     'image-dpi' => 300,
  6865.                 ));
  6866.                 return new Response(
  6867.                     $pdf_response,
  6868.                     200,
  6869.                     array(
  6870.                         'Content-Type' => 'application/pdf',
  6871.                         'Content-Disposition' => 'attachment; filename="Stock_Consumption.pdf"'
  6872.                     )
  6873.                 );
  6874.             }
  6875.             return $this->render('@Inventory/pages/print/print_stock_consumption.html.twig',
  6876.                 array(
  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.         }
  6917. //        return new JsonResponse(Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()));
  6918.         return $this->render('@Inventory/pages/report/stock_consumption.html.twig',
  6919.             array(
  6920.                 'page_title' => 'Stock Consumption',
  6921.                 'start_date' => $start_date,
  6922.                 'end_date' => $end_date,
  6923.                 'openFilter' => empty($post_data->keys()) ? 0,
  6924.                 'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6925.                 'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6926.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6927.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6928.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6929.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6930.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6931.                 'action_tag' => $warehouse_action_list,
  6932.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6933.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6934.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6935.                 'data_searched' => $data_searched
  6936.             )
  6937.         );
  6938.     }
  6939.     public function ItemViewAction(Request $request)
  6940.     {
  6941.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  6942.             array(
  6943.                 'page_title' => 'Stock Return'
  6944.             )
  6945.         );
  6946.     }
  6947.     public function ProductViewAction(Request $request$id 0)
  6948.     {
  6949.         $em $this->getDoctrine()->getManager();
  6950.         $companyId $this->getLoggedUserCompanyId($request);
  6951.         $company_data Company::getCompanyData($em$companyId);
  6952.         $data = [];
  6953.         $specData =[];
  6954.         $specIds=[];
  6955.         $productData $em->getRepository('ApplicationBundle:InvProducts')
  6956.             ->findOneBy(
  6957.                 array(
  6958.                     'id' => $id
  6959.                 )
  6960.             );
  6961.         if($productData){
  6962.             $tempSpecData json_decode($productData->getSpecData(),true);
  6963.             if($tempSpecData == null ){
  6964.                 $tempSpecData=[];
  6965.             }
  6966.             foreach ($tempSpecData as $indSpecData)
  6967.             {
  6968. //                $specId = $indSpecData['id'];
  6969.                 $specData[]=[
  6970.                     'id'=> $indSpecData['id'],
  6971.                     'value'=> $indSpecData['value']
  6972.                 ];
  6973.                 $specIds[]= $indSpecData['id'];
  6974.             }
  6975.         }
  6976.         $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  6977.             ->findBy(
  6978.                 array(
  6979.                     'productId' => $id
  6980.                 )
  6981.             );
  6982.         $trans_history $em->getRepository('ApplicationBundle:InvItemTransaction')
  6983.             ->findBy(
  6984.                 array(
  6985.                     'productId' => $id
  6986.                 ), array(
  6987.                     'transactionDate' => 'ASC',
  6988.                     'id' => 'ASC'
  6989.                 )
  6990.             );
  6991. //        $specId = array_keys($specData);
  6992.         $finSpecData=[];
  6993. //        if($productData){
  6994. //            $tempSpec = json_decode($productData->getSpecData(),true);
  6995. //
  6996. //            if($tempSpec == null){
  6997. //                $tempSpecName=[];
  6998. //            }
  6999. //            foreach ($tempSpec as $indSpec)
  7000. //            {
  7001. //                $specIds[]=$indSpec['id'];
  7002. //
  7003. //                $spec = $em->getRepository('ApplicationBundle:SpecType')
  7004. //                    ->findOneBy(
  7005. //                        array(
  7006. //                            'id' => $indSpec['id']
  7007. //                        )
  7008. //                    );
  7009. //
  7010. //                if($spec)
  7011. //                    $indSpec['name']=$spec->getName();
  7012. //                else
  7013. //                    $indSpec['name']='';
  7014. ////                $specId = $indSpecData['id'];
  7015. //
  7016. //                $finSpecData[]=$indSpec;
  7017. //
  7018. //            }
  7019. //        }
  7020.         $specList $em->getRepository('ApplicationBundle:SpecType')
  7021.             ->findBy(
  7022.                 array(
  7023.                     'id' =>$specIds
  7024.                 )
  7025.             );
  7026.         $specListById=[];
  7027.         foreach ($specList as $specHere)
  7028.         {
  7029.             $specListById[$specHere->getId()]=$specHere->getName();
  7030.         }
  7031.         foreach ($specData as $specDatum){
  7032.             $finSpecData[]=[
  7033.                 'id' => $specDatum['id'],
  7034.                 'name' => isset($specListById[$specDatum['id']])?$specListById[$specDatum['id']]:'',
  7035.                 'value' => $specDatum['value']
  7036.             ];
  7037.         }
  7038.         $productDataObj = array();
  7039.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  7040.             $getters array_filter(get_class_methods($productData), function ($method) {
  7041.                 return 'get' === substr($method03);
  7042.             });
  7043.             foreach ($getters as $getter) {
  7044.                 if ($getter == 'getGlobalId')
  7045.                     continue;
  7046. //                    if ($getter == 'getId')
  7047. //                        continue;
  7048.                 $Fieldname str_replace('get'''$getter);
  7049.                 $productDataObj[$Fieldname] = $productData->{$getter}(); // `foo!`
  7050.             }
  7051.             if ($request->request->has('genInfoOnly') && $request->request->get('genInfoOnly') == 1) {
  7052.                 $dataArray = array(
  7053.                     'success' => true,
  7054.                     'page_title' => 'Product Details',
  7055.                     'company_data' => $company_data,
  7056.                     'productData' => $productData,
  7057.                     'productDataObj' => $productDataObj,
  7058.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7059.                 );
  7060.             } else {
  7061.                 $dataArray = array(
  7062.                     'success' => true,
  7063.                     'page_title' => 'Product Details',
  7064.                     'company_data' => $company_data,
  7065.                     'productData' => $productData,
  7066.                     'productDataObj' => $productDataObj,
  7067.                     'currInvList' => $currInvList,
  7068.                     'finSpecData' => $finSpecData,
  7069.                     'specList' => $specList,
  7070.                     'trans_history' => $trans_history,
  7071.                     'entityList' => GeneralConstant::$Entity_list_details,
  7072. //                    'productList' => Inventory::ProductList($em, $companyId),
  7073.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7074.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7075.                     'igList' => Inventory::ItemGroupList($em$companyId),
  7076.                     'unitList' => Inventory::UnitTypeList($em),
  7077.                     'brandList' => Inventory::GetBrandList($em$companyId),
  7078.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7079.                     'warehouseList' => Inventory::WarehouseList($em),
  7080.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7081.                 );
  7082.             }
  7083.             return new JsonResponse(
  7084.                 $dataArray
  7085.             );
  7086.         }
  7087.         $dataArray = array(
  7088.             'page_title' => 'Product Details',
  7089.             'company_data' => $company_data,
  7090.             'productData' => $productData,
  7091.             'currInvList' => $currInvList,
  7092.             'specData' => $specData,
  7093. //            'specListById' => $specListById,
  7094.             'finSpecData' => $finSpecData,
  7095.             'trans_history' => $trans_history,
  7096.             'entityList' => GeneralConstant::$Entity_list_details,
  7097. //            'productList' => Inventory::ProductList($em, $companyId),
  7098.             'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7099.             'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7100.             'igList' => Inventory::ItemGroupList($em$companyId),
  7101.             'unitList' => Inventory::UnitTypeList($em),
  7102.             'brandList' => Inventory::GetBrandList($em$companyId),
  7103.             'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7104.             'warehouseList' => Inventory::WarehouseList($em),
  7105.         );
  7106.         return $this->render('@Inventory/pages/views/product_view.html.twig'$dataArray
  7107.         );
  7108.     }
  7109.     public function CheckForProductInWarehouseAction(Request $request$queryStr '')
  7110.     {
  7111.         $em $this->getDoctrine()->getManager();
  7112.         $companyId $this->getLoggedUserCompanyId($request);
  7113.         $data = [
  7114.             'availableQty' => 0,
  7115.             'productByCodesArray' => [],
  7116.             'indRowId' => 0
  7117.         ];
  7118.         $html '';
  7119.         $productByCodeData = [];
  7120.         if ($request->isMethod('POST')) {
  7121.             $warehouseId $request->request->get('warehouseId'0);
  7122.             $warehouseActionId $request->request->get('warehouseActionId'0);
  7123.             $productId $request->request->get('productId'0);
  7124.             $indRowId $request->request->get('indRowId'0);
  7125.             $data['indRowId'] = $indRowId;
  7126.             $inStorage $em->getRepository('ApplicationBundle:InventoryStorage')
  7127.                 ->findBy(
  7128.                     array(
  7129.                         'productId' => $productId,
  7130.                         'warehouseId' => $warehouseId,
  7131.                         'actionTagId' => $warehouseActionId,
  7132.                         'CompanyId' => $companyId,
  7133.                     )
  7134.                 );
  7135.             foreach ($inStorage as $strg) {
  7136.                 $data['availableQty'] += $strg->getQty();
  7137.             }
  7138.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  7139.                 ->findBy(
  7140.                     array(
  7141.                         'productId' => $productId,
  7142.                         'warehouseId' => $warehouseId,
  7143.                         'warehouseActionId' => $warehouseActionId,
  7144.                         'CompanyId' => $companyId,
  7145.                     )
  7146.                 );
  7147.             foreach ($productByCodeData as $pbc) {
  7148.                 $data['productByCodesArray'][] = array(
  7149.                     'id' => $pbc->getProductByCodeId(),
  7150.                     'productId' => $pbc->getProductId(),
  7151.                     'warehouseId' => $pbc->getWarehouseId(),
  7152.                     'warehouseActionId' => $pbc->getWarehouseActionId(),
  7153. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7154.                     'sales_code' => str_pad($pbc->getSalesCode(), 13'0'STR_PAD_LEFT),
  7155. //                'sales_code'=>$d['sales_code'],
  7156.                 );
  7157.             }
  7158.             return new JsonResponse(array(
  7159.                     'success' => true,
  7160.                     'data' => $data,
  7161.                 )
  7162.             );
  7163.         }
  7164.         return new JsonResponse(
  7165.             array(
  7166.                 'success' => false,
  7167.                 'data' => $data,
  7168.             )
  7169.         );
  7170.     }
  7171.     public function ProductByCodeListAjaxAction(Request $request$queryStr '')
  7172.     {
  7173.         $em $this->getDoctrine()->getManager();
  7174.         $companyId $this->getLoggedUserCompanyId($request);
  7175.         $company_data Company::getCompanyData($em$companyId);
  7176.         $data = [];
  7177.         $html '';
  7178.         $productByCodeData = [];
  7179.         if ($request->request->has('query') && $queryStr == '')
  7180.             $queryStr $request->request->get('queryStr');
  7181.         $get_kids_sql "select product_by_code_id id, product_id, warehouse_id, warehouse_action_id,
  7182.                             sales_code ,
  7183.                             serial_no,
  7184.                             imei1,
  7185.                             imei2,
  7186.                             imei3,
  7187.                             imei4
  7188.                             from product_by_code
  7189.                             where ( CONVERT(sales_code,char)  like '%" $queryStr "%'
  7190.                                     or  CONVERT(serial_no,char)  like '%" $queryStr "%'
  7191.                                     or  CONVERT(imei1,char)  like '%" $queryStr "%'
  7192.                                     or  CONVERT(imei2,char)  like '%" $queryStr "%'
  7193.                                     or  CONVERT(imei3,char)  like '%" $queryStr "%'
  7194.                                     or  CONVERT(imei4,char)  like '%" $queryStr "%'
  7195.                                     ) ";
  7196.         if ($request->query->has('warehouseId'))
  7197.             $get_kids_sql .= " and warehouse_id=" $request->query->get('warehouseId') . " ";
  7198.         if ($request->query->has('position'))
  7199.             $get_kids_sql .= " and position=" $request->query->get('position') . " ";
  7200.         if ($request->query->has('deliveryReceiptId'))
  7201.             $get_kids_sql .= " and deliveryReceiptId=" $request->query->get('deliveryReceiptId') . " ";
  7202.         if ($request->query->has('warehouseActionId'))
  7203.             $get_kids_sql .= " and warehouse_action_id=" $request->query->get('warehouseActionId') . " ";
  7204.         if ($request->query->has('productId'))
  7205.             $get_kids_sql .= " and product_id=" $request->query->get('productId') . " ";
  7206.         $get_kids_sql .= " and company_id=" $companyId " limit 25";
  7207.         $stmt $em->getConnection()->prepare($get_kids_sql);
  7208.         $stmt->execute();
  7209.         $get_kids $stmt->fetchAll();
  7210.         if (!empty($get_kids)) {
  7211.             foreach ($get_kids as $d) {
  7212.                 $dt = array(
  7213.                     'id' => $d['id'],
  7214.                     'productId' => $d['product_id'],
  7215.                     'warehouseId' => $d['warehouse_id'],
  7216.                     'warehouseActionId' => $d['warehouse_action_id'],
  7217. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7218.                     'sales_code' => str_pad($d['sales_code'], 13'0'STR_PAD_LEFT),
  7219.                     'serial_no' => str_pad($d['serial_no'], 13'0'STR_PAD_LEFT),
  7220.                     'imei1' => str_pad($d['imei1'], 13'0'STR_PAD_LEFT),
  7221.                     'imei2' => str_pad($d['imei2'], 13'0'STR_PAD_LEFT),
  7222.                     'imei3' => str_pad($d['imei3'], 13'0'STR_PAD_LEFT),
  7223.                     'imei4' => str_pad($d['imei4'], 13'0'STR_PAD_LEFT),
  7224. //                'sales_code'=>$d['sales_code'],
  7225.                 );
  7226.                 $data[] = $dt;
  7227.             }
  7228.         }
  7229. //        if($request->query->has('returnJson'))
  7230.         {
  7231.             return new JsonResponse(
  7232.                 array(
  7233.                     'success' => true,
  7234. //                    'page_title' => 'Product Details',
  7235. //                    'company_data' => $company_data,
  7236.                     'data' => $data,
  7237. //                    'exId'=>$id,
  7238. //                'productByCodeData' => $productByCodeData,
  7239. //                'productData' => $productData,
  7240. //                'currInvList' => $currInvList,
  7241. //                'productList' => Inventory::ProductList($em, $companyId),
  7242. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  7243. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  7244. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  7245. //                'unitList' => Inventory::UnitTypeList($em),
  7246. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  7247. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  7248. //                'warehouseList' => Inventory::WarehouseList($em),
  7249.                 )
  7250.             );
  7251.         }
  7252.     }
  7253.     public function selectDataAjaxAction(Request $request$queryStr '',
  7254.                                                  $version 'latest',
  7255.                                                  $identifier '_default_',
  7256.                                                  $apiKey '_ignore_'
  7257.     )
  7258.     {
  7259.         $em $this->getDoctrine()->getManager();
  7260.         $em_goc $this->getDoctrine()->getManager('company_group');
  7261.         $companyId 0;
  7262.         $skipCurrentUserIdRestriction $request->get('skipCurrentUserIdRestriction'0);
  7263.         $dataOnly $request->get('dataOnly'0);
  7264.         $skipCurrentEmployeeIdRestriction $request->get('skipCurrentEmployeeIdRestriction'0);
  7265.         $skipCurrentUserLoginIdRestriction $request->get('skipCurrentUserLoginIdRestriction'0);
  7266.         $currentUserId $request->getSession()->get(UserConstants::USER_ID0);
  7267.         $currentEmployeeId $request->getSession()->get(UserConstants::USER_EMPLOYEE_ID0);
  7268.         $currentUserLoginIds = [];
  7269.         if ($request->request->get('entity_group'0)) {
  7270.             $companyId 0;
  7271.             $em $this->getDoctrine()->getManager('company_group');
  7272.         } else {
  7273.             if ($request->request->get('appId'0) != 0) {
  7274.                 $gocEnabled 0;
  7275.                 if ($this->container->hasParameter('entity_group_enabled'))
  7276.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7277.                 else
  7278.                     $gocEnabled 1;
  7279.                 if ($gocEnabled == 1) {
  7280.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7281.                         $this->getDoctrine()->getManager('company_group'),
  7282.                         $gocEnabled,
  7283.                         $request->request->get('appId'0)
  7284.                     );
  7285.                     if (!empty($dataToConnect)) {
  7286.                         $connector $this->container->get('application_connector');
  7287.                         $connector->resetConnection(
  7288.                             'default',
  7289.                             $dataToConnect['dbName'],
  7290.                             $dataToConnect['dbUser'],
  7291.                             $dataToConnect['dbPass'],
  7292.                             $dataToConnect['dbHost'],
  7293.                             $reset true
  7294.                         );
  7295.                         $em $this->getDoctrine()->getManager();
  7296.                     }
  7297.                 }
  7298.             } else if ($request->getSession()->get(UserConstants::USER_APP_ID) != && $request->getSession()->get(UserConstants::USER_APP_ID) != null) {
  7299.                 $gocEnabled 0;
  7300.                 if ($this->container->hasParameter('entity_group_enabled'))
  7301.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7302.                 else
  7303.                     $gocEnabled 1;
  7304.                 if ($gocEnabled == 1) {
  7305.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7306.                         $this->getDoctrine()->getManager('company_group'),
  7307.                         $gocEnabled,
  7308.                         $request->getSession()->get(UserConstants::USER_APP_ID)
  7309.                     );
  7310.                     if (!empty($dataToConnect)) {
  7311.                         $connector $this->container->get('application_connector');
  7312.                         $connector->resetConnection(
  7313.                             'default',
  7314.                             $dataToConnect['dbName'],
  7315.                             $dataToConnect['dbUser'],
  7316.                             $dataToConnect['dbPass'],
  7317.                             $dataToConnect['dbHost'],
  7318.                             $reset true
  7319.                         );
  7320.                         $em $this->getDoctrine()->getManager();
  7321.                     }
  7322.                 }
  7323.             }
  7324.             $companyId $this->getLoggedUserCompanyId($request);
  7325.         }
  7326.         $configData = [];
  7327.         $isSingleDataset 1;
  7328.         $dataSet $request->request->has('dataset') ? $request->request->get('dataset') : [];
  7329.         if (is_string($dataSet)) $dataSet json_decode($dataSettrue);
  7330.         $valuePairs $request->get('valuePairs', []);
  7331.         if (is_string($valuePairs)) $valuePairs json_decode($valuePairstrue);
  7332.         $allResult = [];
  7333.         $datasetFromConfig = [];
  7334.         if ($identifier != '_default_') {
  7335.             $config_file $this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' $identifier 'Config.json';
  7336.             if (!file_exists($config_file)) {
  7337.             } else {
  7338.                 $fileText file_get_contents($config_file);
  7339.                 //now replace any value pairs
  7340.                 foreach ($valuePairs as $kkeeyy => $vvaalluuee) {
  7341.                     if (is_array($vvaalluuee)) {
  7342.                         if (isset($vvaalluuee['value']) && isset($vvaalluuee['type'])) {
  7343.                             if ($vvaalluuee['type'] == 'array'$fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee['value']), $fileText);
  7344.                             if ($vvaalluuee['type'] == 'value'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7345.                             if ($vvaalluuee['type'] == 'text'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7346.                         } else {
  7347.                             $fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee), $fileText);
  7348.                         }
  7349.                     }
  7350.                     $fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee$fileText);
  7351.                 }
  7352.                 $fileText str_ireplace('_query_'$request->get('query'$queryStr), $fileText);
  7353.                 $fileText str_ireplace('_itemLimit_'$request->get('itemLimit''_all_'), $fileText);
  7354.                 $fileText str_ireplace('_offset_'$request->get('offset', ($request->get('itemLimit'10))*($request->get('page'1)-1)), $fileText);
  7355.                 if (!(strpos($fileText'_CURRENT_USER_LOGIN_IDS_') === false) && $skipCurrentUserLoginIdRestriction == 0) {
  7356.                     $userInfo = [];
  7357.                     if ($request->getSession()->get(UserConstants::USER_TYPE0) == UserConstants::USER_TYPE_APPLICANT) {
  7358.                         $userInfo $em_goc->getRepository('CompanyGroupBundle:EntityLoginLog')->findBy(
  7359.                             array('userId' => $currentUserId)
  7360.                         );
  7361.                     } else {
  7362.                         $userInfo $em->getRepository('ApplicationBundle:SysLoginLog')->findBy(
  7363.                             array('userId' => $currentUserId)
  7364.                         );
  7365.                     }
  7366.                     foreach ($userInfo as $uLogininfo) {
  7367.                         $currentUserLoginIds[] = $uLogininfo->getLoginId();
  7368.                     }
  7369.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_'json_encode($currentUserLoginIds), $fileText);
  7370.                 } else {
  7371.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_''_EMPTY_'$fileText);
  7372.                 }
  7373.                 if (!(strpos($fileText'_CURRENT_USER_ID_') === false) && $skipCurrentUserIdRestriction == 0) {
  7374.                     $fileText str_ireplace('_CURRENT_USER_ID_'$currentUserId$fileText);
  7375.                 } else {
  7376.                     $fileText str_ireplace('_CURRENT_USER_ID_''_EMPTY_'$fileText);
  7377.                 }
  7378.                 if (!(strpos($fileText'_CURRENT_USER_EMPLOYEE_ID_') === false) && $skipCurrentEmployeeIdRestriction == 0) {
  7379.                     if ((strpos($fileText'skipCurrentEmployeeIdRestriction') === false)) {
  7380.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_'$currentEmployeeId$fileText);
  7381.                     } else {
  7382.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  7383.                     }
  7384.                 } else {
  7385.                     $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  7386.                 }
  7387.                 if ($fileText)
  7388.                     $datasetFromConfig json_decode($fileTexttrue);
  7389.                 $skipCurrentUserIdRestriction = isset($datasetFromConfig['skipCurrentUserIdRestriction']) ? $datasetFromConfig['skipCurrentUserIdRestriction'] : $skipCurrentUserIdRestriction;
  7390.                 $skipCurrentEmployeeIdRestriction = isset($datasetFromConfig['skipCurrentEmployeeIdRestriction']) ? $datasetFromConfig['skipCurrentEmployeeIdRestriction'] : $skipCurrentEmployeeIdRestriction;
  7391.                 $skipCurrentUserLoginIdRestriction = isset($datasetFromConfig['skipCurrentUserLoginIdRestriction']) ? $datasetFromConfig['skipCurrentUserLoginIdRestriction'] : $skipCurrentUserLoginIdRestriction;
  7392.             }
  7393.         }
  7394.         if ($dataSet == null$dataSet = [];
  7395. //        return new JsonResponse(array(
  7396. //            'queryStr'=>$queryStr
  7397. //        ));
  7398.         if (!empty($datasetFromConfig)) {
  7399.             if (isset($datasetFromConfig['tableName'])) {
  7400.                 $isSingleDataset 1;
  7401.                 $dataSet[] = $datasetFromConfig;
  7402.             } else {
  7403.                 if (count($datasetFromConfig) == 1)
  7404.                     $isSingleDataset 1;
  7405.                 $dataSet $datasetFromConfig;
  7406.             }
  7407.         }
  7408.         if (empty($dataSet)) {
  7409.             $isSingleDataset 1;
  7410.             $singleDataSet = array(
  7411.                 "valueField" => $request->request->has('valueField') ? $request->request->get('valueField') : 'id',
  7412.                 "query" => $request->get('query'$queryStr),
  7413.                 "headMarkers" => $request->get('headMarkers'''),
  7414.                 "headMarkersStrictMatch" => $request->get('headMarkersStrictMatch'0),
  7415.                 "itemLimit" => $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25,
  7416.                 "selectorId" => $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_',
  7417.                 "textField" => $request->request->has('textField') ? $request->request->get('textField') : 'name',
  7418.                 "tableName" => $request->request->has('tableName') ? $request->request->get('tableName') : '',
  7419.                 "isMultiple" => $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0,
  7420.                 "orConditions" => $request->request->has('orConditions') ? $request->request->get('orConditions') : [],
  7421.                 "andConditions" => $request->request->has('andConditions') ? $request->request->get('andConditions') : [],
  7422.                 "andOrConditions" => $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [],
  7423.                 "mustConditions" => $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [],
  7424.                 "joinTableData" => $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [],
  7425.                 "renderTextFormat" => $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '',
  7426.                 "setDataForSingle" => $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0,
  7427.                 "dataId" => $request->request->has('dataId') ? $request->request->get('dataId') : 0,
  7428.                 "lastChildrenOnly" => $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0,
  7429.                 "parentOnly" => $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0,
  7430.                 "parentIdField" => $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id',
  7431.                 "skipDefaultCompanyId" => $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1,
  7432.                 "offset" => $request->request->has('offset') ? $request->request->get('offset') : 0,
  7433.                 "returnTotalMatchedEntriesFlag" => $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0,
  7434.                 "nextOffset" => 0,
  7435.                 "totalMatchedEntries" => 0,
  7436.                 "convertToObject" => $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [],
  7437.                 "convertDateToStringFieldList" => $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [],
  7438.                 "orderByConditions" => $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [],
  7439.                 "convertToUrl" => $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [],
  7440.                 "fullPathList" => $request->request->has('fullPathList') ? $request->request->get('fullPathList') : [],
  7441.                 "ret_data" => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  7442.             );
  7443.             $dataSet[] = $singleDataSet;
  7444.         }
  7445. //        $lastResult = [
  7446. //            'identifier' => $identifier,
  7447. //            'dataSet' => $dataSet,
  7448. //        ];
  7449. //        return new JsonResponse($lastResult);
  7450.         $userId $request->getSession()->get(UserConstants::USER_ID);
  7451. //        public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [],$userId=0)
  7452.         foreach ($dataSet as $dsIndex => $dataConfig) {
  7453.             $companyId 0;
  7454.             $queryStringIndividual $queryStr;
  7455.             $data = [];
  7456.             $data_by_id = [];
  7457.             $setValueArray = [];
  7458.             $silentChangeSelectize 0;
  7459.             $setValue 0;
  7460.             $setValueType 0;// 0 for id , 1 for query
  7461.             $selectAll 0;
  7462.             if ($queryStringIndividual == '_EMPTY_')
  7463.                 $queryStringIndividual '';
  7464.             if (isset($dataConfig['query']))
  7465.                 $queryStringIndividual $dataConfig['query'];
  7466.             if ($queryStringIndividual == '_EMPTY_')
  7467.                 $queryStringIndividual '';
  7468.             $queryStringIndividual str_replace('_FSLASH_''/'$queryStringIndividual);
  7469.             if ($queryStringIndividual === '#setValue:') {
  7470.                 $queryStringIndividual '';
  7471.             }
  7472.             if (!(strpos($queryStringIndividual'_silent_change_') === false)) {
  7473.                 $silentChangeSelectize 1;
  7474.                 $queryStringIndividual str_ireplace('_silent_change_'''$queryStringIndividual);
  7475.             }
  7476.             if (!(strpos($queryStringIndividual'#setValue:') === false)) {
  7477.                 $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStringIndividual));
  7478.                 foreach ($setValueArrayBeforeFilter as $svf) {
  7479.                     if ($svf == '_ALL_') {
  7480.                         $selectAll 1;
  7481.                         $setValueArray = [];
  7482.                         continue;
  7483.                     }
  7484.                     if (is_numeric($svf)) {
  7485.                         $setValueArray[] = ($svf 1);
  7486.                         $setValue $svf 1;
  7487.                     }
  7488.                 }
  7489.                 $queryStringIndividual '';
  7490.             }
  7491.             $valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
  7492.             $headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''//Special Field
  7493.             $headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0//Special Field
  7494.             $itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
  7495.             $selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
  7496.             $textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
  7497.             $table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
  7498.             $isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
  7499.             $orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
  7500.             $andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
  7501.             $andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
  7502.             $mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
  7503.             $joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
  7504.             $renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
  7505.             $setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
  7506.             $dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
  7507.             $lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
  7508.             $parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
  7509.             $parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
  7510.             $skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
  7511.             $offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
  7512.             $returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
  7513.             $nextOffset 0;
  7514.             $totalMatchedEntries 0;
  7515.             $convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
  7516.             $convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
  7517.             $orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
  7518.             $convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
  7519.             $fullPathList = isset($dataConfig['fullPathList']) ? $dataConfig['fullPathList'] : [];
  7520.             if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  7521.             if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  7522.             if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  7523.             if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  7524.             if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  7525.             if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  7526.             if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  7527.             if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  7528.             if (is_string($fullPathList)) $fullPathList json_decode($fullPathListtrue);
  7529. //            return new JsonResponse(array(
  7530. //                'dataSet'=>$dataSet,
  7531. //                'dataConfig'=>$dataConfig,
  7532. //                'hi'=>$this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json',
  7533. //                'hiD'=>file_get_contents($this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json')
  7534. //            ));
  7535.             if ($table == '') {
  7536.                 $lastResult = array(
  7537.                     'success' => false,
  7538.                     'currentTs' => (new \Datetime())->format('U'),
  7539.                     'isMultiple' => $isMultiple,
  7540.                     'setValueArray' => $setValueArray,
  7541.                     'setValue' => $setValue,
  7542.                     'data' => $data,
  7543.                     'dataId' => $dataId,
  7544.                     'selectorId' => $selectorId,
  7545.                     'dataById' => $data_by_id,
  7546.                     'selectedId' => 0,
  7547.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  7548.                 );
  7549.             } else {
  7550.                 $restrictionData = array(
  7551. //            'table'=>'relevantField in restriction'
  7552.                     'warehouse_action' => 'warehouseActionIds',
  7553.                     'branch' => 'branchIds',
  7554.                     'warehouse' => 'warehouseIds',
  7555.                     'production_process_settings' => 'productionProcessIds',
  7556.                 );
  7557.                 $restrictionIdList = [];
  7558.                 $filterQryForCriteria "select ";
  7559.                 $selectQry "";
  7560. //        $selectQry=" `$table`.* ";
  7561.                 $selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
  7562.                 $selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
  7563.                 if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  7564.                 foreach ($selectFieldList as $selField) {
  7565.                     if ($selectQry != '')
  7566.                         $selectQry .= ", ";
  7567.                     if ($selField == '*')
  7568.                         $selectQry .= " `$table`.$selField ";
  7569.                     else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7570.                         if ($selectPrefix == '')
  7571.                             $selectQry .= " count(*)  ";
  7572.                         else
  7573.                             $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  7574.                     } else {
  7575.                         if ($selectPrefix == '')
  7576.                             $selectQry .= " `$table`.`$selField` ";
  7577.                         else
  7578.                             $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  7579.                     }
  7580.                 }
  7581.                 $joinQry " from $table ";
  7582. //        $filterQryForCriteria = "select * from $table ";
  7583.                 foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  7584. //            $conditionStr.=' 1=1 ';
  7585.                     $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  7586.                     $joinTableAlias $joinTableName '_' $joinIndex;
  7587.                     $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  7588.                     $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  7589.                     $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  7590.                     $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  7591.                     $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  7592.                     $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  7593.                     $joinMustConditions = isset($joinTableDatum['joinMustConditions']) ? $joinTableDatum['joinMustConditions'] : [];
  7594.                     $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  7595.                     $joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
  7596.                     $joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
  7597.                     if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  7598.                     if (is_string($joinMustConditions)) $joinMustConditions json_decode($joinMustConditionstrue);
  7599.                     if (is_string($joinAndOrConditions)) $joinAndOrConditions json_decode($joinAndOrConditionstrue);
  7600.                     if (is_string($joinOrConditions)) $joinOrConditions json_decode($joinOrConditionstrue);
  7601.                     foreach ($selectFieldList as $selField) {
  7602.                         if ($selField == '*')
  7603.                             $selectQry .= ", `$joinTableAlias`.$selField ";
  7604.                         else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7605.                             if ($selectPrefix == '')
  7606.                                 $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  7607.                             else
  7608.                                 $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  7609.                         } else {
  7610.                             if ($selectPrefix == '')
  7611.                                 $selectQry .= ", `$joinTableAlias`.`$selField`  ";
  7612.                             else
  7613.                                 $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  7614.                         }
  7615.                     }
  7616.                     $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  7617. //            if($joinTablePrimaryField!='')
  7618. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7619. //            $joinAndString = '';
  7620.                     $joinMustString '';
  7621.                     if ($joinTablePrimaryField != '')
  7622.                         $joinQry .= "  `$joinTableAlias`.`$joinTableOnField$fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7623.                     foreach ($joinMustConditions as $mustCondition) {
  7624. //            $conditionStr.=' 1=1 ';
  7625.                         $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  7626.                         $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  7627.                         $aliasInCondition $table;
  7628.                         if (!(strpos($cfield'.') === false)) {
  7629.                             $fullCfieldArray explode('.'$cfield);
  7630.                             $aliasInCondition $fullCfieldArray[0];
  7631.                             $cfield $fullCfieldArray[1];
  7632.                         }
  7633.                         $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  7634.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7635.                             if ($joinMustString != '')
  7636.                                 $joinMustString .= " and ";
  7637.                             if ($ctype == 'like') {
  7638.                                 $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7639.                                 $wordsBySpaces explode(' '$cvalue);
  7640.                                 foreach ($wordsBySpaces as $word) {
  7641.                                     if ($joinMustString != '')
  7642.                                         $joinMustString .= " and ";
  7643.                                     $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7644.                                 }
  7645.                             } else if ($ctype == 'not like') {
  7646.                                 $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7647.                                 $wordsBySpaces explode(' '$cvalue);
  7648.                                 foreach ($wordsBySpaces as $word) {
  7649.                                     if ($joinMustString != '')
  7650.                                         $joinMustString .= " and ";
  7651.                                     $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7652.                                 }
  7653.                             } else if ($ctype == 'not_in') {
  7654.                                 $joinMustString .= " ( ";
  7655.                                 if (in_array('null'$cvalue)) {
  7656.                                     $joinMustString .= " `$joinTableAlias`.$cfield is not null";
  7657.                                     $cvalue array_diff($cvalue, ['null']);
  7658.                                     if (!empty($cvalue))
  7659.                                         $joinMustString .= " and ";
  7660.                                 }
  7661.                                 if (in_array(''$cvalue)) {
  7662.                                     $joinMustString .= "`$joinTableAlias`.$cfield != '' ";
  7663.                                     $cvalue array_diff($cvalue, ['']);
  7664.                                     if (!empty($cvalue))
  7665.                                         $joinMustString .= " and ";
  7666.                                 }
  7667.                                 $joinMustString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7668.                             } else if ($ctype == 'in') {
  7669.                                 if (in_array('null'$cvalue)) {
  7670.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null";
  7671.                                     $cvalue array_diff($cvalue, ['null']);
  7672.                                     if (!empty($cvalue))
  7673.                                         $joinMustString .= " and ";
  7674.                                 }
  7675.                                 if (in_array(''$cvalue)) {
  7676.                                     $joinMustString .= "`$joinTableAlias`.$cfield = '' ";
  7677.                                     $cvalue array_diff($cvalue, ['']);
  7678.                                     if (!empty($cvalue))
  7679.                                         $joinMustString .= " and ";
  7680.                                 }
  7681.                                 $joinMustString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7682.                             } else if ($ctype == '=') {
  7683. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7684. //                            $fullCfieldArray = explode('.', $cfield);
  7685. //                            $aliasInCondition = $fullCfieldArray[0];
  7686. //                            $cfield = $fullCfieldArray[1];
  7687. //                        }
  7688.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7689.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null ";
  7690.                                 else
  7691.                                     $joinMustString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7692.                             } else if ($ctype == '!=') {
  7693.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7694.                                     $joinMustString .= "`$joinTableAlias`.$cfield is not null ";
  7695.                                 else
  7696.                                     $joinMustString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7697.                             } else {
  7698.                                 if (is_string($cvalue))
  7699.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7700.                                 else
  7701.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7702.                             }
  7703.                         }
  7704.                     }
  7705. //            if ($joinMustString != '') {
  7706. //                if ($conditionStr != '')
  7707. //                    $conditionStr .= (" and (" . $joinMustString . ") ");
  7708. //                else
  7709. //                    $conditionStr .= ("  (" . $joinMustString . ") ");
  7710. //            }
  7711.                     if ($joinMustString != '') {
  7712.                         $joinQry .= (' and ' $joinMustString);
  7713. //                        $joinQry.=' and (';
  7714.                     }
  7715.                     $mustBracketDone 0;
  7716.                     $joinAndString '';
  7717. //                    if ($joinTablePrimaryField != '')
  7718. //                        $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7719.                     foreach ($joinAndConditions as $andCondition) {
  7720. //            $conditionStr.=' 1=1 ';
  7721.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  7722.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  7723.                         $aliasInCondition $table;
  7724.                         if (!(strpos($cfield'.') === false)) {
  7725.                             $fullCfieldArray explode('.'$cfield);
  7726.                             $aliasInCondition $fullCfieldArray[0];
  7727.                             $cfield $fullCfieldArray[1];
  7728.                         }
  7729.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  7730.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7731.                             if ($joinAndString != '')
  7732.                                 $joinAndString .= " and ";
  7733.                             if ($ctype == 'like') {
  7734.                                 $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7735.                                 $wordsBySpaces explode(' '$cvalue);
  7736.                                 foreach ($wordsBySpaces as $word) {
  7737.                                     if ($joinAndString != '')
  7738.                                         $joinAndString .= " and ";
  7739.                                     $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7740.                                 }
  7741.                             } else if ($ctype == 'not like') {
  7742.                                 $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7743.                                 $wordsBySpaces explode(' '$cvalue);
  7744.                                 foreach ($wordsBySpaces as $word) {
  7745.                                     if ($joinAndString != '')
  7746.                                         $joinAndString .= " and ";
  7747.                                     $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7748.                                 }
  7749.                             } else if ($ctype == 'not_in') {
  7750.                                 $joinAndString .= " ( ";
  7751.                                 if (in_array('null'$cvalue)) {
  7752.                                     $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  7753.                                     $cvalue array_diff($cvalue, ['null']);
  7754.                                     if (!empty($cvalue))
  7755.                                         $joinAndString .= " and ";
  7756.                                 }
  7757.                                 if (in_array(''$cvalue)) {
  7758.                                     $joinAndString .= "`$joinTableAlias`.$cfield != '' ";
  7759.                                     $cvalue array_diff($cvalue, ['']);
  7760.                                     if (!empty($cvalue))
  7761.                                         $joinAndString .= " and ";
  7762.                                 }
  7763.                                 $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7764.                             } else if ($ctype == 'in') {
  7765.                                 if (in_array('null'$cvalue)) {
  7766.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null";
  7767.                                     $cvalue array_diff($cvalue, ['null']);
  7768.                                     if (!empty($cvalue))
  7769.                                         $joinAndString .= " and ";
  7770.                                 }
  7771.                                 if (in_array(''$cvalue)) {
  7772.                                     $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  7773.                                     $cvalue array_diff($cvalue, ['']);
  7774.                                     if (!empty($cvalue))
  7775.                                         $joinAndString .= " and ";
  7776.                                 }
  7777.                                 $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7778.                             } else if ($ctype == '=') {
  7779. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7780. //                            $fullCfieldArray = explode('.', $cfield);
  7781. //                            $aliasInCondition = $fullCfieldArray[0];
  7782. //                            $cfield = $fullCfieldArray[1];
  7783. //                        }
  7784.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7785.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  7786.                                 else
  7787.                                     $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7788.                             } else if ($ctype == '!=') {
  7789.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7790.                                     $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  7791.                                 else
  7792.                                     $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7793.                             } else {
  7794.                                 if (is_string($cvalue))
  7795.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7796.                                 else
  7797.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7798.                             }
  7799.                         }
  7800.                     }
  7801. //            if ($joinAndString != '') {
  7802. //                if ($conditionStr != '')
  7803. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  7804. //                else
  7805. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  7806. //            }
  7807.                     if ($joinAndString != '') {
  7808.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7809.                             $joinQry .= ' and (';
  7810.                             $mustBracketDone 1;
  7811.                         }
  7812.                         if ($joinQry != '')
  7813.                             $joinQry .= (" and (" $joinAndString ") ");
  7814.                         else
  7815.                             $joinQry .= ("  (" $joinAndString ") ");
  7816.                     }
  7817.                     $joinAndOrString "";
  7818.                     foreach ($joinAndOrConditions as $andOrCondition) {
  7819. //            $conditionStr.=' 1=1 ';
  7820.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  7821.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  7822.                         $aliasInCondition $table;
  7823.                         if (!(strpos($cfield'.') === false)) {
  7824.                             $fullCfieldArray explode('.'$cfield);
  7825.                             $aliasInCondition $fullCfieldArray[0];
  7826.                             $cfield $fullCfieldArray[1];
  7827.                         }
  7828.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  7829.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7830.                             if ($joinAndOrString != '')
  7831.                                 $joinAndOrString .= " or ";
  7832.                             if ($ctype == 'like') {
  7833.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7834.                                 $wordsBySpaces explode(' '$cvalue);
  7835.                                 foreach ($wordsBySpaces as $word) {
  7836.                                     if ($joinAndOrString != '')
  7837.                                         $joinAndOrString .= " or ";
  7838.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7839.                                 }
  7840.                             } else if ($ctype == 'not like') {
  7841.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7842.                                 $wordsBySpaces explode(' '$cvalue);
  7843.                                 foreach ($wordsBySpaces as $word) {
  7844.                                     if ($joinAndOrString != '')
  7845.                                         $joinAndOrString .= " or ";
  7846.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7847.                                 }
  7848.                             } else if ($ctype == 'not_in') {
  7849.                                 $joinAndOrString .= " ( ";
  7850.                                 if (in_array('null'$cvalue)) {
  7851.                                     $joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
  7852.                                     $cvalue array_diff($cvalue, ['null']);
  7853.                                     if (!empty($cvalue))
  7854.                                         $joinAndOrString .= " or ";
  7855.                                 }
  7856.                                 if (in_array(''$cvalue)) {
  7857.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != '' ";
  7858.                                     $cvalue array_diff($cvalue, ['']);
  7859.                                     if (!empty($cvalue))
  7860.                                         $joinAndOrString .= " or ";
  7861.                                 }
  7862.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7863.                             } else if ($ctype == 'in') {
  7864.                                 if (in_array('null'$cvalue)) {
  7865.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null";
  7866.                                     $cvalue array_diff($cvalue, ['null']);
  7867.                                     if (!empty($cvalue))
  7868.                                         $joinAndOrString .= " or ";
  7869.                                 }
  7870.                                 if (in_array(''$cvalue)) {
  7871.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  7872.                                     $cvalue array_diff($cvalue, ['']);
  7873.                                     if (!empty($cvalue))
  7874.                                         $joinAndOrString .= " or ";
  7875.                                 }
  7876.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7877.                             } else if ($ctype == '=') {
  7878. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7879. //                            $fullCfieldArray = explode('.', $cfield);
  7880. //                            $aliasInCondition = $fullCfieldArray[0];
  7881. //                            $cfield = $fullCfieldArray[1];
  7882. //                        }
  7883.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7884.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
  7885.                                 else
  7886.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7887.                             } else if ($ctype == '!=') {
  7888.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7889.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
  7890.                                 else
  7891.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7892.                             } else {
  7893.                                 if (is_string($cvalue))
  7894.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7895.                                 else
  7896.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7897.                             }
  7898.                         }
  7899.                     }
  7900. //            if ($joinAndOrString != '')
  7901. //                $joinQry .= $joinAndOrString;
  7902.                     if ($joinAndOrString != '') {
  7903.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7904.                             $joinQry .= ' and (';
  7905.                             $mustBracketDone 1;
  7906.                         }
  7907.                         if ($joinQry != '')
  7908.                             $joinQry .= (" and (" $joinAndOrString ") ");
  7909.                         else
  7910.                             $joinQry .= ("  (" $joinAndOrString ") ");
  7911.                     }
  7912.                     //pika
  7913.                     $joinOrString "";
  7914.                     foreach ($joinOrConditions as $orCondition) {
  7915. //            $conditionStr.=' 1=1 ';
  7916.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  7917.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  7918.                         $aliasInCondition $table;
  7919.                         if (!(strpos($cfield'.') === false)) {
  7920.                             $fullCfieldArray explode('.'$cfield);
  7921.                             $aliasInCondition $fullCfieldArray[0];
  7922.                             $cfield $fullCfieldArray[1];
  7923.                         }
  7924.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  7925.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7926.                             if ($joinOrString != '' || $joinAndString != '' || $joinMustString != '')
  7927.                                 $joinOrString .= " or ";
  7928.                             if ($ctype == 'like') {
  7929.                                 $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7930.                                 $wordsBySpaces explode(' '$cvalue);
  7931.                                 foreach ($wordsBySpaces as $word) {
  7932.                                     if ($joinOrString != '')
  7933.                                         $joinOrString .= " or ";
  7934.                                     $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7935.                                 }
  7936.                             } else if ($ctype == 'not like') {
  7937.                                 $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7938.                                 $wordsBySpaces explode(' '$cvalue);
  7939.                                 foreach ($wordsBySpaces as $word) {
  7940.                                     if ($joinOrString != '')
  7941.                                         $joinOrString .= " or ";
  7942.                                     $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7943.                                 }
  7944.                             } else if ($ctype == 'not_in') {
  7945.                                 $joinOrString .= " ( ";
  7946.                                 if (in_array('null'$cvalue)) {
  7947.                                     $joinOrString .= " `$joinTableAlias`.$cfield is not null";
  7948.                                     $cvalue array_diff($cvalue, ['null']);
  7949.                                     if (!empty($cvalue))
  7950.                                         $joinOrString .= " or ";
  7951.                                 }
  7952.                                 if (in_array(''$cvalue)) {
  7953.                                     $joinOrString .= "`$joinTableAlias`.$cfield != '' ";
  7954.                                     $cvalue array_diff($cvalue, ['']);
  7955.                                     if (!empty($cvalue))
  7956.                                         $joinOrString .= " or ";
  7957.                                 }
  7958.                                 $joinOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7959.                             } else if ($ctype == 'in') {
  7960.                                 if (in_array('null'$cvalue)) {
  7961.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null";
  7962.                                     $cvalue array_diff($cvalue, ['null']);
  7963.                                     if (!empty($cvalue))
  7964.                                         $joinOrString .= " or ";
  7965.                                 }
  7966.                                 if (in_array(''$cvalue)) {
  7967.                                     $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  7968.                                     $cvalue array_diff($cvalue, ['']);
  7969.                                     if (!empty($cvalue))
  7970.                                         $joinOrString .= " or ";
  7971.                                 }
  7972.                                 $joinOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7973.                             } else if ($ctype == '=') {
  7974. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7975. //                            $fullCfieldArray = explode('.', $cfield);
  7976. //                            $aliasInCondition = $fullCfieldArray[0];
  7977. //                            $cfield = $fullCfieldArray[1];
  7978. //                        }
  7979.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7980.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null ";
  7981.                                 else
  7982.                                     $joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7983.                             } else if ($ctype == '!=') {
  7984.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7985.                                     $joinOrString .= "`$joinTableAlias`.$cfield is not null ";
  7986.                                 else
  7987.                                     $joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7988.                             } else {
  7989.                                 if (is_string($cvalue))
  7990.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7991.                                 else
  7992.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7993.                             }
  7994.                         }
  7995.                     }
  7996. //            if ($joinOrString != '')
  7997. //                $joinQry .= $joinOrString;
  7998.                     if ($joinOrString != '') {
  7999.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  8000.                             $joinQry .= ' and (';
  8001.                             $mustBracketDone 1;
  8002.                         }
  8003.                         if ($joinQry != '')
  8004.                             $joinQry .= (" or (" $joinOrString ") ");
  8005.                         else
  8006.                             $joinQry .= ("  (" $joinOrString ") ");
  8007.                     }
  8008.                     if ($joinMustString != '' && $mustBracketDone == 1) {
  8009.                         $joinQry .= ' ) ';
  8010.                     }
  8011. //
  8012. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8013.                 }
  8014.                 $filterQryForCriteria .= $selectQry;
  8015.                 $filterQryForCriteria .= $joinQry;
  8016.                 if ($skipDefaultCompanyId == && $companyId != && !isset($dataConfig['entity_group']))
  8017.                     $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  8018.                 else
  8019.                     $filterQryForCriteria .= " where 1=1 ";
  8020.                 $conditionStr "";
  8021.                 $aliasInCondition $table;
  8022.                 if ($headMarkers != '' && $table == 'acc_accounts_head') {
  8023.                     $markerList explode(','$headMarkers);
  8024.                     $spMarkerQry "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
  8025.                     $markerPassedHeads = [];
  8026.                     foreach ($markerList as $mrkr) {
  8027.                         $spMarkerQry .= " and marker_hash like '%" $mrkr "%'";
  8028.                     }
  8029.                     $spStmt $em->getConnection()->prepare($spMarkerQry);
  8030.                     $spStmt->execute();
  8031.                     $spStmtResults $spStmt->fetchAll();
  8032.                     foreach ($spStmtResults as $ggres) {
  8033.                         $markerPassedHeads[] = $ggres['accounts_head_id'];
  8034.                     }
  8035.                     if (!empty($markerPassedHeads)) {
  8036.                         if ($conditionStr != '')
  8037.                             $conditionStr .= " and (";
  8038.                         else
  8039.                             $conditionStr .= " (";
  8040.                         if ($headMarkersStrictMatch != 1) {
  8041.                             foreach ($markerPassedHeads as $mh) {
  8042.                                 $conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" $mh "/%' or ";
  8043.                             }
  8044.                         }
  8045.                         $conditionStr .= "  `$aliasInCondition`.`accounts_head_id` in (" implode(','$markerPassedHeads) . ") ";
  8046.                         $conditionStr .= " )";
  8047.                     }
  8048.                 }
  8049.                 if (isset($restrictionData[$table])) {
  8050.                     $userRestrictionData Users::getUserApplicationAccessSettings($em$userId)['options'];
  8051.                     if (isset($userRestrictionData[$restrictionData[$table]])) {
  8052.                         $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  8053.                         if ($restrictionIdList == null)
  8054.                             $restrictionIdList = [];
  8055.                     }
  8056.                     if (!empty($restrictionIdList)) {
  8057.                         if ($conditionStr != '')
  8058.                             $conditionStr .= " and ";
  8059.                         $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  8060.                     }
  8061.                 }
  8062. //        $aliasInCondition = $table;
  8063.                 if (!empty($setValueArray) || $selectAll == 1) {
  8064.                     if (!empty($setValueArray)) {
  8065.                         if ($conditionStr != '')
  8066.                             $conditionStr .= " and ";
  8067.                         $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  8068.                     }
  8069.                 } else {
  8070.                     $andString '';
  8071.                     foreach ($andConditions as $andCondition) {
  8072. //            $conditionStr.=' 1=1 ';
  8073.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  8074.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  8075.                         $aliasInCondition $table;
  8076.                         if (!(strpos($cfield'.') === false)) {
  8077.                             $fullCfieldArray explode('.'$cfield);
  8078.                             $aliasInCondition $fullCfieldArray[0];
  8079.                             $cfield $fullCfieldArray[1];
  8080.                         }
  8081.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  8082.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8083.                             if ($andString != '')
  8084.                                 $andString .= " and ";
  8085.                             if ($ctype == 'like') {
  8086.                                 $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8087.                                 $wordsBySpaces explode(' '$cvalue);
  8088.                                 foreach ($wordsBySpaces as $word) {
  8089.                                     if ($andString != '')
  8090.                                         $andString .= " and ";
  8091.                                     $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8092.                                 }
  8093.                             } else if ($ctype == 'not like') {
  8094.                                 $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8095.                                 $wordsBySpaces explode(' '$cvalue);
  8096.                                 foreach ($wordsBySpaces as $word) {
  8097.                                     if ($andString != '')
  8098.                                         $andString .= " and ";
  8099.                                     $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8100.                                 }
  8101.                             } else if ($ctype == 'not_in') {
  8102.                                 $andString .= " ( ";
  8103.                                 if (in_array('null'$cvalue)) {
  8104.                                     $andString .= " `$aliasInCondition`.$cfield is not null";
  8105.                                     $cvalue array_diff($cvalue, ['null']);
  8106.                                     if (!empty($cvalue))
  8107.                                         $andString .= " and ";
  8108.                                 }
  8109.                                 if (in_array(''$cvalue)) {
  8110.                                     $andString .= "`$aliasInCondition`.$cfield != '' ";
  8111.                                     $cvalue array_diff($cvalue, ['']);
  8112.                                     if (!empty($cvalue))
  8113.                                         $andString .= " and ";
  8114.                                 }
  8115.                                 $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8116.                             } else if ($ctype == 'in') {
  8117.                                 if (in_array('null'$cvalue)) {
  8118.                                     $andString .= "`$aliasInCondition`.$cfield is null";
  8119.                                     $cvalue array_diff($cvalue, ['null']);
  8120.                                     if (!empty($cvalue))
  8121.                                         $andString .= " and ";
  8122.                                 }
  8123.                                 if (in_array(''$cvalue)) {
  8124.                                     $andString .= "`$aliasInCondition`.$cfield = '' ";
  8125.                                     $cvalue array_diff($cvalue, ['']);
  8126.                                     if (!empty($cvalue))
  8127.                                         $andString .= " and ";
  8128.                                 }
  8129.                                 $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  8130.                             } else if ($ctype == '=') {
  8131.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8132.                                     $andString .= "`$aliasInCondition`.$cfield is null ";
  8133.                                 else
  8134.                                     $andString .= "`$aliasInCondition`.$cfield = $cvalue ";
  8135.                             } else if ($ctype == '!=') {
  8136.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8137.                                     $andString .= "`$aliasInCondition`.$cfield is not null ";
  8138.                                 else
  8139.                                     $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8140.                             } else {
  8141.                                 if (is_string($cvalue))
  8142.                                     $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8143.                                 else
  8144.                                     $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8145.                             }
  8146.                         }
  8147.                     }
  8148.                     if ($andString != '') {
  8149.                         if ($conditionStr != '')
  8150.                             $conditionStr .= (" and (" $andString ") ");
  8151.                         else
  8152.                             $conditionStr .= ("  (" $andString ") ");
  8153.                     }
  8154.                     $orString '';
  8155.                     foreach ($orConditions as $orCondition) {
  8156.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  8157.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  8158.                         $aliasInCondition $table;
  8159.                         if (!(strpos($cfield'.') === false)) {
  8160.                             $fullCfieldArray explode('.'$cfield);
  8161.                             $aliasInCondition $fullCfieldArray[0];
  8162.                             $cfield $fullCfieldArray[1];
  8163.                         }
  8164.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  8165.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8166.                             if ($orString != '')
  8167.                                 $orString .= " or ";
  8168.                             if ($ctype == 'like') {
  8169.                                 $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8170.                                 $wordsBySpaces explode(' '$cvalue);
  8171.                                 foreach ($wordsBySpaces as $word) {
  8172.                                     if ($orString != '')
  8173.                                         $orString .= " or ";
  8174.                                     $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8175.                                 }
  8176.                             } else if ($ctype == 'not like') {
  8177.                                 $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8178.                                 $wordsBySpaces explode(' '$cvalue);
  8179.                                 foreach ($wordsBySpaces as $word) {
  8180.                                     if ($orString != '')
  8181.                                         $orString .= " or ";
  8182.                                     $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8183.                                 }
  8184.                             } else if ($ctype == 'not_in') {
  8185.                                 $orString .= " ( ";
  8186.                                 if (in_array('null'$cvalue)) {
  8187.                                     $orString .= " `$aliasInCondition`.$cfield is not null";
  8188.                                     $cvalue array_diff($cvalue, ['null']);
  8189.                                     if (!empty($cvalue))
  8190.                                         $orString .= " or ";
  8191.                                 }
  8192.                                 if (in_array(''$cvalue)) {
  8193.                                     $orString .= "`$aliasInCondition`.$cfield != '' ";
  8194.                                     $cvalue array_diff($cvalue, ['']);
  8195.                                     if (!empty($cvalue))
  8196.                                         $orString .= " or ";
  8197.                                 }
  8198.                                 $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8199.                             } else if ($ctype == 'in') {
  8200.                                 $orString .= " ( ";
  8201.                                 if (in_array('null'$cvalue)) {
  8202.                                     $orString .= " `$aliasInCondition`.$cfield is null";
  8203.                                     $cvalue array_diff($cvalue, ['null']);
  8204.                                     if (!empty($cvalue))
  8205.                                         $orString .= " or ";
  8206.                                 }
  8207.                                 if (in_array(''$cvalue)) {
  8208.                                     $orString .= "`$aliasInCondition`.$cfield = '' ";
  8209.                                     $cvalue array_diff($cvalue, ['']);
  8210.                                     if (!empty($cvalue))
  8211.                                         $orString .= " or ";
  8212.                                 }
  8213.                                 $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8214.                             } else if ($ctype == '=') {
  8215.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8216.                                     $orString .= "`$aliasInCondition`.$cfield is null ";
  8217.                                 else
  8218.                                     $orString .= "`$aliasInCondition`.$cfield = $cvalue ";
  8219.                             } else if ($ctype == '!=') {
  8220.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8221.                                     $orString .= "`$aliasInCondition`.$cfield is not null ";
  8222.                                 else
  8223.                                     $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8224.                             } else {
  8225.                                 if (is_string($cvalue))
  8226.                                     $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8227.                                 else
  8228.                                     $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8229.                             }
  8230.                         }
  8231.                     }
  8232.                     if ($orString != '') {
  8233.                         if ($conditionStr != '')
  8234.                             $conditionStr .= (" or (" $orString ") ");
  8235.                         else
  8236.                             $conditionStr .= ("  (" $orString ") ");
  8237.                     }
  8238.                     $andOrString '';
  8239.                     foreach ($andOrConditions as $andOrCondition) {
  8240.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  8241.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  8242.                         $aliasInCondition $table;
  8243.                         if (!(strpos($cfield'.') === false)) {
  8244.                             $fullCfieldArray explode('.'$cfield);
  8245.                             $aliasInCondition $fullCfieldArray[0];
  8246.                             $cfield $fullCfieldArray[1];
  8247.                         }
  8248.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  8249.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8250.                             if ($andOrString != '')
  8251.                                 $andOrString .= " or ";
  8252.                             if ($ctype == 'like') {
  8253.                                 $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8254.                                 $wordsBySpaces explode(' '$cvalue);
  8255.                                 foreach ($wordsBySpaces as $word) {
  8256.                                     if ($andOrString != '')
  8257.                                         $andOrString .= " or ";
  8258.                                     $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8259.                                 }
  8260.                             } else if ($ctype == 'not like') {
  8261.                                 $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8262.                                 $wordsBySpaces explode(' '$cvalue);
  8263.                                 foreach ($wordsBySpaces as $word) {
  8264.                                     if ($andOrString != '')
  8265.                                         $andOrString .= " or ";
  8266.                                     $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8267.                                 }
  8268.                             } else if ($ctype == 'in') {
  8269.                                 $andOrString .= " ( ";
  8270.                                 if (in_array('null'$cvalue)) {
  8271.                                     $andOrString .= " `$aliasInCondition`.$cfield is null";
  8272.                                     $cvalue array_diff($cvalue, ['null']);
  8273.                                     if (!empty($cvalue))
  8274.                                         $andOrString .= " or ";
  8275.                                 }
  8276.                                 if (in_array(''$cvalue)) {
  8277.                                     $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  8278.                                     $cvalue array_diff($cvalue, ['']);
  8279.                                     if (!empty($cvalue))
  8280.                                         $andOrString .= " or ";
  8281.                                 }
  8282.                                 if (!empty($cvalue))
  8283.                                     $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8284.                                 else
  8285.                                     $andOrString .= "  ) ";
  8286.                             } else if ($ctype == 'not_in') {
  8287.                                 $andOrString .= " ( ";
  8288.                                 if (in_array('null'$cvalue)) {
  8289.                                     $andOrString .= " `$aliasInCondition`.$cfield is not null";
  8290.                                     $cvalue array_diff($cvalue, ['null']);
  8291.                                     if (!empty($cvalue))
  8292.                                         $andOrString .= " or ";
  8293.                                 }
  8294.                                 if (in_array(''$cvalue)) {
  8295.                                     $andOrString .= "`$aliasInCondition`.$cfield != '' ";
  8296.                                     $cvalue array_diff($cvalue, ['']);
  8297.                                     if (!empty($cvalue))
  8298.                                         $andOrString .= " or ";
  8299.                                 }
  8300.                                 if (!empty($cvalue))
  8301.                                     $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8302.                                 else
  8303.                                     $andOrString .= "  ) ";
  8304.                             } else if ($ctype == '=') {
  8305.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8306.                                     $andOrString .= "`$aliasInCondition`.$cfield is null ";
  8307.                                 else
  8308.                                     $andOrString .= "`$aliasInCondition`.$cfield = $cvalue ";
  8309.                             } else if ($ctype == '!=') {
  8310.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8311.                                     $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  8312.                                 else
  8313.                                     $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8314.                             } else {
  8315.                                 if (is_string($cvalue))
  8316.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8317.                                 else
  8318.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8319.                             }
  8320.                         }
  8321.                     }
  8322.                     if ($andOrString != '') {
  8323.                         if ($conditionStr != '')
  8324.                             $conditionStr .= (" and (" $andOrString ") ");
  8325.                         else
  8326.                             $conditionStr .= ("  (" $andOrString ") ");
  8327.                     }
  8328.                 }
  8329.                 $mustStr '';
  8330. ///now must conditions
  8331.                 foreach ($mustConditions as $mustCondition) {
  8332. //            $conditionStr.=' 1=1 ';
  8333.                     $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  8334.                     $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  8335.                     $aliasInCondition $table;
  8336.                     if (!(strpos($cfield'.') === false)) {
  8337.                         $fullCfieldArray explode('.'$cfield);
  8338.                         $aliasInCondition $fullCfieldArray[0];
  8339.                         $cfield $fullCfieldArray[1];
  8340.                     }
  8341.                     $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  8342.                     if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8343.                         if ($mustStr != '')
  8344.                             $mustStr .= " and ";
  8345.                         if ($ctype == 'like') {
  8346.                             $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8347.                             $wordsBySpaces explode(' '$cvalue);
  8348.                             foreach ($wordsBySpaces as $word) {
  8349.                                 if ($mustStr != '')
  8350.                                     $mustStr .= " or ";
  8351.                                 $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8352.                             }
  8353.                             $mustStr .= " )";
  8354.                         } else if ($ctype == 'not like') {
  8355.                             $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8356.                             $wordsBySpaces explode(' '$cvalue);
  8357.                             foreach ($wordsBySpaces as $word) {
  8358.                                 if ($mustStr != '')
  8359.                                     $mustStr .= " and ";
  8360.                                 $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8361.                             }
  8362.                         } else if ($ctype == 'in') {
  8363.                             $mustStr .= " ( ";
  8364.                             if (in_array('null'$cvalue)) {
  8365.                                 $mustStr .= " `$aliasInCondition`.$cfield is null";
  8366.                                 $cvalue array_diff($cvalue, ['null']);
  8367.                                 if (!empty($cvalue))
  8368.                                     $mustStr .= " or ";
  8369.                             }
  8370.                             if (in_array(''$cvalue)) {
  8371.                                 $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  8372.                                 $cvalue array_diff($cvalue, ['']);
  8373.                                 if (!empty($cvalue))
  8374.                                     $mustStr .= " or ";
  8375.                             }
  8376.                             $mustStr .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8377.                         } else if ($ctype == 'not_in') {
  8378.                             $mustStr .= " ( ";
  8379.                             if (in_array('null'$cvalue)) {
  8380.                                 $mustStr .= " `$aliasInCondition`.$cfield is not null";
  8381.                                 $cvalue array_diff($cvalue, ['null']);
  8382.                                 if (!empty($cvalue))
  8383.                                     $mustStr .= " and ";
  8384.                             }
  8385.                             if (in_array(''$cvalue)) {
  8386.                                 $mustStr .= "`$aliasInCondition`.$cfield != '' ";
  8387.                                 $cvalue array_diff($cvalue, ['']);
  8388.                                 if (!empty($cvalue))
  8389.                                     $mustStr .= " and ";
  8390.                             }
  8391.                             $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8392.                         } else if ($ctype == '=') {
  8393.                             if ($cvalue == 'null' || $cvalue == 'Null')
  8394.                                 $mustStr .= "`$aliasInCondition`.$cfield is null ";
  8395.                             else
  8396.                                 $mustStr .= "`$aliasInCondition`.$cfield = $cvalue ";
  8397.                         } else if ($ctype == '!=') {
  8398.                             if ($cvalue == 'null' || $cvalue == 'Null')
  8399.                                 $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  8400.                             else
  8401.                                 $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  8402.                         } else {
  8403.                             if (is_string($cvalue))
  8404.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8405.                             else
  8406.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8407.                         }
  8408.                     }
  8409.                 }
  8410.                 if ($mustStr != '') {
  8411.                     if ($conditionStr != '')
  8412.                         $conditionStr .= (" and (" $mustStr ") ");
  8413.                     else
  8414.                         $conditionStr .= ("  (" $mustStr ") ");
  8415.                 }
  8416.                 if ($conditionStr != '')
  8417.                     $filterQryForCriteria .= (" and (" $conditionStr ") ");
  8418.                 if ($lastChildrenOnly == 1) {
  8419.                     if ($filterQryForCriteria != '')
  8420.                         $filterQryForCriteria .= ' and';
  8421.                     $filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  8422.                 } else if ($parentOnly == 1) {
  8423.                     if ($filterQryForCriteria != '')
  8424.                         $filterQryForCriteria .= ' and';
  8425.                     $filterQryForCriteria .= "`$table`.`$valueField`  in ( select distinct $parentIdField from  $table)";
  8426.                 }
  8427.                 if (!empty($orderByConditions)) {
  8428.                     $filterQryForCriteria .= "  order by ";
  8429.                     $fone 1;
  8430.                     foreach ($orderByConditions as $orderByCondition) {
  8431.                         if ($fone != 1) {
  8432.                             $filterQryForCriteria .= " , ";
  8433.                         }
  8434.                         if (isset($orderByCondition['valueList'])) {
  8435.                             if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  8436.                             if ($orderByCondition['valueList'] == null)
  8437.                                 $orderByCondition['valueList'] = [];
  8438.                             $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  8439.                         } else
  8440.                             $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  8441.                         $fone 0;
  8442.                     }
  8443.                 }
  8444.                 if ($returnTotalMatchedEntriesFlag == 1) {
  8445. //            $stmt = $em->getConnection()->prepare($get_kids_sql);
  8446. //            $stmt->execute();
  8447. //            $get_kids = $stmt->fetchAll();
  8448.                 }
  8449.                 if ($filterQryForCriteria != '')
  8450.                     if (!empty($setValueArray) || $selectAll == 1) {
  8451.                     } else {
  8452.                         if ($itemLimit != '_ALL_')
  8453.                             $filterQryForCriteria .= "  limit $offset$itemLimit ";
  8454.                         else
  8455.                             $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  8456.                     }
  8457.                 $get_kids_sql $filterQryForCriteria;
  8458.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  8459.                 $stmt->execute();
  8460.                 $get_kids $stmt->fetchAll();
  8461.                 $selectedId 0;
  8462.                 if ($table == 'warehouse_action') {
  8463.                     if (empty($get_kids)) {
  8464.                         $get_kids_sql_2 "select * from warehouse_action";
  8465.                         $stmt $em->getConnection()->prepare($get_kids_sql_2);
  8466.                         $stmt->execute();
  8467.                         $get_kids2 $stmt->fetchAll();
  8468.                         if (empty($get_kids2))
  8469.                             $get_kids GeneralConstant::$warehouse_action_list;
  8470.                     }
  8471.                 }
  8472.                 if (!empty($get_kids)) {
  8473.                     $nextOffset $offset count($get_kids);
  8474.                     $nextOffset++;
  8475.                     foreach ($get_kids as $pa) {
  8476.                         if (!empty($setValueArray) && $selectAll == 0) {
  8477.                             if (!in_array($pa[$valueField], $setValueArray))
  8478.                                 continue;
  8479.                         }
  8480.                         if (!empty($restrictionIdList)) {
  8481.                             if (!in_array($pa[$valueField], $restrictionIdList))
  8482.                                 continue;
  8483.                         }
  8484.                         if ($selectAll == 1) {
  8485.                             $setValueArray[] = $pa[$valueField];
  8486.                             $setValue $pa[$valueField];
  8487.                         } else if (count($get_kids) == && $setDataForSingle == 1) {
  8488.                             $setValueArray[] = $pa[$valueField];
  8489.                             $setValue $pa[$valueField];
  8490.                         }
  8491.                         if ($valueField != '')
  8492.                             $pa['value'] = $pa[$valueField];
  8493.                         $renderedText $renderTextFormat;
  8494.                         $compare_array = [];
  8495.                         if ($renderTextFormat != '') {
  8496.                             $renderedText $renderTextFormat;
  8497.                             $compare_arrayFull = [];
  8498.                             $compare_array = [];
  8499.                             $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  8500.                             );
  8501.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  8502.                             if (isset($compare_arrayFull[0]))
  8503.                                 $compare_array $compare_arrayFull[0];
  8504. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  8505.                             foreach ($compare_array as $cmpdt) {
  8506.                                 $tbr str_replace("__"""$cmpdt);
  8507.                                 if ($tbr != '') {
  8508.                                     if (isset($pa[$tbr])) {
  8509.                                         if ($pa[$tbr] == null)
  8510.                                             $renderedText str_replace($cmpdt''$renderedText);
  8511.                                         else
  8512.                                             $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  8513.                                     } else {
  8514.                                         $renderedText str_replace($cmpdt''$renderedText);
  8515.                                     }
  8516.                                 }
  8517.                             }
  8518.                         }
  8519.                         $pa['rendered_text'] = $renderedText;
  8520.                         $pa['text'] = ($textField != '' $pa[$textField] : '');
  8521. //                $pa['compare_array'] = $compare_array;
  8522.                         foreach ($convertToObjectFieldList as $convField) {
  8523.                             if (isset($pa[$convField])) {
  8524.                                 $taA json_decode($pa[$convField], true);
  8525.                                 if ($taA == null$taA = [];
  8526.                                 $pa[$convField] = $taA;
  8527.                             } else {
  8528.                                 $pa[$convField] = [];
  8529.                             }
  8530.                         }
  8531.                         foreach ($convertDateToStringFieldList as $convField) {
  8532.                             if (is_array($convField)) {
  8533.                                 $fld $convField['field'];
  8534.                                 $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  8535.                             } else {
  8536.                                 $fld $convField;
  8537.                                 $frmt 'Y-m-d H:i:s';
  8538.                             }
  8539.                             if (isset($pa[$fld])) {
  8540.                                 $taA = new \DateTime($pa[$fld]);
  8541.                                 $pa[$fld] = $taA->format($frmt);
  8542.                             }
  8543.                         }
  8544.                         foreach ($convertToUrl as $convField) {
  8545. //
  8546. //                            $fld = $convField;
  8547. //
  8548. //
  8549. //                            if (isset($pa[$fld])) {
  8550. //
  8551. //
  8552. //                                $pa[$fld] =
  8553. //                                    $this->generateUrl(
  8554. //                                        'dashboard', [
  8555. //
  8556. //                                    ], UrlGenerator::ABSOLUTE_URL
  8557. //                                    ).'/'.$pa[$fld];
  8558. //
  8559. //                            }
  8560.                         }
  8561.                         foreach ($fullPathList as $pathField) {
  8562.                             $fld $pathField;
  8563.                             if (isset($pa[$fld])) {
  8564.                                 if ($pa[$fld] !='' && $pa[$fld] !=null) {
  8565.                                     $pa[$fld]=($this->generateUrl(
  8566.                                             'dashboard', [
  8567.                                         ], UrlGenerator::ABSOLUTE_URL
  8568.                                         ).$pa[$fld]);
  8569.                                 }
  8570.                             }
  8571.                         }
  8572.                         $pa['currentTs'] = (new \Datetime())->format('U');
  8573.                         $data[] = $pa;
  8574.                         if ($valueField != '') {
  8575.                             $data_by_id[$pa[$valueField]] = $pa;
  8576.                             $selectedId $pa[$valueField];
  8577.                         }
  8578.                     }
  8579.                 }
  8580.                 if ($dataOnly == 1)
  8581.                     $lastResult = array(
  8582.                         'success' => true,
  8583.                         'data' => $data,
  8584.                         'currentTs' => (new \Datetime())->format('U'),
  8585.                         'restrictionIdList' => $restrictionIdList,
  8586.                         'nextOffset' => $nextOffset,
  8587.                         'totalMatchedEntries' => $totalMatchedEntries,
  8588.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8589.                     );
  8590.                 else
  8591.                     $lastResult = array(
  8592.                         'success' => true,
  8593.                         'data' => $data,
  8594.                         'tableName' => $table,
  8595.                         'setValue' => $setValue,
  8596.                         'currentTs' => (new \Datetime())->format('U'),
  8597.                         'restrictionIdList' => $restrictionIdList,
  8598.                         'andConditions' => $andConditions,
  8599.                         'queryStr' => $queryStringIndividual,
  8600.                         'isMultiple' => $isMultiple,
  8601.                         'nextOffset' => $nextOffset,
  8602.                         'totalMatchedEntries' => $totalMatchedEntries,
  8603.                         'selectorId' => $selectorId,
  8604.                         'setValueArray' => $setValueArray,
  8605.                         'silentChangeSelectize' => $silentChangeSelectize,
  8606.                         'convertToObjectFieldList' => $convertToObjectFieldList,
  8607.                         'conditionStr' => $conditionStr,
  8608. //                    'andStr' => $andString,
  8609. //                    'andOrStr' => $andOrString,
  8610.                         'dataById' => $data_by_id,
  8611.                         'selectedId' => $selectedId,
  8612.                         'dataId' => $dataId,
  8613.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8614.                     );
  8615.             }
  8616.             $allResult[] = $lastResult;
  8617.         }
  8618.         if ($isSingleDataset == 1)
  8619.             return new JsonResponse($lastResult);
  8620.         else
  8621.             return new JsonResponse($allResult);
  8622.     }
  8623.     public function updatePlanningItemSequenceAction(Request $request$queryStr '')
  8624.     {
  8625.         $em $this->getDoctrine()->getManager();
  8626.         $stmt $em->getConnection()->prepare("select  `id` , parent_id, sequence from planning_item where sequence is null 
  8627.             ORDER BY parent_id ASC, id ASC
  8628.                         ");
  8629.         $stmt->execute();
  8630.         $query_output $stmt->fetchAll();
  8631.         foreach ($query_output as $dupe) {
  8632.             System::updatePlanningItemSequence($em$dupe["id"]);
  8633.         }
  8634.         System::updatePlanningItemSequence(
  8635.             $em,
  8636.             $request->request->get('planningItemId'0),
  8637.             $request->request->get('assignType''_ASSIGN_')   ///can be _MOVE_UP_ or _MOVE_DOWN_
  8638.         );
  8639. //        if($request->query->has('returnJson'))
  8640.         return new JsonResponse(
  8641.             array(
  8642.                 'success' => true,
  8643.                 'data' => [],
  8644.             )
  8645.         );
  8646.     }
  8647.     public function insertDataAjaxAction(Request $request$queryStr '')
  8648.     {
  8649.         $em $this->getDoctrine()->getManager();
  8650. //        if($request->query->has('big_data_test'))
  8651. //        {
  8652. //            for($t=0;$t<$request->request->get('big_data_test',10000);$t++) {
  8653. //                $em = $this->getDoctrine()->getManager('company_group');
  8654. //                $NOTIFICATION = new EntityNotification();
  8655. //                $NOTIFICATION->setAppId(1);
  8656. //                $NOTIFICATION->setCompanyId(0);
  8657. //                $NOTIFICATION->setCompanyId(0);
  8658. //                $NOTIFICATION->setBody('Test Description'.$t);
  8659. //                $NOTIFICATION->setTitle('Test Title'.$t);
  8660. //                $NOTIFICATION->setExpireTs(0);
  8661. //                $NOTIFICATION->setIsBuddybee(0);
  8662. //                $NOTIFICATION->setType(0);
  8663. //                $em->persist($NOTIFICATION);
  8664. //                $em->flush();
  8665. //            }
  8666. //
  8667. //            return new JsonResponse(
  8668. //                array(
  8669. //                    'success' => true,
  8670. //                    'data' => [],
  8671. //
  8672. //
  8673. //                )
  8674. //            );
  8675. //
  8676. //
  8677. //        }
  8678.         if ($request->request->get('entity_group'0)) {
  8679.             $companyId 0;
  8680.             $em $this->getDoctrine()->getManager('company_group');
  8681.         } else
  8682.             $companyId $this->getLoggedUserCompanyId($request);
  8683.         if ($companyId) {
  8684.             $company_data = [];
  8685. //            $company_data = Company::getCompanyData($em, $companyId);
  8686.         } else {
  8687.             $companyId 0;
  8688.             $company_data = [];
  8689.         }
  8690. //        $theEntity= new EntityNotification();
  8691. //        $entityName = 'EntityNotification';
  8692. //
  8693. //        $className='\\CompanyGroupBundle\\Entity\\'.$entityName;
  8694. //
  8695. //
  8696. //            $theEntity= new $className();
  8697.         $dataToAdd $request->request->has('dataToAdd') ? $request->request->get('dataToAdd') : [];
  8698.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8699.         if ($dataToAdd == null$dataToAdd = [];
  8700.         $dataToRemove $request->request->has('dataToRemove') ? $request->request->get('dataToRemove') : [];
  8701.         if (is_string($dataToRemove)) $dataToAdd json_decode($dataToRemovetrue);
  8702.         if ($dataToRemove == null$dataToRemove = [];
  8703.         $relData = [];
  8704.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8705.         $updatedDataList = [];
  8706.         foreach ($dataToAdd as $dataInd => $dat) {
  8707.             $entityName $dat['entityName'];
  8708.             $idField $dat['idField'];
  8709.             $findByField = isset($dat['findByField']) ? $dat['findByField'] : '';
  8710.             $findByValue = isset($dat['findByValue']) ? $dat['findByValue'] : '';
  8711.             $returnRefIndex $dat['returnRefIndex'];
  8712.             $findById $dat['findId'];
  8713.             $dataFields = isset($dat['dataFields']) ? $dat['dataFields'] : [];
  8714.             $noCreation = isset($dat['noCreation']) ? $dat['noCreation'] : 0;
  8715.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  8716.             $preAdditionalSql = isset($dat['preAdditionalSql']) ? $dat['preAdditionalSql'] : '';
  8717.             if ($preAdditionalSql != '') {
  8718. //            if ($entityName == 'PlanningItem') {
  8719. //
  8720. //                $stmt='select disctinct parent_id from planning_item;';
  8721. //                $stmt->execute();
  8722. //                $get_kids = $stmt->fetchAll();
  8723. //                $p_ids=[];
  8724. //                foreach($get_kids as $g)
  8725. //                {
  8726. //                    $p_ids[]=$g['parent_id'];
  8727. //                }
  8728. //
  8729. //
  8730. //
  8731.                 $stmt $em->getConnection()->prepare($preAdditionalSql);
  8732.                 $stmt->execute();
  8733.                 $stmt->closeCursor();
  8734. //
  8735. //
  8736.             }
  8737.             if ($entityName == 'PlanningItem') {
  8738.                 $stmt $em->getConnection()->prepare("select  `id` , parent_id, sequence from planning_item where sequence is null
  8739.             ORDER BY parent_id ASC, id ASC
  8740.                         ");
  8741.                 $stmt->execute();
  8742.                 $query_output $stmt->fetchAll();
  8743.                 foreach ($query_output as $dupe) {
  8744.                     System::updatePlanningItemSequence($em$dupe["id"]);
  8745.                 }
  8746.             }
  8747.             $className = ($request->request->get('entity_group'0) ? '\\CompanyGroupBundle\\Entity\\' '\\ApplicationBundle\\Entity\\') . $entityName;
  8748.             if (
  8749.                 ($findById == || $findById == '_NA_') && $findByField == '' && $noCreation == 0
  8750.             ) {
  8751.                 $theEntity = new $className();
  8752. //                $theEntity= new EntityNotification();
  8753.             } else {
  8754.                 if ($findByField != '') {
  8755.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findOneBy(
  8756.                         array
  8757.                         (
  8758.                             $findByField => $findByValue,
  8759.                         )
  8760.                     );
  8761.                 } else {
  8762.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findOneBy(
  8763.                         array
  8764.                         (
  8765.                             $idField => $findById,
  8766.                         )
  8767.                     );
  8768.                 }
  8769.             }
  8770.             if (!$theEntity && $noCreation == 0)
  8771.                 $theEntity = new $className();
  8772.             foreach ($dataFields as $dt) {
  8773.                 $setMethod 'set' ucfirst($dt['field']);
  8774.                 $getMethod 'get' ucfirst($dt['field']);
  8775.                 $type = isset($dt['type']) ? $dt['type'] : '_VALUE_';
  8776.                 $action = isset($dt['action']) ? $dt['action'] : '_REPLACE_';
  8777.                 if (method_exists($theEntity$setMethod)) {
  8778.                     $oldValue $theEntity->{$getMethod}();
  8779.                     $newValue $oldValue;
  8780.                     if ($type == '_VALUE_') {
  8781.                         $newValue $dt['value'];
  8782.                     }
  8783.                     if ($type == '_DECIMAL_') {
  8784.                         $newValue $dt['value'];
  8785.                     }
  8786.                     if ($type == '_DATE_') {
  8787.                         $newValue = new \DateTime($dt['value']);
  8788.                     }
  8789.                     if ($type == '_ARRAY_') {
  8790.                         $oldValue json_decode($oldValue);
  8791.                         if ($oldValue == null$oldValue = [];
  8792.                         if ($action == '_REPLACE_') {
  8793.                             $newValue json_encode($dt['value']);
  8794.                         }
  8795.                         if ($action == '_APPEND_') {
  8796.                             $newValue array_merge($oldValuearray_values(array_diff([$dt['value']], $oldValue)));
  8797.                         }
  8798.                         if ($action == '_MERGE_') {
  8799.                             $newValue array_merge($oldValuearray_values(array_diff($dt['value'], $oldValue)));
  8800.                         }
  8801.                         if ($action == '_EXCLUDE_') {
  8802.                             $newValue array_values(array_diff($oldValue, [$dt['value']]));
  8803.                         }
  8804.                         if ($action == '_EXCLUDE_ARRAY_') {
  8805.                             $newValue array_values(array_diff($oldValue$dt['value']));
  8806.                         }
  8807.                         $newValue json_encode($newValue);
  8808.                     }
  8809.                     $theEntity->{$setMethod}($newValue); // `foo!`
  8810. //                    $theEntity->setCompletionPercentage(78); // `foo!`
  8811.                 }
  8812.             }
  8813.             if ($additionalSql != '') {
  8814. //            if ($entityName == 'PlanningItem') {
  8815. //
  8816. //                $stmt='select disctinct parent_id from planning_item;';
  8817. //                $stmt->execute();
  8818. //                $get_kids = $stmt->fetchAll();
  8819. //                $p_ids=[];
  8820. //                foreach($get_kids as $g)
  8821. //                {
  8822. //                    $p_ids[]=$g['parent_id'];
  8823. //                }
  8824. //
  8825. //
  8826. //
  8827.                 $stmt $em->getConnection()->prepare($additionalSql);
  8828.                 $stmt->execute();
  8829.                 $stmt->closeCursor();
  8830. //
  8831. //
  8832.             }
  8833.             if (($findById == || $findById == '_NA_') && $noCreation == 0) {
  8834.                 $em->persist($theEntity);
  8835.                 $em->flush();
  8836.                 $getMethod 'get' ucfirst($idField);
  8837.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8838.             } else if ($theEntity) {
  8839.                 $em->flush();
  8840.                 $getMethod 'get' ucfirst($idField);
  8841.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8842.             }
  8843.             if ($entityName == 'PlanningItem') {
  8844.                 $stmt $em->getConnection()->prepare('select distinct parent_id from planning_item;');
  8845.                 $stmt->execute();
  8846.                 $get_kids $stmt->fetchAll();
  8847.                 $p_ids = [];
  8848.                 foreach ($get_kids as $g) {
  8849.                     $p_ids[] = $g['parent_id'];
  8850.                 }
  8851.                 $stmt $em->getConnection()->prepare('UPDATE planning_item d SET d.`has_child` =0 WHERE d.id NOT IN (' implode(','$p_ids) . '); 
  8852.                           UPDATE planning_item d SET d.`has_child` =1 WHERE d.id  IN (' implode(','$p_ids) . ')');
  8853.                 $stmt->execute();
  8854.                 $stmt->closeCursor();
  8855.                 $updatedData System::updatePlanningItemSequence($em$theEntity->getId());
  8856.                 $theEntity $updatedData['primaryOne'];
  8857.                 $theEntityUpdated $theEntity;
  8858.                 if ($theEntityUpdated->getEntryType() == 4)///cashflow
  8859.                 {
  8860.                     MiscActions::AddCashFlowProjection($em0, [
  8861.                         'planningItemId' => $theEntityUpdated->getId(),
  8862.                         'fundRequisitionId' => 0,
  8863.                         'concernedPersonId' => 0,
  8864.                         'type' => 1//exp
  8865.                         'subType' => 1//1== khoroch hobe 2: ashbe
  8866.                         'cashFlowType' => 1//2== RCV /in  1: Payment/out
  8867.                         'creationType' => 1//auto
  8868.                         'amountType' => 1//fund
  8869.                         'cashFlowAmount' => 0,
  8870.                         'expAstAmount' => 0,
  8871.                         'accumulatedCashFlowAmount' => 0,
  8872.                         'accumulatedCashFlowBalance' => 0,
  8873.                         'accumulatedExpAstAmount' => 0,
  8874.                         'relevantExpAstHeadId' => 0,
  8875.                         'balancingHeadId' => 0,
  8876.                         'cashFlowHeadId' => 0,
  8877.                         'cashFlowHeadType' => 1,
  8878.                         'relevantProductIds' => [],
  8879.                         'reminderDateTs' => 0,
  8880.                         'cashFlowDateTs' => 0,
  8881.                         'expAstRealizationDateTs' => 0,
  8882.                     ]);
  8883.                 }
  8884.             } else if ($entityName == 'TaskLog') {
  8885.                 $session $request->getSession();
  8886.                 if ($theEntity) {
  8887.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  8888.                     $currTime = new \DateTime();
  8889.                     $options = array(
  8890.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8891.                         'notification_server' => $this->container->getParameter('notification_server'),
  8892.                     );
  8893.                     $positionsArray = [
  8894.                         array(
  8895.                             'employeeId' => $empId,
  8896.                             'userId' => $session->get(UserConstants::USER_ID0),
  8897.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  8898.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  8899.                             'lat' => 23.8623834,
  8900.                             'lng' => 90.3979294,
  8901.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING,
  8902. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  8903.                         )
  8904.                     ];
  8905.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  8906.                     if ($positionsArray == null$positionsArray = [];
  8907.                     $dataByAttId = [];
  8908.                     $workPlaceType '_UNSET_';
  8909.                     foreach ($positionsArray as $findex => $d) {
  8910.                         $sysUserId 0;
  8911.                         $userId 0;
  8912.                         $empId 0;
  8913.                         $dtTs 0;
  8914.                         $timeZoneStr '+0000';
  8915.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  8916.                         if (isset($d['userId'])) $userId $d['userId'];
  8917.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  8918.                         if (isset($d['tsMilSec'])) {
  8919.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  8920.                         }
  8921.                         if ($dtTs == 0) {
  8922.                             $currTsTime = new \DateTime();
  8923.                             $dtTs $currTsTime->format('U');
  8924.                         } else {
  8925.                             $currTsTime = new \DateTime('@' $dtTs);
  8926.                         }
  8927.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  8928.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  8929.                         $EmployeeAttendance $this->getDoctrine()
  8930.                             ->getRepository(EmployeeAttendance::class)
  8931.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  8932.                         if (!$EmployeeAttendance) {
  8933.                             $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8934.                             $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8935.                             $EmployeeAttendance = new EmployeeAttendance;
  8936.                         } else {
  8937.                             if ($EmployeeAttendance->getCurrentLocation() == 'out') {
  8938.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8939.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8940.                             } else {
  8941.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8942.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8943.                             }
  8944.                         }
  8945.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  8946.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  8947.                             $workPlaceType '_STATIC_';
  8948.                         }
  8949.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  8950.                             $dataByAttId[$attendanceInfo->getId()] = array(
  8951.                                 'attendanceInfo' => $attendanceInfo,
  8952.                                 'empId' => $empId,
  8953.                                 'lat' => 0,
  8954.                                 'lng' => 0,
  8955.                                 'address' => 0,
  8956.                                 'sysUserId' => $sysUserId,
  8957.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8958.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8959.                                 'positionArray' => []
  8960.                             );
  8961.                         $posData = array(
  8962.                             'ts' => $dtTs,
  8963.                             'lat' => $d['lat'],
  8964.                             'lng' => $d['lng'],
  8965.                             'marker' => $d['markerId'],
  8966.                             'src' => 2,
  8967.                         );
  8968.                         $posDataArray = array(
  8969.                             $dtTs,
  8970.                             $d['lat'],
  8971.                             $d['lng'],
  8972.                             $d['markerId'],
  8973.                             2
  8974.                         );
  8975.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  8976.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  8977.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  8978.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  8979.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  8980.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  8981.                         if (isset($d['address']))
  8982.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  8983. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  8984.                     }
  8985.                     $response = array(
  8986.                         'success' => true,
  8987.                     );
  8988.                     foreach ($dataByAttId as $attInfoId => $d) {
  8989.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  8990.                             $d['empId'],
  8991.                             $d['sysUserId'],
  8992.                             $d['companyId'],
  8993.                             $d['appId'],
  8994.                             $request,
  8995.                             $d['attendanceInfo'],
  8996.                             $options,
  8997.                             $d['positionArray'],
  8998.                             $d['lat'],
  8999.                             $d['lng'],
  9000.                             $d['address'],
  9001.                             $d['markerId']
  9002.                         );
  9003.                     }
  9004.                     $session->set(UserConstants::USER_CURRENT_TASK_ID$theEntity->getId());
  9005.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$theEntity->getPlanningItemId());
  9006.                 } else {
  9007.                     $session->set(UserConstants::USER_CURRENT_TASK_ID0);
  9008.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID0);
  9009.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  9010.                     $currTime = new \DateTime();
  9011.                     $options = array(
  9012.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  9013.                         'notification_server' => $this->container->getParameter('notification_server'),
  9014.                     );
  9015.                     $positionsArray = [
  9016.                         array(
  9017.                             'employeeId' => $empId,
  9018.                             'userId' => $session->get(UserConstants::USER_ID0),
  9019.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  9020.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  9021.                             'lat' => 23.8623834,
  9022.                             'lng' => 90.3979294,
  9023.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT,
  9024. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  9025.                         )
  9026.                     ];
  9027.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  9028.                     if ($positionsArray == null$positionsArray = [];
  9029.                     $dataByAttId = [];
  9030.                     $workPlaceType '_UNSET_';
  9031.                     foreach ($positionsArray as $findex => $d) {
  9032.                         $sysUserId 0;
  9033.                         $userId 0;
  9034.                         $empId 0;
  9035.                         $dtTs 0;
  9036.                         $timeZoneStr '+0000';
  9037.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  9038.                         if (isset($d['userId'])) $userId $d['userId'];
  9039.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  9040.                         if (isset($d['tsMilSec'])) {
  9041.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  9042.                         }
  9043.                         if ($dtTs == 0) {
  9044.                             $currTsTime = new \DateTime();
  9045.                             $dtTs $currTsTime->format('U');
  9046.                         } else {
  9047.                             $currTsTime = new \DateTime('@' $dtTs);
  9048.                         }
  9049.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  9050.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  9051.                         $EmployeeAttendance $this->getDoctrine()
  9052.                             ->getRepository(EmployeeAttendance::class)
  9053.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  9054.                         if (!$EmployeeAttendance) {
  9055.                             continue;
  9056.                         } else {
  9057.                         }
  9058.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  9059.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT) {
  9060.                             $workPlaceType '_STATIC_';
  9061.                         }
  9062.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  9063.                             $dataByAttId[$attendanceInfo->getId()] = array(
  9064.                                 'attendanceInfo' => $attendanceInfo,
  9065.                                 'empId' => $empId,
  9066.                                 'lat' => 0,
  9067.                                 'lng' => 0,
  9068.                                 'address' => 0,
  9069.                                 'sysUserId' => $sysUserId,
  9070.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  9071.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  9072.                                 'positionArray' => []
  9073.                             );
  9074.                         $posData = array(
  9075.                             'ts' => $dtTs,
  9076.                             'lat' => $d['lat'],
  9077.                             'lng' => $d['lng'],
  9078.                             'marker' => $d['markerId'],
  9079.                             'src' => 2,
  9080.                         );
  9081.                         $posDataArray = array(
  9082.                             $dtTs,
  9083.                             $d['lat'],
  9084.                             $d['lng'],
  9085.                             $d['markerId'],
  9086.                             2
  9087.                         );
  9088.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  9089.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  9090.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  9091.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  9092.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  9093.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  9094.                         if (isset($d['address']))
  9095.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  9096. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  9097.                     }
  9098.                     $response = array(
  9099.                         'success' => true,
  9100.                     );
  9101.                     foreach ($dataByAttId as $attInfoId => $d) {
  9102.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  9103.                             $d['empId'],
  9104.                             $d['sysUserId'],
  9105.                             $d['companyId'],
  9106.                             $d['appId'],
  9107.                             $request,
  9108.                             $d['attendanceInfo'],
  9109.                             $options,
  9110.                             $d['positionArray'],
  9111.                             $d['lat'],
  9112.                             $d['lng'],
  9113.                             $d['address'],
  9114.                             $d['markerId']
  9115.                         );
  9116.                     }
  9117.                 }
  9118.                 $theEntityUpdated $theEntity;
  9119.             } else
  9120.                 $theEntityUpdated $theEntity;
  9121. //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  9122.             $getters = [];
  9123.             if ($theEntityUpdated)
  9124.                 $getters array_filter(get_class_methods($theEntityUpdated), function ($method) {
  9125.                     return 'get' === substr($method03);
  9126.                 });
  9127.             $updatedData = [];
  9128.             foreach ($getters as $getter) {
  9129.                 $indForThis str_replace('get'''$getter);
  9130.                 $indForThis lcfirst($indForThis);
  9131.                 $updatedData[$indForThis] = $theEntityUpdated->{$getter}();
  9132.             }
  9133.             $updatedDataList[$dataInd] = $updatedData;
  9134.         }
  9135.         foreach ($dataToRemove as $dataInd => $dat) {
  9136.             $entityName $dat['entityName'];
  9137.             $idField $dat['idField'];
  9138.             $findById $dat['findId'];
  9139.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  9140.             $theEntityList $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findBy(
  9141.                 array
  9142.                 (
  9143.                     $idField => $findById,
  9144.                 )
  9145.             );
  9146.             foreach ($theEntityList as $dt) {
  9147.                 $em->remove($dt);
  9148.                 $em->flush();
  9149.             }
  9150.             if ($additionalSql != '') {
  9151. //            if ($entityName == 'PlanningItem') {
  9152. //
  9153. //                $stmt='select disctinct parent_id from planning_item;';
  9154. //                $stmt->execute();
  9155. //                $get_kids = $stmt->fetchAll();
  9156. //                $p_ids=[];
  9157. //                foreach($get_kids as $g)
  9158. //                {
  9159. //                    $p_ids[]=$g['parent_id'];
  9160. //                }
  9161. //
  9162. //
  9163. //
  9164.                 $stmt $em->getConnection()->prepare($additionalSql);
  9165.                 $stmt->execute();
  9166.                 $stmt->closeCursor();
  9167. //
  9168. //
  9169.             }
  9170.             $updatedDataList[$dataInd] = [];
  9171.         }
  9172. //        if ($table == '') {
  9173. //            return new JsonResponse(
  9174. //                array(
  9175. //                    'success' => false,
  9176. ////                    'page_title' => 'Product Details',
  9177. ////                    'company_data' => $company_data,
  9178. //                    'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9179. //
  9180. //                )
  9181. //            );
  9182. //        }
  9183. //        if($request->query->has('returnJson'))
  9184.         return new JsonResponse(
  9185.             array(
  9186.                 'success' => true,
  9187.                 'data' => $relData,
  9188.                 'updatedDataList' => $updatedDataList,
  9189.             )
  9190.         );
  9191.     }
  9192.     public function GetAvailableQtyAction(Request $request$id 0)
  9193.     {
  9194.         $em $this->getDoctrine()->getManager();
  9195.         $productId $request->request->has('productId') ? $request->request->get('productId') : 0;
  9196.         $colorId $request->request->has('colorId') ? $request->request->get('colorId') : 0;
  9197.         $dataId $request->request->has('dataId') ? $request->request->get('dataId') : 0;
  9198.         $allowedWarehouseIds $request->request->has('warehouseId') ? [$request->request->get('warehouseId')] : [];
  9199.         $allowedWarehouseActionIds $request->request->has('warehouseActionId') ? [$request->request->get('warehouseActionId')] : [];
  9200.         $qty Inventory::getProductQty($em$productId$allowedWarehouseIds$allowedWarehouseActionIds$colorId);
  9201.         return new JsonResponse(array("success" => true,
  9202.             "qty" => $qty,
  9203.             "dataId" => $dataId,
  9204.         ));
  9205.     }
  9206.     public
  9207.     function ProductListSelectAjaxAction(Request $request$queryStr '')
  9208.     {
  9209.         $em $this->getDoctrine()->getManager();
  9210.         $companyId $this->getLoggedUserCompanyId($request);
  9211.         $company_data Company::getCompanyData($em$companyId);
  9212.         $data = [];
  9213.         $data_by_id = [];
  9214.         $html '';
  9215.         $productByCodeData = [];
  9216.         if ($queryStr == '_EMPTY_')
  9217.             $queryStr '';
  9218.         if ($request->request->has('query') && $queryStr == '')
  9219.             $queryStr $request->request->get('queryStr');
  9220.         if ($queryStr == '_EMPTY_')
  9221.             $queryStr '';
  9222. //        $queryStr=urldecode($queryStr);
  9223.         $queryStr str_replace('_FSLASH_''/'$queryStr);
  9224.         $filterQryForCriteria "select * from inv_products where 1=1 ";
  9225.         if ($request->request->has('sellableOnly') && $request->request->get('sellableOnly') != 0)
  9226.             $filterQryForCriteria .= " and sellable=1";
  9227.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9228.             $filterQryForCriteria .= " and sub_category_id=" $request->request->get('subCategoryId');
  9229.         else if ($request->request->has('categoryId') && $request->request->get('categoryId') != '')
  9230.             $filterQryForCriteria .= " and category_id=" $request->request->get('categoryId');
  9231.         else if ($request->request->has('igId') && $request->request->get('igId') != '')
  9232.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  9233.         if ($request->request->has('brandId') && $request->request->get('brandId') != '')
  9234.             $filterQryForCriteria .= " and brand_company=" $request->request->get('brandId');
  9235.         if ($request->request->has('restrictedBrandIds') && $request->request->get('restrictedBrandIds') != [])
  9236.             $filterQryForCriteria .= " and brand_company in (" implode(','$request->request->get('restrictedBrandIds')) . ")";
  9237.         if ($request->request->has('productIds'))
  9238.             $filterQryForCriteria .= " and id in (" implode(','$request->request->get('productIds')) . ") ";
  9239.         else if ($request->request->has('productCode'))
  9240.             $filterQryForCriteria .= " and product_code  like '%" $request->request->get('productCode') . "%'  ";
  9241.         else if ($queryStr != '')
  9242.             $filterQryForCriteria .= " and  (product_code  like '%" $queryStr "%' or `name`   like '%" $queryStr "%' or model_no like '%" $queryStr "%') ";
  9243.         if ($filterQryForCriteria != '')
  9244.             $filterQryForCriteria .= "  limit 25";
  9245.         $get_kids_sql $filterQryForCriteria;
  9246. //        if ($request->request->has('productIds'))
  9247. //
  9248. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9249. //        else if ($request->request->has('productCode'))
  9250. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9251. //        else if ($filterQryForCriteria!='')
  9252. //            $get_kids_sql = $filterQryForCriteria;
  9253. //
  9254. //        else
  9255. //               $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";
  9256.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9257.         $stmt->execute();
  9258.         $get_kids $stmt->fetchAll();
  9259.         $productId 0;
  9260.         if (!empty($get_kids)) {
  9261.             foreach ($get_kids as $product) {
  9262.                 $pa = array();
  9263.                 $pa['id'] = $product['id'];
  9264.                 $pa['name'] = $product['name'];
  9265.                 $pa['id_name'] = $product['id'] . '. ' $product['name'];
  9266.                 $pa['id_mn'] = $product['id'] . '. ' $product['model_no'];;
  9267.                 $pa['id_name_mn'] = $product['id'] . '. ' $product['name'] . ' ( ' $product['model_no'] . ' )';
  9268.                 $pa['globalId'] = $product['global_id'];
  9269.                 $pa['classSuffix'] = $product['class_suffix'];
  9270.                 $pa['productFdm'] = $product['product_fdm'];
  9271.                 $pa['modelNo'] = $product['model_no'];
  9272.                 $pa['partId'] = $product['part_id'];
  9273.                 $pa['hsCode'] = $product['hs_code'];
  9274.                 $pa['productCode'] = $product['product_code'];
  9275.                 $pa['text'] = $product['name'];
  9276.                 $pa['value'] = $product['id'];
  9277.                 $pa['tac'] = $product['tac'];
  9278.                 $pa['igId'] = $product['ig_id'];
  9279.                 $pa['categoryId'] = $product['category_id'];
  9280.                 $pa['subCategoryId'] = $product['sub_category_id'];
  9281.                 $pa['brandCompany'] = $product['brand_company'];
  9282.                 $pa['sales_price'] = $product['curr_sales_price'];
  9283.                 $pa['purchase_price'] = $product['curr_purchase_price'];
  9284.                 $pa['unit_type'] = $product['unit_type_id'];
  9285.                 $pa['single_weight'] = $product['single_weight'];
  9286.                 $pa['single_weight_variance_type'] = $product['single_weight_variance_type'];
  9287.                 $pa['single_weight_variance_value'] = $product['single_weight_variance_value'];
  9288.                 $pa['weight'] = $product['weight'];
  9289.                 $pa['weight_variance_type'] = $product['weight_variance_type'];
  9290.                 $pa['weight_variance_value'] = $product['weight_variance_value'];
  9291.                 $pa['carton_capacity_count'] = $product['carton_capacity_count'];
  9292.                 $pa['type'] = $product['type'];
  9293.                 $pa['qty'] = $product['qty'];
  9294. //                $pa['alias'] = '';
  9295.                 $pa['alias'] = $product['alias'];
  9296.                 $pa['note'] = $product['note'];
  9297.                 $pa['defaultTaxConfigId'] = $product['default_tax_config_id'] == null $product['default_tax_config_id'];
  9298.                 $pa['defaultPurchaseTaxConfigId'] = $product['default_purchase_tax_config_id'] == null $product['default_purchase_tax_config_id'];
  9299.                 $tax_config_ids json_decode($product['tax_config_ids'], true);
  9300.                 if ($tax_config_ids == null)
  9301.                     $tax_config_ids = [];
  9302.                 $pa['taxConfigIds'] = $tax_config_ids;
  9303.                 $purchase_tax_config_ids json_decode($product['purchase_tax_config_ids'], true);
  9304.                 if ($purchase_tax_config_ids == null)
  9305.                     $purchase_tax_config_ids = [];
  9306.                 $pa['purchaseTaxConfigIds'] = $tax_config_ids;
  9307.                 $inco_terms json_decode($product['inco_terms'], true);
  9308.                 if ($inco_terms == null)
  9309.                     $inco_terms = [];
  9310.                 $pa['incoTerms'] = $inco_terms;
  9311.                 $pa['defaultIncoTerm'] = $product['default_inco_term'] == null $product['default_inco_term'];
  9312.                 $pa['has_serial'] = $product['has_serial'];
  9313.                 $pa['expiry_days'] = $product['expiry_days'];
  9314.                 $pa['image'] = $product['default_image'];
  9315.                 $pa['sales_warranty'] = $product['sales_warranty_months'];;
  9316.                 $pa['defaultColorId'] = $product['default_color_id'];;
  9317.                 $allowedColorIds json_decode($product['colors'], true);
  9318.                 if ($allowedColorIds == null$allowedColorIds = [];
  9319.                 if (!in_array($product['default_color_id'], $allowedColorIds))
  9320.                     $allowedColorIds[] = $product['default_color_id'];
  9321.                 $pa['allowedColorIds'] = $allowedColorIds;;
  9322.                 $data[] = $pa;
  9323.                 $data_by_id[$product['id']] = $pa;
  9324.                 $productId $product['id'];
  9325.             }
  9326.         }
  9327. //        if($request->query->has('returnJson'))
  9328.         {
  9329.             return new JsonResponse(
  9330.                 array(
  9331.                     'success' => true,
  9332. //                    'page_title' => 'Product Details',
  9333. //                    'company_data' => $company_data,
  9334.                     'data' => $data,
  9335.                     'dataById' => $data_by_id,
  9336.                     'productId' => $productId,
  9337.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9338. //                    'exId'=>$id,
  9339. //                'productByCodeData' => $productByCodeData,
  9340. //                'productData' => $productData,
  9341. //                'currInvList' => $currInvList,
  9342. //                'productList' => Inventory::ProductList($em, $companyId),
  9343. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9344. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9345. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9346. //                'unitList' => Inventory::UnitTypeList($em),
  9347. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9348. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9349. //                'warehouseList' => Inventory::WarehouseList($em),
  9350.                 )
  9351.             );
  9352.         }
  9353.     }
  9354.     public function labelFormatSelectAjaxAction(Request $request$queryStr '')
  9355.     {
  9356.         $em $this->getDoctrine()->getManager();
  9357.         $companyId $this->getLoggedUserCompanyId($request);
  9358.         $company_data Company::getCompanyData($em$companyId);
  9359.         $data = [];
  9360.         $data_by_id = [];
  9361.         $html '';
  9362.         $productByCodeData = [];
  9363.         if ($queryStr == '_EMPTY_')
  9364.             $queryStr '';
  9365.         if ($request->request->has('query') && $queryStr == '')
  9366.             $queryStr $request->request->get('queryStr');
  9367.         if ($queryStr == '_EMPTY_')
  9368.             $queryStr '';
  9369.         $filterQryForCriteria "select * from label_format where company_id=" $companyId " ";
  9370.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  9371.             $filterQryForCriteria .= " and label_type=" $request->request->get('dataType');
  9372.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  9373.             $filterQryForCriteria .= " and format_id=" $request->request->get('formatId');
  9374.         else if ($queryStr != '')
  9375.             $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' or `format_code` like '%" $queryStr "%') ";
  9376.         if ($filterQryForCriteria != '')
  9377.             $filterQryForCriteria .= "  limit 25";
  9378.         $get_kids_sql $filterQryForCriteria;
  9379. //        if ($request->request->has('productIds'))
  9380. //
  9381. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9382. //        else if ($request->request->has('productCode'))
  9383. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9384. //        else if ($filterQryForCriteria!='')
  9385. //            $get_kids_sql = $filterQryForCriteria;
  9386. //
  9387. //        else
  9388. //               $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";
  9389.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9390.         $stmt->execute();
  9391.         $get_kids $stmt->fetchAll();
  9392.         $productId 0;
  9393.         if (!empty($get_kids)) {
  9394.             foreach ($get_kids as $product) {
  9395.                 $pa = array();
  9396.                 $pa['id'] = $product['format_id'];
  9397.                 $pa['name'] = $product['name'];
  9398.                 $pa['format_code'] = $product['format_code'] . '. ' $product['name'];
  9399.                 $pa['id_code_name'] = $product['format_id'] . '. ' $product['format_code'] . ' - ' $product['name'] . ' ';
  9400.                 $pa['text'] = $product['name'];
  9401.                 $pa['value'] = $product['format_id'];
  9402.                 $data[] = $pa;
  9403.                 $data_by_id[$product['format_id']] = $pa;
  9404.                 $productId $product['format_id'];
  9405.             }
  9406.         }
  9407. //        if($request->query->has('returnJson'))
  9408.         {
  9409.             return new JsonResponse(
  9410.                 array(
  9411.                     'success' => true,
  9412. //                    'page_title' => 'Product Details',
  9413. //                    'company_data' => $company_data,
  9414.                     'data' => $data,
  9415.                     'dataById' => $data_by_id,
  9416.                     'productId' => $productId,
  9417.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9418. //                    'exId'=>$id,
  9419. //                'productByCodeData' => $productByCodeData,
  9420. //                'productData' => $productData,
  9421. //                'currInvList' => $currInvList,
  9422. //                'productList' => Inventory::ProductList($em, $companyId),
  9423. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9424. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9425. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9426. //                'unitList' => Inventory::UnitTypeList($em),
  9427. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9428. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9429. //                'warehouseList' => Inventory::WarehouseList($em),
  9430.                 )
  9431.             );
  9432.         }
  9433.     }
  9434.     public function CategoryListSelectAjaxAction(Request $request$queryStr '')
  9435.     {
  9436.         $em $this->getDoctrine()->getManager();
  9437.         $companyId $this->getLoggedUserCompanyId($request);
  9438.         $company_data Company::getCompanyData($em$companyId);
  9439.         $data = [];
  9440.         $data_by_id = [];
  9441.         $html '';
  9442.         $productByCodeData = [];
  9443.         if ($queryStr == '_EMPTY_')
  9444.             $queryStr '';
  9445.         if ($request->request->has('query') && $queryStr == '')
  9446.             $queryStr $request->request->get('queryStr');
  9447.         if ($queryStr == '_EMPTY_')
  9448.             $queryStr '';
  9449.         $filterQryForCriteria "select * from inv_product_categories where company_id=" $companyId " ";
  9450.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  9451.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  9452.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  9453.         if ($filterQryForCriteria != '')
  9454.             $filterQryForCriteria .= "  limit 25";
  9455.         $get_kids_sql $filterQryForCriteria;
  9456. //        if ($request->request->has('productIds'))
  9457. //
  9458. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9459. //        else if ($request->request->has('productCode'))
  9460. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9461. //        else if ($filterQryForCriteria!='')
  9462. //            $get_kids_sql = $filterQryForCriteria;
  9463. //
  9464. //        else
  9465. //               $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";
  9466.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9467.         $stmt->execute();
  9468.         $get_kids $stmt->fetchAll();
  9469.         $productId 0;
  9470.         if (!empty($get_kids)) {
  9471.             foreach ($get_kids as $product) {
  9472.                 $pa = array();
  9473.                 $pa['id'] = $product['id'];
  9474.                 $pa['name'] = $product['name'];
  9475.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  9476.                 $pa['globalId'] = $product['global_id'];
  9477.                 $pa['text'] = $product['name'];
  9478.                 $pa['value'] = $product['id'];
  9479.                 $pa['igId'] = $product['ig_id'];
  9480. //                $pa['categoryId'] = $product['category_id'];
  9481. //                $pa['subCategoryId'] = $product['sub_category_id'];
  9482.                 $data[] = $pa;
  9483.                 $data_by_id[$product['id']] = $pa;
  9484.                 $productId $product['id'];
  9485.             }
  9486.         }
  9487. //        if($request->query->has('returnJson'))
  9488.         {
  9489.             return new JsonResponse(
  9490.                 array(
  9491.                     'success' => true,
  9492. //                    'page_title' => 'Product Details',
  9493. //                    'company_data' => $company_data,
  9494.                     'data' => $data,
  9495.                     'dataById' => $data_by_id,
  9496.                     'productId' => $productId,
  9497.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9498. //                    'exId'=>$id,
  9499. //                'productByCodeData' => $productByCodeData,
  9500. //                'productData' => $productData,
  9501. //                'currInvList' => $currInvList,
  9502. //                'productList' => Inventory::ProductList($em, $companyId),
  9503. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9504. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9505. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9506. //                'unitList' => Inventory::UnitTypeList($em),
  9507. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9508. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9509. //                'warehouseList' => Inventory::WarehouseList($em),
  9510.                 )
  9511.             );
  9512.         }
  9513.     }
  9514.     public function SubCategoryListSelectAjaxAction(Request $request$queryStr '')
  9515.     {
  9516.         $em $this->getDoctrine()->getManager();
  9517.         $companyId $this->getLoggedUserCompanyId($request);
  9518.         $company_data Company::getCompanyData($em$companyId);
  9519.         $data = [];
  9520.         $data_by_id = [];
  9521.         $html '';
  9522.         $productByCodeData = [];
  9523.         if ($queryStr == '_EMPTY_')
  9524.             $queryStr '';
  9525.         if ($request->request->has('query') && $queryStr == '')
  9526.             $queryStr $request->request->get('queryStr');
  9527.         if ($queryStr == '_EMPTY_')
  9528.             $queryStr '';
  9529.         $filterQryForCriteria "select * from inv_product_sub_categories where company_id=" $companyId " ";
  9530.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9531.             $filterQryForCriteria .= " and sub_category_id=" $request->request->get('subCategoryId');
  9532.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  9533.             $filterQryForCriteria .= " and category_id=" $request->request->get('categoryId');
  9534.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  9535.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  9536.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  9537.             if ($request->request->get('parentId') != 0)
  9538.                 $filterQryForCriteria .= " and  parent_id=" $request->request->get('parentId');
  9539.             else
  9540.                 $filterQryForCriteria .= " and ( parent_id =0 or parent_id is null ) ";
  9541.         if ($request->request->has('level') && $request->request->get('level') != '')
  9542.             if ($request->request->get('level') != 0)
  9543.                 $filterQryForCriteria .= " and level=" $request->request->get('level');
  9544.             else
  9545.                 $filterQryForCriteria .= " and ( level =0 or level is null) ";
  9546.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  9547.         if ($filterQryForCriteria != '')
  9548.             $filterQryForCriteria .= "  limit 25";
  9549.         $get_kids_sql $filterQryForCriteria;
  9550. //        if ($request->request->has('productIds'))
  9551. //
  9552. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9553. //        else if ($request->request->has('productCode'))
  9554. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9555. //        else if ($filterQryForCriteria!='')
  9556. //            $get_kids_sql = $filterQryForCriteria;
  9557. //
  9558. //        else
  9559. //               $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";
  9560.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9561.         $stmt->execute();
  9562.         $get_kids $stmt->fetchAll();
  9563.         $productId 0;
  9564.         if (!empty($get_kids)) {
  9565.             foreach ($get_kids as $product) {
  9566.                 $pa = array();
  9567.                 $pa['id'] = $product['id'];
  9568.                 $pa['name'] = $product['name'];
  9569.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  9570.                 $pa['globalId'] = $product['global_id'];
  9571.                 $pa['parentId'] = $product['parent_id'];
  9572.                 $pa['text'] = $product['name'];
  9573.                 $pa['value'] = $product['id'];
  9574.                 $pa['igId'] = $product['ig_id'];
  9575.                 $pa['categoryId'] = $product['category_id'];
  9576. //                $pa['subCategoryId'] = $product['sub_category_id'];
  9577.                 $data[] = $pa;
  9578.                 $data_by_id[$product['id']] = $pa;
  9579.                 $productId $product['id'];
  9580.             }
  9581.         }
  9582. //        if($request->query->has('returnJson'))
  9583.         {
  9584.             return new JsonResponse(
  9585.                 array(
  9586.                     'success' => true,
  9587. //                    'page_title' => 'Product Details',
  9588. //                    'company_data' => $company_data,
  9589.                     'data' => $data,
  9590.                     'dataById' => $data_by_id,
  9591.                     'productId' => $productId,
  9592.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9593. //                    'exId'=>$id,
  9594. //                'productByCodeData' => $productByCodeData,
  9595. //                'productData' => $productData,
  9596. //                'currInvList' => $currInvList,
  9597. //                'productList' => Inventory::ProductList($em, $companyId),
  9598. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9599. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9600. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9601. //                'unitList' => Inventory::UnitTypeList($em),
  9602. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9603. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9604. //                'warehouseList' => Inventory::WarehouseList($em),
  9605.                 )
  9606.             );
  9607.         }
  9608.     }
  9609.     public
  9610.     function ProductByCodeViewAction(Request $request$id 0)
  9611.     {
  9612.         $em $this->getDoctrine()->getManager();
  9613.         $companyId $this->getLoggedUserCompanyId($request);
  9614.         $company_data Company::getCompanyData($em$companyId);
  9615.         $data = [];
  9616.         $html '';
  9617.         $productByCodeData = [];
  9618.         if ($id != 0) {
  9619.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9620.                 ->findOneBy(
  9621.                     array(
  9622.                         'productByCodeId' => $id
  9623.                     )
  9624.                 );
  9625.         } else {
  9626.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9627.                 ->findOneBy(
  9628.                     array(
  9629. //                        'productByCodeId' => $id,
  9630.                         'CompanyId' => $companyId
  9631.                     ), array(
  9632.                         'productByCodeId' => 'DESC'
  9633.                     )
  9634.                 );
  9635.             if ($productByCodeData)
  9636.                 $id $productByCodeData->getProductByCodeId();
  9637.         }
  9638.         if ($id != 0) {
  9639.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9640.                 ->findOneBy(
  9641.                     array(
  9642.                         'id' => $productByCodeData->getProductId()
  9643.                     )
  9644.                 );
  9645.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9646.                 ->findBy(
  9647.                     array(
  9648.                         'productId' => $id
  9649.                     )
  9650.                 );
  9651.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  9652.                 array(
  9653.                     'page_title' => 'Product Details',
  9654.                     'company_data' => $company_data,
  9655.                     'productByCodeData' => $productByCodeData,
  9656.                     'productData' => $productData,
  9657.                     'currInvList' => $currInvList,
  9658.                     'exId' => $id,
  9659.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9660.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9661.                     'productList' => Inventory::ProductList($em$companyId),
  9662.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9663.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9664.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9665.                     'unitList' => Inventory::UnitTypeList($em),
  9666.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9667.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9668.                     'warehouseList' => Inventory::WarehouseList($em),
  9669.                 )
  9670.             );
  9671.         } else {
  9672.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  9673.                 array(
  9674.                     'exId' => $id,
  9675.                 )
  9676.             );
  9677.         }
  9678.         if ($request->query->has('returnJson')) {
  9679.             return new JsonResponse(
  9680.                 array(
  9681.                     'success' => true,
  9682.                     'page_title' => 'Product Details',
  9683.                     'company_data' => $company_data,
  9684.                     'renderedHtml' => $html,
  9685.                     'exId' => $id,
  9686. //                'productByCodeData' => $productByCodeData,
  9687. //                'productData' => $productData,
  9688. //                'currInvList' => $currInvList,
  9689. //                'productList' => Inventory::ProductList($em, $companyId),
  9690. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9691. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9692. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9693. //                'unitList' => Inventory::UnitTypeList($em),
  9694. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9695. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9696. //                'warehouseList' => Inventory::WarehouseList($em),
  9697.                 )
  9698.             );
  9699.         } else {
  9700. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9701. //                ->findBy(
  9702. //                    array(
  9703. ////                        'productByCodeId' => $id,
  9704. //                    'CompanyId'=>$companyId
  9705. //                    )
  9706. //                );
  9707.             $productByCodeList = []; //called by ajax
  9708.             return $this->render('@Inventory/pages/views/product_by_code_view.html.twig',
  9709.                 array(
  9710.                     'page_title' => 'Product Details',
  9711.                     'company_data' => $company_data,
  9712.                     'renderedHtml' => $html,
  9713.                     'exId' => $id,
  9714.                     'productByCodeList' => $productByCodeList,
  9715. //                'productByCodeData' => $productByCodeData,
  9716. //                'productData' => $productData,
  9717. //                'currInvList' => $currInvList,
  9718. //                'productList' => Inventory::ProductList($em, $companyId),
  9719. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9720. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9721. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9722. //                'unitList' => Inventory::UnitTypeList($em),
  9723. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9724. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9725. //                'warehouseList' => Inventory::WarehouseList($em),
  9726.                 )
  9727.             );
  9728.         }
  9729.     }
  9730.     public
  9731.     function ConsumptionSettingsAction(Request $request$id)
  9732.     {
  9733.         $cc_id '';
  9734.         $cc_name '';
  9735.         $em $this->getDoctrine()->getManager();
  9736.         $companyId $this->getLoggedUserCompanyId($request);
  9737.         $consumptionTypeId 0;
  9738.         if ($request->isMethod('POST')) {
  9739.             $new_cc = [];
  9740.             if ($request->request->get('consumptionTypeId') != '' && $request->request->get('consumptionTypeId') != 0) {
  9741.                 $em $this->getDoctrine()->getManager();
  9742.                 $new_cc $this->getDoctrine()
  9743.                     ->getRepository('ApplicationBundle:ConsumptionType')
  9744.                     ->findOneBy(
  9745.                         array(
  9746.                             'consumptionTypeId' => $request->request->get('consumptionTypeId'),
  9747.                         )
  9748.                     );
  9749.                 $new_cc->setName($request->request->get('name'));
  9750.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9751.                 $new_cc->setCompanyId($companyId);
  9752.                 $em->flush();
  9753.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9754.                 $this->addFlash(
  9755.                     'success',
  9756.                     'Consumption Information Updated'
  9757.                 );
  9758.             } else {
  9759.                 $new_cc = new ConsumptionType();
  9760.                 $new_cc->setName($request->request->get('name'));
  9761.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9762.                 $new_cc->setCompanyId($companyId);
  9763.                 $em->persist($new_cc);
  9764.                 $em->flush();
  9765.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9766.                 $em->flush();
  9767.                 $this->addFlash(
  9768.                     'success',
  9769.                     'New Consumption Type Added'
  9770.                 );
  9771.             }
  9772.         }
  9773.         $extData = [];
  9774.         if ($id != 0) {
  9775.             $extData $this->getDoctrine()
  9776.                 ->getRepository('ApplicationBundle:ConsumptionType')
  9777.                 ->findOneBy(
  9778.                     array(
  9779.                         'consumptionTypeId' => $id
  9780.                     )
  9781.                 );
  9782. //            $cc_data_list = [];
  9783. //            foreach ($cc_data as $value) {
  9784. //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  9785. //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  9786. //
  9787. //                if ($value->getSupplierCategoryId() == $id) {
  9788. //                    $cc_id = $value->getSupplierCategoryId();
  9789. //                    $cc_name = $value->getName();
  9790. //                }
  9791. //            }
  9792.         }
  9793.         return $this->render('@Inventory/pages/input_forms/consumption_settings.html.twig',
  9794.             array(
  9795.                 'page_title' => 'Consumption Settings',
  9796.                 'consumptionTypeList' => $this->getDoctrine()
  9797.                     ->getRepository('ApplicationBundle:ConsumptionType')
  9798.                     ->findBy(
  9799.                         array(
  9800.                             'CompanyId' => $companyId
  9801.                         )
  9802.                     ),
  9803.                 'extData' => $extData,
  9804.                 'headList' => Accounts::getParentLedgerHeads($em),
  9805. //                'countryList'=>SalesOrderM::Co
  9806.             )
  9807.         );
  9808.     }
  9809.     public
  9810.     function ProductByCodeCheckAssignPrintAction(Request $request$id 0)
  9811.     {
  9812.         $em $this->getDoctrine()->getManager();
  9813.         $companyId $this->getLoggedUserCompanyId($request);
  9814.         $company_data Company::getCompanyData($em$companyId);
  9815.         $data = [];
  9816.         $html '';
  9817.         $productByCodeData = [];
  9818.         $productDataWeightPackageGm '';
  9819.         $productDataWeightVarianceValue 0;
  9820.         $productDataWeightVarianceType 0;
  9821.         $productByCodeDataObj = [];
  9822.         $dr_id 0;//for dr_id
  9823.         $skipRenderData 0;
  9824.         if ($request->query->has('skipRenderData'))
  9825.             $skipRenderData $request->query->get('skipRenderData');
  9826.         if ($id != 0) {
  9827.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9828.                 ->findOneBy(
  9829.                     array(
  9830.                         'productByCodeId' => $id
  9831.                     )
  9832.                 );
  9833.         } else {
  9834.             if ($request->query->has('scanCode')) {
  9835.                 $query $em->getRepository('ApplicationBundle:ProductByCode')
  9836.                     ->createQueryBuilder('p');
  9837.                 if ($request->query->has('assigned')) {
  9838.                     $query->where('p.assigned > :av')
  9839.                         ->setParameter('av'$request->query->get('assigned'));
  9840.                 } else
  9841.                     $query->where("1=0");
  9842.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  9843.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  9844.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  9845.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  9846.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  9847.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  9848.                 $query->setMaxResults(1);
  9849.                 $results $query->getQuery()->getResult();
  9850.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  9851.             } else
  9852.                 $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9853.                     ->findOneBy(
  9854.                         array(
  9855. //                        'productByCodeId' => $id,
  9856.                             'CompanyId' => $companyId
  9857.                         ), array(
  9858.                             'productByCodeId' => 'DESC'
  9859.                         )
  9860.                     );
  9861.             if ($productByCodeData)
  9862.                 $id $productByCodeData->getProductByCodeId();
  9863.         }
  9864.         if ($id != 0) {
  9865.             $productByCodeDataObj = array(
  9866.                 'salesCode' => $productByCodeData->getSalesCode(),
  9867.                 'sales_code' => $productByCodeData->getSalesCode(),
  9868.                 'sn' => $productByCodeData->getSerialNo(),
  9869.                 'serialNo' => $productByCodeData->getSerialNo(),
  9870.                 'imei1' => $productByCodeData->getImei1(),
  9871.                 'imei2' => $productByCodeData->getImei2(),
  9872.                 'soId' => $productByCodeData->getSalesOrderId(),
  9873.                 'poId' => $productByCodeData->getPurchaseOrderId(),
  9874.                 'irrId' => $productByCodeData->getIrrId(),
  9875.                 'productId' => $productByCodeData->getProductId(),
  9876.                 'productByCodeId' => $productByCodeData->getProductByCodeId(),
  9877.                 'warehouseId' => $productByCodeData->getWarehouseId(),
  9878.                 'warehouseActionId' => $productByCodeData->getWarehouseActionId(),
  9879.                 'stId' => $productByCodeData->getStockTransferId(),
  9880.                 'srId' => $productByCodeData->getStockReceivedNoteId(),
  9881.                 'scmpId' => $productByCodeData->getStockConsumptionNoteId(),
  9882.                 'clientId' => $productByCodeData->getClientId(),
  9883.                 'supplierId' => $productByCodeData->getSupplierId(),
  9884.                 'drId' => $productByCodeData->getDeliveryReceiptId(),
  9885.                 'consumerName' => $productByCodeData->getConsumerName(),
  9886.                 'drItemData' => [],
  9887. //                'salesCodes' => $productByCodeData->getDeliveryReceiptId(),
  9888.             );
  9889.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9890.                 ->findOneBy(
  9891.                     array(
  9892.                         'id' => $productByCodeData->getProductId()
  9893.                     )
  9894.                 );
  9895.             if ($productByCodeData->getProductionId() != null) {
  9896.                 $productionDataHere $em->getRepository('ApplicationBundle:Production')
  9897.                     ->findOneBy(
  9898.                         array(
  9899.                             'productionId' => $productByCodeData->getProductionId()
  9900.                         )
  9901.                     );
  9902.                 if ($productionDataHere) {
  9903.                     $productDataWeightPackageGm $productionDataHere->getPackageWeight();
  9904.                     $productDataWeightVarianceValue $productionDataHere->getPackageWeightVarianceValue();
  9905.                     $productDataWeightVarianceType $productionDataHere->getPackageWeightVarianceType();
  9906.                 }
  9907.             } else {
  9908.                 if ($productData) {
  9909.                     $productDataWeightPackageGm $productData->getWeight();
  9910.                     $productDataWeightVarianceValue $productData->getWeightVarianceValue();
  9911.                     $productDataWeightVarianceType $productData->getWeightVarianceType();
  9912.                 }
  9913.             }
  9914.             if ($productData) {
  9915.                 $productByCodeDataObj['unitTypeId'] = $productData->getUnitTypeId();
  9916.                 $productByCodeDataObj['purchasePrice'] = $productData->getPurchasePrice();
  9917.                 $productByCodeDataObj['productFdm'] = $productData->getProductFdm();
  9918.                 $productByCodeDataObj['productName'] = $productData->getName();
  9919.                 if ($request->request->has('forSalesReturn') || $request->query->has('forSalesReturn')) {
  9920.                     $QD $this->getDoctrine()
  9921.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  9922.                         ->findOneBy(
  9923.                             array(
  9924.                                 'deliveryReceiptId' => $productByCodeData->getDeliveryReceiptId(),
  9925.                                 'productId' => $productByCodeData->getProductId(),
  9926.                             )
  9927.                         );
  9928. //            if($request->request->get('wareHouseId')!='')
  9929.                     if ($QD) {
  9930.                         $new_pid $QD->getProductId();
  9931.                         $sales_code_range = [];
  9932.                         if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  9933.                             $sales_code_range json_decode($QD->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  9934.                         } else {
  9935.                             $max_int_length strlen((string)PHP_INT_MAX) - 1;
  9936.                             $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$QD->getSalesCodeRange());
  9937.                             $sales_code_range json_decode($json_without_bigintstrue);
  9938.                         }
  9939.                         $p_data = array(
  9940.                             'details_id' => $QD->getId(),
  9941.                             'productId' => $new_pid,
  9942.                             'dr_id' => $productByCodeData->getDeliveryReceiptId(),
  9943.                             'product_name' => $productData->getName(),
  9944.                             'qty' => $QD->getQty(),
  9945.                             'delivered' => $QD->getDelivered(),
  9946.                             'unitTypeId' => $QD->getUnitTypeId(),
  9947.                             'deliverable' => $QD->getDeliverable(),
  9948.                             'balance' => $QD->getBalance(),
  9949.                             'salesCodeRangeStr' => $QD->getSalesCodeRange(),
  9950.                             'salesCodeRange' => $sales_code_range,
  9951.                             'sales_codes' => $sales_code_range,
  9952.                             'sales_price' => $QD->getPrice(),
  9953.                             'purchase_price' => $QD->getCurrentPurchasePrice()
  9954. //                        'delivered'=>$product->getDelivered(),
  9955.                         );
  9956.                         $productByCodeDataObj['drItemData'][] = $p_data;
  9957.                     }
  9958.                 }
  9959.             }
  9960.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9961.                 ->findBy(
  9962.                     array(
  9963.                         'productId' => $id
  9964.                     )
  9965.                 );
  9966.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  9967.                 array(
  9968.                     'page_title' => 'Details',
  9969.                     'company_data' => $company_data,
  9970.                     'productByCodeData' => $productByCodeData,
  9971.                     'productByCodeDataObj' => $productByCodeDataObj,
  9972.                     'productData' => $productData,
  9973.                     'currInvList' => $currInvList,
  9974.                     'productDataWeightPackageGm' => $productDataWeightPackageGm,
  9975.                     'productDataWeightVarianceValue' => $productDataWeightVarianceValue,
  9976.                     'productDataWeightVarianceType' => $productDataWeightVarianceType,
  9977.                     'exId' => $id,
  9978.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9979.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9980.                     'productList' => Inventory::ProductList($em$companyId),
  9981.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9982.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9983.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9984.                     'unitList' => Inventory::UnitTypeList($em),
  9985.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9986.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9987.                     'warehouseList' => Inventory::WarehouseList($em),
  9988.                 )
  9989.             ));
  9990.         } else {
  9991.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  9992.                 array(
  9993.                     'exId' => $id,
  9994.                 )
  9995.             ));
  9996.         }
  9997.         if ($request->query->has('returnJson')) {
  9998.             return new JsonResponse(
  9999.                 array(
  10000.                     'success' => true,
  10001.                     'page_title' => 'Product Details',
  10002.                     'company_data' => $company_data,
  10003.                     'renderedHtml' => $html,
  10004.                     'exId' => $id,
  10005.                     'productByCodeDataObj' => $productByCodeDataObj,
  10006. //                'productData' => $productData,
  10007. //                'currInvList' => $currInvList,
  10008. //                'productList' => Inventory::ProductList($em, $companyId),
  10009. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10010. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10011. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10012. //                'unitList' => Inventory::UnitTypeList($em),
  10013. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10014. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10015. //                'warehouseList' => Inventory::WarehouseList($em),
  10016.                 )
  10017.             );
  10018.         } else {
  10019. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  10020. //                ->findBy(
  10021. //                    array(
  10022. ////                        'productByCodeId' => $id,
  10023. //                    'CompanyId'=>$companyId
  10024. //                    )
  10025. //                );
  10026.             $productByCodeList = []; //called by ajax
  10027.             return $this->render('@Inventory/pages/views/product_by_code_assign_check_print.html.twig',
  10028.                 array(
  10029.                     'page_title' => 'Serial Manager',
  10030.                     'company_data' => $company_data,
  10031.                     'renderedHtml' => $html,
  10032.                     'exId' => $id,
  10033.                     'productByCodeList' => $productByCodeList,
  10034.                     'productByCodeDataObj' => $productByCodeDataObj,
  10035. //                'productByCodeData' => $productByCodeData,
  10036. //                'productData' => $productData,
  10037. //                'currInvList' => $currInvList,
  10038. //                'productList' => Inventory::ProductList($em, $companyId),
  10039. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10040. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10041. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10042. //                'unitList' => Inventory::UnitTypeList($em),
  10043. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10044. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10045. //                'warehouseList' => Inventory::WarehouseList($em),
  10046.                 )
  10047.             );
  10048.         }
  10049.     }
  10050.     public
  10051.     function TestProductByCodeCheckAssignPrintAction(Request $request$id 0)
  10052.     {
  10053.         $em $this->getDoctrine()->getManager();
  10054.         $companyId $this->getLoggedUserCompanyId($request);
  10055.         $company_data Company::getCompanyData($em$companyId);
  10056.         $data = [];
  10057.         $html '';
  10058.         $productByCodeData = [];
  10059.         $productByCodeDataObj = [];
  10060.         if ($id != 0) {
  10061.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  10062.                 ->findOneBy(
  10063.                     array(
  10064.                         'productByCodeId' => $id
  10065.                     )
  10066.                 );
  10067.         } else {
  10068.             if ($request->query->has('scanCode')) {
  10069.                 $query $em->getRepository('ApplicationBundle:ProductByCode')
  10070.                     ->createQueryBuilder('p');
  10071.                 if ($request->query->has('assigned')) {
  10072.                     $query->where('p.assigned > :av')
  10073.                         ->setParameter('av'$request->query->get('assigned'));
  10074.                 } else
  10075.                     $query->where("1=0");
  10076.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  10077.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  10078.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  10079.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  10080.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  10081.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  10082.                 $query->setMaxResults(1);
  10083.                 $results $query->getQuery()->getResult();
  10084.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  10085.             } else
  10086.                 $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  10087.                     ->findOneBy(
  10088.                         array(
  10089. //                        'productByCodeId' => $id,
  10090.                             'CompanyId' => $companyId
  10091.                         ), array(
  10092.                             'productByCodeId' => 'DESC'
  10093.                         )
  10094.                     );
  10095.             if ($productByCodeData)
  10096.                 $id $productByCodeData->getProductByCodeId();
  10097.         }
  10098.         if ($id != 0) {
  10099.             $productByCodeDataObj = array(
  10100.                 'sn' => $productByCodeData->getSalesCode(),
  10101.                 'imei1' => $productByCodeData->getImei1(),
  10102.                 'imei2' => $productByCodeData->getImei2(),
  10103.                 'colorId' => $productByCodeData->getColorId(),
  10104.             );
  10105.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  10106.                 ->findOneBy(
  10107.                     array(
  10108.                         'id' => $productByCodeData->getProductId()
  10109.                     )
  10110.                 );
  10111.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  10112.                 ->findBy(
  10113.                     array(
  10114.                         'productId' => $id
  10115.                     )
  10116.                 );
  10117.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  10118.                 array(
  10119.                     'page_title' => 'Details',
  10120.                     'company_data' => $company_data,
  10121.                     'productByCodeData' => $productByCodeData,
  10122.                     'productData' => $productData,
  10123.                     'currInvList' => $currInvList,
  10124.                     'exId' => $id,
  10125.                     'clientList' => Client::GetExistingClientList($em$companyId),
  10126.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  10127.                     'productList' => Inventory::ProductList($em$companyId),
  10128.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10129.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10130.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10131.                     'unitList' => Inventory::UnitTypeList($em),
  10132.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10133.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10134.                     'warehouseList' => Inventory::WarehouseList($em),
  10135.                 )
  10136.             );
  10137.         } else {
  10138.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  10139.                 array(
  10140.                     'exId' => $id,
  10141.                 )
  10142.             );
  10143.         }
  10144.         if ($request->query->has('returnJson')) {
  10145.             return new JsonResponse(
  10146.                 array(
  10147.                     'success' => true,
  10148.                     'page_title' => 'Product Details',
  10149.                     'company_data' => $company_data,
  10150.                     'renderedHtml' => $html,
  10151.                     'exId' => $id,
  10152.                     'productByCodeDataObj' => $productByCodeDataObj,
  10153. //                'productData' => $productData,
  10154. //                'currInvList' => $currInvList,
  10155. //                'productList' => Inventory::ProductList($em, $companyId),
  10156. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10157. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10158. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10159. //                'unitList' => Inventory::UnitTypeList($em),
  10160. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10161. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10162. //                'warehouseList' => Inventory::WarehouseList($em),
  10163.                 )
  10164.             );
  10165.         } else {
  10166. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  10167. //                ->findBy(
  10168. //                    array(
  10169. ////                        'productByCodeId' => $id,
  10170. //                    'CompanyId'=>$companyId
  10171. //                    )
  10172. //                );
  10173.             $productByCodeList = []; //called by ajax
  10174.             return $this->render('@Inventory/pages/views/test_product_by_code_assign_check_print.html.twig',
  10175.                 array(
  10176.                     'page_title' => ' Test Serial Manager',
  10177.                     'company_data' => $company_data,
  10178.                     'renderedHtml' => $html,
  10179.                     'exId' => $id,
  10180.                     'productByCodeList' => $productByCodeList,
  10181.                     'productByCodeDataObj' => $productByCodeDataObj,
  10182. //                'productByCodeData' => $productByCodeData,
  10183. //                'productData' => $productData,
  10184. //                'currInvList' => $currInvList,
  10185. //                'productList' => Inventory::ProductList($em, $companyId),
  10186. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10187. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10188. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10189. //                'unitList' => Inventory::UnitTypeList($em),
  10190. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10191. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10192. //                'warehouseList' => Inventory::WarehouseList($em),
  10193.                 )
  10194.             );
  10195.         }
  10196.     }
  10197.     public function DeleteProductAction(Request $request$id '')
  10198.     {
  10199.         $em $this->getDoctrine()->getManager();
  10200.         $idListArray = [];
  10201.         if ($request->isMethod('POST')) {
  10202.             if ($id == 0)
  10203.                 $id $request->request->get('productId');
  10204.             //now check the product closing , if nothing then we cna remove it
  10205.             $query_here $this->getDoctrine()
  10206.                 ->getRepository('ApplicationBundle:InvClosingBalance')
  10207.                 ->findBy(
  10208.                     array(
  10209.                         'productId' => $request->request->get('productId')
  10210.                     )
  10211.                 );
  10212.             if (!empty($query_here)) {
  10213.                 return new JsonResponse(
  10214.                     array(
  10215.                         'success' => false,
  10216.                     )
  10217.                 );
  10218.             } else {
  10219.                 $qry $em->getRepository('ApplicationBundle:ProductByCode')->findBy(array(
  10220.                     'productId' => $id
  10221.                 ));
  10222.                 foreach ($qry as $det) {
  10223.                     //remove any barcoded products
  10224.                     $em->remove($det);
  10225.                     $em->flush();
  10226.                 }
  10227.                 $qry $em->getRepository('ApplicationBundle:InvProducts')->findBy(array(
  10228.                     'id' => $id
  10229.                 ));
  10230.                 foreach ($qry as $det) {
  10231.                     //remove any barcoded products
  10232.                     $em->remove($det);
  10233.                     $em->flush();
  10234.                 }
  10235.                 $qry $em->getRepository('ApplicationBundle:InvItemTransaction')->findBy(array(
  10236.                     'productId' => $id
  10237.                 ));
  10238.                 foreach ($qry as $det) {
  10239.                     //remove any barcoded products
  10240.                     $em->remove($det);
  10241.                     $em->flush();
  10242.                 }
  10243.                 return new JsonResponse(
  10244.                     array(
  10245.                         'success' => true,
  10246.                     )
  10247.                 );
  10248.             }
  10249.         }
  10250.         return new JsonResponse(
  10251.             array(
  10252.                 'success' => false,
  10253.             )
  10254.         );
  10255.     }
  10256.     public
  10257.     function RegisterProductAction(Request $request$idListStr '')
  10258.     {
  10259.         $em $this->getDoctrine()->getManager();
  10260.         $companyId $this->getLoggedUserCompanyId($request);
  10261.         $company_data Company::getCompanyData($em$companyId);
  10262.         $session $request->getSession();
  10263. //        System::setSessionForUser($session );
  10264.         $idListArray = [];
  10265.         if ($idListStr != '')
  10266.             $idListArray explode(','$idListStr);
  10267.         $data = [];
  10268. //        if ($request->isMethod('POST')) {
  10269. //            $post = $request->request;
  10270. //            if ($request->request->get('formatId') != '') {
  10271. //                $query_here = $this->getDoctrine()
  10272. //                    ->getRepository('ApplicationBundle:CheckFormat')
  10273. //                    ->findOneBy(
  10274. //                        array(
  10275. //                            'formatId' => $request->request->get('formatId')
  10276. //                        )
  10277. //                    );
  10278. //                if (!empty($query_here))
  10279. //                    $new = $query_here;
  10280. //            } else
  10281. //                $new = new CheckFormat();
  10282. //            $new->setName($request->request->get('name'));
  10283. //            $new->setWidth($request->request->get('width'));
  10284. //            $new->setHeight($request->request->get('height'));
  10285. //            $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
  10286. //            $new->setCheckPayToTop($request->request->get('checkPayToTop'));
  10287. //            $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
  10288. //            $new->setCheckAmountTop($request->request->get('checkAmountTop'));
  10289. //            $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
  10290. //            $new->setCheckAiWTop($request->request->get('checkAiWTop'));
  10291. //            $new->setCheckDateLeft($request->request->get('checkDateLeft'));
  10292. //            $new->setCheckDateTop($request->request->get('checkDateTop'));
  10293. //            $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
  10294. //            $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
  10295. //            $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
  10296. //            $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
  10297. //            $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
  10298. //            $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
  10299. //            $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
  10300. //            $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
  10301. //            $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
  10302. //            $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
  10303. //            $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 1 : 0);
  10304. //            $new->setCheckImage($request->request->get('checkImage'));
  10305. //
  10306. //            $em = $this->getDoctrine()->getManager();
  10307. //            $em->persist($new);
  10308. //            $em->flush();
  10309. //
  10310. //        }
  10311. //        if (!empty($idListArray)) {
  10312. //            $query_here = $this->getDoctrine()
  10313. //                ->getRepository('ApplicationBundle:ProductByCode')
  10314. //                ->findBy(
  10315. //                    array(
  10316. //                        'productByCodeId' => $idListArray
  10317. //                    )
  10318. //                );
  10319. //            if (!empty($query_here))
  10320. //                $data = $query_here;
  10321. //
  10322. //        }
  10323. //        else if ($request->query->has('formatId')) {
  10324. //            $query_here = $this->getDoctrine()
  10325. //                ->getRepository('ApplicationBundle:CheckFormat')
  10326. //                ->findOneBy(
  10327. //                    array(
  10328. //                        'formatId' => $request->query->get('formatId')
  10329. //                    )
  10330. //                );
  10331. //            if (!empty($query_here))
  10332. //                $data = $query_here;
  10333. //        }
  10334.         $data = [];
  10335.         $html '';
  10336.         $productByCodeData = [];
  10337.         if ($request->query->has('returnJson')) {
  10338.             return new JsonResponse(
  10339.                 array(
  10340.                     'success' => true,
  10341.                     'page_title' => 'Product Details',
  10342.                     'company_data' => $company_data,
  10343.                     'renderedHtml' => $html,
  10344.                     'data' => $data,
  10345.                     'idListArray' => $idListArray,
  10346. //                    'exId'=>$id,
  10347. //                'productByCodeData' => $productByCodeData,
  10348. //                'productData' => $productData,
  10349. //                'currInvList' => $currInvList,
  10350. //                'productList' => Inventory::ProductList($em, $companyId),
  10351. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10352. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10353. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10354. //                'unitList' => Inventory::UnitTypeList($em),
  10355. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10356. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10357. //                'warehouseList' => Inventory::WarehouseList($em),
  10358.                 )
  10359.             );
  10360.         } else {
  10361.             return $this->render('@Inventory/pages/input_forms/register_product.html.twig',
  10362.                 array(
  10363.                     'page_title' => 'Register Product',
  10364.                     'company_data' => $company_data,
  10365.                     'renderedHtml' => $html,
  10366. //                    'exIdList'=>$i,
  10367.                     'idListArray' => $idListArray,
  10368.                     'data' => $data,
  10369.                     'productByCodeList' => [],
  10370.                     'productByCodeData' => [],
  10371.                     'productList' => Inventory::ProductList($em$companyId),
  10372.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10373.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10374.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10375.                     'unitList' => Inventory::UnitTypeList($em),
  10376.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10377.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10378.                     'warehouseList' => Inventory::WarehouseList($em),
  10379.                 )
  10380.             );
  10381.         }
  10382.     }
  10383.     public
  10384.     function BrandViewAction(Request $request)
  10385.     {
  10386.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  10387.             array(
  10388.                 'page_title' => 'Stock Return'
  10389.             )
  10390.         );
  10391.     }
  10392.     public
  10393.     function PrintTableDataAction(Request $request)
  10394.     {
  10395.         $em $this->getDoctrine()->getManager();
  10396.         $company_data Company::getCompanyData($em1);
  10397.         $data = [];
  10398.         $print_title "test";
  10399.         $document_mark = array(
  10400.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10401.             'copy' => ''
  10402.         );
  10403.         $mis_data = [];
  10404.         $p 1;
  10405.         return $this->render('@Inventory/pages/print/print_table_data.html.twig',
  10406.             array(
  10407.                 'page_title' => 'Data Report',
  10408.                 'data' => $data,
  10409.                 'page_header' => 'Report',
  10410.                 'print_title' => $print_title,
  10411.                 'document_type' => 'Journal voucher',
  10412.                 'document_mark_image' => $document_mark['original'],
  10413.                 'page_header_sub' => 'Add',
  10414. //                'type_list'=>$type_list,
  10415.                 'mis_data' => $mis_data,
  10416.                 'item_data' => [],
  10417.                 'received' => 2,
  10418.                 'return' => 1,
  10419.                 'total_w_vat' => 1,
  10420.                 'total_vat' => 1,
  10421.                 'total_wo_vat' => 1,
  10422.                 'invoice_id' => 'abcd1234',
  10423.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10424.                 'created_by' => 'created by',
  10425.                 'created_at' => '',
  10426.                 'red' => 0,
  10427.                 'company_name' => $company_data->getName(),
  10428.                 'company_data' => $company_data,
  10429.                 'company_address' => $company_data->getAddress(),
  10430.                 'company_image' => $company_data->getImage(),
  10431.                 'p' => $p
  10432.             )
  10433.         );
  10434.     }
  10435.     public
  10436.     function ReplacementReportAction(Request $request)
  10437.     {
  10438.         $qry_data = array(
  10439.             'warehouseId' => [0],
  10440.             'igId' => [0],
  10441.             'brandId' => [0],
  10442.             'categoryId' => [0],
  10443.             'actionTagId' => [0],
  10444.         );
  10445.         $em $this->getDoctrine()->getManager();
  10446.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  10447.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  10448.         $data_searched = [];
  10449.         $companyId $this->getLoggedUserCompanyId($request);
  10450.         $company_data Company::getCompanyData($em$companyId);
  10451.         $data = [];
  10452.         $print_title "Inventory Report";
  10453.         $document_mark = array(
  10454.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10455.             'copy' => ''
  10456.         );
  10457.         $post_data $request->request;
  10458.         $start_date $post_data->has('start_date') ? $post_data->get('start_date') : '';
  10459.         $end_date $post_data->has('end_date') ? $post_data->get('end_date') : '';
  10460.         if ($request->isMethod('POST'))
  10461.             $method 'POST';
  10462.         else
  10463.             $method 'GET';
  10464.         {
  10465. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  10466.             $data_searched Inventory::GetReplacementReportData($this->getDoctrine()->getManager(),
  10467.                 $request->request$method,
  10468.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  10469.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  10470.                 return new JsonResponse(
  10471.                     array(
  10472.                         'page_title' => 'Inventory ',
  10473.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10474.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10475.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10476.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10477.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10478.                         'action_tag' => $warehouse_action_list,
  10479.                         'start_date' => $start_date,
  10480.                         'end_date' => $end_date,
  10481.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10482.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10483.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10484.                         'data_searched' => $data_searched,
  10485.                         'success' => empty($data_searched['query_result']) ? false true
  10486.                     )
  10487.                 );
  10488.             }
  10489.             if ($request->request->get('print_data_enabled') == 1) {
  10490.                 $print_sub_title "";
  10491.                 return $this->render('@Inventory/pages/print/print_replacement_report.html.twig',
  10492.                     array(
  10493.                         'page_title' => 'Replacement Report',
  10494.                         'page_header' => 'Report',
  10495.                         'print_title' => $print_title,
  10496.                         'document_type' => 'Journal voucher',
  10497.                         'document_mark_image' => $document_mark['original'],
  10498.                         'page_header_sub' => 'Add',
  10499.                         'item_data' => [],
  10500.                         'received' => 2,
  10501.                         'return' => 1,
  10502.                         'total_w_vat' => 1,
  10503.                         'total_vat' => 1,
  10504.                         'total_wo_vat' => 1,
  10505.                         'invoice_id' => 'abcd1234',
  10506.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  10507.                         'created_by' => 'created by',
  10508.                         'created_at' => '',
  10509.                         'red' => 0,
  10510.                         'company_name' => $company_data->getName(),
  10511.                         'company_data' => $company_data,
  10512.                         'company_address' => $company_data->getAddress(),
  10513.                         'company_image' => $company_data->getImage(),
  10514.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10515.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10516.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10517.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10518.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10519.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10520.                         'action_tag' => $warehouse_action_list,
  10521.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10522.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10523.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10524.                         'start_date' => $start_date,
  10525.                         'end_date' => $end_date,
  10526.                         'data_searched' => $data_searched
  10527.                     )
  10528.                 );
  10529.             }
  10530.         }
  10531.         return $this->render('@Inventory/pages/report/replacement_report.html.twig',
  10532.             array(
  10533.                 'page_title' => 'Replacement Report',
  10534.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10535.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10536.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10537.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10538.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10539. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10540.                 'action_tag' => $warehouse_action_list,
  10541.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10542.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10543.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10544.                 'start_date' => $start_date,
  10545.                 'end_date' => $end_date,
  10546.                 'data_searched' => $data_searched,
  10547.                 'success' => empty($data_searched['query_result']) ? false true
  10548.             )
  10549.         );
  10550.     }
  10551.     public
  10552.     function InventoryViewAction(Request $request)
  10553.     {
  10554.         $qry_data = array(
  10555.             'warehouseId' => [0],
  10556.             'igId' => [0],
  10557.             'brandId' => [0],
  10558.             'categoryId' => [0],
  10559.             'actionTagId' => [0],
  10560.         );
  10561.         $em $this->getDoctrine()->getManager();
  10562.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  10563.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  10564.         $data_searched = [];
  10565.         $companyId $this->getLoggedUserCompanyId($request);
  10566.         $company_data Company::getCompanyData($em$companyId);
  10567.         $data = [];
  10568.         $print_title "Inventory Report";
  10569.         $document_mark = array(
  10570.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10571.             'copy' => ''
  10572.         );
  10573.         if ($request->isMethod('POST'))
  10574.             $method 'POST';
  10575.         else
  10576.             $method 'GET';
  10577.         {
  10578. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  10579.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  10580.                 $request->request$method,
  10581.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  10582.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  10583.                 return new JsonResponse(
  10584.                     array(
  10585.                         'page_title' => 'Inventory ',
  10586.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10587.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10588.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10589.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10590.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10591.                         'action_tag' => $warehouse_action_list,
  10592.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10593.                         'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  10594.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10595.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10596.                         'data_searched' => $data_searched,
  10597.                         'success' => empty($data_searched['query_result']) ? false true
  10598.                     )
  10599.                 );
  10600.             }
  10601.             if ($request->request->get('print_data_enabled') == 1) {
  10602.                 $print_sub_title "";
  10603.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  10604.                     array(
  10605.                         'page_title' => 'Inventory Report',
  10606.                         'page_header' => 'Report',
  10607.                         'print_title' => $print_title,
  10608.                         'document_type' => 'Journal voucher',
  10609.                         'document_mark_image' => $document_mark['original'],
  10610.                         'page_header_sub' => 'Add',
  10611.                         'item_data' => [],
  10612.                         'received' => 2,
  10613.                         'return' => 1,
  10614.                         'total_w_vat' => 1,
  10615.                         'total_vat' => 1,
  10616.                         'total_wo_vat' => 1,
  10617.                         'invoice_id' => 'abcd1234',
  10618.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  10619.                         'created_by' => 'created by',
  10620.                         'created_at' => '',
  10621.                         'red' => 0,
  10622.                         'company_name' => $company_data->getName(),
  10623.                         'company_data' => $company_data,
  10624.                         'company_address' => $company_data->getAddress(),
  10625.                         'company_image' => $company_data->getImage(),
  10626.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10627.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10628.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10629.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10630.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10631.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10632.                         'action_tag' => $warehouse_action_list,
  10633.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10634.                         'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  10635.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10636.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10637.                         'data_searched' => $data_searched
  10638.                     )
  10639.                 );
  10640.             }
  10641.         }
  10642.         return $this->render('@Inventory/pages/report/inventory_view.html.twig',
  10643.             array(
  10644.                 'page_title' => 'Inventory',
  10645.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10646.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10647.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10648.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10649.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10650. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10651.                 'action_tag' => $warehouse_action_list,
  10652.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10653.                 'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  10654.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10655.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10656.                 'data_searched' => $data_searched
  10657.             )
  10658.         );
  10659.     }
  10660.     public
  10661.     function GrnListAction(Request $request)
  10662.     {
  10663.         $q $this->getDoctrine()
  10664.             ->getRepository('ApplicationBundle:Grn')
  10665.             ->findBy(
  10666.                 array(
  10667.                     'status' => GeneralConstant::ACTIVE,
  10668. //                    'approved' =>  GeneralConstant::APPROVED,
  10669.                 )
  10670.             );
  10671.         $stage_list = array(
  10672.             => 'Pending',
  10673.             => 'Pending',
  10674.             => 'Complete',
  10675.             => 'Partial',
  10676.         );
  10677.         $data = [];
  10678.         foreach ($q as $entry) {
  10679.             $data[] = array(
  10680.                 'doc_date' => $entry->getGrnDate(),
  10681.                 'id' => $entry->getGrnId(),
  10682.                 'doc_hash' => $entry->getDocumentHash(),
  10683.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  10684.                 'stage' => $stage_list[$entry->getStage()]
  10685.             );
  10686.         }
  10687.         return $this->render('@Inventory/pages/views/grn_list.html.twig',
  10688.             array(
  10689.                 'page_title' => 'Grn List',
  10690.                 'data' => $data
  10691.             )
  10692.         );
  10693.     }
  10694.     public
  10695.     function ViewGrnAction(Request $request$id)
  10696.     {
  10697.         $em $this->getDoctrine()->getManager();
  10698.         $dt Inventory::GetGrnDetails($em$id);
  10699.         return $this->render(
  10700.                                     '@Inventory/pages/views/view_grn.html.twig',
  10701.             array(
  10702.                 'page_title' => 'View',
  10703.                 'data' => $dt,
  10704.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  10705.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10706.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10707.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10708.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10709.                     $id,
  10710.                     $dt['created_by'],
  10711.                     $dt['edited_by'])
  10712.             )
  10713.         );
  10714.     }
  10715.     public
  10716.     function PrintGrnAction(Request $request$id)
  10717.     {
  10718.         $em $this->getDoctrine()->getManager();
  10719.         $dt Inventory::GetGrnDetails($em$id);
  10720.         $company_data Company::getCompanyData($em1);
  10721.         $document_mark = array(
  10722.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10723.             'copy' => ''
  10724.         );
  10725.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10726.             $html $this->renderView('@Inventory/pages/print/print_received_note.html.twig',
  10727.                 array(
  10728.                     //full array here
  10729.                     'pdf' => true,
  10730.                     'page_title' => 'Grn',
  10731.                     'export' => 'pdf,print',
  10732.                     'data' => $dt,
  10733.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10734.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10735.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10736.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10737.                         $id,
  10738.                         $dt['created_by'],
  10739.                         $dt['edited_by']),
  10740.                     'document_mark_image' => $document_mark['original'],
  10741.                     'company_name' => $company_data->getName(),
  10742.                     'company_data' => $company_data,
  10743.                     'company_address' => $company_data->getAddress(),
  10744.                     'company_image' => $company_data->getImage(),
  10745.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10746.                     'red' => 0
  10747.                 )
  10748.             );
  10749.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10750. //                'orientation' => 'landscape',
  10751. //                'enable-javascript' => true,
  10752. //                'javascript-delay' => 1000,
  10753.                 'no-stop-slow-scripts' => false,
  10754.                 'no-background' => false,
  10755.                 'lowquality' => false,
  10756.                 'encoding' => 'utf-8',
  10757. //            'images' => true,
  10758. //            'cookie' => array(),
  10759.                 'dpi' => 300,
  10760.                 'image-dpi' => 300,
  10761. //                'enable-external-links' => true,
  10762. //                'enable-internal-links' => true
  10763.             ));
  10764.             return new Response(
  10765.                 $pdf_response,
  10766.                 200,
  10767.                 array(
  10768.                     'Content-Type' => 'application/pdf',
  10769.                     'Content-Disposition' => 'attachment; filename="grn.pdf"'
  10770.                 )
  10771.             );
  10772.         }
  10773.         return $this->render('@Inventory/pages/print/print_received_note.html.twig',
  10774.             array(
  10775.                 'page_title' => 'Grn',
  10776.                 'export' => 'pdf,print',
  10777.                 'data' => $dt,
  10778.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10779.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10780.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10781.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10782.                     $id,
  10783.                     $dt['created_by'],
  10784.                     $dt['edited_by']),
  10785.                 'document_mark_image' => $document_mark['original'],
  10786.                 'company_name' => $company_data->getName(),
  10787.                 'company_data' => $company_data,
  10788.                 'company_address' => $company_data->getAddress(),
  10789.                 'company_image' => $company_data->getImage(),
  10790.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10791.                 'red' => 0
  10792.             )
  10793.         );
  10794.     }
  10795.     public
  10796.     function PrintGrnBarcodeAction(Request $request$id)
  10797.     {
  10798.         $em $this->getDoctrine()->getManager();
  10799.         $dt Inventory::GetGrnDetails($em$id);
  10800.         $company_data Company::getCompanyData($em1);
  10801.         $repeatCount 1;
  10802.         if ($request->query->has('repeatCount'))
  10803.             $repeatCount $request->query->get('repeatCount');
  10804.         $document_mark = array(
  10805.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10806.             'copy' => ''
  10807.         );
  10808.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10809.             $html $this->renderView('@Inventory/pages/print/print_grn_barcodes.html.twig',
  10810.                 array(
  10811.                     //full array here
  10812.                     'pdf' => true,
  10813.                     'page_title' => 'Grn Barcodes',
  10814.                     'export' => 'print',
  10815.                     'data' => $dt,
  10816.                     'repeatCount' => $repeatCount,
  10817.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10818.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10819.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10820.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10821.                         $id,
  10822.                         $dt['created_by'],
  10823.                         $dt['edited_by']),
  10824.                     'document_mark_image' => $document_mark['original'],
  10825.                     'company_name' => $company_data->getName(),
  10826.                     'company_data' => $company_data,
  10827.                     'company_address' => $company_data->getAddress(),
  10828.                     'company_image' => $company_data->getImage(),
  10829.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10830.                     'red' => 0
  10831.                 )
  10832.             );
  10833.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10834. //                'orientation' => 'landscape',
  10835.                 'enable-javascript' => true,
  10836. //                'javascript-delay' => 1000,
  10837.                 'no-stop-slow-scripts' => false,
  10838.                 'no-background' => false,
  10839.                 'lowquality' => false,
  10840.                 'encoding' => 'utf-8',
  10841. //            'images' => true,
  10842. //            'cookie' => array(),
  10843.                 'dpi' => 300,
  10844.                 'image-dpi' => 300,
  10845. //                'enable-external-links' => true,
  10846. //                'enable-internal-links' => true
  10847.             ));
  10848.             return new Response(
  10849.                 $pdf_response,
  10850.                 200,
  10851.                 array(
  10852.                     'Content-Type' => 'application/pdf',
  10853.                     'Content-Disposition' => 'attachment; filename="grn_barcodes.pdf"'
  10854.                 )
  10855.             );
  10856.         }
  10857.         return $this->render('@Inventory/pages/print/print_grn_barcodes.html.twig',
  10858.             array(
  10859.                 'page_title' => 'Grn barcodes',
  10860. //                'export'=>'pdf,print',
  10861.                 'data' => $dt,
  10862.                 'repeatCount' => $repeatCount,
  10863.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10864.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10865.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10866.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10867.                     $id,
  10868.                     $dt['created_by'],
  10869.                     $dt['edited_by']),
  10870.                 'document_mark_image' => $document_mark['original'],
  10871.                 'company_name' => $company_data->getName(),
  10872.                 'company_data' => $company_data,
  10873.                 'company_address' => $company_data->getAddress(),
  10874.                 'company_image' => $company_data->getImage(),
  10875.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10876.                 'red' => 0
  10877.             )
  10878.         );
  10879.     }
  10880.     public function GenerateBarcodeAction(Request $request$type$id$item_id)
  10881.     {
  10882.         $em $this->getDoctrine()->getManager();
  10883.         $repeatCount 1;
  10884.         $spec_item_id 0;
  10885.         $skip_ids = [];
  10886.         $clearUnnecessaryOnly 0;
  10887.         if ($request->query->has('skipIds'))
  10888.             $skip_ids $request->query->get('skipIds');
  10889.         if ($request->query->has('clearUnnecessaryOnly'))
  10890.             $clearUnnecessaryOnly $request->query->get('clearUnnecessaryOnly');
  10891.         if ($type == 'srcv') {
  10892.             $doc_data $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  10893.                 array(
  10894.                     'stockReceivedNoteId' => $id
  10895.                 )
  10896.             );
  10897.             if ($item_id == '_single_') {
  10898.                 $doc_item_data $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
  10899.                     array(
  10900.                         'stockReceivedNoteId' => $id,
  10901. //                        'id' => $item_id
  10902.                     )
  10903.                 );
  10904.             } else {
  10905.                 $doc_item_data $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
  10906.                     array(
  10907.                         'stockReceivedNoteId' => $id,
  10908.                         'id' => $item_id
  10909.                     )
  10910.                 );
  10911.             }
  10912.             $inv_acc_data = [
  10913.                 'fa_amount' => 0,
  10914.                 'tg_amount' => 0,
  10915.             ];
  10916.             $inv_acc_data_by_head = [
  10917.             ];
  10918.             $new_non_delivered_sales_code_range = [];
  10919.             foreach ($doc_item_data as $entry) {
  10920.                 //adding transaction
  10921.                 $sales_code_range_ser = [];
  10922.                 if (in_array($entry->getId(), $skip_ids))
  10923.                     continue;
  10924.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10925.                     ->findOneBy(
  10926.                         array(
  10927.                             'id' => $entry->getProductId()
  10928.                         )
  10929.                     );
  10930.                 $stitem $em->getRepository('ApplicationBundle:StockTransferItem')
  10931.                     ->findOneBy(
  10932.                         array(
  10933.                             'id' => $entry->getStockTransferItemId(),
  10934.                             'productId' => $entry->getProductId()
  10935.                         )
  10936.                     );
  10937.                 if ($product) {
  10938.                     if ($product->getHasSerial() == 1) {
  10939.                         //clear if exists
  10940.                         if ($clearUnnecessaryOnly == 1) {
  10941.                             $get_kids_sql "DELETE FROM product_by_code
  10942.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10943. //                $get_kids_sql .=' ORDER BY name ASC';
  10944.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  10945.                             $stmt->execute();
  10946.                             $em->flush();
  10947.                         } else {
  10948.                             $get_kids_sql "DELETE FROM product_by_code
  10949.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10950. //                $get_kids_sql .=' ORDER BY name ASC';
  10951.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  10952.                             $stmt->execute();
  10953.                             $em->flush();
  10954.                         }
  10955. //                        $check_here = $stmt->fetchAll();
  10956.                         //now addng product by code
  10957.                         $sales_code_range = [];
  10958.                         if ($doc_data->getType() == || $doc_data->getType() == 4) {
  10959. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10960. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10961.                             $product_action_tag_id $entry->getWarehouseActionId();
  10962.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getQty(),
  10963.                                 $doc_data->getStockReceivedNoteDate(), $entry->getWarrantyMon(), 0$doc_data->getCompanyId(), $entry->getWarehouseId(),
  10964.                                 $entry->getWarehouseActionId(), $entry->getPurchaseCodeRange(), nullnullnullnull$doc_data->getStockReceivedNoteId()
  10965.                             );
  10966.                             $sales_code_range $barcodeData['sales_code_range'];
  10967.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  10968.                             $em->flush();
  10969.                         }
  10970. //                        else {
  10971. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10972. //
  10973. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10974. //                            } else {
  10975. //
  10976. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10977. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10978. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10979. //                            }
  10980. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10981. //
  10982. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10983. //                            } else {
  10984. //
  10985. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10986. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10987. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10988. //                            }
  10989. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10990. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10991. //                            $new_non_delivered_sales_code_range = [];
  10992. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10993. //                                if (!(in_array($ndsc, $sales_code_range)))
  10994. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10995. //                            }
  10996. //                            if ($sales_code_range != null) {
  10997. //                                foreach ($sales_code_range as $ind => $dt) {
  10998. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  10999. //                                        ->findOneBy(
  11000. //                                            array(
  11001. //                                                'salesCode' => [$dt],
  11002. //                                                'productId' => $entry->getProductId()
  11003. //                                            )
  11004. //                                        );
  11005. //
  11006. //                                    if ($np) {
  11007. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  11008. //                                        $np->setProductId($entry->getProductId());
  11009. //                                        $np->setWarehouseId($entry->getWarehouseId());
  11010. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  11011. //                                        $np->setPosition(1);//in warehouse
  11012. //                                        $np->setStockReceivedNoteId($id);
  11013. //
  11014. //
  11015. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  11016. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  11017. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  11018. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  11019. //                                            'direction' => 'in',
  11020. //                                            'warehouseId' => $entry->getWarehouseId(),
  11021. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  11022. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  11023. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  11024. //                                        );
  11025. //                                        $np->setTransactionHistory(json_encode(
  11026. //                                            $trans_history
  11027. //                                        ));
  11028. //
  11029. //
  11030. //                                        $em->persist($np);
  11031. //                                        $em->flush();
  11032. //                                    }
  11033. //                                }
  11034. //                            }
  11035. //                        }
  11036.                     }
  11037.                 }
  11038.                 //adding transaction
  11039.                 if ($stitem) {
  11040.                     $stitem->setNonDeliveredSalesCodeRange(json_encode($new_non_delivered_sales_code_range));
  11041.                 }
  11042.                 $spec_item_id $entry->getId();
  11043.                 if ($item_id == '_single_') {
  11044.                     break;
  11045.                 }
  11046.             }
  11047.         }
  11048.         if ($type == 'irr') {
  11049.             $doc_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacement')->findOneBy(
  11050.                 array(
  11051.                     'itemReceivedAndReplacementId' => $id
  11052.                 )
  11053.             );
  11054.             if ($item_id == '_single_') {
  11055.                 $doc_item_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
  11056.                     array(
  11057.                         'itemReceivedAndReplacementId' => $id,
  11058. //                        'id' => $item_id
  11059.                     )
  11060.                 );
  11061.             } else {
  11062.                 $doc_item_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
  11063.                     array(
  11064.                         'itemReceivedAndReplacementId' => $id,
  11065.                         'id' => $item_id
  11066.                     )
  11067.                 );
  11068.             }
  11069.             $inv_acc_data = [
  11070.                 'fa_amount' => 0,
  11071.                 'tg_amount' => 0,
  11072.             ];
  11073.             $inv_acc_data_by_head = [
  11074.             ];
  11075.             $new_non_delivered_sales_code_range = [];
  11076.             foreach ($doc_item_data as $entry) {
  11077.                 //adding transaction
  11078.                 $sales_code_range_ser = [];
  11079.                 if (in_array($entry->getId(), $skip_ids))
  11080.                     continue;
  11081.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  11082.                     ->findOneBy(
  11083.                         array(
  11084.                             'id' => $entry->getReceivedProductId()
  11085.                         )
  11086.                     );
  11087.                 if ($product) {
  11088.                     if ($product->getHasSerial() == 1) {
  11089.                         //clear if exists
  11090. //                        if($clearUnnecessaryOnly==1) {
  11091. //                            $get_kids_sql = "DELETE FROM product_by_code
  11092. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  11093. ////                $get_kids_sql .=' ORDER BY name ASC';
  11094. //
  11095. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  11096. //                            $stmt->execute();
  11097. //                            $em->flush();
  11098. //                        }
  11099. //                        else{
  11100. //                            $get_kids_sql = "DELETE FROM product_by_code
  11101. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  11102. ////                $get_kids_sql .=' ORDER BY name ASC';
  11103. //
  11104. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  11105. //                            $stmt->execute();
  11106. //                            $em->flush();
  11107. //                        }
  11108. //                        $check_here = $stmt->fetchAll();
  11109.                         //now addng product by code
  11110.                         $sales_code_range = [];
  11111.                         if ($entry->getReceivedQty() > 0) {
  11112. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  11113. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  11114. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  11115.                             $barcodeData Inventory::GenerateBarcode($em$entry->getReceivedProductId(), $entry->getReceivedQty(),
  11116.                                 $doc_data->getItemReceivedAndReplacementDate(), 00$doc_data->getCompanyId(), $entry->getReceivedWarehouseId(),
  11117.                                 $entry->getReceivedWarehouseActionId(), nullnullnullnullnullnullnullnull$doc_data->getItemReceivedAndReplacementId()
  11118.                             );
  11119.                             $sales_code_range $barcodeData['sales_code_range'];
  11120.                             $entry->setReceivedCodeRange(json_encode($sales_code_range));
  11121.                             $em->flush();
  11122.                         }
  11123. //                        else {
  11124. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11125. //
  11126. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11127. //                            } else {
  11128. //
  11129. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11130. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  11131. //                                $sales_code_range = json_decode($json_without_bigints, true);
  11132. //                            }
  11133. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11134. //
  11135. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11136. //                            } else {
  11137. //
  11138. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11139. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  11140. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  11141. //                            }
  11142. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  11143. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  11144. //                            $new_non_delivered_sales_code_range = [];
  11145. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  11146. //                                if (!(in_array($ndsc, $sales_code_range)))
  11147. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  11148. //                            }
  11149. //                            if ($sales_code_range != null) {
  11150. //                                foreach ($sales_code_range as $ind => $dt) {
  11151. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  11152. //                                        ->findOneBy(
  11153. //                                            array(
  11154. //                                                'salesCode' => [$dt],
  11155. //                                                'productId' => $entry->getProductId()
  11156. //                                            )
  11157. //                                        );
  11158. //
  11159. //                                    if ($np) {
  11160. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  11161. //                                        $np->setProductId($entry->getProductId());
  11162. //                                        $np->setWarehouseId($entry->getWarehouseId());
  11163. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  11164. //                                        $np->setPosition(1);//in warehouse
  11165. //                                        $np->setStockReceivedNoteId($id);
  11166. //
  11167. //
  11168. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  11169. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  11170. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  11171. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  11172. //                                            'direction' => 'in',
  11173. //                                            'warehouseId' => $entry->getWarehouseId(),
  11174. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  11175. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  11176. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  11177. //                                        );
  11178. //                                        $np->setTransactionHistory(json_encode(
  11179. //                                            $trans_history
  11180. //                                        ));
  11181. //
  11182. //
  11183. //                                        $em->persist($np);
  11184. //                                        $em->flush();
  11185. //                                    }
  11186. //                                }
  11187. //                            }
  11188. //                        }
  11189.                     }
  11190.                 }
  11191.                 //adding transaction
  11192.                 $spec_item_id $entry->getId();
  11193.                 if ($item_id == '_single_') {
  11194.                     break;
  11195.                 }
  11196.             }
  11197.         }
  11198.         if ($type == 'prdcn') {
  11199.             $doc_data $em->getRepository('ApplicationBundle:Production')->findOneBy(
  11200.                 array(
  11201.                     'productionId' => $id
  11202.                 )
  11203.             );
  11204.             if ($item_id == '_single_') {
  11205.                 $doc_item_data $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
  11206.                     array(
  11207.                         'productionId' => $id,
  11208. //                        'id' => $item_id
  11209.                     )
  11210.                 );
  11211.             } else {
  11212.                 $doc_item_data $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
  11213.                     array(
  11214.                         'productionId' => $id,
  11215.                         'id' => $item_id
  11216.                     )
  11217.                 );
  11218.             }
  11219.             $inv_acc_data = [
  11220.                 'fa_amount' => 0,
  11221.                 'tg_amount' => 0,
  11222.             ];
  11223.             $inv_acc_data_by_head = [
  11224.             ];
  11225.             $new_non_delivered_sales_code_range = [];
  11226.             foreach ($doc_item_data as $entry) {
  11227.                 //adding transaction
  11228.                 $sales_code_range_ser = [];
  11229.                 if (in_array($entry->getId(), $skip_ids))
  11230.                     continue;
  11231.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  11232.                     ->findOneBy(
  11233.                         array(
  11234.                             'id' => $entry->getProductId()
  11235.                         )
  11236.                     );
  11237.                 if ($product) {
  11238.                     if ($product->getHasSerial() == 1) {
  11239.                         //clear if exists
  11240. //                        if($clearUnnecessaryOnly==1) {
  11241. //                            $get_kids_sql = "DELETE FROM product_by_code
  11242. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  11243. ////                $get_kids_sql .=' ORDER BY name ASC';
  11244. //
  11245. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  11246. //                            $stmt->execute();
  11247. //                            $em->flush();
  11248. //                        }
  11249. //                        else{
  11250. //                            $get_kids_sql = "DELETE FROM product_by_code
  11251. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  11252. ////                $get_kids_sql .=' ORDER BY name ASC';
  11253. //
  11254. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  11255. //                            $stmt->execute();
  11256. //                            $em->flush();
  11257. //                        }
  11258. //                        $check_here = $stmt->fetchAll();
  11259.                         //now addng product by code
  11260.                         $sales_code_range = [];
  11261.                         if ($entry->getProducedQty() > 0) {
  11262. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  11263. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  11264. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  11265.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getProducedQty(),
  11266.                                 $doc_data->getProductionDate(), 00$doc_data->getCompanyId(), $entry->getWarehouseId(),
  11267.                                 $entry->getProducedItemActionTagId(), nullnullnullnullnullnullnull$doc_data->getProductionId(), null
  11268.                             );
  11269.                             $sales_code_range $barcodeData['sales_code_range'];
  11270.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  11271.                             $em->flush();
  11272.                         }
  11273. //                        else {
  11274. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11275. //
  11276. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11277. //                            } else {
  11278. //
  11279. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11280. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  11281. //                                $sales_code_range = json_decode($json_without_bigints, true);
  11282. //                            }
  11283. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11284. //
  11285. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11286. //                            } else {
  11287. //
  11288. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11289. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  11290. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  11291. //                            }
  11292. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  11293. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  11294. //                            $new_non_delivered_sales_code_range = [];
  11295. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  11296. //                                if (!(in_array($ndsc, $sales_code_range)))
  11297. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  11298. //                            }
  11299. //                            if ($sales_code_range != null) {
  11300. //                                foreach ($sales_code_range as $ind => $dt) {
  11301. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  11302. //                                        ->findOneBy(
  11303. //                                            array(
  11304. //                                                'salesCode' => [$dt],
  11305. //                                                'productId' => $entry->getProductId()
  11306. //                                            )
  11307. //                                        );
  11308. //
  11309. //                                    if ($np) {
  11310. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  11311. //                                        $np->setProductId($entry->getProductId());
  11312. //                                        $np->setWarehouseId($entry->getWarehouseId());
  11313. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  11314. //                                        $np->setPosition(1);//in warehouse
  11315. //                                        $np->setStockReceivedNoteId($id);
  11316. //
  11317. //
  11318. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  11319. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  11320. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  11321. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  11322. //                                            'direction' => 'in',
  11323. //                                            'warehouseId' => $entry->getWarehouseId(),
  11324. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  11325. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  11326. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  11327. //                                        );
  11328. //                                        $np->setTransactionHistory(json_encode(
  11329. //                                            $trans_history
  11330. //                                        ));
  11331. //
  11332. //
  11333. //                                        $em->persist($np);
  11334. //                                        $em->flush();
  11335. //                                    }
  11336. //                                }
  11337. //                            }
  11338. //                        }
  11339.                     }
  11340.                 }
  11341.                 //adding transaction
  11342.                 $spec_item_id $entry->getId();
  11343.                 if ($item_id == '_single_') {
  11344.                     break;
  11345.                 }
  11346.             }
  11347.         }
  11348.         return new JsonResponse(array(
  11349.             'success' => $spec_item_id != true false,
  11350.             'skipIds' => [],
  11351.             'spec_item_id' => $spec_item_id
  11352.         ));
  11353. //        return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  11354. //            array(
  11355. //                'page_title' => 'Srcv barcodes',
  11356. ////                'export'=>'pdf,print',
  11357. //                'data' => $dt,
  11358. //                'repeatCount' => $repeatCount,
  11359. //                'item_id' => $item_id,
  11360. //                'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11361. //                    $id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11362. //                'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11363. //                    array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11364. //                    $id,
  11365. //                    $dt['created_by'],
  11366. //                    $dt['edited_by']),
  11367. //                'document_mark_image' => $document_mark['original'],
  11368. //                                    'company_name' => $company_data->getName(),
  11369. //                    'company_data'=>$company_data,
  11370. //                'company_address' => $company_data->getAddress(),
  11371. //                'company_image' => $company_data->getImage(),
  11372. //                'invoice_footer' => $company_data->getInvoiceFooter(),
  11373. //                'red' => 0
  11374. //
  11375. //            )
  11376. //        );
  11377.     }
  11378.     public
  11379.     function PrintLabelAction(Request $request$id)
  11380.     {
  11381.         $em $this->getDoctrine()->getManager();
  11382. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11383.         $repeatCount 1;
  11384.         $assignProductId '';
  11385.         $productByCodeIds = [];
  11386.         $print_selection_type 1;
  11387.         $print_selection_string 1;
  11388.         $assignLabelFormatId 0;
  11389.         $assignColorId 0;
  11390.         $assignProductionScheduleId 0;
  11391.         $warehouseId '';
  11392.         $warehouseActionId '';
  11393.         $toAssignPosition '';
  11394.         $printFlag $request->request->has('printFlag') ? $request->request->get('printFlag') : 1;
  11395.         $returnJson $request->request->has('returnJson') ? $request->request->get('returnJson') : 0;
  11396.         if ($returnJson == 1)
  11397.             $printFlag 0;
  11398.         $companyId $this->getLoggedUserCompanyId($request);
  11399.         if ($request->query->has('repeatCount'))
  11400.             $repeatCount $request->query->get('repeatCount');
  11401.         if ($request->request->has('print_selection_type'))
  11402.             $print_selection_type $request->request->get('print_selection_type');
  11403.         if ($request->request->has('print_selection_string'))
  11404.             $print_selection_string $request->request->get('print_selection_string');
  11405.         if ($request->request->has('productByCodeIds'))
  11406.             $productByCodeIds json_decode($request->request->get('productByCodeIds'), true);
  11407.         if ($request->request->has('formatId'))
  11408.             $assignLabelFormatId $request->request->get('formatId');
  11409.         if ($printFlag == 0) {
  11410.             if ($request->request->has('productSelector'))
  11411.                 $assignProductId $request->request->get('productSelector');
  11412.             if ($request->request->has('colorId'))
  11413.                 $assignColorId $request->request->get('colorId');
  11414.             if ($request->request->has('productionScheduleId'))
  11415.                 $assignProductionScheduleId $request->request->get('productionScheduleId');
  11416.             if ($request->request->has('warehouseId'))
  11417.                 $warehouseId $request->request->get('warehouseId');
  11418.             if ($request->request->has('warehouseActionId'))
  11419.                 $warehouseActionId $request->request->get('warehouseActionId');
  11420.             if ($request->request->has('position'))
  11421.                 $toAssignPosition $request->request->get('position');
  11422.             if ($assignColorId == '')
  11423.                 $assignColorId 0;
  11424.         }
  11425.         if ($productByCodeIds == null)
  11426.             $productByCodeIds = [];
  11427.         $productByCodeData = [];
  11428.         $productList = [];
  11429.         $productIds = [];
  11430.         if ($print_selection_type == 2) {
  11431.             //range
  11432.             $productByCodeIds Inventory::getIdsFromIdSelectionStr($print_selection_string);
  11433.         }
  11434.         $labelData = [
  11435.             'formatId' => 0
  11436.         ];
  11437.         $formatId 0;
  11438.         if (!empty($productByCodeIds)) {
  11439.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11440.                 ->findBy(
  11441.                     array(
  11442.                         'productByCodeId' => $productByCodeIds
  11443.                     )
  11444.                 );
  11445.             foreach ($productByCodeData as $d) {
  11446.                 if ($d->getStage() < 10$d->setStage(11);
  11447.                 if ($assignProductId != '') {
  11448.                     $d->setProductId($assignProductId);
  11449.                 }
  11450.                 if ($assignColorId != 0) {
  11451.                     $d->setColorId($assignColorId);
  11452.                 } else {
  11453.                     $productData $em->getRepository('ApplicationBundle:InvProducts')
  11454.                         ->findOneBy(
  11455.                             array(
  11456.                                 'id' => $assignProductId
  11457.                             )
  11458.                         );
  11459.                     if ($productData) {
  11460.                         $d->setColorId($productData->getDefaultColorId());
  11461.                     }
  11462.                 }
  11463.                 if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  11464.                     $d->setDefaultLabelFormatId($assignLabelFormatId);
  11465.                     $d->setDeviceLabelFormatId($assignLabelFormatId);
  11466.                 }
  11467.                 $toAssignPosition != '' $d->setPosition($toAssignPosition) : '';
  11468.                 $warehouseId != '' $d->setWarehouseId($warehouseId) : '';
  11469.                 $warehouseActionId != '' $d->setWarehouseActionId($warehouseActionId) : '';
  11470.                 if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  11471.                     $d->setProductionScheduleId($assignProductionScheduleId);
  11472.                     $productionSchedule $em->getRepository('ApplicationBundle:ProductionSchedule')
  11473.                         ->findOneBy(
  11474.                             array(
  11475.                                 'productionScheduleId' => $assignProductionScheduleId
  11476.                             )
  11477.                         );
  11478.                     if ($productionSchedule) {
  11479.                         if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  11480.                             //becuase it will assigned at previous lines
  11481.                         } else {
  11482.                             $d->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  11483.                             $d->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  11484.                         }
  11485.                         $d->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  11486.                         $d->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  11487.                     }
  11488.                 }
  11489.                 $em->flush();
  11490.                 if ($d->getProductId() != '' || $d->getProductId() != null)
  11491.                     $productIds[] = $d->getProductId();
  11492.                 $formatId $d->getDeviceLabelFormatId();
  11493.             }
  11494.         }
  11495.         $labelFormatHere $em->getRepository('ApplicationBundle:LabelFormat')
  11496.             ->findOneBy(
  11497.                 array(
  11498.                     'formatId' => $formatId,
  11499. //                        'CompanyId' => $companyId
  11500.                 )
  11501.             );
  11502.         if ($labelFormatHere) {
  11503.             $formatData json_decode($labelFormatHere->getFormatData(), true);
  11504.             if ($formatData == null$formatData = [];
  11505.             $labelData = array(
  11506.                 'id' => $labelFormatHere->getFormatId(),
  11507.                 'formatId' => $labelFormatHere->getFormatId(),
  11508.                 'labelType' => $labelFormatHere->getLabelType(),
  11509.                 'name' => $labelFormatHere->getName(),
  11510.                 'width' => $labelFormatHere->getWidth(),
  11511.                 'pageWidth' => $labelFormatHere->getPageWidth(),
  11512.                 'height' => $labelFormatHere->getheight(),
  11513.                 'pageHeight' => $labelFormatHere->getPageHeight(),
  11514.                 'formatData' => $formatData,
  11515.             );
  11516.         }
  11517.         $productList Inventory::ProductList($em$this->getLoggedUserCompanyId($request), 10''$productIds);
  11518.         $company_data Company::getCompanyData($em1);
  11519.         $document_mark = array(
  11520.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11521.             'copy' => ''
  11522.         );
  11523.         $dt $productByCodeData;
  11524.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11525.             $html $this->renderView('@Inventory/pages/print/print_label.html.twig',
  11526.                 array(
  11527.                     //full array here
  11528.                     'pdf' => true,
  11529.                     'page_title' => 'Device Labels',
  11530.                     'export' => 'print',
  11531.                     'repeatCount' => $repeatCount,
  11532.                     'labelData' => $labelData,
  11533.                     'brandList' => Inventory::GetBrandList($em$companyId),
  11534. //                    'item_id' => $item_id,
  11535.                     'data' => $dt,
  11536.                     'productList' => $productList,
  11537.                     'approval_data' => [],
  11538.                     'document_log' => [],
  11539.                     'document_mark_image' => $document_mark['original'],
  11540.                     'company_name' => $company_data->getName(),
  11541.                     'company_data' => $company_data,
  11542.                     'company_address' => $company_data->getAddress(),
  11543.                     'company_image' => $company_data->getImage(),
  11544.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11545.                     'red' => 0
  11546.                 )
  11547.             );
  11548.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11549. //                'orientation' => 'landscape',
  11550.                 'enable-javascript' => true,
  11551. //                'javascript-delay' => 1000,
  11552.                 'no-stop-slow-scripts' => false,
  11553.                 'no-background' => false,
  11554.                 'lowquality' => false,
  11555.                 'encoding' => 'utf-8',
  11556. //            'images' => true,
  11557. //            'cookie' => array(),
  11558.                 'dpi' => 300,
  11559.                 'image-dpi' => 300,
  11560. //                'enable-external-links' => true,
  11561. //                'enable-internal-links' => true
  11562.             ));
  11563.             return new Response(
  11564.                 $pdf_response,
  11565.                 200,
  11566.                 array(
  11567.                     'Content-Type' => 'application/pdf',
  11568.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11569.                 )
  11570.             );
  11571.         }
  11572.         $url $this->generateUrl(
  11573.             'print_label'
  11574.         );
  11575.         if ($returnJson == && $printFlag == 0) {
  11576. //                    $dr = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  11577. //                        array(
  11578. //                            'salesOrderId' => $orderId, ///material
  11579. //
  11580. //                        )
  11581. //                    );
  11582.             return new JsonResponse(array(
  11583.                 'success' => true,
  11584. //                        'documentHash' => $order->getDocumentHash(),
  11585. //                'documentId' => $receiptId,
  11586. //                'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
  11587. //
  11588. //                'viewUrl' => $url . "/" . $receiptId,
  11589.             ));
  11590.         } else return $this->render('@Inventory/pages/print/print_label.html.twig',
  11591.             array(
  11592.                 'page_title' => 'Product Labels',
  11593. //                'export'=>'pdf,print',
  11594.                 'data' => $dt,
  11595.                 'productList' => $productList,
  11596.                 'repeatCount' => $repeatCount,
  11597. //                'item_id' => $item_id,
  11598.                 'labelData' => $labelData,
  11599.                 'brandList' => Inventory::GetBrandList($em$companyId),
  11600.                 'approval_data' => [],
  11601.                 'document_log' => [],
  11602.                 'document_mark_image' => $document_mark['original'],
  11603.                 'company_name' => $company_data->getName(),
  11604.                 'company_data' => $company_data,
  11605.                 'company_address' => $company_data->getAddress(),
  11606.                 'company_image' => $company_data->getImage(),
  11607.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11608.                 'red' => 0
  11609.             )
  11610.         );
  11611.     }
  11612.     public
  11613.     function PrintCartonLabelAction(Request $request$id)
  11614.     {
  11615.         $em $this->getDoctrine()->getManager();
  11616. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11617.         $repeatCount 1;
  11618.         $assignProductId '';
  11619.         $productByCodeIds = [];
  11620.         $cartonId 0;
  11621.         if ($id != 0)
  11622.             $cartonId $id;
  11623.         $colorText '';
  11624.         $weightText '';
  11625.         if ($request->query->has('repeatCount'))
  11626.             $repeatCount $request->query->get('repeatCount');
  11627.         if ($request->request->has('printCartonId'))
  11628.             $cartonId $request->request->get('printCartonId');
  11629.         if ($request->request->has('printCartonColorText'))
  11630.             $colorText $request->request->get('printCartonColorText');
  11631.         if ($request->request->has('printCartonWeightText'))
  11632.             $weightText $request->request->get('printCartonWeightText');
  11633.         $labelData = [
  11634.             'formatId' => 0
  11635.         ];
  11636.         if ($productByCodeIds == null)
  11637.             $productByCodeIds = [];
  11638.         $productByCodeData = [];
  11639.         $cartonData = [];
  11640.         $product = [];
  11641.         if ($cartonId != 0) {
  11642.             $cartonData $em->getRepository('ApplicationBundle:Carton')
  11643.                 ->findOneBy(
  11644.                     array(
  11645.                         'id' => $cartonId
  11646.                     )
  11647.                 );
  11648.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11649.                 ->findBy(
  11650.                     array(
  11651.                         'cartonId' => $cartonId
  11652.                     )
  11653.                 );
  11654. //            if(!empty($productByCodeData))
  11655. //                $product = $em->getRepository('ApplicationBundle:InvProducts')
  11656. //                ->findOneBy(
  11657. //                    array(
  11658. //                        'id' => $productByCodeData[0]->getProductId()
  11659. //                    )
  11660. //                );
  11661. //            else
  11662.             $product $em->getRepository('ApplicationBundle:InvProducts')
  11663.                 ->findOneBy(
  11664.                     array(
  11665.                         'id' => $cartonData->getProductId()
  11666.                     )
  11667.                 );
  11668.             $formatId $cartonData->getCartonLabelFormatId();
  11669.             $labelFormatHere $em->getRepository('ApplicationBundle:LabelFormat')
  11670.                 ->findOneBy(
  11671.                     array(
  11672.                         'formatId' => $formatId,
  11673. //                        'CompanyId' => $companyId
  11674.                     )
  11675.                 );
  11676.             if ($labelFormatHere) {
  11677.                 $formatData json_decode($labelFormatHere->getFormatData(), true);
  11678.                 if ($formatData == null$formatData = [];
  11679.                 $labelData = array(
  11680.                     'id' => $labelFormatHere->getFormatId(),
  11681.                     'formatId' => $labelFormatHere->getFormatId(),
  11682.                     'labelType' => $labelFormatHere->getLabelType(),
  11683.                     'name' => $labelFormatHere->getName(),
  11684.                     'width' => $labelFormatHere->getWidth(),
  11685.                     'pageWidth' => $labelFormatHere->getPageWidth(),
  11686.                     'height' => $labelFormatHere->getheight(),
  11687.                     'pageHeight' => $labelFormatHere->getPageHeight(),
  11688.                     'formatData' => $formatData,
  11689.                 );
  11690.             }
  11691.         }
  11692.         $company_data Company::getCompanyData($em1);
  11693.         $document_mark = array(
  11694.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11695.             'copy' => ''
  11696.         );
  11697.         $dt $productByCodeData;
  11698.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11699.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  11700.                 array(
  11701.                     //full array here
  11702.                     'pdf' => true,
  11703.                     'page_title' => 'Carton Labels',
  11704.                     'export' => 'print',
  11705.                     'labelData' => $labelData,
  11706.                     'repeatCount' => $repeatCount,
  11707. //                    'item_id' => $item_id,
  11708.                     'data' => $dt,
  11709.                     'cartonData' => $cartonData,
  11710.                     'product' => $product,
  11711.                     'colorText' => $colorText,
  11712.                     'weightText' => $weightText,
  11713.                     'approval_data' => [],
  11714.                     'document_log' => [],
  11715.                     'document_mark_image' => $document_mark['original'],
  11716.                     'company_name' => $company_data->getName(),
  11717.                     'company_data' => $company_data,
  11718.                     'company_address' => $company_data->getAddress(),
  11719.                     'company_image' => $company_data->getImage(),
  11720.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11721.                     'red' => 0
  11722.                 )
  11723.             );
  11724.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11725. //                'orientation' => 'landscape',
  11726.                 'enable-javascript' => true,
  11727. //                'javascript-delay' => 1000,
  11728.                 'no-stop-slow-scripts' => false,
  11729.                 'no-background' => false,
  11730.                 'lowquality' => false,
  11731.                 'encoding' => 'utf-8',
  11732. //            'images' => true,
  11733. //            'cookie' => array(),
  11734.                 'dpi' => 300,
  11735.                 'image-dpi' => 300,
  11736. //                'enable-external-links' => true,
  11737. //                'enable-internal-links' => true
  11738.             ));
  11739.             return new Response(
  11740.                 $pdf_response,
  11741.                 200,
  11742.                 array(
  11743.                     'Content-Type' => 'application/pdf',
  11744.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11745.                 )
  11746.             );
  11747.         }
  11748.         if ($request->query->has('previewOnly')) {
  11749.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  11750.                 array(
  11751.                     'page_title' => 'Carton Labels',
  11752. //                'export'=>'pdf,print',
  11753.                     'data' => $dt,
  11754.                     'skip_parameters' => 1,
  11755.                     'labelData' => $labelData,
  11756.                     'cartonData' => $cartonData,
  11757.                     'product' => $product,
  11758.                     'colorText' => $colorText,
  11759.                     'weightText' => $weightText,
  11760.                     'repeatCount' => $repeatCount,
  11761. //                'item_id' => $item_id,
  11762.                     'approval_data' => [],
  11763.                     'document_log' => [],
  11764.                     'document_mark_image' => $document_mark['original'],
  11765.                     'company_name' => $company_data->getName(),
  11766.                     'company_data' => $company_data,
  11767.                     'company_address' => $company_data->getAddress(),
  11768.                     'company_image' => $company_data->getImage(),
  11769.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11770.                     'red' => 0
  11771.                 )
  11772.             );
  11773.             if ($request->query->has('returnJson')) {
  11774.                 return new JsonResponse(
  11775.                     array(
  11776.                         'success' => true,
  11777.                         'page_title' => 'Product Details',
  11778.                         'company_data' => $company_data,
  11779.                         'renderedHtml' => $html,
  11780. //                'productData' => $productData,
  11781. //                'currInvList' => $currInvList,
  11782. //                'productList' => Inventory::ProductList($em, $companyId),
  11783. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11784. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11785. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11786. //                'unitList' => Inventory::UnitTypeList($em),
  11787. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11788. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11789. //                'warehouseList' => Inventory::WarehouseList($em),
  11790.                     )
  11791.                 );
  11792.             }
  11793.         }
  11794.         return $this->render('@Inventory/pages/print/print_carton_label.html.twig',
  11795.             array(
  11796.                 'page_title' => 'Carton Labels',
  11797. //                'export'=>'pdf,print',
  11798.                 'data' => $dt,
  11799.                 'cartonData' => $cartonData,
  11800.                 'product' => $product,
  11801. //                'productByCodeData' => $productByCodeData,
  11802.                 'colorText' => $colorText,
  11803.                 'weightText' => $weightText,
  11804.                 'repeatCount' => $repeatCount,
  11805.                 'labelData' => $labelData,
  11806. //                'item_id' => $item_id,
  11807.                 'approval_data' => [],
  11808.                 'document_log' => [],
  11809.                 'document_mark_image' => $document_mark['original'],
  11810.                 'company_name' => $company_data->getName(),
  11811.                 'company_data' => $company_data,
  11812.                 'company_address' => $company_data->getAddress(),
  11813.                 'company_image' => $company_data->getImage(),
  11814.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11815.                 'red' => 0
  11816.             )
  11817.         );
  11818.     }
  11819.     public function AssignInfoToProductByCodeAction(Request $request$id)
  11820.     {
  11821.         $em $this->getDoctrine()->getManager();
  11822.         $companyId $this->getLoggedUserCompanyId($request);
  11823. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11824.         $cartonId '';
  11825.         $passStatus 5;
  11826.         $assignProductId '';
  11827.         $assignProductionId '';
  11828.         $assignProductionScheduleId '';
  11829.         $gbWeightGm '';
  11830.         $dvWeightGm '';
  11831.         $cartonWeightGm '';
  11832.         if ($request->request->has('cartonId'))
  11833.             $cartonId $request->request->get('cartonId');
  11834.         if ($request->request->has('passStatus'))
  11835.             $passStatus $request->request->get('passStatus');
  11836.         if ($request->request->has('productByCodeId'))
  11837.             $id $request->request->get('productByCodeId');
  11838.         if ($request->request->has('productId'))
  11839.             $assignProductId $request->request->get('productId');
  11840.         if ($request->request->has('productionId'))
  11841.             $assignProductionId $request->request->get('productionId');
  11842.         if ($request->request->has('productionScheduleId'))
  11843.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  11844.         if ($request->request->has('gbWeightGm'))
  11845.             $gbWeightGm $request->request->get('gbWeightGm');
  11846.         if ($request->request->has('dvWeightGm'))
  11847.             $dvWeightGm $request->request->get('dvWeightGm');
  11848.         if ($request->request->has('cartonWeightGm'))
  11849.             $cartonWeightGm $request->request->get('cartonWeightGm');
  11850.         $cartonAssignedAlready 0;
  11851.         $otherData = array(
  11852.             'currentCartonBalance' => 0,
  11853.             'currentCartonCapacity' => 0,
  11854.             'currentCartonAssigned' => 0,
  11855.             'currentCartonFull' => 0,
  11856.         );
  11857.         if ($id != && $id != '') {
  11858.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11859.                 ->findOneBy(
  11860.                     array(
  11861.                         'productByCodeId' => $id
  11862.                     )
  11863.                 );
  11864.             if ($assignProductId != ''$productByCodeData->setProductId($assignProductId);
  11865.             if ($productByCodeData->getCartonId() != '' || $productByCodeData->getCartonId() != null)
  11866.                 $cartonAssignedAlready 1;
  11867.             else if ($cartonId != ''$productByCodeData->setCartonId($cartonId);
  11868.             if ($dvWeightGm != ''$productByCodeData->setSingleWeightGm($dvWeightGm);
  11869.             if ($gbWeightGm != '') {
  11870.                 $productByCodeData->setPackagedWeightGm($gbWeightGm);
  11871.             }
  11872.             $colorText '_NA_';
  11873.             if ($passStatus != 5$productByCodeData->setStage($passStatus);
  11874.             $productByCodeData->setCompanyId($companyId);
  11875.             if ($assignProductionId != '') {
  11876.                 $productByCodeData->setProductionId($assignProductionId);
  11877.                 $productionData $em->getRepository('ApplicationBundle:Production')
  11878.                     ->findOneBy(
  11879.                         array(
  11880.                             'productionId' => $assignProductionId
  11881.                         )
  11882.                     );
  11883.                 if ($assignProductId != '' && $assignProductId != null && $assignProductId != 0)
  11884.                     $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11885.                         array(
  11886.                             'productionId' => $assignProductionId,
  11887.                             'productId' => $assignProductId,
  11888.                             'type' => 1,
  11889.                         )
  11890.                     );
  11891.                 else
  11892.                     $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11893.                         array(
  11894.                             'productionId' => $assignProductionId,
  11895. //                            'productId' => $assignProductId,
  11896.                             'type' => 1,
  11897.                         )
  11898.                     );
  11899.                 $assignProductionScheduleId $productionData->getProductionScheduleId();
  11900.                 if ($productionItemData) {
  11901.                     $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11902.                     $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11903.                     $productByCodeData->setPosition(1);//in inventory
  11904.                     $productByCodeData->setSerialAssigned(1);
  11905.                     $productByCodeData->setColorId($productionItemData->getColorId());
  11906.                     $productByCodeData->setColorText($productionItemData->getColorText());
  11907.                     $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11908.                     $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11909.                     if ($passStatus == 1)//passed
  11910.                     {
  11911. //                    $transDate = new \DateTime();
  11912. //                    Inventory::addItemToInventoryCompact($em,
  11913. //                        $productionItemData->getProductId(),
  11914. //                        $productionItemData->getWarehouseId(),
  11915. //                        $productionItemData->getWarehouseId(),
  11916. //                        $productionData->getProducedItemActionTagId(),
  11917. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11918. //                        $transDate,
  11919. //                        1,
  11920. //                        1,
  11921. //                        $entry['valueAdd'],
  11922. //                        $entry['valueSub'],
  11923. //                        $entry['price'],
  11924. //                        $this->getLoggedUserCompanyId($request),
  11925. //                        0,
  11926. //                        $entry['entity'],
  11927. //                        $entry['entityId'],
  11928. //                        $entry['entityDocHash']
  11929. //                    );
  11930.                     }
  11931.                     $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  11932.                     if ($transHistory == null)
  11933.                         $transHistory = [];
  11934.                     $transHistory[] = array(
  11935.                         'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  11936.                         'direction' => 'in',
  11937.                         'warehouseId' => $productionItemData->getWarehouseId(),
  11938.                         'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  11939.                         'fromWarehouseId' => 0,
  11940.                         'fromWarehouseActionId' => //stock of goods
  11941.                     );
  11942.                     $productByCodeData->setTransactionHistory(json_encode($transHistory));
  11943.                 }
  11944.             }
  11945.             if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  11946.                 $productByCodeData->setProductionScheduleId($assignProductionScheduleId);
  11947.                 $productionSchedule $em->getRepository('ApplicationBundle:ProductionSchedule')
  11948.                     ->findOneBy(
  11949.                         array(
  11950.                             'productionScheduleId' => $assignProductionScheduleId
  11951.                         )
  11952.                     );
  11953.                 if ($productionSchedule) {
  11954.                     $productByCodeData->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  11955.                     $productByCodeData->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  11956.                     $productByCodeData->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  11957.                     $productByCodeData->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  11958.                     if ($productByCodeData->getProductionId() == null || $productByCodeData->getProductionId() == '' || $productByCodeData->getProductionId() == 0) {
  11959.                         $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11960.                             array(
  11961.                                 'productionScheduleId' => $assignProductionScheduleId,
  11962.                                 'productId' => $productionSchedule->getProducedProductId(),
  11963.                                 'type' => 1,
  11964.                             )
  11965.                         );
  11966. //                        $assignProductionScheduleId=$productionData->getProductionScheduleId();
  11967.                         if ($productionItemData) {
  11968.                             $productByCodeData->setProductionId($productionItemData->getProductionId());
  11969.                             $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11970.                             $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11971.                             $productByCodeData->setPosition(1);//in inventory
  11972.                             $productByCodeData->setSerialAssigned(1);
  11973.                             $productByCodeData->setColorId($productionItemData->getColorId());
  11974.                             $productByCodeData->setColorText($productionItemData->getColorText());
  11975.                             $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11976.                             $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11977.                             if ($passStatus == 1)//passed
  11978.                             {
  11979. //                    $transDate = new \DateTime();
  11980. //                    Inventory::addItemToInventoryCompact($em,
  11981. //                        $productionItemData->getProductId(),
  11982. //                        $productionItemData->getWarehouseId(),
  11983. //                        $productionItemData->getWarehouseId(),
  11984. //                        $productionData->getProducedItemActionTagId(),
  11985. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11986. //                        $transDate,
  11987. //                        1,
  11988. //                        1,
  11989. //                        $entry['valueAdd'],
  11990. //                        $entry['valueSub'],
  11991. //                        $entry['price'],
  11992. //                        $this->getLoggedUserCompanyId($request),
  11993. //                        0,
  11994. //                        $entry['entity'],
  11995. //                        $entry['entityId'],
  11996. //                        $entry['entityDocHash']
  11997. //                    );
  11998.                             }
  11999.                             $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  12000.                             if ($transHistory == null)
  12001.                                 $transHistory = [];
  12002.                             $transHistory[] = array(
  12003.                                 'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  12004.                                 'direction' => 'in',
  12005.                                 'warehouseId' => $productionItemData->getWarehouseId(),
  12006.                                 'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  12007.                                 'fromWarehouseId' => 0,
  12008.                                 'fromWarehouseActionId' => //stock of goods
  12009.                             );
  12010.                             $productByCodeData->setTransactionHistory(json_encode($transHistory));
  12011.                         }
  12012.                     }
  12013.                 }
  12014.             }
  12015. //                $productByCodeData->setPurchaseWarrantyLastDate($new_pwld);
  12016.             $em->flush();
  12017.             //now adding carton
  12018.         }
  12019.         if ($cartonId != '') {
  12020.             $carton $em->getRepository('ApplicationBundle:Carton')
  12021.                 ->findOneBy(
  12022.                     array(
  12023.                         'id' => $cartonId
  12024.                     )
  12025.                 );
  12026.             if ($cartonWeightGm != ''$carton->setCartonWeightGm($cartonWeightGm);
  12027.             $otherData['currentCartonCapacity'] = $carton->getCartonCapacityCount();
  12028.             if ($cartonAssignedAlready == 0)
  12029.                 $carton->setCartonAssignedCount(($carton->getCartonAssignedCount()) + 1);
  12030.             $otherData['currentCartonAssigned'] = $carton->getCartonAssignedCount();
  12031.             $otherData['currentCartonBalance'] = $otherData['currentCartonCapacity'] - $otherData['currentCartonAssigned'];
  12032.             if ($otherData['currentCartonAssigned'] >= $otherData['currentCartonCapacity'])
  12033.                 $otherData['currentCartonFull'] = 1;
  12034.             $em->flush();
  12035.         }
  12036.         if ($cartonId != '') {
  12037. //                    if($cartonAssignedAlready==1)
  12038. //                    {
  12039.             $productByCodeDataListForThisCarton $em->getRepository('ApplicationBundle:ProductByCode')
  12040.                 ->findBy(
  12041.                     array(
  12042.                         'cartonId' => $cartonId
  12043.                     )
  12044.                 );
  12045.             $carton $em->getRepository('ApplicationBundle:Carton')
  12046.                 ->findOneBy(
  12047.                     array(
  12048.                         'id' => $cartonId
  12049.                     )
  12050.                 );
  12051.             $total_carton_predicted_weight 0;
  12052.             $colorTextList = [];
  12053.             $cartonProductByCodeIds = [];
  12054.             foreach ($productByCodeDataListForThisCarton as $pikamaster) {
  12055.                 if (!in_array($pikamaster->getProductByCodeId(), $cartonProductByCodeIds))
  12056.                     $cartonProductByCodeIds[] = $pikamaster->getProductByCodeId();
  12057.                 if (!in_array($pikamaster->getColorText(), $colorTextList) && $pikamaster->getColorText() != null)
  12058.                     $colorTextList[] = $pikamaster->getColorText();
  12059.                 $total_carton_predicted_weight += ($pikamaster->getPackagedWeightGm());
  12060.                 if ($passStatus != 5)
  12061.                     if ($pikamaster->getStage() < $passStatus)
  12062.                         $pikamaster->setStage($passStatus);
  12063.             }
  12064.             if ($carton)
  12065.                 $carton->setCartonCalculatedWeightGm($total_carton_predicted_weight);
  12066.             if ($passStatus != 5)
  12067.                 $carton->setStage($passStatus);
  12068.             $carton->setColors(implode(','$colorTextList));
  12069.             $carton->setCartonProductByCodeIds(json_encode($cartonProductByCodeIds));
  12070.             $em->flush();
  12071.         }
  12072.         return new JsonResponse(array(
  12073.             'success' => true,
  12074.             'otherData' => $otherData,
  12075.         ));
  12076.     }
  12077.     public function RefreshCartonListAction(Request $request$id)
  12078.     {
  12079.         $em $this->getDoctrine()->getManager();
  12080. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12081.         $cartonListArray = [];
  12082.         $cartonList = [];
  12083.         $assignableCartonList = [];
  12084.         $assignableCartonListArray = [];
  12085.         $assignable 0;
  12086.         $cartonId '';
  12087.         $passStatus 5;
  12088.         $assignProductId '';
  12089.         $assignProductionId '';
  12090.         $assignProductionScheduleId '';
  12091.         if ($request->request->has('productionId'))
  12092.             $assignProductionId $request->request->get('productionId');
  12093.         if ($request->request->has('productionScheduleId'))
  12094.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  12095.         if ($request->request->has('assignable'))
  12096.             $assignable $request->request->get('assignable');
  12097.         $cartonAssignedAlready 0;
  12098.         $otherData = array(
  12099.             'currentCartonBalance' => 0,
  12100.             'currentCartonCapacity' => 0,
  12101.             'currentCartonAssigned' => 0,
  12102.             'currentCartonFull' => 0,
  12103.         );
  12104.         //1st get all cartons for this production id
  12105.         $cartonList $em->getRepository('ApplicationBundle:Carton')
  12106.             ->findBy(
  12107.                 array(
  12108. //                    'productionId' => $assignProductionId,
  12109.                     'productionScheduleId' => $assignProductionScheduleId
  12110.                 )
  12111.             );
  12112.         $foundAssignable 0;
  12113.         $setId 0;
  12114.         $lastdmySer '';
  12115.         foreach ($cartonList as $carton) {
  12116.             $cartonData = array(
  12117.                 'id' => $carton->getId(),
  12118.                 'name' => $carton->getCartonNumber(),
  12119.                 'colors' => $carton->getColors(),
  12120.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  12121.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  12122.             );
  12123.             $cartonListArray[] = $cartonData;
  12124.             $cartonList[$cartonData['id']] = $cartonData;
  12125.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  12126.                 $foundAssignable 1;
  12127.                 $setId $cartonData['id'];
  12128.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  12129.                 $assignableCartonListArray[] = $cartonData;
  12130.             }
  12131.         }
  12132.         if ($assignable == && $foundAssignable == 0) {
  12133. //            $productionData = $em->getRepository('ApplicationBundle:Production')
  12134. //                ->findOneBy(
  12135. //                    array(
  12136. //                        'productionId' => $assignProductionId
  12137. //                    )
  12138. //                );
  12139.             $productionScheduleData $em->getRepository('ApplicationBundle:ProductionSchedule')
  12140.                 ->findOneBy(
  12141.                     array(
  12142.                         'productionScheduleId' => $assignProductionScheduleId
  12143.                     )
  12144.                 );
  12145.             $productId 0;
  12146.             $product = [];
  12147.             $productModel '';
  12148.             if ($productionScheduleData)
  12149.                 $productId $productionScheduleData->getProducedProductId();
  12150. //            $productionItem = $em->getRepository('ApplicationBundle:ProductionEntryItem')
  12151. //                ->findOneBy(
  12152. //                    array(
  12153. //                        'productionId' => $assignProductionId,
  12154. //                        'type' => 1
  12155. //                    )
  12156. //                );
  12157.             if ($productId != 0) {
  12158. //                    $productId = $productionItem->getProductId();
  12159.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  12160.                     ->findOneBy(
  12161.                         array(
  12162.                             'id' => $productId,
  12163.                         )
  12164.                     );
  12165.                 $productModel $product->getModelNo();
  12166.             }
  12167.             $carton = new Carton();
  12168.             $carton_capacity $productionScheduleData->getCartonCapacity();
  12169.             $carton->setProductId($productId);
  12170.             $carton->setProductionId($assignProductionId);
  12171.             $carton->setProductionScheduleId($assignProductionScheduleId);
  12172.             if ($productionScheduleData) {
  12173.                 $carton->setCartonLabelFormatId($productionScheduleData->getCartonLabelFormatId());
  12174.             }
  12175.             $carton->setCartonCapacityCount($carton_capacity == null $carton_capacity);
  12176.             $carton->setCartonAssignedCount(0);
  12177.             $carton->setCompanyId($this->getLoggedUserCompanyId($request));
  12178.             $today = new \DateTime();
  12179.             $dmy $productModel '-' . ($today->format('m')) . '-' . ($today->format('Y')) . '-' $productionScheduleData->getBatchNumber();
  12180.             $ser 0;
  12181.             $carton->setCartonNumberDmy($dmy);
  12182.             $carton->setCartonNumberLastSer(* (($today->format('h')) . '' . ($today->format('i'))));
  12183.             $carton->setCartonNumber($dmy '-' . ($today->format('h')) . '' . ($today->format('i')));
  12184.             $em->persist($carton);
  12185.             $em->flush();
  12186.             $cartonData = array(
  12187.                 'id' => $carton->getId(),
  12188.                 'name' => $carton->getCartonNumber(),
  12189.                 'colors' => $carton->getColors(),
  12190.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  12191.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  12192.             );
  12193.             $cartonListArray[] = $cartonData;
  12194.             $cartonList[$cartonData['id']] = $cartonData;
  12195.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  12196.                 $foundAssignable 1;
  12197.                 $setId $cartonData['id'];
  12198.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  12199.                 $assignableCartonListArray[] = $cartonData;
  12200.             }
  12201.         }
  12202.         return new JsonResponse(array(
  12203.             'success' => true,
  12204.             'cartonList' => $cartonList,
  12205.             'cartonListArray' => $cartonListArray,
  12206.             'assignableCartonList' => $assignableCartonList,
  12207.             'assignableCartonListArray' => $assignableCartonListArray,
  12208.             'setId' => $setId,
  12209.         ));
  12210.     }
  12211.     public
  12212.     function PrintDrBarcodeAction(Request $request$id$item_id)
  12213.     {
  12214.         $em $this->getDoctrine()->getManager();
  12215.         $dt Inventory::GetDrDetails($em$id$item_id);
  12216.         $repeatCount 1;
  12217.         if ($request->query->has('repeatCount'))
  12218.             $repeatCount $request->query->get('repeatCount');
  12219.         $company_data Company::getCompanyData($em1);
  12220.         $document_mark = array(
  12221.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12222.             'copy' => ''
  12223.         );
  12224.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12225.             $html $this->renderView('@Inventory/pages/print/print_dr_barcodes.html.twig',
  12226.                 array(
  12227.                     //full array here
  12228.                     'pdf' => true,
  12229.                     'page_title' => 'Challan Barcodes',
  12230.                     'export' => 'print',
  12231.                     'repeatCount' => $repeatCount,
  12232.                     'item_id' => $item_id,
  12233.                     'data' => $dt,
  12234.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12235.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12236.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12237.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12238.                         $id,
  12239.                         $dt['created_by'],
  12240.                         $dt['edited_by']),
  12241.                     'document_mark_image' => $document_mark['original'],
  12242.                     'company_name' => $company_data->getName(),
  12243.                     'company_data' => $company_data,
  12244.                     'company_address' => $company_data->getAddress(),
  12245.                     'company_image' => $company_data->getImage(),
  12246.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12247.                     'red' => 0
  12248.                 )
  12249.             );
  12250.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12251. //                'orientation' => 'landscape',
  12252.                 'enable-javascript' => true,
  12253. //                'javascript-delay' => 1000,
  12254.                 'no-stop-slow-scripts' => false,
  12255.                 'no-background' => false,
  12256.                 'lowquality' => false,
  12257.                 'encoding' => 'utf-8',
  12258. //            'images' => true,
  12259. //            'cookie' => array(),
  12260.                 'dpi' => 300,
  12261.                 'image-dpi' => 300,
  12262. //                'enable-external-links' => true,
  12263. //                'enable-internal-links' => true
  12264.             ));
  12265.             return new Response(
  12266.                 $pdf_response,
  12267.                 200,
  12268.                 array(
  12269.                     'Content-Type' => 'application/pdf',
  12270.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  12271.                 )
  12272.             );
  12273.         }
  12274.         return $this->render('@Inventory/pages/print/print_dr_barcodes.html.twig',
  12275.             array(
  12276.                 'page_title' => 'Challan barcodes',
  12277. //                'export'=>'pdf,print',
  12278.                 'data' => $dt,
  12279.                 'repeatCount' => $repeatCount,
  12280.                 'item_id' => $item_id,
  12281.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12282.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12283.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12284.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12285.                     $id,
  12286.                     $dt['created_by'],
  12287.                     $dt['edited_by']),
  12288.                 'document_mark_image' => $document_mark['original'],
  12289.                 'company_name' => $company_data->getName(),
  12290.                 'company_data' => $company_data,
  12291.                 'company_address' => $company_data->getAddress(),
  12292.                 'company_image' => $company_data->getImage(),
  12293.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12294.                 'red' => 0
  12295.             )
  12296.         );
  12297.     }
  12298.     public
  12299.     function PrintIrrBarcodeAction(Request $request$id$item_id)
  12300.     {
  12301.         $em $this->getDoctrine()->getManager();
  12302.         $dt Inventory::GetIrrDetails($em$id$item_id);
  12303.         $repeatCount 1;
  12304.         if ($request->query->has('repeatCount'))
  12305.             $repeatCount $request->query->get('repeatCount');
  12306.         $company_data Company::getCompanyData($em1);
  12307.         $document_mark = array(
  12308.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12309.             'copy' => ''
  12310.         );
  12311.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12312.             $html $this->renderView('@Inventory/pages/print/print_irr_barcodes.html.twig',
  12313.                 array(
  12314.                     //full array here
  12315.                     'pdf' => true,
  12316.                     'page_title' => 'Sales Return Barcodes',
  12317.                     'export' => 'print',
  12318.                     'repeatCount' => $repeatCount,
  12319.                     'item_id' => $item_id,
  12320.                     'data' => $dt,
  12321.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12322.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12323.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12324.                         array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12325.                         $id,
  12326.                         $dt['created_by'],
  12327.                         $dt['edited_by']),
  12328.                     'document_mark_image' => $document_mark['original'],
  12329.                     'company_name' => $company_data->getName(),
  12330.                     'company_data' => $company_data,
  12331.                     'company_address' => $company_data->getAddress(),
  12332.                     'company_image' => $company_data->getImage(),
  12333.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12334.                     'red' => 0
  12335.                 )
  12336.             );
  12337.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12338. //                'orientation' => 'landscape',
  12339.                 'enable-javascript' => true,
  12340. //                'javascript-delay' => 1000,
  12341.                 'no-stop-slow-scripts' => false,
  12342.                 'no-background' => false,
  12343.                 'lowquality' => false,
  12344.                 'encoding' => 'utf-8',
  12345. //            'images' => true,
  12346. //            'cookie' => array(),
  12347.                 'dpi' => 300,
  12348.                 'image-dpi' => 300,
  12349. //                'enable-external-links' => true,
  12350. //                'enable-internal-links' => true
  12351.             ));
  12352.             return new Response(
  12353.                 $pdf_response,
  12354.                 200,
  12355.                 array(
  12356.                     'Content-Type' => 'application/pdf',
  12357.                     'Content-Disposition' => 'attachment; filename="irr_barcodes.pdf"'
  12358.                 )
  12359.             );
  12360.         }
  12361.         return $this->render('@Inventory/pages/print/print_irr_barcodes.html.twig',
  12362.             array(
  12363.                 'page_title' => 'Sales Return barcodes',
  12364. //                'export'=>'pdf,print',
  12365.                 'data' => $dt,
  12366.                 'repeatCount' => $repeatCount,
  12367.                 'item_id' => $item_id,
  12368.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12369.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12370.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12371.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12372.                     $id,
  12373.                     $dt['created_by'],
  12374.                     $dt['edited_by']),
  12375.                 'document_mark_image' => $document_mark['original'],
  12376.                 'company_name' => $company_data->getName(),
  12377.                 'company_data' => $company_data,
  12378.                 'company_address' => $company_data->getAddress(),
  12379.                 'company_image' => $company_data->getImage(),
  12380.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12381.                 'red' => 0
  12382.             )
  12383.         );
  12384.     }
  12385.     public
  12386.     function PrintSrcvBarcodeAction(Request $request$id$item_id)
  12387.     {
  12388.         $em $this->getDoctrine()->getManager();
  12389.         $dt Inventory::GetSrcvDetails($em$id$item_id);
  12390.         $repeatCount 1;
  12391.         if ($request->query->has('repeatCount'))
  12392.             $repeatCount $request->query->get('repeatCount');
  12393.         $company_data Company::getCompanyData($em1);
  12394.         $document_mark = array(
  12395.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12396.             'copy' => ''
  12397.         );
  12398.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12399.             $html $this->renderView('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12400.                 array(
  12401.                     //full array here
  12402.                     'pdf' => true,
  12403.                     'page_title' => 'Grn Barcodes',
  12404.                     'export' => 'print',
  12405.                     'repeatCount' => $repeatCount,
  12406.                     'item_id' => $item_id,
  12407.                     'data' => $dt,
  12408.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12409.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12410.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12411.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12412.                         $id,
  12413.                         $dt['created_by'],
  12414.                         $dt['edited_by']),
  12415.                     'document_mark_image' => $document_mark['original'],
  12416.                     'company_name' => $company_data->getName(),
  12417.                     'company_data' => $company_data,
  12418.                     'company_address' => $company_data->getAddress(),
  12419.                     'company_image' => $company_data->getImage(),
  12420.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12421.                     'red' => 0
  12422.                 )
  12423.             );
  12424.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12425. //                'orientation' => 'landscape',
  12426.                 'enable-javascript' => true,
  12427. //                'javascript-delay' => 1000,
  12428.                 'no-stop-slow-scripts' => false,
  12429.                 'no-background' => false,
  12430.                 'lowquality' => false,
  12431.                 'encoding' => 'utf-8',
  12432. //            'images' => true,
  12433. //            'cookie' => array(),
  12434.                 'dpi' => 300,
  12435.                 'image-dpi' => 300,
  12436. //                'enable-external-links' => true,
  12437. //                'enable-internal-links' => true
  12438.             ));
  12439.             return new Response(
  12440.                 $pdf_response,
  12441.                 200,
  12442.                 array(
  12443.                     'Content-Type' => 'application/pdf',
  12444.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  12445.                 )
  12446.             );
  12447.         }
  12448.         return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12449.             array(
  12450.                 'page_title' => 'Srcv barcodes',
  12451. //                'export'=>'pdf,print',
  12452.                 'data' => $dt,
  12453.                 'repeatCount' => $repeatCount,
  12454.                 'item_id' => $item_id,
  12455.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12456.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12457.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12458.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12459.                     $id,
  12460.                     $dt['created_by'],
  12461.                     $dt['edited_by']),
  12462.                 'document_mark_image' => $document_mark['original'],
  12463.                 'company_name' => $company_data->getName(),
  12464.                 'company_data' => $company_data,
  12465.                 'company_address' => $company_data->getAddress(),
  12466.                 'company_image' => $company_data->getImage(),
  12467.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12468.                 'red' => 0
  12469.             )
  12470.         );
  12471.     }
  12472. //product by code
  12473.     public function ImeiListExcelUploadAction(Request $request)
  12474.     {
  12475.         $lastIndex $request->request->get('lastIndex'0);
  12476.         if ($request->isMethod('POST')) {
  12477.             $post $request->request;
  12478.             if ($request->request->has('chunkData')) {
  12479.                 //now getting the relevant checks
  12480.                 $check_list = [];
  12481.                 $csv_data $request->request->get('chunkData', []);
  12482.                 $em $this->getDoctrine()->getManager();
  12483.                 foreach ($csv_data as $ind => $data_row) {
  12484. //                    if ($ind == 1)
  12485. //                        continue;
  12486.                     $np $this->getDoctrine()
  12487.                         ->getRepository('ApplicationBundle:ProductByCode')
  12488.                         ->findOneBy(
  12489.                             array(
  12490.                                 'salesCode' => isset($data_row[4]) ? $data_row[4] : 0,
  12491. //                    'approved' =>  GeneralConstant::APPROVED,
  12492.                             )
  12493.                         );
  12494.                     if (!$np)
  12495.                         $np = new ProductByCode();
  12496. //                    $np = new ProductByCode();
  12497.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  12498.                     if (isset($data_row[1])) $np->setProductId($data_row[1]);
  12499.                     if (isset($data_row[0])) $np->setLcNumber($data_row[0]);
  12500.                     if (isset($data_row[2])) $np->setCartonNumber($data_row[2]);
  12501.                     if (isset($data_row[3])) $np->setSerialNo($data_row[3]);
  12502.                     $np->setSerialAssigned(isset($data_row[10]) ? $data_row[10] : 0);
  12503.                     if (isset($data_row[4])) $np->setImei1($data_row[4]);
  12504.                     if (isset($data_row[5])) $np->setImei2($data_row[5]);
  12505.                     if (isset($data_row[6])) $np->setImei3($data_row[6]);
  12506.                     if (isset($data_row[7])) $np->setImei4($data_row[7]);
  12507.                     if (isset($data_row[8])) $np->setBtMac($data_row[8]);
  12508.                     if (isset($data_row[9])) $np->setWlanMac($data_row[9]);
  12509.                     $np->setWarehouseId(isset($data_row[11]) ? $data_row[11] : 0);
  12510.                     $np->setWarehouseActionId(isset($data_row[12]) ? $data_row[12] : 0);
  12511.                     $np->setPosition(isset($data_row[13]) ? $data_row[13] : 0);//in inventory
  12512.                     $np->setPurchaseOrderId(0);
  12513.                     $np->setGrnId(0);
  12514.                     $np->setStage(0);
  12515.                     if (isset($data_row[3])) $np->setSalesCodeRange(json_encode([$data_row[3]]));
  12516. //                $np->setSalesCode($data_row[3]);
  12517.                     if (isset($data_row[4])) $np->setSalesCode($data_row[4]); //IMEI
  12518.                     $np->setSalesCodeSer(0);
  12519.                     $np->setSalesCodeDmy('');
  12520.                     $np->setPurchaseCodeRange("");
  12521.                     $np->setPurchaseReceiptDate(null);
  12522.                     $np->setLastInDate(null);
  12523.                     $np->setStatus(GeneralConstant::ACTIVE);
  12524.                     $np->setTransactionHistory(json_encode([
  12525.                         ]
  12526.                     ));
  12527.                     $np->setPurchaseWarrantyLastDate(null);
  12528.                     $em->persist($np);
  12529.                     $em->flush();
  12530.                 }
  12531.                 return new JsonResponse(array(
  12532.                     "success" => true,
  12533.                     "lastIndex" => $lastIndex,
  12534.                     "file_path" => '',
  12535.                     "csv_data" => $csv_data,
  12536.                     //                "debug_data"=>System::encryptSignature($r)
  12537.                 ));
  12538.             } else {
  12539.                 $path "";
  12540.                 $file_path "";
  12541.                 //            var_dump($request->files);
  12542.                 //        var_dump($request->getFile());
  12543.                 foreach ($request->files as $uploadedFile) {
  12544.                     //            if($uploadedFile->getImage())
  12545.                     //                var_dump($uploadedFile->getFile());
  12546.                     //                var_dump($uploadedFile);
  12547.                     if ($uploadedFile != null) {
  12548.                         $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  12549.                         $path $fileName;
  12550.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  12551.                         if (!file_exists($upl_dir)) {
  12552.                             mkdir($upl_dir0777true);
  12553.                         }
  12554.                         $file $uploadedFile->move($upl_dir$path);
  12555.                     }
  12556.                 }
  12557.                 //        print_r($file);
  12558.                 if ($path != "")
  12559.                     $file_path 'uploads/FileUploads/' $path;
  12560.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  12561.                 //
  12562.                 //            $img_file = file_get_contents($g_path);
  12563.                 //            $r=base64_encode($img_file);
  12564.                 $row 1;
  12565.                 $csv_data = [];
  12566.                 if (($handle fopen($g_path"r")) !== FALSE) {
  12567.                     while (($data fgetcsv($handle1000",")) !== FALSE) {
  12568.                         $num count($data);
  12569.                         $csv_data[$row] = $data;
  12570.                         //                    echo "<p> $num fields in line $row: <br /></p>\n";
  12571.                         $row++;
  12572.                         //                    for ($c=0; $c < $num; $c++) {
  12573.                         //                        echo $data[$c] . "<br />\n";
  12574.                         //                    }
  12575.                     }
  12576.                     fclose($handle);
  12577.                 }
  12578.                 //now getting the relevant checks
  12579.                 $check_list = [];
  12580.                 $em $this->getDoctrine()->getManager();
  12581.                 foreach ($csv_data as $ind => $data_row) {
  12582.                     if ($ind == 1)
  12583.                         continue;
  12584.                     $np = new ProductByCode();
  12585.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  12586.                     $np->setProductId($data_row[1]);
  12587.                     $np->setLcNumber($data_row[0]);
  12588.                     $np->setCartonNumber($data_row[2]);
  12589.                     $np->setSerialNo($data_row[3]);
  12590.                     $np->setSerialAssigned(0);
  12591.                     $np->setImei1($data_row[4]);
  12592.                     $np->setImei2($data_row[5]);
  12593.                     $np->setImei3($data_row[6]);
  12594.                     $np->setImei4($data_row[7]);
  12595.                     $np->setBtMac($data_row[8]);
  12596.                     $np->setWlanMac($data_row[9]);
  12597.                     $np->setWarehouseId(0);
  12598.                     $np->setWarehouseActionId(0);
  12599.                     $np->setPosition(0);//in inventory
  12600.                     $np->setPurchaseOrderId(0);
  12601.                     $np->setGrnId(0);
  12602.                     $np->setStage(0);
  12603.                     $np->setSalesCodeRange(json_encode([$data_row[3]]));
  12604. //                $np->setSalesCode($data_row[3]);
  12605.                     $np->setSalesCode($data_row[4]); //IMEI
  12606.                     $np->setSalesCodeSer(0);
  12607.                     $np->setSalesCodeDmy('');
  12608.                     $np->setPurchaseCodeRange("");
  12609.                     $np->setPurchaseReceiptDate(null);
  12610.                     $np->setLastInDate(null);
  12611.                     $np->setStatus(GeneralConstant::ACTIVE);
  12612.                     $np->setTransactionHistory(json_encode([
  12613.                         ]
  12614.                     ));
  12615.                     $np->setPurchaseWarrantyLastDate(null);
  12616.                     $em->persist($np);
  12617.                     $em->flush();
  12618.                 }
  12619.                 return new JsonResponse(array(
  12620.                     "success" => true,
  12621.                     "lastIndex" => $lastIndex,
  12622.                     "file_path" => $file_path,
  12623.                     "csv_data" => $csv_data,
  12624.                     //                "debug_data"=>System::encryptSignature($r)
  12625.                 ));
  12626.             }
  12627.         }
  12628.         return new JsonResponse(array(
  12629.             "success" => false,
  12630.             "file_path" => '',
  12631.             "csv_data" => [],
  12632.             "lastIndex" => $lastIndex,
  12633.         ));
  12634.     }
  12635.     public
  12636.     function ProductByCodeListAction(Request $request)
  12637.     {
  12638.         $em $this->getDoctrine()->getManager();
  12639.         $companyId $this->getLoggedUserCompanyId($request);
  12640.         $listData Inventory::GetProductListForProductByCodeListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  12641.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  12642.             if ($request->query->has('dataTableQry')) {
  12643.                 return new JsonResponse(
  12644.                     $listData
  12645.                 );
  12646.             }
  12647.         }
  12648.         $q = [];
  12649. //        $q = $this->getDoctrine()
  12650. //            ->getRepository('ApplicationBundle:ProductByCode')
  12651. //            ->findBy(
  12652. //                array(
  12653. //                    'status' => GeneralConstant::ACTIVE,
  12654. ////                    'approved' =>  GeneralConstant::APPROVED,
  12655. //                )
  12656. //
  12657. //            );
  12658.         //temp start
  12659. //        foreach($q as $np) {
  12660. //            if($np->getPosition()==1) {   /// only starting ones or in warehouse ones
  12661. //                $temp_obj = json_decode($np->getTransactionHistory());
  12662. //                if ($temp_obj != null) {
  12663. //                    $transHistory = [];
  12664. //                    $transHistory[] = $temp_obj;
  12665. //                    $np->setTransactionHistory(json_encode($transHistory));
  12666. //                }
  12667. //            }
  12668. //            $em->flush();
  12669. //        }
  12670.         ///temp end
  12671.         $stage_list = array(
  12672.             => 'Pending',
  12673.             => 'Pending',
  12674.             => 'Complete',
  12675.             => 'Partial',
  12676.         );
  12677.         $data = [];
  12678. //        foreach($q as $entry)
  12679. //        {
  12680. //            $data[]=array(
  12681. //                'doc_date'=>$entry->getStockRequisitionDate(),
  12682. //                'id'=>$entry->getStockRequisitionId(),
  12683. //                'doc_hash'=>$entry->getDocumentHash(),
  12684. //                'approval_status'=>GeneralConstant::$approvalStatus[$entry->getApproved()],
  12685. //                'stage'=>$stage_list[$entry->getStage()]
  12686. //
  12687. //            );
  12688. //        }
  12689.         return $this->render('@Inventory/pages/views/product_by_code_list.html.twig',
  12690.             array(
  12691.                 'page_title' => 'Product List',
  12692.                 'data' => $q,
  12693. //                'listData' => $listData,
  12694.                 'products' => Inventory::ProductList($em),
  12695.                 'warehouseList' => Inventory::WarehouseList($em)
  12696.             )
  12697.         );
  12698.     }
  12699. //SR
  12700.     public
  12701.     function SrListAction(Request $request)
  12702.     {
  12703.         $q $this->getDoctrine()
  12704.             ->getRepository('ApplicationBundle:StockRequisition')
  12705.             ->findBy(
  12706.                 array(
  12707.                     'status' => GeneralConstant::ACTIVE,
  12708. //                    'approved' =>  GeneralConstant::APPROVED,
  12709.                 )
  12710.                 ,
  12711.                 array(
  12712.                     'stockRequisitionDate' => 'DESC'
  12713.                 )
  12714.             );
  12715.         $stage_list = array(
  12716.             => 'Pending',
  12717.             => 'Pending',
  12718.             => 'Complete',
  12719.             => 'Partial',
  12720.         );
  12721.         $data = [];
  12722.         foreach ($q as $entry) {
  12723.             $data[] = array(
  12724.                 'doc_date' => $entry->getStockRequisitionDate(),
  12725.                 'id' => $entry->getStockRequisitionId(),
  12726.                 'doc_hash' => $entry->getDocumentHash(),
  12727.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12728.                 'stage' => $stage_list[$entry->getStage()],
  12729.                 'indentTagged' => $entry->getIndentTagged(),
  12730.                 'srIds' => $entry->getSrIds(),
  12731.                 'irIds' => $entry->getIrIds(),
  12732.                 'prIds' => $entry->getPrIds(),
  12733.                 'poIds' => $entry->getPoIds(),
  12734.             );
  12735.         }
  12736.         return $this->render('@Inventory/pages/views/sr_list.html.twig',
  12737.             array(
  12738.                 'page_title' => 'Stock Requisition List',
  12739.                 'data' => $data
  12740.             )
  12741.         );
  12742.     }
  12743.     public
  12744.     function ViewSrAction(Request $request$id)
  12745.     {
  12746.         $em $this->getDoctrine()->getManager();
  12747.         $dt Inventory::GetSrDetails($em$id);
  12748.         return $this->render(
  12749.             '@Inventory/pages/views/view_stock_requisition.html.twig',
  12750.             array(
  12751.                 'page_title' => 'Stock requisition',
  12752.                 'data' => $dt,
  12753.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12754.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12755.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12756.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12757.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12758.                     $id,
  12759.                     $dt['created_by'],
  12760.                     $dt['edited_by'])
  12761.             )
  12762.         );
  12763.     }
  12764.     public
  12765.     function PrintSrAction(Request $request$id)
  12766.     {
  12767.         $em $this->getDoctrine()->getManager();
  12768.         $dt Inventory::GetSrDetails($em$id);
  12769.         $company_data Company::getCompanyData($em1);
  12770.         $document_mark = array(
  12771.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12772.             'copy' => ''
  12773.         );
  12774.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12775.             $html $this->renderView('@Inventory/pages/print/print_sr.html.twig',
  12776.                 array(
  12777.                     //full array here
  12778.                     'pdf' => true,
  12779.                     'page_title' => 'Stock Requisition',
  12780.                     'export' => 'pdf,print',
  12781.                     'data' => $dt,
  12782.                     'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12783.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12784.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12785.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12786.                         array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12787.                         $id,
  12788.                         $dt['created_by'],
  12789.                         $dt['edited_by']),
  12790.                     'document_mark_image' => $document_mark['original'],
  12791.                     'company_name' => $company_data->getName(),
  12792.                     'company_data' => $company_data,
  12793.                     'company_address' => $company_data->getAddress(),
  12794.                     'company_image' => $company_data->getImage(),
  12795.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12796.                     'red' => 0
  12797.                 )
  12798.             );
  12799.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12800.             //     'orientation' => 'landscape',
  12801.             //     'enable-javascript' => true,
  12802.             //     'javascript-delay' => 1000,
  12803.                 'no-stop-slow-scripts' => false,
  12804.                 'no-background' => false,
  12805.                 'lowquality' => false,
  12806.                 'encoding' => 'utf-8',
  12807.             //    'images' => true,
  12808.             //    'cookie' => array(),
  12809.                 'dpi' => 300,
  12810.                 'image-dpi' => 300,
  12811.             //    'enable-external-links' => true,
  12812.             //    'enable-internal-links' => true
  12813.         ));
  12814.             return new Response(
  12815.                 $pdf_response,
  12816.                 200,
  12817.                 array(
  12818.                     'Content-Type' => 'application/pdf',
  12819.                     'Content-Disposition' => 'attachment; filename="stock_requisition_' $id '.pdf"'
  12820.                 )
  12821.             );
  12822.         }
  12823.         return $this->render('@Inventory/pages/print/print_sr.html.twig',
  12824.             array(
  12825.                 'page_title' => 'Stock Requisition',
  12826.                 'export' => 'pdf,print',
  12827.                 'data' => $dt,
  12828.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12829.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12830.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12831.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12832.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12833.                     $id,
  12834.                     $dt['created_by'],
  12835.                     $dt['edited_by']),
  12836.                 'document_mark_image' => $document_mark['original'],
  12837.                 'company_name' => $company_data->getName(),
  12838.                 'company_data' => $company_data,
  12839.                 'company_address' => $company_data->getAddress(),
  12840.                 'company_image' => $company_data->getImage(),
  12841.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12842.                 'red' => 0
  12843.             )
  12844.         );
  12845.     }
  12846. //IR
  12847.     public
  12848.     function IrListAction(Request $request)
  12849.     {
  12850.         $q $this->getDoctrine()
  12851.             ->getRepository('ApplicationBundle:StoreRequisition')
  12852.             ->findBy(
  12853.                 array(
  12854.                     'status' => GeneralConstant::ACTIVE,
  12855. //                    'approved' =>  GeneralConstant::APPROVED,
  12856.                 ),
  12857.                 array(
  12858.                     'storeRequisitionDate' => 'DESC'
  12859.                 )
  12860.             );
  12861.         $stage_list = array(
  12862.             => 'Pending',
  12863.             => 'Pending',
  12864.             => 'Complete',
  12865.             => 'Partial',
  12866.         );
  12867.         $data = [];
  12868.         foreach ($q as $entry) {
  12869.             $data[] = array(
  12870.                 'doc_date' => $entry->getStoreRequisitionDate(),
  12871.                 'id' => $entry->getStoreRequisitionId(),
  12872.                 'doc_hash' => $entry->getDocumentHash(),
  12873.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12874.                 'stage' => $stage_list[$entry->getStage()],
  12875.                 'prTagged' => $entry->getIndentTagged(),
  12876.                 'srIds' => $entry->getSrIds(),
  12877.                 'irIds' => $entry->getIrIds(),
  12878.                 'prIds' => $entry->getPrIds(),
  12879.                 'poIds' => $entry->getPoIds(),
  12880.             );
  12881.         }
  12882.         return $this->render('@Inventory/pages/views/ir_list.html.twig',
  12883.             array(
  12884.                 'page_title' => 'Indent Requisition List',
  12885.                 'data' => $data
  12886.             )
  12887.         );
  12888.     }
  12889.     public
  12890.     function ViewIrAction(Request $request$id)
  12891.     {
  12892.         $em $this->getDoctrine()->getManager();
  12893.         $dt Inventory::GetIrDetails($em$id);
  12894.         return $this->render(
  12895.             '@Inventory/pages/views/view_indent_requisition.html.twig',
  12896.             array(
  12897.                 'page_title' => 'Indent',
  12898.                 'data' => $dt,
  12899.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12900.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12901.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12902.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12903.                     $id,
  12904.                     $dt['created_by'],
  12905.                     $dt['edited_by'])
  12906.             )
  12907.         );
  12908.     }
  12909.     public
  12910.     function PrintIrAction(Request $request$id)
  12911.     {
  12912.         $em $this->getDoctrine()->getManager();
  12913.         $dt Inventory::GetIrDetails($em$id);
  12914.         $company_data Company::getCompanyData($em1);
  12915.         $document_mark = array(
  12916.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12917.             'copy' => ''
  12918.         );
  12919.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12920.             $html $this->renderView('@Inventory/pages/print/print_ir.html.twig',
  12921.                 array(
  12922.                     //full array here
  12923.                     'pdf' => true,
  12924.                     'page_title' => 'Indent Requisition',
  12925.                     'export' => 'pdf,print',
  12926.                     'data' => $dt,
  12927.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12928.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12929.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12930.                         array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12931.                         $id,
  12932.                         $dt['created_by'],
  12933.                         $dt['edited_by']),
  12934.                     'document_mark_image' => $document_mark['original'],
  12935.                     'company_name' => $company_data->getName(),
  12936.                     'company_data' => $company_data,
  12937.                     'company_address' => $company_data->getAddress(),
  12938.                     'company_image' => $company_data->getImage(),
  12939.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12940.                     'red' => 0
  12941.                 )
  12942.             );
  12943.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12944. //                'orientation' => 'landscape',
  12945. //                'enable-javascript' => true,
  12946. //                'javascript-delay' => 1000,
  12947.                 'no-stop-slow-scripts' => false,
  12948.                 'no-background' => false,
  12949.                 'lowquality' => false,
  12950.                 'encoding' => 'utf-8',
  12951. //            'images' => true,
  12952. //            'cookie' => array(),
  12953.                 'dpi' => 300,
  12954.                 'image-dpi' => 300,
  12955. //                'enable-external-links' => true,
  12956. //                'enable-internal-links' => true
  12957.             ));
  12958.             return new Response(
  12959.                 $pdf_response,
  12960.                 200,
  12961.                 array(
  12962.                     'Content-Type' => 'application/pdf',
  12963.                     'Content-Disposition' => 'attachment; filename="indent_' $id '.pdf"'
  12964.                 )
  12965.             );
  12966.         }
  12967.         return $this->render('@Inventory/pages/print/print_ir.html.twig',
  12968.             array(
  12969.                 'page_title' => 'Indent Requisition',
  12970.                 'export' => 'pdf,print',
  12971.                 'data' => $dt,
  12972.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12973.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12974.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12975.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12976.                     $id,
  12977.                     $dt['created_by'],
  12978.                     $dt['edited_by']),
  12979.                 'document_mark_image' => $document_mark['original'],
  12980.                 'company_name' => $company_data->getName(),
  12981.                 'company_data' => $company_data,
  12982.                 'company_address' => $company_data->getAddress(),
  12983.                 'company_image' => $company_data->getImage(),
  12984.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12985.                 'red' => 0
  12986.             )
  12987.         );
  12988.     }
  12989. //PR
  12990.     public
  12991.     function PrListAction(Request $request)
  12992.     {
  12993.         $q $this->getDoctrine()
  12994.             ->getRepository('ApplicationBundle:PurchaseRequisition')
  12995.             ->findBy(
  12996.                 array(
  12997.                     'status' => GeneralConstant::ACTIVE,
  12998. //                    'approved' =>  GeneralConstant::APPROVED,
  12999.                 ),
  13000.                 array(
  13001.                     'purchaseRequisitionDate' => 'DESC'
  13002.                 )
  13003.             );
  13004.         $stage_list = array(
  13005.             => 'Pending',
  13006.             => 'Pending',
  13007.             => 'Complete',
  13008.             => 'Partial',
  13009.         );
  13010.         $data = [];
  13011.         foreach ($q as $entry) {
  13012.             $data[] = array(
  13013.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  13014.                 'id' => $entry->getPurchaseRequisitionId(),
  13015.                 'doc_hash' => $entry->getDocumentHash(),
  13016.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13017.                 'acquisition_status' => $entry->getAcquisitionStatus(),
  13018.                 'acquisition_start_date' => $entry->getAcquisitionStartDate(),
  13019.                 'acquisition_end_date' => $entry->getAcquisitionEndDate(),
  13020.                 'acquisition_method' => $entry->getquotationAcquisitionMethod(),
  13021.                 'poTagged' => $entry->getPoTagged(),
  13022.                 'typeHash' => $entry->getTypehash(),
  13023.                 'srIds' => $entry->getSrIds(),
  13024.                 'irIds' => $entry->getIrIds(),
  13025.                 'prIds' => $entry->getPrIds(),
  13026.                 'poIds' => $entry->getPoIds(),
  13027.             );
  13028.         }
  13029.         return $this->render('@Inventory/pages/views/pr_list.html.twig',
  13030.             array(
  13031.                 'page_title' => 'Purchase Requisition List',
  13032.                 'data' => $data
  13033.             )
  13034.         );
  13035.     }
  13036.     public
  13037.     function ServiceRequisitionListAction(Request $request)
  13038.     {
  13039.         $q $this->getDoctrine()
  13040.             ->getRepository('ApplicationBundle:PurchaseRequisition')
  13041.             ->findBy(
  13042.                 array(
  13043.                     'status' => GeneralConstant::ACTIVE,
  13044. //                    'approved' =>  GeneralConstant::APPROVED,
  13045.                 ),
  13046.                 array(
  13047.                     'purchaseRequisitionDate' => 'DESC'
  13048.                 )
  13049.             );
  13050.         $stage_list = array(
  13051.             => 'Pending',
  13052.             => 'Pending',
  13053.             => 'Complete',
  13054.             => 'Partial',
  13055.         );
  13056.         $data = [];
  13057.         foreach ($q as $entry) {
  13058.             $data[] = array(
  13059.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  13060.                 'id' => $entry->getPurchaseRequisitionId(),
  13061.                 'doc_hash' => $entry->getDocumentHash(),
  13062.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13063.                 'poTagged' => $entry->getPoTagged(),
  13064.                 'typeHash' => $entry->getTypehash(),
  13065.                 'srIds' => $entry->getSrIds(),
  13066.                 'irIds' => $entry->getIrIds(),
  13067.                 'prIds' => $entry->getPrIds(),
  13068.                 'poIds' => $entry->getPoIds(),
  13069.             );
  13070.         }
  13071.         return $this->render('@Inventory/pages/views/service_requisition_list.html.twig',
  13072.             array(
  13073.                 'page_title' => 'Service Requisition List',
  13074.                 'data' => $data
  13075.             )
  13076.         );
  13077.     }
  13078.     public
  13079.     function ViewPrAction(Request $request$id)
  13080.     {
  13081.         $em $this->getDoctrine()->getManager();
  13082.         $dt Inventory::GetPrDetails($em$id);
  13083.         $companyId $this->getLoggedUserCompanyId($request);
  13084.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  13085.             array(
  13086.                 'page_title' => 'Purchase Requisition',
  13087.                 'data' => $dt,
  13088.                 'branchList' => Client::BranchList($em$companyId),
  13089.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  13090.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13091.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13092.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13093.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13094.                     $id,
  13095.                     $dt['created_by'],
  13096.                     $dt['edited_by'])
  13097.             )
  13098.         );
  13099.     }
  13100.     public
  13101.     function ViewServiceRequisitionAction(Request $request$id)
  13102.     {
  13103.         $em $this->getDoctrine()->getManager();
  13104.         $dt Inventory::GetPrDetails($em$id);
  13105.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  13106.             array(
  13107.                 'page_title' => 'Service Requisition',
  13108.                 'data' => $dt,
  13109.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13110.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13111.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13112.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13113.                     $id,
  13114.                     $dt['created_by'],
  13115.                     $dt['edited_by'])
  13116.             )
  13117.         );
  13118.     }
  13119.     public
  13120.     function PrintPrAction(Request $request$id)
  13121.     {
  13122.         $em $this->getDoctrine()->getManager();
  13123.         $dt Inventory::GetPrDetails($em$id);
  13124.         $companyId $this->getLoggedUserCompanyId($request);
  13125.         $company_data Company::getCompanyData($em$companyId);
  13126.         $document_mark = array(
  13127.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13128.             'copy' => ''
  13129.         );
  13130.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13131.             $html $this->renderView('@Inventory/pages/print/print_pr.html.twig',
  13132.                 array(
  13133.                     //full array here
  13134.                     'pdf' => true,
  13135.                     'page_title' => 'Purchase Requisition',
  13136.                     'export' => 'pdf,print',
  13137.                     'data' => $dt,
  13138.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13139.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13140.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13141.                         array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13142.                         $id,
  13143.                         $dt['created_by'],
  13144.                         $dt['edited_by']),
  13145.                     'document_mark_image' => $document_mark['original'],
  13146.                     'branchList' => Client::BranchList($em$companyId),
  13147.                     'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  13148.                     'company_name' => $company_data->getName(),
  13149.                     'company_data' => $company_data,
  13150.                     'company_address' => $company_data->getAddress(),
  13151.                     'company_image' => $company_data->getImage(),
  13152.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13153.                     'red' => 0
  13154.                 )
  13155.             );
  13156.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13157. //                'orientation' => 'landscape',
  13158. //                'enable-javascript' => true,
  13159. //                'javascript-delay' => 1000,
  13160.                 'no-stop-slow-scripts' => false,
  13161.                 'no-background' => false,
  13162.                 'lowquality' => false,
  13163.                 'encoding' => 'utf-8',
  13164. //            'images' => true,
  13165. //            'cookie' => array(),
  13166.                 'dpi' => 300,
  13167.                 'image-dpi' => 300,
  13168. //                'enable-external-links' => true,
  13169. //                'enable-internal-links' => true
  13170.             ));
  13171.             return new Response(
  13172.                 $pdf_response,
  13173.                 200,
  13174.                 array(
  13175.                     'Content-Type' => 'application/pdf',
  13176.                     'Content-Disposition' => 'attachment; filename="purchase_requisition_' $id '.pdf"'
  13177.                 )
  13178.             );
  13179.         }
  13180.         return $this->render('@Inventory/pages/print/print_pr.html.twig',
  13181.             array(
  13182.                 'page_title' => 'Purchase Requisition',
  13183.                 'export' => 'pdf,print',
  13184.                 'data' => $dt,
  13185.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13186.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13187.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13188.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13189.                     $id,
  13190.                     $dt['created_by'],
  13191.                     $dt['edited_by']),
  13192.                 'document_mark_image' => $document_mark['original'],
  13193.                 'company_name' => $company_data->getName(),
  13194.                 'company_data' => $company_data,
  13195.                 'branchList' => Client::BranchList($em$companyId),
  13196.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  13197.                 'company_address' => $company_data->getAddress(),
  13198.                 'company_image' => $company_data->getImage(),
  13199.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13200.                 'red' => 0
  13201.             )
  13202.         );
  13203.     }
  13204.     public
  13205.     function CreateSecondaryDeliveryReceiptAction(Request $request)
  13206.     {
  13207.         $em $this->getDoctrine()->getManager();
  13208.         $companyId $this->getLoggedUserCompanyId($request);
  13209.         $userBranchIdList $request->getSession()->get('branchIdList');
  13210.         if ($userBranchIdList == null$userBranchIdList = [];
  13211.         $userBranchId $request->getSession()->get('branchId');
  13212.         if ($request->isMethod('POST')) {
  13213.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  13214.             $dochash $request->request->get('docHash'); //change
  13215.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13216.             $approveRole 1;  //created
  13217.             $approveHash $request->request->get('approvalHash');
  13218.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  13219.                 $loginId$approveRole$approveHash)
  13220.             ) {
  13221.                 $this->addFlash(
  13222.                     'error',
  13223.                     'Sorry Couldnot insert Data.'
  13224.                 );
  13225.             } else {
  13226.                 $receiptId SalesOrderM::CreateNewSecondaryDeliveryReceipt($this->getDoctrine()->getManager(), $request->request,
  13227.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13228.                     $this->getLoggedUserCompanyId($request));
  13229.                 //now add Approval info
  13230.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13231.                 $approveRole 1;  //created
  13232.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  13233.                     $receiptId,
  13234.                     $loginId,
  13235.                     $approveRole,
  13236.                     $request->request->get('approvalHash'));
  13237.                 $options = array(
  13238.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  13239.                     'notification_server' => $this->container->getParameter('notification_server'),
  13240.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  13241.                     'url' => $this->generateUrl(
  13242.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  13243.                         ['entity_view_route_path_name']
  13244.                     )
  13245.                 );
  13246.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  13247.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  13248.                     $receiptId,
  13249.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  13250.                 );
  13251.                 $this->addFlash(
  13252.                     'success',
  13253.                     'New Delivery Receipt Created'
  13254.                 );
  13255.                 $url $this->generateUrl(
  13256.                     'view_delivery_receipt'
  13257.                 );
  13258.                 return $this->redirect($url "/" $receiptId);
  13259.             }
  13260.         }
  13261.         $debugData = [];
  13262. //        $dr_data=$em->getRepository('ApplicationBundle:DeliveryReceipt')->findOneBy(
  13263. //            array(
  13264. //                'deliveryReceiptId'=>$dr_id
  13265. //            )
  13266. //        );
  13267.         $new_swld = new \DateTime('2017-07-09');
  13268. //        if ($entry->getWarranty() > 0)
  13269. //            $new_swld->modify('+' . $entry->getWarranty() . ' month');
  13270.         $debugData[] = $new_swld->format('Y-m-d');
  13271.         $debugData[] = $new_swld;
  13272. //        $debugData[]=$dr_data->getDeliveryReceiptDate();
  13273.         $debugData[] = '+' '1' ' month';
  13274.         $branchList Client::BranchList($em$companyId, [], $userBranchIdList);
  13275.         $warehouseIds = [];
  13276.         foreach ($branchList as $br) {
  13277.             $warehouseIds[] = $br['warehouseId'];
  13278.         }
  13279.         return $this->render('@Inventory/pages/input_forms/secondaryDeliveryReceipt.html.twig',
  13280.             array(
  13281.                 'page_title' => 'New Delivery Receipt',
  13282.                 'ExistingClients' => Accounts::getClientLedgerHeads($em),
  13283.                 'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($em),
  13284.                 'ClientList' => SalesOrderM::GetSecondaryClientList($em),
  13285.                 'warehouse' => Inventory::WarehouseList($em$companyId$warehouseIds),
  13286.                 'salesOrders' => SalesOrderM::SecondarySalesOrderListPendingDelivery($em$warehouseIds),
  13287.                 'salesOrdersArray' => SalesOrderM::SecondarySalesOrderListPendingDeliveryArray($em$warehouseIds),
  13288.                 'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
  13289.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
  13290.                 'debugData' => $debugData,
  13291.             )
  13292.         );
  13293.     }
  13294.     public function AddUnitTypeAction(Request $request$id 0)
  13295.     {
  13296.         $em $this->getDoctrine()->getManager();
  13297.         $companyId $this->getLoggedUserCompanyId($request);
  13298.         if ($request->isMethod('POST')) {
  13299.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13300.             $unitType = new UnitType();
  13301.             $unitType->setName($request->request->get('name'));
  13302.             $unitType->setStatus(1);
  13303.             $em->persist($unitType);
  13304.             $em->flush();
  13305.             $this->addFlash(
  13306.                 'success',
  13307.                 'Unit Type Added'
  13308.             );
  13309.         }
  13310.         $unitTypeDetails $em->getRepository(UnitType::class)->findAll();
  13311.         return $this->render('@Inventory/pages/input_forms/addUnitType.html.twig',
  13312.             array(
  13313.                 'page_title' => 'Add Unit Type',
  13314.                 'unitTypeDetails' => $unitTypeDetails
  13315.             )
  13316.         );
  13317.     }
  13318.     public
  13319.     function SubcategoryListAction()
  13320.     {
  13321.         return $this->render('@Inventory/pages/input_forms/subCategoryList.html.twig',
  13322.             array(
  13323.                 'page_title' => 'Sub Category List',
  13324.             )
  13325.         );
  13326.     }
  13327. //    public function getInventoryProductList(Request $request)
  13328. //    {
  13329. //        $em = $this->getDoctrine()->getManager();
  13330. //
  13331. //        $page = (int) $request->query->get('page', 1);     // Default page = 1
  13332. //        $limit = (int) $request->query->get('limit', 10);   // Default limit = 10
  13333. //        $offset = ($page - 1) * $limit;
  13334. //
  13335. //        // First, get the total count of products
  13336. //        $totalQuery = $em->createQueryBuilder()
  13337. //            ->select('COUNT(i.id)')
  13338. //            ->from('ApplicationBundle:InventoryStorage', 'i')
  13339. //            ->where('i.qty > :minQty')
  13340. //            ->setParameter('minQty', 0)
  13341. //            ->getQuery();
  13342. //
  13343. //        $totalRecords = (int) $totalQuery->getSingleScalarResult();
  13344. //        $totalPages = $limit > 0 ? (int) ceil($totalRecords / $limit) : 1;
  13345. //
  13346. //        // Then, get the paginated data
  13347. //        $qb = $em->getRepository('ApplicationBundle:InventoryStorage')->createQueryBuilder('i')
  13348. //            ->select([
  13349. //                'i.productId AS productId',
  13350. //                'COALESCE(ig.name, \'\') AS itemGroupName',
  13351. //                'COALESCE(w.name, \'\') AS wareHouseName',
  13352. //                'i.qty AS quantity',
  13353. //                'COALESCE(b.name, \'\') AS brandName',
  13354. //                'COALESCE(u.name, \'\') AS UnitName',
  13355. //                'COALESCE(c.name, \'\') AS color',
  13356. //                'COALESCE(s.name, \'\') AS size',
  13357. //                'COALESCE(i.salesPrice, 0) AS salesPrice',
  13358. //                'COALESCE(p.name, \'\') AS productName'
  13359. //            ])
  13360. //            ->leftJoin('ApplicationBundle:InvProducts', 'p', 'WITH', 'i.productId = p.id')
  13361. //            ->leftJoin('ApplicationBundle:InvItemGroup', 'ig', 'WITH', 'i.igId = ig.id')
  13362. //            ->leftJoin('ApplicationBundle:Warehouse', 'w', 'WITH', 'i.warehouseId = w.id')
  13363. //            ->leftJoin('ApplicationBundle:BrandCompany', 'b', 'WITH', 'i.brandId = b.id')
  13364. //            ->leftJoin('ApplicationBundle:UnitType', 'u', 'WITH', 'i.unitTypeId = u.id')
  13365. //            ->leftJoin('ApplicationBundle:Colors', 'c', 'WITH', 'i.color = c.id')
  13366. //            ->leftJoin('ApplicationBundle:ProductSizes', 's', 'WITH', 'i.size = s.id')
  13367. //            ->where('i.qty > :minQty')
  13368. //            ->setParameter('minQty', 0)
  13369. //            ->setFirstResult($offset)
  13370. //            ->setMaxResults($limit);
  13371. //
  13372. //        $inventoryData = $qb->getQuery()->getResult();
  13373. //
  13374. //        return $this->json([
  13375. //            'page' => $page,
  13376. //            'limit' => $limit,
  13377. //            'totalRecords' => $totalRecords,
  13378. //            'totalPages' => $totalPages,
  13379. //            'data' => $inventoryData,
  13380. //        ]);
  13381. //    }
  13382.     public function getInventoryProductList(Request $request)
  13383.     {
  13384.         $em $this->getDoctrine()->getManager();
  13385.         $page = (int) $request->query->get('page'1);
  13386.         $limit = (int) $request->query->get('limit'10);
  13387.         $offset = ($page 1) * $limit;
  13388.         $totalQuery $em->createQueryBuilder()
  13389.             ->select('COUNT(i.id)')
  13390.             ->from('ApplicationBundle:InventoryStorage''i')
  13391.             ->where('i.qty > :minQty')
  13392.             ->setParameter('minQty'0)
  13393.             ->getQuery();
  13394.         $totalRecords = (int) $totalQuery->getSingleScalarResult();
  13395.         $totalPages $limit ? (int) ceil($totalRecords $limit) : 1;
  13396.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  13397.         $qb $em->getRepository('ApplicationBundle:InventoryStorage')->createQueryBuilder('i')
  13398.             ->select([
  13399.                 'i.productId AS productId',
  13400.                 'COALESCE(ig.name, \'\') AS itemGroupName',
  13401.                 'COALESCE(w.name, \'\') AS wareHouseName',
  13402.                 'COALESCE(wa.name, \'\') AS subWareHouseName',
  13403.                 'i.qty AS quantity',
  13404.                 'i.qty AS lastSold',
  13405.                 'i.qty AS lastPurchase',
  13406.                 'COALESCE(b.name, \'\') AS brandName',
  13407.                 'COALESCE(u.name, \'\') AS UnitName',
  13408.                 'COALESCE(c.name, \'\') AS color',
  13409.                 'COALESCE(s.name, \'\') AS size',
  13410.                 'COALESCE(i.purchasePrice, 0) AS purchasePrice',
  13411.                 'COALESCE(i.salesPrice, 0) AS salesPrice',
  13412.                 'COALESCE(p.name, \'\') AS productName',
  13413.                 'COALESCE(p.productCode, \'\') AS productCode',
  13414.                 "CASE 
  13415.                 WHEN p.images IS NOT NULL AND p.images <> '' 
  13416.                 THEN p.images 
  13417.                 ELSE '$defaultImage
  13418.             END AS image"
  13419.             ])
  13420.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  13421.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''i.igId = ig.id')
  13422.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''i.warehouseId = w.id')
  13423.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''i.actionTagId = wa.id')
  13424.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''i.brandId = b.id')
  13425.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''i.unitTypeId = u.id')
  13426.             ->leftJoin('ApplicationBundle:Colors''c''WITH''i.color = c.id')
  13427.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''i.size = s.id')
  13428.             ->where('i.qty > :minQty')
  13429.             ->setParameter('minQty'0)
  13430.             ->setFirstResult($offset)
  13431.             ->setMaxResults($limit);
  13432.         $inventoryData $qb->getQuery()->getResult();
  13433.         return $this->json([
  13434.             'page' => $page,
  13435.             'limit' => $limit,
  13436.             'totalRecords' => $totalRecords,
  13437.             'totalPages' => $totalPages,
  13438.             'data' => $inventoryData,
  13439.         ]);
  13440.     }
  13441.     public function CreateStockTransferForAppAction(Request $request)
  13442.     {
  13443.         $em $this->getDoctrine()->getManager();
  13444.         $companyId $this->getLoggedUserCompanyId($request);
  13445.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  13446.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  13447.         if ($request->isMethod('POST')) {
  13448.             $em $this->getDoctrine()->getManager();
  13449.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  13450.             $dochash $request->request->get('docHash'); //change
  13451.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13452.             $approveRole $request->request->get('approvalRole');
  13453.             $approveHash $request->request->get('approvalHash');
  13454.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  13455.                 $loginId$approveRole$approveHash)
  13456.             ) {
  13457.                 $this->addFlash(
  13458.                     'error',
  13459.                     'Sorry Couldnot insert Data.'
  13460.                 );
  13461.             } else {
  13462.                 if ($request->request->has('check_allowed'))
  13463.                     $check_allowed 1;
  13464.                 $StID Inventory::CreateNewStockTransferForAPP(
  13465.                     $this->getDoctrine()->getManager(),
  13466.                     $request->request,
  13467.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13468.                     $this->getLoggedUserCompanyId($request)
  13469.                 );
  13470.                 //now add Approval info
  13471.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13472.                 $approveRole 1;  //created
  13473.                 $options = array(
  13474.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  13475.                     'notification_server' => $this->container->getParameter('notification_server'),
  13476.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  13477.                     'url' => $this->generateUrl(
  13478.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  13479.                         ['entity_view_route_path_name']
  13480.                     )
  13481.                 );
  13482.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  13483.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  13484.                     $StID,
  13485.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  13486.                 );
  13487.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  13488.                     $loginId,
  13489.                     $approveRole,
  13490.                     $request->request->get('approvalHash'));
  13491.                 $this->addFlash(
  13492.                     'success',
  13493.                     'Stock Transfer Added.'
  13494.                 );
  13495.                 $url $this->generateUrl(
  13496.                     'view_st'
  13497.                 );
  13498. //                return $this->redirect($url . "/" . $StID);
  13499.                 return $this->json(['success' => true]);
  13500.             }
  13501.         }
  13502.        $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  13503.             array(
  13504.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  13505.            )
  13506.         );
  13507.         $INVLIST = [];
  13508.        foreach ($slotList as $slot) {
  13509.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  13510.        }
  13511.         return $this->json(['success' => true]);
  13512. //       return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  13513. //           array(
  13514. //         'page_title' => 'Stock Transfer Note',
  13515. //               'warehouseList' => Inventory::WarehouseList($em),
  13516. //        'warehouseListArray' => Inventory::WarehouseListArray($em),
  13517. //               'colorList' => Inventory::GetColorList($em),
  13518. //               'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13519. //                'srList' => [],
  13520. //               'warehouseActionList' => $warehouse_action_list,
  13521. //                'warehouseActionListArray' => $warehouse_action_list_array,
  13522. //                'item_list' => Inventory::ItemGroupList($em),
  13523. //                'item_list_array' => Inventory::ItemGroupListArray($em),
  13524. //               'category_list_array' => Inventory::ProductCategoryListArray($em),
  13525. //              'product_list_array' => Inventory::ProductListDetailedArray($em),
  13526. ////               'product_list_array' => [],
  13527. //               'product_list' => Inventory::ProductList($em, $companyId),
  13528. ////                'product_list' => [],
  13529. //               'prefix_list' => array(
  13530. //                   [
  13531. //                       'id' => 1,
  13532. //                       'value' => 'GN',
  13533. //                        'text' => 'GN'
  13534. //
  13535. //                   ]
  13536. //              ),
  13537. //              'assoc_list' => array(
  13538. //                  [
  13539. //                       'id' => 1,
  13540. //                        'value' => 1,
  13541. //                        'text' => 'GN'
  13542. //
  13543. //                  ]
  13544. //               ),
  13545. //              'INVLIST' => $INVLIST
  13546. //           )
  13547. //      );
  13548.     }
  13549.     public function getWarehouseList(Request $request){
  13550.         $em $this->getDoctrine()->getManager();
  13551.         $warehouses $em->getRepository('ApplicationBundle:Warehouse')
  13552.             ->createQueryBuilder('w')
  13553.             ->select('w.id''w.name')
  13554.             ->orderBy('w.name''ASC')
  13555.             ->getQuery()
  13556.             ->getResult();
  13557.         return $this->json($warehouses);
  13558.     }
  13559.     public function getSubWarehouseList(Request $request){
  13560.         $em $this->getDoctrine()->getManager();
  13561.         $warehouses $em->getRepository('ApplicationBundle:WarehouseAction')
  13562.             ->createQueryBuilder('w')
  13563.             ->select('w.id''w.name')
  13564. //            ->orderBy('w.name', 'ASC')
  13565.             ->getQuery()
  13566.             ->getResult();
  13567.         return $this->json($warehouses);
  13568.     }
  13569.     public function getStockReceiveList(Request $request){
  13570.         $list GeneralConstant::$stockReceiveType;
  13571.         return $this->json($list);
  13572.     }
  13573.     public function getOrderListByStockReceiveId(Request $request)
  13574.     {
  13575.         $em $this->getDoctrine()->getManager();
  13576.         $typeName $request->request->get('type');
  13577.         $typeId $request->request->get('id');
  13578.         $document null;
  13579.         if($typeName == 'From Stock Transfer' || $typeId == 1){
  13580.             $document $em->getRepository('ApplicationBundle:StockTransfer')->createQueryBuilder('s')->select('s.stockTransferId','s.documentHash')->where('s.approved !=1')->getQuery()->getResult();
  13581.         } else if($typeName == 'For Stock In' || $typeId == 3){
  13582.             $document $em->getRepository('ApplicationBundle:AccAccountsHead')->createQueryBuilder('a')->select('a.accountsHeadId','a.name')->getQuery()->getResult();
  13583.         }
  13584.         else if($typeName == 'For Opening Entity' || $typeId == 4){
  13585.             $document $em->getRepository('ApplicationBundle:WarehouseAction')
  13586.                 ->createQueryBuilder('w')
  13587.                 ->select('w.id''w.name')
  13588.                 ->getQuery()
  13589.                 ->getResult();
  13590.         }
  13591.         return $this->json($document);
  13592.     }
  13593.     public function GetProductFromInvStorage(Request $request)
  13594.     {
  13595.         $em $this->getDoctrine()->getManager();
  13596.         $searchTerm trim($request->get('name'));
  13597.         // Fetch all or filtered products
  13598.         if ($searchTerm) {
  13599.             $products $em->getRepository('ApplicationBundle:InvProducts')
  13600.                 ->createQueryBuilder('p')
  13601.                 ->where('p.name LIKE :term')
  13602.                 ->setParameter('term''%' $searchTerm '%')
  13603.                 ->getQuery()
  13604.                 ->getResult();
  13605.         } else {
  13606.             $products $em->getRepository('ApplicationBundle:InvProducts')->findAll();
  13607.         }
  13608.         $response = [];
  13609.         foreach ($products as $product) {
  13610.             // All InventoryStorage entries for the product
  13611.             $invStorageItems $em->getRepository('ApplicationBundle:InventoryStorage')->findBy([
  13612.                 'productId' => $product->getId()
  13613.             ]);
  13614.             $inventoryList = [];
  13615.             foreach ($invStorageItems as $item) {
  13616.                 $warehouse $em->getRepository('ApplicationBundle:Warehouse')->find($item->getWarehouseId());
  13617.                 $subWarehouse $em->getRepository('ApplicationBundle:WarehouseAction')->find($item->getActionTagId());
  13618.                 $inventoryList[] = [
  13619.                     'warehouse_id'      => $item->getWarehouseId(),
  13620.                     'warehouse_name'    => $warehouse $warehouse->getName() : '',
  13621.                     'sub_warehouse_id'  => $item->getActionTagId(),
  13622.                     'sub_warehouse_name'=> $subWarehouse $subWarehouse->getName() : '',
  13623.                     'quantity'          => $item->getQty(),
  13624.                     'lastSold'          => $item->getNonInvoicedQty(),
  13625.                     'lastPurchase'      => $item->getPhysicalQty(),
  13626.                     'purchasePrice'     => $item->getPurchasePrice(),
  13627.                     'salesPrice'        => $item->getSalesPrice(),
  13628.                     'brandName'         => $item->getBrandId(),
  13629.                     'unitName'          => 'pcs'// Optional: Resolve via Unit table
  13630.                 ];
  13631.             }
  13632.             $response[] = [
  13633.                 'productId'     => $product->getId(),
  13634.                 'itemGroupName' => $product->getIgId(),
  13635.                 'productName'   => $product->getName(),
  13636.                 'productCode'   => $product->getProductCode(),
  13637.                 'color'         => $product->getColors(),
  13638.                 'size'          => $product->getSizes(),
  13639.                 'image'         => $product->getDefaultImage(),
  13640.                 'inventory'     => $inventoryList
  13641.             ];
  13642.         }
  13643.         return new JsonResponse($response);
  13644.     }
  13645.     public function getProductByDocumentId(Request $request)
  13646.     {
  13647.         $em $this->getDoctrine()->getManager();
  13648.         $documentId $request->request->get('documentId');
  13649.         $accountsHeadId $request->request->get('accountsHeadId');
  13650.         if($documentId){
  13651.             $productIdRows $em->getRepository('ApplicationBundle:StockTransferItem')
  13652.                 ->createQueryBuilder('s')
  13653.                 ->select('s.productId')
  13654.                 ->where('s.stockTransferId = :documentId')
  13655.                 ->setParameter('documentId'$documentId)
  13656.                 ->getQuery()
  13657.                 ->getResult();
  13658.             $fromWarehouseRow $em->getRepository('ApplicationBundle:StockTransferItem')
  13659.                 ->createQueryBuilder('s')
  13660.                 ->select('s.warehouseId''s.toWarehouseId''s.warehouseActionId''s.toWarehouseActionId','s.qty','s.price')
  13661.                 ->where('s.stockTransferId = :documentId')
  13662.                 ->setParameter('documentId'$documentId)
  13663.                 ->setMaxResults(1)
  13664.                 ->getQuery()
  13665.                 ->getOneOrNullResult();
  13666.             $productIds array_map(function($row) {
  13667.                 return $row['productId'];
  13668.             }, $productIdRows);
  13669.             $product $em->getRepository('ApplicationBundle:InvProducts')->findBy([
  13670.                 'id'=>$productIds
  13671.             ]);
  13672.             $productData array_map(function($p) {
  13673.                 return [
  13674.                     'id' => $p->getId(),
  13675.                     'name' => $p->getName(),
  13676.                     'modelNo' => $p->getModelNo(),
  13677.                     'sku' => $p->getSkuCode(),
  13678.                     'productCode' => $p->getProductCode(),
  13679.                     'purchasePrice' => $p->getPurchasePrice(),
  13680.                     'salesPrice' => $p->getSalesPrice(),
  13681.                     'purchasePriceWoExpense' => $p->getPurchasePriceWoExpense(),
  13682.                     'qty' => $p->getQty(),
  13683.                     'nonInvoicedQty' => $p->getNonInvoicedQty(),
  13684.                     'nonSalesInvoicedQty' => $p->getNonSalesInvoicedQty(),
  13685.                     'unitTypeId' => $p->getUnitTypeId(),
  13686.                     'dimension' => $p->getDimension(),
  13687.                     'dimensionUnitTypeId' => $p->getDimensionUnitTypeId(),
  13688.                     'weight' => $p->getWeight(),
  13689.                     'categoryId' => $p->getCategoryId(),
  13690.                     'subCategoryId' => $p->getSubCategoryId(),
  13691.                     'brandCompany' => $p->getBrandCompany(),
  13692.                     'warehouseId' => $p->getWarehouseId(),
  13693.                     'reorderLevel' => $p->getReorderLevel(),
  13694.                     'defaultImage' => $p->getDefaultImage(),
  13695.                     'status' => $p->getStatus()
  13696.                 ];
  13697.             }, $product);
  13698.             return $this->json([
  13699.                 'warehouseId' => $fromWarehouseRow['warehouseId'],
  13700.                 'toWarehouseId' => $fromWarehouseRow['toWarehouseId'],
  13701.                 'warehouseActionId' => $fromWarehouseRow['warehouseActionId'],
  13702.                 'toWarehouseActionId' => $fromWarehouseRow['toWarehouseActionId'],
  13703.                 'quantity'=>$fromWarehouseRow['qty'],
  13704.                 'price'=>$fromWarehouseRow['price'],
  13705.                 'products' => $productData
  13706.             ]);
  13707.         }else if($accountsHeadId){
  13708.             $products $em->getRepository('ApplicationBundle:InvProducts')->findAll();
  13709.             $productData array_map(function($p) {
  13710.                 return [
  13711.                     'id' => $p->getId(),
  13712.                     'name' => $p->getName(),
  13713.                     'modelNo' => $p->getModelNo(),
  13714.                     'sku' => $p->getSkuCode(),
  13715.                     'productCode' => $p->getProductCode(),
  13716.                     'purchasePrice' => $p->getPurchasePrice(),
  13717.                     'salesPrice' => $p->getSalesPrice(),
  13718.                     'purchasePriceWoExpense' => $p->getPurchasePriceWoExpense(),
  13719.                     'qty' => $p->getQty(),
  13720.                     'nonInvoicedQty' => $p->getNonInvoicedQty(),
  13721.                     'nonSalesInvoicedQty' => $p->getNonSalesInvoicedQty(),
  13722.                     'unitTypeId' => $p->getUnitTypeId(),
  13723.                     'dimension' => $p->getDimension(),
  13724.                     'dimensionUnitTypeId' => $p->getDimensionUnitTypeId(),
  13725.                     'weight' => $p->getWeight(),
  13726.                     'categoryId' => $p->getCategoryId(),
  13727.                     'subCategoryId' => $p->getSubCategoryId(),
  13728.                     'brandCompany' => $p->getBrandCompany(),
  13729.                     'warehouseId' => $p->getWarehouseId(),
  13730.                     'reorderLevel' => $p->getReorderLevel(),
  13731.                     'defaultImage' => $p->getDefaultImage(),
  13732.                     'status' => $p->getStatus()
  13733.                 ];
  13734.             }, $products);
  13735.             return $this->json($productData);
  13736.         }else{
  13737.             return new JsonResponse([
  13738.                 "status"=>false,
  13739.                 "message"=>"Please insert valid documentId or accountsHead!"
  13740.             ]);
  13741.         }
  13742.     }
  13743.     public function getQuantityBasedOnSubWareHouse(Request $request)
  13744.     {
  13745.         $em $this->getDoctrine()->getManager();
  13746.         $productId $request->get('product_id');
  13747.         $productName trim($request->get('product_name'));
  13748.         $warehouseId $request->get('warehouse_id');
  13749.         $warehouseActionId $request->get('warehouse_action_id');
  13750.         if (!$productId && $productName) {
  13751.             $product $em->getRepository('ApplicationBundle:InvProducts')
  13752.                 ->createQueryBuilder('p')
  13753.                 ->where('p.name LIKE :name')
  13754.                 ->setParameter('name''%' $productName '%')
  13755.                 ->setMaxResults(1)
  13756.                 ->getQuery()
  13757.                 ->getOneOrNullResult();
  13758.             if ($product) {
  13759.                 $productId $product->getId();
  13760.             }
  13761.         }
  13762.         if (!$productId || !$warehouseId || !$warehouseActionId) {
  13763.             return new JsonResponse(['error' => 'Product ID, Warehouse ID, and Action Tag ID are required'], 400);
  13764.         }
  13765.         $criteria = [
  13766.             'productId'   => $productId,
  13767.             'warehouseId' => $warehouseId,
  13768.             'actionTagId' => $warehouseActionId,
  13769.         ];
  13770.         $invStorageItems $em->getRepository('ApplicationBundle:InventoryStorage')->findBy($criteria);
  13771.         if (empty($invStorageItems)) {
  13772.             return new JsonResponse([
  13773.                 'product_id' => $productId,
  13774.                 'quantities' => []
  13775.             ]);
  13776.         }
  13777.         $totalQty 0;
  13778.         $totalNonInvoicedQty 0;
  13779.         $totalPhysicalQty 0;
  13780.         $purchasePrice null;
  13781.         $salesPrice null;
  13782.         foreach ($invStorageItems as $item) {
  13783.             $totalQty += $item->getQty();
  13784.             $totalNonInvoicedQty += $item->getNonInvoicedQty();
  13785.             $totalPhysicalQty += $item->getPhysicalQty();
  13786.             $purchasePrice $item->getPurchasePrice();
  13787.             $salesPrice $item->getSalesPrice();
  13788.         }
  13789.         $subWarehouse $em->getRepository('ApplicationBundle:WarehouseAction')->find($warehouseActionId);
  13790.         $quantitiesBySubWarehouse = [[
  13791.             'action_tag_id'     => $warehouseActionId,
  13792.             'sub_warehouse'     => $subWarehouse $subWarehouse->getName() : '',
  13793.             'qty'               => $totalQty,
  13794.             'non_invoiced_qty'  => $totalNonInvoicedQty,
  13795.             'physical_qty'      => $totalPhysicalQty,
  13796.             'purchase_price'    => $purchasePrice,
  13797.             'sales_price'       => $salesPrice,
  13798.         ]];
  13799.         return new JsonResponse([
  13800.             'product_id' => $productId,
  13801.             'quantities' => $quantitiesBySubWarehouse
  13802.         ]);
  13803.     }
  13804.     public function getPriceByWareHouseId(Request $request)
  13805.     {
  13806.         $em $this->getDoctrine()->getManager();
  13807.         $warehouseId $request->request->get('warehouseId');
  13808.         $productId $request->request->get('productId');
  13809.         $actionTagId $request->request->get('actionTagId');
  13810.         $unitPrice $em->getRepository('ApplicationBundle:InventoryStorage')->createQueryBuilder('st')
  13811.             ->select('st.purchasePrice AS purchasePrice')
  13812.             ->where('st.productId = :productId')
  13813.             ->andWhere('st.warehouseId = :warehouseId')
  13814.             ->andWhere('st.actionTagId = :actionTagId')
  13815.             ->setParameter('productId'$productId)
  13816.             ->setParameter('warehouseId'$warehouseId)
  13817.             ->setParameter('actionTagId'$actionTagId)
  13818.             ->setMaxResults(1)
  13819.             ->getQuery()
  13820.             ->getOneOrNullResult();
  13821.         return new JsonResponse([
  13822.             'purchasePrice' => $unitPrice $unitPrice['purchasePrice'] : null
  13823.         ]);
  13824.     }
  13825.     public function getStockTransferList(Request $request){
  13826.         $em $this->getDoctrine()->getManager();
  13827.         $warehouses $em->getRepository('ApplicationBundle:StockTransfer')
  13828.             ->createQueryBuilder('s')
  13829.             ->select('s.stockTransferId''s.documentHash')
  13830. //            ->orderBy('s.name', 'ASC')
  13831.             ->getQuery()
  13832.             ->getResult();
  13833.         return $this->json($warehouses);
  13834.     }
  13835.     public function stockTransferItemList(Request $request)
  13836.     {
  13837.         $em $this->getDoctrine()->getManager();
  13838.         $stockTransferId $request->query->get('stockTransferId');
  13839.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  13840.         $qb $em->createQueryBuilder();
  13841.         $qb->select(
  13842.             'sti.id AS id',
  13843.             'sti.productId AS productId',
  13844.             'sti.stockTransferId AS stockTransferId',
  13845.             'p.name AS productName',
  13846.             'sti.price AS price',
  13847.             'p.images AS images',
  13848.             'ig.name AS itemGroupName',
  13849.             'w.name AS wareHouseName',
  13850.             'sti.warehouseId AS warehouseId',
  13851.             'wa.name AS subWareHouseName',
  13852.             'sti.warehouseActionId AS warehouseActionId',
  13853.             'sti.qty AS quantity',
  13854.             'b.name AS brandName',
  13855.             'u.name AS UnitName',
  13856.             'c.name AS color',
  13857.             's.name AS size'
  13858.         )
  13859.             ->from('ApplicationBundle:StockTransferItem''sti')
  13860.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''sti.productId = p.id')
  13861.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''p.igId = ig.id')
  13862.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''sti.warehouseId = w.id')
  13863.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''sti.warehouseActionId = wa.id')
  13864.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''p.brandCompany = b.id')
  13865.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''p.unitTypeId = u.id')
  13866.             ->leftJoin('ApplicationBundle:Colors''c''WITH''sti.colorId = c.id')
  13867.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''sti.sizeId = s.id')
  13868.             ->where('sti.stockTransferId = :stockTransferId')
  13869.             ->setParameter('stockTransferId'$stockTransferId);
  13870.         $results $qb->getQuery()->getResult();
  13871.         $response = [];
  13872.         foreach ($results as $item) {
  13873.             $response[] = [
  13874.                 'id' => $item['id'],
  13875.                 'stockTransferId' => $item['stockTransferId'],
  13876.                 'productId'    => (int) $item['productId'],
  13877.                 'itemGroupName'=> $item['itemGroupName'] ?? '',
  13878.                 'wareHouseName'=> $item['wareHouseName'] ?? '',
  13879.                 'wareHouseId'=> $item['warehouseId'] ?? '',
  13880.                 'subWareHouseName'=> $item['subWareHouseName'] ?? '',
  13881.                 'subWareHouseId'=> $item['warehouseActionId'] ?? '',
  13882.                 'quantity'     => (int) $item['quantity'],
  13883.                 'brandName'    => $item['brandName'] ?? '',
  13884.                 'UnitName'     => $item['UnitName'] ?? '',
  13885.                 'color'        => $item['color'] ?? '',
  13886.                 'size'         => $item['size'] ?? '',
  13887.                 'price'   => (float) $item['price'],
  13888.                 'productName'  => $item['productName'] ?? '',
  13889.                 'image'        => !empty($item['images']) ? $item['images'] : $defaultImage,
  13890.             ];
  13891.         }
  13892.         return $this->json($response);
  13893.     }
  13894.     public function inventoryStorageFilter(Request $request)
  13895.     {
  13896.         $em $this->getDoctrine()->getManager();
  13897.         $qb $em->createQueryBuilder();
  13898.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  13899.         $qb->select(
  13900.             'i.productId',
  13901.             'ig.name AS itemGroupName',
  13902.             'w.name AS wareHouseName',
  13903.             'wa.name AS subWareHouseName',
  13904.             'i.qty AS quantity',
  13905.             'b.name AS brandName',
  13906.             'u.name AS UnitName',
  13907.             'c.name AS color',
  13908.             's.name AS size',
  13909.             'i.purchasePrice AS price',
  13910.             'p.name AS productName',
  13911.             'p.images'
  13912.         )
  13913.             ->from('ApplicationBundle:InventoryStorage''i')
  13914.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  13915.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''i.igId = ig.id')
  13916.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''i.warehouseId = w.id')
  13917.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''i.brandId = b.id')
  13918.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''i.unitTypeId = u.id')
  13919.             ->leftJoin('ApplicationBundle:Colors''c''WITH''i.color = c.id')
  13920.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''i.size = s.id')
  13921.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''i.actionTagId = wa.id');
  13922.         // Define available filters with their mappings
  13923.         $filters = [
  13924.             'itemGroup'    => 'ig.id',
  13925.             'category'     => 'p.categoryId',
  13926.             'warehouse'    => 'w.id',
  13927.             'storageType'  => 'i.actionTagId',
  13928.             'brand'        => 'b.id',
  13929.             'color'        => 'c.id',
  13930.             'colorCode'    => 'c.hexCode',
  13931.             'size'         => 's.id',
  13932.         ];
  13933.         foreach ($filters as $param => $field) {
  13934.             $value $request->query->get($param);
  13935.             if ($value !== null) {
  13936.                 $values array_map('trim'explode(','$value));
  13937.                 if (count($values) > 1) {
  13938.                     $qb->andWhere($qb->expr()->in($field":$param"))
  13939.                         ->setParameter($param$values);
  13940.                 } else {
  13941.                     $qb->andWhere("$field = :$param")
  13942.                         ->setParameter($param$values[0]);
  13943.                 }
  13944.             }
  13945.         }
  13946.         $rawResult $qb->getQuery()->getArrayResult();
  13947.         $finalResult = [];
  13948.         foreach ($rawResult as $row) {
  13949.             $finalResult[] = [
  13950.                 'productId'     => $row['productId'],
  13951.                 'itemGroupName' => $row['itemGroupName'],
  13952.                 'wareHouseName' => $row['wareHouseName'],
  13953.                 'subWareHouseName' => $row['subWareHouseName'],
  13954.                 'quantity'      => $row['quantity'],
  13955.                 'brandName'     => $row['brandName'],
  13956.                 'UnitName'      => $row['UnitName'],
  13957.                 'color'         => $row['color'] ?? '',
  13958.                 'size'          => $row['size'] ?? '',
  13959.                 'price'         => $row['price'],
  13960.                 'productName'   => $row['productName'],
  13961.                 'image'         => !empty($row['images']) ? $row['images'] : $defaultImage,
  13962.             ];
  13963.         }
  13964.         // Check if finalResult is empty
  13965.         if (empty($finalResult)) {
  13966.             return $this->json([
  13967.                 'success' => false,
  13968.                 'message' => 'No inventory items found matching your criteria'
  13969.             ]);
  13970.         }
  13971.         return $this->json([
  13972.             'success' => true,
  13973.             'data' => $finalResult
  13974.         ]);
  13975.     }
  13976. //    public function inventoryStorageFilter(Request $request)
  13977. //    {
  13978. //        $em = $this->getDoctrine()->getManager();
  13979. //        $qb = $em->createQueryBuilder();
  13980. //        $defaultImage = 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  13981. //
  13982. //        $qb->select(
  13983. //            'i.productId',
  13984. //            'ig.name AS itemGroupName',
  13985. //            'w.name AS wareHouseName',
  13986. //            'wa.name AS subWareHouseName',
  13987. //            'i.qty AS quantity',
  13988. //            'b.name AS brandName',
  13989. //            'u.name AS UnitName',
  13990. //            'c.name AS color',
  13991. //            's.name AS size',
  13992. //            'i.purchasePrice AS price',
  13993. //            'p.name AS productName',
  13994. //            'p.images'
  13995. //        )
  13996. //            ->from('ApplicationBundle:InventoryStorage', 'i')
  13997. //            ->leftJoin('ApplicationBundle:InvProducts', 'p', 'WITH', 'i.productId = p.id')
  13998. //            ->leftJoin('ApplicationBundle:InvItemGroup', 'ig', 'WITH', 'i.igId = ig.id')
  13999. //            ->leftJoin('ApplicationBundle:Warehouse', 'w', 'WITH', 'i.warehouseId = w.id')
  14000. //            ->leftJoin('ApplicationBundle:BrandCompany', 'b', 'WITH', 'i.brandId = b.id')
  14001. //            ->leftJoin('ApplicationBundle:UnitType', 'u', 'WITH', 'i.unitTypeId = u.id')
  14002. //            ->leftJoin('ApplicationBundle:Colors', 'c', 'WITH', 'i.color = c.id')
  14003. //            ->leftJoin('ApplicationBundle:ProductSizes', 's', 'WITH', 'i.size = s.id')
  14004. //            ->leftJoin('ApplicationBundle:WarehouseAction', 'wa', 'WITH', 'i.actionTagId = wa.id');
  14005. //
  14006. //        // Define available filters with their mappings
  14007. //        $filters = [
  14008. //            'itemGroup'    => 'ig.id',
  14009. //            'category'     => 'p.categoryId',
  14010. //            'warehouse'    => 'w.id',
  14011. //            'storageType'  => 'i.actionTagId',
  14012. //            'brand'        => 'b.id',
  14013. //            'color'        => 'c.id',
  14014. //            'colorCode'    => 'c.hexCode',
  14015. //            'size'         => 's.id',
  14016. //        ];
  14017. //
  14018. //        foreach ($filters as $param => $field) {
  14019. //            $value = $request->query->get($param);
  14020. //
  14021. //            if ($value !== null) {
  14022. //                $values = array_map('trim', explode(',', $value)); // handle multiple
  14023. //                if (count($values) > 1) {
  14024. //                    $qb->andWhere($qb->expr()->in($field, ":$param"))
  14025. //                        ->setParameter($param, $values);
  14026. //                } else {
  14027. //                    $qb->andWhere("$field = :$param")
  14028. //                        ->setParameter($param, $values[0]);
  14029. //                }
  14030. //            }
  14031. //        }
  14032. //
  14033. //        $rawResult = $qb->getQuery()->getArrayResult();
  14034. //
  14035. //        // Now process for validation (color, size, images)
  14036. //        $finalResult = [];
  14037. //
  14038. //        foreach ($rawResult as $row) {
  14039. //            $finalResult[] = [
  14040. //                'productId'     => $row['productId'],
  14041. //                'itemGroupName' => $row['itemGroupName'],
  14042. //                'wareHouseName' => $row['wareHouseName'],
  14043. //                'subWareHouseName' => $row['subWareHouseName'],
  14044. //                'quantity'      => $row['quantity'],
  14045. //                'brandName'     => $row['brandName'],
  14046. //                'UnitName'      => $row['UnitName'],
  14047. //                'color'         => $row['color'] ?? '',
  14048. //                'size'          => $row['size'] ?? '',
  14049. //                'price'         => $row['price'],
  14050. //                'productName'   => $row['productName'],
  14051. //                'image'         => !empty($row['images']) ? $row['images'] : $defaultImage,
  14052. //            ];
  14053. //        }
  14054. //
  14055. //
  14056. //
  14057. //        return $this->json($finalResult);
  14058. //    }
  14059.     public function getItemGroupList()
  14060.     {
  14061.         $em $this->getDoctrine()->getManager();
  14062.         $itemGroups $em->getRepository('ApplicationBundle:InvItemGroup')
  14063.             ->createQueryBuilder('ig')
  14064.             ->select('ig.id''ig.name')
  14065.             ->getQuery()
  14066.             ->getResult();
  14067.         return $this->json($itemGroups);
  14068.     }
  14069.     public function getProductCategoryList()
  14070.     {
  14071.         $em $this->getDoctrine()->getManager();
  14072.         $categories $em->getRepository('ApplicationBundle:InvProductCategories')
  14073.             ->createQueryBuilder('pc')
  14074.             ->select('pc.id''pc.name')
  14075.             ->getQuery()
  14076.             ->getResult();
  14077.         return $this->json($categories);
  14078.     }
  14079.     public function getBrandList()
  14080.     {
  14081.         $em $this->getDoctrine()->getManager();
  14082.         $brands $em->getRepository('ApplicationBundle:BrandCompany')
  14083.             ->createQueryBuilder('b')
  14084.             ->select('b.id''b.name')
  14085.             ->getQuery()
  14086.             ->getResult();
  14087.         return $this->json($brands);
  14088.     }
  14089.     public function getColorList()
  14090.     {
  14091.         $em $this->getDoctrine()->getManager();
  14092.         $colors $em->getRepository('ApplicationBundle:Colors')
  14093.             ->createQueryBuilder('c')
  14094.             ->select('c.id''c.name')
  14095.             ->getQuery()
  14096.             ->getResult();
  14097.         return $this->json($colors);
  14098.     }
  14099.     public function getColorCodeList()
  14100.     {
  14101.         $em $this->getDoctrine()->getManager();
  14102.         $colorCodes $em->getRepository('ApplicationBundle:Colors')
  14103.             ->createQueryBuilder('c')
  14104.             ->select('c.id''c.hexCode')
  14105.             ->getQuery()
  14106.             ->getResult();
  14107.         return $this->json($colorCodes);
  14108.     }
  14109.     public function getSizeList()
  14110.     {
  14111.         $em $this->getDoctrine()->getManager();
  14112.         $sizes $em->getRepository('ApplicationBundle:ProductSizes')
  14113.             ->createQueryBuilder('s')
  14114.             ->select('s.id''s.name')
  14115.             ->getQuery()
  14116.             ->getResult();
  14117.         if (empty($sizes)) {
  14118.             return $this->json([
  14119.                 'success' => false,
  14120.                 'message' => 'No data found'
  14121.             ]);
  14122.         }
  14123.         return $this->json($sizes);
  14124.     }
  14125.     public function productCodeList()
  14126.     {
  14127.         $em $this->getDoctrine()->getManager();
  14128.         $productCode $em->getRepository('ApplicationBundle:ProductByCode')
  14129.             ->createQueryBuilder('p')
  14130.             ->select('p.productByCodeId''p.productId','p.salesCode')
  14131.             ->getQuery()
  14132.             ->getResult();
  14133.         if (empty($productCode)) {
  14134.             return $this->json([
  14135.                 'success' => false,
  14136.                 'message' => 'No data found'
  14137.             ]);
  14138.         }
  14139.         return $this->json($productCode);
  14140.     }
  14141.     public function getItemInOutHistory(Request $request)
  14142.     {
  14143.         $em $this->getDoctrine()->getManager();
  14144.         $qb $em->getRepository('ApplicationBundle:InvItemTransaction')->createQueryBuilder('i')
  14145.             ->select([
  14146.                 'i.productId AS productId',
  14147.                 'i.transactionType AS transactionType',
  14148.                 'i.transactionDate AS transactionDate',
  14149.                 'toWarehouse.name AS toWarehouseId',
  14150.                 'toSubWarehouse.name AS toSubWarehouseId',
  14151.                 'fromWarehouse.name AS fromWarehouseId',
  14152.                 'fromSubWarehouse.name AS fromSubWarehouseId',
  14153.                 'i.qty AS quantity',
  14154.                 'i.entityDocHash AS document',
  14155.                 'i.entity AS entity',
  14156.                 'i.entityId AS entityId',
  14157.                 'p.name AS productName',
  14158.             ])
  14159.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  14160.             ->leftJoin('ApplicationBundle:Warehouse''toWarehouse''WITH''i.warehouseId = toWarehouse.id')
  14161.             ->leftJoin('ApplicationBundle:WarehouseAction''toSubWarehouse''WITH''i.actionTagId = toSubWarehouse.id')
  14162.             ->leftJoin('ApplicationBundle:Warehouse''fromWarehouse''WITH''i.fromWarehouseId = fromWarehouse.id')
  14163.             ->leftJoin('ApplicationBundle:WarehouseAction''fromSubWarehouse''WITH''i.fromActionTagId = fromSubWarehouse.id');
  14164.         // Parse dd-mm-yyyy to Y-m-d
  14165.         $startDateStr $request->query->get('startDate');
  14166.         $endDateStr   $request->query->get('endDate');
  14167.         if ($startDateStr && $endDateStr) {
  14168.             try {
  14169.                 $startDate = \DateTime::createFromFormat('d-m-Y'$startDateStr)->setTime(000);
  14170.                 $endDate   = \DateTime::createFromFormat('d-m-Y'$endDateStr)->setTime(235959);
  14171.                 $qb->andWhere('i.transactionDate BETWEEN :startDate AND :endDate')
  14172.                     ->setParameter('startDate'$startDate)
  14173.                     ->setParameter('endDate'$endDate);
  14174.             } catch (\Exception $e) {
  14175.                 return $this->json(['error' => 'Invalid date format. Use dd-mm-yyyy.'], 400);
  14176.             }
  14177.         }
  14178.         $results $qb->getQuery()->getResult();
  14179.         $data array_map(function ($item) {
  14180.             return [
  14181.                 'productId'          => $item['productId'],
  14182.                 'transactionType'    => $item['transactionType'] == 'IN' 'OUT',
  14183.                 'transactionDate'    => $item['transactionDate']->format('Y-m-d'),
  14184.                 'toWarehouseId'      => $item['toWarehouseId'] ?? '',
  14185.                 'toSubWarehouseId'   => $item['toSubWarehouseId'] ?? '',
  14186.                 'toSubWarehouseShortName'   => $item['toSubWarehouseId'] ?? '',
  14187.                 'fromWarehouseId'    => $item['fromWarehouseId'] ?? '',
  14188.                 'fromSubWarehouseId' => $item['fromSubWarehouseId'] ?? '',
  14189.                 'fromSubWarehouseShortName' => $item['fromSubWarehouseId'] ?? '',
  14190.                 'quantity'           => $item['quantity'],
  14191.                 'document'           => !empty($item['document']) ? $item['document'] : 0,
  14192.                 'entity'             => !empty($item['entity']) ? $item['entity'] : 0,
  14193.                 'entityId'           => !empty($item['entityId']) ? $item['entityId'] : 0,
  14194.                 'productName'        => $item['productName'],
  14195.             ];
  14196.         }, $results);
  14197.         return $this->json($data);
  14198.     }
  14199.     public function CreateStockReceivedNoteForApp(Request $request$id 0)
  14200.     {
  14201.         $em $this->getDoctrine()->getManager();
  14202.         $companyId $this->getLoggedUserCompanyId($request);
  14203.         $extDocData = [];
  14204.         $userId $request->getSession()->get(UserConstants::USER_ID);
  14205.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  14206.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  14207. //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  14208.         $userBranchIdList $request->getSession()->get('branchIdList');
  14209.         if ($userBranchIdList == null$userBranchIdList = [];
  14210.         $userBranchId $request->getSession()->get('branchId');
  14211.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  14212.             $em $this->getDoctrine()->getManager();
  14213.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //change
  14214.             $dochash $request->request->get('docHash'); //change
  14215.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14216.             $approveRole $request->request->get('approvalRole');
  14217.             $approveHash $request->request->get('approvalHash');
  14218.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  14219.                 $loginId$approveRole$approveHash$id)
  14220.             ) {
  14221.                 if ($request->request->has('returnJson')) {
  14222.                     return new JsonResponse(array(
  14223.                         'success' => false,
  14224.                         'documentHash' => 0,
  14225.                         'documentId' => 0,
  14226.                         'billIds' => [],
  14227.                         'drIds' => [],
  14228.                         'pmntTransIds' => [],
  14229.                         'viewUrl' => '',
  14230.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  14231.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  14232.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  14233.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  14234.                     ));
  14235.                 } else
  14236.                     $this->addFlash(
  14237.                         'error',
  14238.                         'Sorry Could not insert Data.'
  14239.                     );
  14240.             } else {
  14241.                 if ($request->request->has('check_allowed'))
  14242.                     $check_allowed 1;
  14243.                 $StID Inventory::CreateNewStockReceivedNoteForApp(
  14244.                     $this->getDoctrine()->getManager(),
  14245.                     $request->request,
  14246.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  14247.                     $this->getLoggedUserCompanyId($request)
  14248.                 );
  14249.                 //now add Approval info
  14250.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14251.                 $approveRole 1;  //created
  14252.                 $options = array(
  14253.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  14254.                     'notification_server' => $this->container->getParameter('notification_server'),
  14255.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  14256.                     'url' => $this->generateUrl(
  14257.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  14258.                         ['entity_view_route_path_name']
  14259.                     )
  14260.                 );
  14261.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  14262.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  14263.                     $StID,
  14264.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  14265.                 );
  14266.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  14267.                     $loginId,
  14268.                     $approveRole,
  14269.                     $request->request->get('approvalHash'));
  14270.                 $url $this->generateUrl(
  14271.                     'view_srcv'
  14272.                 );
  14273.                 if ($request->request->has('returnJson')) {
  14274.                     return new JsonResponse(array(
  14275.                         'success' => true,
  14276.                         'documentHash' => $dochash,
  14277.                         'documentId' => $StID,
  14278. //                        'viewUrl' => $url . "/" . $StID,
  14279.                     ));
  14280.                 } else {
  14281.                     $this->addFlash(
  14282.                         'success',
  14283.                         'Stock Received Note Added.'
  14284.                     );
  14285.                     return $this->redirect($url "/" $StID);
  14286.                 }
  14287.             }
  14288.         }
  14289.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  14290.             array(
  14291.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  14292.             )
  14293.         );
  14294.         if ($id == 0) {
  14295.         } else {
  14296.             $extDoc $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  14297.                 array(
  14298.                     'salesOrderId' => $id///material
  14299.                 )
  14300.             );
  14301.             //now if its not editable, redirect to view
  14302.             if ($extDoc) {
  14303.                 if ($extDoc->getEditFlag() != 1) {
  14304.                     $url $this->generateUrl(
  14305.                         'view_srcv'
  14306.                     );
  14307.                     return $this->redirect($url "/" $id);
  14308.                 } else {
  14309.                     $extDocData $extDoc;
  14310.                     $extDocDataDetails $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findOneBy(
  14311.                         array(
  14312.                             'stockReceivedNoteId' => $id///material
  14313.                         )
  14314.                     );
  14315.                 }
  14316.             } else {
  14317.             }
  14318.         }
  14319.         $INVLIST = [];
  14320.         foreach ($slotList as $slot) {
  14321.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  14322.         }
  14323.         $dataArray = array(
  14324.             'page_title' => 'Stock Received Note',
  14325. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  14326.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  14327.             'users' => Users::getUserListById($em),
  14328.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  14329.             'warehouseList' => Inventory::WarehouseList($em),
  14330.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  14331.             'warehouseActionList' => $warehouse_action_list,
  14332.             'warehouseActionListArray' => $warehouse_action_list_array,
  14333.             'extDocData' => $extDocData,
  14334.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  14335.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  14336.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  14337.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  14338. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  14339. //            'product_list' => Inventory::ProductList($em, $companyId),
  14340.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  14341.             'prefix_list' => array(
  14342.                 [
  14343.                     'id' => 1,
  14344.                     'value' => 'GN',
  14345.                     'text' => 'GN'
  14346.                 ]
  14347.             ),
  14348.             'assoc_list' => array(
  14349.                 [
  14350.                     'id' => 1,
  14351.                     'value' => 1,
  14352.                     'text' => 'GN'
  14353.                 ]
  14354.             ),
  14355.             'INVLIST' => $INVLIST,
  14356.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  14357.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  14358.             'userBranchIdList' => $userBranchIdList,
  14359.             'userBranchId' => $userBranchId,
  14360. //            'headList' => Accounts::HeadList($em),
  14361.         );
  14362.         //json
  14363.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  14364.         {
  14365.             $dataArray['success'] = true;
  14366.             return new JsonResponse(
  14367.                 $dataArray
  14368.             );
  14369.         }
  14370.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  14371.             $dataArray
  14372.         );
  14373.     }
  14374.     public function RefreshTaskOnSessionAction(Request $request)
  14375.     {
  14376.         $session $request->getSession();
  14377.         $em $this->getDoctrine()->getManager();
  14378.         $currentPlanningItemId=0;
  14379.         $currentTaskId=0;
  14380.         $taskActualStartTs=0;
  14381.         $currentTask $em->getRepository('ApplicationBundle:TaskLog')
  14382.             ->findOneBy(
  14383.                 array(
  14384.                     'userId' => $session->get(UserConstants::USER_ID),
  14385.                     'workingStatus' => 1
  14386.                 )
  14387.             );
  14388.         if ($currentTask) {
  14389.             $currentTaskId $currentTask->getId();
  14390.             $currentPlanningItemId $currentTask->getPlanningItemId();
  14391.             $taskActualStartTs $currentTask->getActualStartTs();
  14392.         }
  14393.         $session->set(UserConstants::USER_CURRENT_TASK_ID,$currentTaskId);
  14394.         $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID,$currentPlanningItemId);
  14395.         return new JsonResponse(
  14396.             array(
  14397.                 'currentPlanningItemId'=>$currentPlanningItemId,
  14398.                 'currentTaskId'=>$currentTaskId,
  14399.                 'taskActualStartTs'=>$taskActualStartTs,
  14400.             )
  14401.         );
  14402.     }
  14403. }