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

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->getId(),
  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.             $po_data = array(
  4830.                 'docHash' => $po->getDocumentHash(),
  4831.                 'docDate' => $po->getPurchaseOrderDate(),
  4832.                 'supplierId' => $po->getSupplierId(),
  4833.                 'supplierName' => $po->getSupplierId(),
  4834.                 'vatRate' => $po->getVatRate(),
  4835.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  4836.                 'aitRate' => $po->getAitRate(),
  4837.                 'aitAmount' => $po->getAitAmount(),
  4838.                 'tdsRate' => $po->getTdsRate(),
  4839.                 'tdsAmount' => $po->getTdsAmount(),
  4840.                 'vdsRate' => $po->getVdsRate(),
  4841.                 'vdsAmount' => $po->getVdsAmount(),
  4842.                 'discountRate' => $po->getDiscountRate(),
  4843.                 'discountAmount' => $po->getVatAmount(),
  4844.             );
  4845.             foreach ($Content_obj as $item) {
  4846.                 $Content[] = $item;
  4847.             }
  4848.             foreach ($Content_service_obj as $item) {
  4849.                 $ContentService[] = $item;
  4850.             }
  4851.             if ($Content) {
  4852.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  4853.             }
  4854.             return new JsonResponse(array("success" => false));
  4855.         }
  4856.         return new JsonResponse(array("success" => false));
  4857.     }
  4858.     public function GetPoDetailsForPiAction(Request $request$poId)
  4859.     {
  4860.     }
  4861.     public function GetPoDetailsAction(Request $request$poId)
  4862.     {
  4863.         if ($request->isMethod('POST')) {
  4864.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findBy(
  4865.                 array('purchaseOrderId' => $poId));
  4866.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4867.                 array('purchaseOrderId' => $poId));
  4868.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4869.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4870.             $spec_type Inventory::SpecTypeList($this->getDoctrine()->getManager());
  4871.             $Content = [];
  4872.             $po_items_list = [];
  4873.             foreach ($po_items as $entry) {
  4874.                 $po_items_list[] = array(
  4875.                     'productId' => $entry->getProductId(),
  4876.                     'productName' => $productList[$entry->getProductId()]['name'],
  4877.                     'price' => $entry->getPrice(),
  4878.                     'unit' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  4879.                     'spec' => $spec_type[$productList[$entry->getProductId()]['spec_type']]['name'],
  4880.                     'received' => $entry->getReceived(),
  4881.                     'qty' => $entry->getQty(),
  4882.                     'balance' => $entry->getBalance()
  4883.                 );
  4884.             }
  4885.             $po_data = [];
  4886.             $po_data = array(
  4887.                 'docHash' => $po->getDocumentHash(),
  4888.                 'docDate' => $po->getPurchaseOrderDate(),
  4889.                 'supplierId' => $po->getSupplierId(),
  4890.                 'supplierName' => $po->getSupplierId(),
  4891.             );
  4892.             if ($po_data) {
  4893.                 return new JsonResponse(array("success" => true"content" => $po_data));
  4894.             }
  4895.             return new JsonResponse(array("success" => false));
  4896.         }
  4897.         return new JsonResponse(array("success" => false));
  4898.     }
  4899.     public function CreateSalesReplacementAction(Request $request)
  4900.     {
  4901.         $em $this->getDoctrine()->getManager();
  4902.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4903.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4904.         if ($request->isMethod('POST')) {
  4905.             $em $this->getDoctrine()->getManager();
  4906.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesReplacement']; //change
  4907.             $dochash $request->request->get('voucherNumber'); //change
  4908.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4909.             $approveRole $request->request->get('approvalRole');
  4910.             $approveHash $request->request->get('approvalHash');
  4911.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4912.                 $loginId$approveRole$approveHash)
  4913.             ) {
  4914.                 $this->addFlash(
  4915.                     'error',
  4916.                     'Sorry Couldnot insert Data.'
  4917.                 );
  4918.             } else {
  4919.                 if ($request->request->has('check_allowed'))
  4920.                     $check_allowed 1;
  4921.                 $StID Inventory::CreateNewSalesReplacement(
  4922.                     $this->getDoctrine()->getManager(),
  4923.                     $request->request,
  4924.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  4925.                     $this->getLoggedUserCompanyId($request)
  4926.                 );
  4927.                 //now add Approval info
  4928.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4929.                 $approveRole 1;  //created
  4930.                 $options = array(
  4931.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4932.                     'notification_server' => $this->container->getParameter('notification_server'),
  4933.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4934.                     'url' => $this->generateUrl(
  4935.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesReplacement']]
  4936.                         ['entity_view_route_path_name']
  4937.                     )
  4938.                 );
  4939.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4940.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4941.                     $StID,
  4942.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  4943.                 );
  4944.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesReplacement'], $StID,
  4945.                     $loginId,
  4946.                     $approveRole,
  4947.                     $request->request->get('approvalHash'));
  4948.                 $this->addFlash(
  4949.                     'success',
  4950.                     'Stock Transfer Added.'
  4951.                 );
  4952.                 $url $this->generateUrl(
  4953.                     'view_st'
  4954.                 );
  4955.                 return $this->redirect($url "/" $StID);
  4956.             }
  4957.         }
  4958.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  4959.             array(
  4960.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  4961.             )
  4962.         );
  4963.         $INVLIST = [];
  4964.         foreach ($slotList as $slot) {
  4965.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  4966.         }
  4967.         return $this->render('@Inventory/pages/input_forms/sales_replacement.html.twig',
  4968.             array(
  4969.                 'page_title' => 'Sales Replacement Note',
  4970.                 'warehouseList' => Inventory::WarehouseList($em),
  4971.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  4972.                 'warehouseActionList' => $warehouse_action_list,
  4973.                 'warehouseActionListArray' => $warehouse_action_list_array,
  4974.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  4975.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  4976.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  4977.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  4978.                 'prefix_list' => array(
  4979.                     [
  4980.                         'id' => 1,
  4981.                         'value' => 'GN',
  4982.                         'text' => 'GN'
  4983.                     ]
  4984.                 ),
  4985.                 'assoc_list' => array(
  4986.                     [
  4987.                         'id' => 1,
  4988.                         'value' => 1,
  4989.                         'text' => 'GN'
  4990.                     ]
  4991.                 ),
  4992.                 'INVLIST' => $INVLIST
  4993.             )
  4994.         );
  4995.     }
  4996.     public function SalesReplacementListAction(Request $request)
  4997.     {
  4998.         $q $this->getDoctrine()
  4999.             ->getRepository('ApplicationBundle:SalesReplacement')
  5000.             ->findBy(
  5001.                 array(
  5002.                     'status' => GeneralConstant::ACTIVE,
  5003.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5004. //                    'approved' =>  GeneralConstant::APPROVED,
  5005.                 )
  5006.             );
  5007.         $stage_list = array(
  5008.             => 'Pending',
  5009.             => 'Pending',
  5010.             => 'Complete',
  5011.             => 'Partial',
  5012.         );
  5013.         $data = [];
  5014.         foreach ($q as $entry) {
  5015.             $data[] = array(
  5016.                 'doc_date' => $entry->getSalesReplacementDate(),
  5017.                 'id' => $entry->getSalesReplacementId(),
  5018.                 'doc_hash' => $entry->getDocumentHash(),
  5019.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5020.                 'stage' => $stage_list[$entry->getStage()]
  5021.             );
  5022.         }
  5023.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5024.             array(
  5025.                 'page_title' => 'Stock Transfer List',
  5026.                 'data' => $data
  5027.             )
  5028.         );
  5029.     }
  5030.     public function ViewSalesReplacementAction(Request $request$id)
  5031.     {
  5032.         $em $this->getDoctrine()->getManager();
  5033.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5034.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  5035.             array(
  5036.                 'page_title' => 'Stock Transfer',
  5037.                 'data' => $dt,
  5038.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5039.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5040.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5041.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5042.                     $id,
  5043.                     $dt['created_by'],
  5044.                     $dt['edited_by'])
  5045.             )
  5046.         );
  5047.     }
  5048.     public function PrintSalesReplacementAction(Request $request$id)
  5049.     {
  5050.         $em $this->getDoctrine()->getManager();
  5051.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5052.         $company_data Company::getCompanyData($em1);
  5053.         $document_mark = array(
  5054.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5055.             'copy' => ''
  5056.         );
  5057.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5058.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5059.                 array(
  5060.                     //full array here
  5061.                     'pdf' => true,
  5062.                     'page_title' => 'Stock Transfer',
  5063.                     'export' => 'pdf,print',
  5064.                     'data' => $dt,
  5065.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5066.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5067.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5068.                         array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5069.                         $id,
  5070.                         $dt['created_by'],
  5071.                         $dt['edited_by']),
  5072.                     'document_mark_image' => $document_mark['original'],
  5073.                     'company_name' => $company_data->getName(),
  5074.                     'company_data' => $company_data,
  5075.                     'company_address' => $company_data->getAddress(),
  5076.                     'company_image' => $company_data->getImage(),
  5077.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5078.                     'red' => 0
  5079.                 )
  5080.             );
  5081.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5082. //                'orientation' => 'landscape',
  5083. //                'enable-javascript' => true,
  5084. //                'javascript-delay' => 1000,
  5085.                 'no-stop-slow-scripts' => false,
  5086.                 'no-background' => false,
  5087.                 'lowquality' => false,
  5088.                 'encoding' => 'utf-8',
  5089. //            'images' => true,
  5090. //            'cookie' => array(),
  5091.                 'dpi' => 300,
  5092.                 'image-dpi' => 300,
  5093. //                'enable-external-links' => true,
  5094. //                'enable-internal-links' => true
  5095.             ));
  5096.             return new Response(
  5097.                 $pdf_response,
  5098.                 200,
  5099.                 array(
  5100.                     'Content-Type' => 'application/pdf',
  5101.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5102.                 )
  5103.             );
  5104.         }
  5105.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5106.             array(
  5107.                 'page_title' => 'Stock Transfer',
  5108.                 'export' => 'pdf,print',
  5109.                 'data' => $dt,
  5110.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5111.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5112.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5113.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5114.                     $id,
  5115.                     $dt['created_by'],
  5116.                     $dt['edited_by']),
  5117.                 'document_mark_image' => $document_mark['original'],
  5118.                 'company_name' => $company_data->getName(),
  5119.                 'company_data' => $company_data,
  5120.                 'company_address' => $company_data->getAddress(),
  5121.                 'company_image' => $company_data->getImage(),
  5122.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5123.                 'red' => 0
  5124.             )
  5125.         );
  5126.     }
  5127.     public function CreateStockTransferAction(Request $request)
  5128.     {
  5129.         $em $this->getDoctrine()->getManager();
  5130.         $companyId $this->getLoggedUserCompanyId($request);
  5131.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5132.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5133.         if ($request->isMethod('POST')) {
  5134.             $em $this->getDoctrine()->getManager();
  5135.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  5136.             $dochash $request->request->get('docHash'); //change
  5137.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5138.             $approveRole $request->request->get('approvalRole');
  5139.             $approveHash $request->request->get('approvalHash');
  5140.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5141.                 $loginId$approveRole$approveHash)
  5142.             ) {
  5143.                 $this->addFlash(
  5144.                     'error',
  5145.                     'Sorry Couldnot insert Data.'
  5146.                 );
  5147.             } else {
  5148.                 if ($request->request->has('check_allowed'))
  5149.                     $check_allowed 1;
  5150.                 $StID Inventory::CreateNewStockTransfer(
  5151.                     $this->getDoctrine()->getManager(),
  5152.                     $request->request,
  5153.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5154.                     $this->getLoggedUserCompanyId($request)
  5155.                 );
  5156.                 //now add Approval info
  5157.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5158.                 $approveRole 1;  //created
  5159.                 $options = array(
  5160.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5161.                     'notification_server' => $this->container->getParameter('notification_server'),
  5162.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5163.                     'url' => $this->generateUrl(
  5164.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  5165.                         ['entity_view_route_path_name']
  5166.                     )
  5167.                 );
  5168.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5169.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5170.                     $StID,
  5171.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  5172.                 );
  5173.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  5174.                     $loginId,
  5175.                     $approveRole,
  5176.                     $request->request->get('approvalHash'));
  5177.                 $this->addFlash(
  5178.                     'success',
  5179.                     'Stock Transfer Added.'
  5180.                 );
  5181.                 $url $this->generateUrl(
  5182.                     'view_st'
  5183.                 );
  5184.                 return $this->redirect($url "/" $StID);
  5185.             }
  5186.         }
  5187. //        $slotList = $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5188. //            array(
  5189. //                'CompanyId' => $this->getLoggedUserCompanyId($request),
  5190. //
  5191. //            )
  5192. //        );
  5193.         $INVLIST = [];
  5194. //        foreach ($slotList as $slot) {
  5195. //            $INVLIST[$slot->getWarehouseId() . '_' . $slot->getActionTagId() . '_' . $slot->getproductId()] = $slot->getQty();
  5196. //        }
  5197.         return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  5198.             array(
  5199.                 'page_title' => 'Stock Transfer Note',
  5200.                 'warehouseList' => Inventory::WarehouseList($em),
  5201.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5202.                 'colorList' => Inventory::GetColorList($em),
  5203.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  5204.                 'srList' => [],
  5205.                 'warehouseActionList' => $warehouse_action_list,
  5206.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5207.                 'item_list' => Inventory::ItemGroupList($em),
  5208.                 'item_list_array' => Inventory::ItemGroupListArray($em),
  5209.                 'category_list_array' => Inventory::ProductCategoryListArray($em),
  5210.                 'product_list_array' => Inventory::ProductListDetailedArray($em),
  5211. //                'product_list_array' => [],
  5212.                 'product_list' => Inventory::ProductList($em$companyId),
  5213. //                'product_list' => [],
  5214.                 'prefix_list' => array(
  5215.                     [
  5216.                         'id' => 1,
  5217.                         'value' => 'GN',
  5218.                         'text' => 'GN'
  5219.                     ]
  5220.                 ),
  5221.                 'assoc_list' => array(
  5222.                     [
  5223.                         'id' => 1,
  5224.                         'value' => 1,
  5225.                         'text' => 'GN'
  5226.                     ]
  5227.                 ),
  5228.                 'INVLIST' => $INVLIST
  5229.             )
  5230.         );
  5231.     }
  5232.     public function GetSrItemForTransferAction(Request $request)
  5233.     {
  5234.         $em $this->getDoctrine()->getManager();
  5235.         $search_query = [];
  5236.         $res_data_by_so_item_id = [];
  5237.         $Content = [];
  5238.         $productionProcessSettings = array(
  5239.             'id' => 0
  5240.         );
  5241.         if ($request->query->has('srId'))
  5242.             $search_query['stockRequisitionId'] = $request->query->get('srId');
  5243.         $DT $this->getDoctrine()
  5244.             ->getRepository('ApplicationBundle:StockRequisitionItem')
  5245.             ->findBy(
  5246.                 $search_query
  5247.             );
  5248.         $Content = array(
  5249.             'requisitioned_product_item_id' => [],
  5250.             'requisitioned_products' => [],
  5251.             'requisitioned_product_fdm' => [],
  5252.             'requisitioned_product_name' => [],
  5253.             'requisitioned_product_units' => [],
  5254.             'requisitioned_product_unit_type' => [],
  5255.             'requisitioned_product_balance' => [],
  5256.         );
  5257.         foreach ($DT as $dt) {
  5258. //            $data=json_decode($DT->getData(),true);
  5259.             $Content['requisitioned_products'][] = $dt->getProductId();
  5260.             $Content['requisitioned_product_item_id'][] = $dt->getId();
  5261.             $Content['requisitioned_product_fdm'][] = $dt->getProductFdm();
  5262.             $Content['requisitioned_product_name'][] = $dt->getProductNameFdm();
  5263.             $Content['requisitioned_product_units'][] = $dt->getQty();
  5264.             $Content['requisitioned_product_balance'][] = $dt->getAlottmentPendingAmount();
  5265.         }
  5266.         $INVLIST = [];
  5267.         if (!empty($Content)) {
  5268.             return new JsonResponse(array("success" => true"content" => $Content"INVLIST" => $INVLIST));
  5269.         } else {
  5270.             return new JsonResponse(array("success" => false"content" => $Content"INVLIST" => $INVLIST));
  5271.         }
  5272.     }
  5273.     public function StockTransferListAction(Request $request)
  5274.     {
  5275.         $q $this->getDoctrine()
  5276.             ->getRepository('ApplicationBundle:StockTransfer')
  5277.             ->findBy(
  5278.                 array(
  5279.                     'status' => GeneralConstant::ACTIVE,
  5280.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5281. //                    'approved' =>  GeneralConstant::APPROVED,
  5282.                 )
  5283.             );
  5284.         $stage_list = array(
  5285.             => 'Pending',
  5286.             => 'Pending',
  5287.             => 'Complete',
  5288.             => 'Partial',
  5289.         );
  5290.         $data = [];
  5291.         foreach ($q as $entry) {
  5292.             $data[] = array(
  5293.                 'doc_date' => $entry->getStockTransferDate(),
  5294.                 'id' => $entry->getStockTransferId(),
  5295.                 'doc_hash' => $entry->getDocumentHash(),
  5296.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5297.                 'stage' => $stage_list[$entry->getStage()]
  5298.             );
  5299.         }
  5300.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5301.             array(
  5302.                 'page_title' => 'Stock Transfer List',
  5303.                 'data' => $data
  5304.             )
  5305.         );
  5306.     }
  5307.     public function ViewStockTransferAction(Request $request$id)
  5308.     {
  5309.         $em $this->getDoctrine()->getManager();
  5310.         $dt Inventory::GetStockTransferDetails($em$id);
  5311.         return $this->render(
  5312.             '@Inventory/pages/views/view_stock_transfer.html.twig',
  5313.             array(
  5314.                 'page_title' => 'Stock Transfer',
  5315.                 'data' => $dt,
  5316.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5317.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5318.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5319.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5320.                     $id,
  5321.                     $dt['created_by'],
  5322.                     $dt['edited_by'])
  5323.             )
  5324.         );
  5325.     }
  5326.     public function PrintStockTransferAction(Request $request$id)
  5327.     {
  5328.         $em $this->getDoctrine()->getManager();
  5329.         $dt Inventory::GetStockTransferDetails($em$id);
  5330.         $company_data Company::getCompanyData($em1);
  5331.         $document_mark = array(
  5332.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5333.             'copy' => ''
  5334.         );
  5335.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5336.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5337.                 array(
  5338.                     //full array here
  5339.                     'pdf' => true,
  5340.                     'page_title' => 'Stock Transfer',
  5341.                     'export' => 'pdf,print',
  5342.                     'data' => $dt,
  5343.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5344.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5345.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5346.                         array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5347.                         $id,
  5348.                         $dt['created_by'],
  5349.                         $dt['edited_by']),
  5350.                     'document_mark_image' => $document_mark['original'],
  5351.                     'company_name' => $company_data->getName(),
  5352.                     'company_data' => $company_data,
  5353.                     'company_address' => $company_data->getAddress(),
  5354.                     'company_image' => $company_data->getImage(),
  5355.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5356.                     'red' => 0
  5357.                 )
  5358.             );
  5359.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5360. //                'orientation' => 'landscape',
  5361. //                'enable-javascript' => true,
  5362. //                'javascript-delay' => 1000,
  5363.                 'no-stop-slow-scripts' => false,
  5364.                 'no-background' => false,
  5365.                 'lowquality' => false,
  5366.                 'encoding' => 'utf-8',
  5367. //            'images' => true,
  5368. //            'cookie' => array(),
  5369.                 'dpi' => 300,
  5370.                 'image-dpi' => 300,
  5371. //                'enable-external-links' => true,
  5372. //                'enable-internal-links' => true
  5373.             ));
  5374.             return new Response(
  5375.                 $pdf_response,
  5376.                 200,
  5377.                 array(
  5378.                     'Content-Type' => 'application/pdf',
  5379.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5380.                 )
  5381.             );
  5382.         }
  5383.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5384.             array(
  5385.                 'page_title' => 'Stock Transfer',
  5386.                 'export' => 'pdf,print',
  5387.                 'data' => $dt,
  5388.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5389.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5390.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5391.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5392.                     $id,
  5393.                     $dt['created_by'],
  5394.                     $dt['edited_by']),
  5395.                 'document_mark_image' => $document_mark['original'],
  5396.                 'company_name' => $company_data->getName(),
  5397.                 'company_data' => $company_data,
  5398.                 'company_address' => $company_data->getAddress(),
  5399.                 'company_image' => $company_data->getImage(),
  5400.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5401.                 'red' => 0
  5402.             )
  5403.         );
  5404.     }
  5405.     public function CreateStockConsumptionNoteAction(Request $request)
  5406.     {
  5407.         $em $this->getDoctrine()->getManager();
  5408.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5409.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5410.         if ($request->isMethod('POST')) {
  5411.             $em $this->getDoctrine()->getManager();
  5412.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']; //change
  5413.             $dochash $request->request->get('voucherNumber'); //change
  5414.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5415.             $approveRole $request->request->get('approvalRole');
  5416.             $approveHash $request->request->get('approvalHash');
  5417.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5418.                 $loginId$approveRole$approveHash)
  5419.             ) {
  5420.                 $this->addFlash(
  5421.                     'error',
  5422.                     'Sorry Could not insert Data.'
  5423.                 );
  5424.             } else {
  5425.                 if ($request->request->has('check_allowed'))
  5426.                     $check_allowed 1;
  5427.                 $StID Inventory::CreateNewStockConsumptionNote(
  5428.                     $this->getDoctrine()->getManager(),
  5429.                     $request->request,
  5430.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5431.                     $this->getLoggedUserCompanyId($request)
  5432.                 );
  5433.                 //now add Approval info
  5434.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5435.                 $approveRole 1;  //created
  5436.                 $options = array(
  5437.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5438.                     'notification_server' => $this->container->getParameter('notification_server'),
  5439.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5440.                     'url' => $this->generateUrl(
  5441.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']]
  5442.                         ['entity_view_route_path_name']
  5443.                     )
  5444.                 );
  5445.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5446.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5447.                     $StID,
  5448.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5449.                 );
  5450.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'], $StID,
  5451.                     $loginId,
  5452.                     $approveRole,
  5453.                     $request->request->get('approvalHash'));
  5454.                 $this->addFlash(
  5455.                     'success',
  5456.                     'Stock Consumption Added.'
  5457.                 );
  5458.                 $url $this->generateUrl(
  5459.                     'view_stock_consumption_note'
  5460.                 );
  5461.                 return $this->redirect($url "/" $StID);
  5462.             }
  5463.         }
  5464.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5465.             array(
  5466.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5467.             )
  5468.         );
  5469.         $INVLIST = [];
  5470.         foreach ($slotList as $slot) {
  5471.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5472.         }
  5473.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5474.             array(
  5475.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5476.             )
  5477.         );
  5478.         $consumptionTypeList = [];
  5479.         $consumptionTypeListArray = [];
  5480.         foreach ($consumptionTypeQry as $entry) {
  5481.             $p = array(
  5482.                 'name' => $entry->getName(),
  5483.                 'id' => $entry->getConsumptionTypeId(),
  5484.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5485.                 'cost_center_id' => $entry->getCostCenterId(),
  5486.             );
  5487.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5488.             $consumptionTypeListArray[] = $p;
  5489.         }
  5490.         //add bill list
  5491.         $service_purchase_bill_query $this->getDoctrine()
  5492.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5493.             ->findBy(
  5494.                 array(
  5495.                     'typeHash' => 'SPB',
  5496.                     'approved' => GeneralConstant::APPROVED
  5497.                 )
  5498.             );
  5499.         $service_purchase_bill_list = [];
  5500.         $service_purchase_bill_list_array = [];
  5501.         $bill = array(
  5502.             'id' => 0,
  5503.             'type' => 'SPB',
  5504.             'name' => 'New Expense',
  5505.             'text' => 'New Expense',
  5506.             'amount' => 0,
  5507.         );
  5508.         $service_purchase_bill_list[0] = $bill;
  5509.         $service_purchase_bill_list_array[] = $bill;
  5510.         foreach ($service_purchase_bill_query as $d) {
  5511.             $bill = array(
  5512.                 'id' => $d->getPurchaseInvoiceId(),
  5513.                 'type' => 'SPB',
  5514.                 'name' => $d->getDocumentHash(),
  5515.                 'text' => $d->getDocumentHash(),
  5516.                 'amount' => $d->getInvoiceAmount(),
  5517.             );
  5518.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5519.             $service_purchase_bill_list_array[] = $bill;
  5520.         }
  5521.         return $this->render('@Inventory/pages/input_forms/stock_consumption_note.html.twig',
  5522.             array(
  5523.                 'page_title' => 'Stock Consumption Note',
  5524.                 'warehouseList' => Inventory::WarehouseList($em),
  5525.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5526.                 'consumptionTypeList' => $consumptionTypeList,
  5527.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5528.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5529.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5530.                 'warehouseActionList' => $warehouse_action_list,
  5531.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5532.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5533.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5534.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5535.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5536.                 'product_list' => Inventory::ProductListDetailed($this->getDoctrine()->getManager()),
  5537.                 'prefix_list' => array(
  5538.                     [
  5539.                         'id' => 1,
  5540.                         'value' => 'GN',
  5541.                         'text' => 'GN'
  5542.                     ]
  5543.                 ),
  5544.                 'assoc_list' => array(
  5545.                     [
  5546.                         'id' => 1,
  5547.                         'value' => 1,
  5548.                         'text' => 'GN'
  5549.                     ]
  5550.                 ),
  5551.                 'INVLIST' => $INVLIST
  5552.             )
  5553.         );
  5554.     }
  5555.     public function StockConsumptionNoteListAction(Request $request)
  5556.     {
  5557.         $q $this->getDoctrine()
  5558.             ->getRepository('ApplicationBundle:StockConsumptionNote')
  5559.             ->findBy(
  5560.                 array(
  5561.                     'status' => GeneralConstant::ACTIVE,
  5562.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5563. //                    'approved' =>  GeneralConstant::APPROVED,
  5564.                 )
  5565.             );
  5566.         $stage_list = array(
  5567.             => 'Pending',
  5568.             => 'Pending',
  5569.             => 'Complete',
  5570.             => 'Partial',
  5571.         );
  5572.         $data = [];
  5573.         foreach ($q as $entry) {
  5574.             $data[] = array(
  5575.                 'doc_date' => $entry->getStockConsumptionNoteDate(),
  5576.                 'id' => $entry->getStockConsumptionNoteId(),
  5577.                 'doc_hash' => $entry->getDocumentHash(),
  5578.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5579.                 'stage' => $stage_list[$entry->getStage()]
  5580.             );
  5581.         }
  5582.         return $this->render('@Inventory/pages/views/stock_consumption_note_list.html.twig',
  5583.             array(
  5584.                 'page_title' => 'Stock Consumption Note List',
  5585.                 'data' => $data
  5586.             )
  5587.         );
  5588.     }
  5589.     public function ViewStockConsumptionNoteAction(Request $request$id)
  5590.     {
  5591.         $em $this->getDoctrine()->getManager();
  5592.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5593.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5594.             array(
  5595.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5596.             )
  5597.         );
  5598.         $consumptionTypeList = [];
  5599.         $consumptionTypeListArray = [];
  5600.         foreach ($consumptionTypeQry as $entry) {
  5601.             $p = array(
  5602.                 'name' => $entry->getName(),
  5603.                 'id' => $entry->getConsumptionTypeId(),
  5604.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5605.                 'cost_center_id' => $entry->getCostCenterId(),
  5606.             );
  5607.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5608.             $consumptionTypeListArray[] = $p;
  5609.         }
  5610.         //add bill list
  5611.         $service_purchase_bill_query $this->getDoctrine()
  5612.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5613.             ->findBy(
  5614.                 array(
  5615.                     'typeHash' => 'SPB',
  5616.                     'approved' => GeneralConstant::APPROVED
  5617.                 )
  5618.             );
  5619.         $service_purchase_bill_list = [];
  5620.         $service_purchase_bill_list_array = [];
  5621.         $bill = array(
  5622.             'id' => 0,
  5623.             'type' => 'SPB',
  5624.             'name' => 'New Expense',
  5625.             'text' => 'New Expense',
  5626.             'amount' => 0,
  5627.         );
  5628.         $service_purchase_bill_list[0] = $bill;
  5629.         $service_purchase_bill_list_array[] = $bill;
  5630.         foreach ($service_purchase_bill_query as $d) {
  5631.             $bill = array(
  5632.                 'id' => $d->getPurchaseInvoiceId(),
  5633.                 'type' => 'SPB',
  5634.                 'name' => $d->getDocumentHash(),
  5635.                 'text' => $d->getDocumentHash(),
  5636.                 'amount' => $d->getInvoiceAmount(),
  5637.             );
  5638.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5639.             $service_purchase_bill_list_array[] = $bill;
  5640.         }
  5641.         return $this->render(
  5642.             '@Inventory/pages/views/view_stock_consumption_note.html.twig',
  5643.             array(
  5644.                 'page_title' => 'Stock Transfer',
  5645.                 'data' => $dt,
  5646.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5647.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5648.                 'consumptionTypeList' => $consumptionTypeList,
  5649.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5650.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5651.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5652.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5653.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5654.                     $id,
  5655.                     $dt['created_by'],
  5656.                     $dt['edited_by'])
  5657.             )
  5658.         );
  5659.     }
  5660.     public function PrintStockConsumptionNoteAction(Request $request$id)
  5661.     {
  5662.         $em $this->getDoctrine()->getManager();
  5663.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5664.         $company_data Company::getCompanyData($em1);
  5665.         $document_mark = array(
  5666.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5667.             'copy' => ''
  5668.         );
  5669.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5670.             array(
  5671.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5672.             )
  5673.         );
  5674.         $consumptionTypeList = [];
  5675.         $consumptionTypeListArray = [];
  5676.         foreach ($consumptionTypeQry as $entry) {
  5677.             $p = array(
  5678.                 'name' => $entry->getName(),
  5679.                 'id' => $entry->getConsumptionTypeId(),
  5680.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5681.                 'cost_center_id' => $entry->getCostCenterId(),
  5682.             );
  5683.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5684.             $consumptionTypeListArray[] = $p;
  5685.         }
  5686.         //add bill list
  5687.         $service_purchase_bill_query $this->getDoctrine()
  5688.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5689.             ->findBy(
  5690.                 array(
  5691.                     'typeHash' => 'SPB',
  5692.                     'approved' => GeneralConstant::APPROVED
  5693.                 )
  5694.             );
  5695.         $service_purchase_bill_list = [];
  5696.         $service_purchase_bill_list_array = [];
  5697.         $bill = array(
  5698.             'id' => 0,
  5699.             'type' => 'SPB',
  5700.             'name' => 'New Expense',
  5701.             'text' => 'New Expense',
  5702.             'amount' => 0,
  5703.         );
  5704.         $service_purchase_bill_list[0] = $bill;
  5705.         $service_purchase_bill_list_array[] = $bill;
  5706.         foreach ($service_purchase_bill_query as $d) {
  5707.             $bill = array(
  5708.                 'id' => $d->getPurchaseInvoiceId(),
  5709.                 'type' => 'SPB',
  5710.                 'name' => $d->getDocumentHash(),
  5711.                 'text' => $d->getDocumentHash(),
  5712.                 'amount' => $d->getInvoiceAmount(),
  5713.             );
  5714.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5715.             $service_purchase_bill_list_array[] = $bill;
  5716.         }
  5717.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5718.             $html $this->renderView('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  5719.                 array(
  5720.                     //full array here
  5721.                     'pdf' => true,
  5722.                     'page_title' => 'Stock Consumption',
  5723.                     'export' => 'pdf,print',
  5724.                     'data' => $dt,
  5725.                     'service_purchase_bill_list' => $service_purchase_bill_list,
  5726.                     'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5727.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5728.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5729.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5730.                         array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5731.                         $id,
  5732.                         $dt['created_by'],
  5733.                         $dt['edited_by']),
  5734.                     'document_mark_image' => $document_mark['original'],
  5735.                     'consumptionTypeList' => $consumptionTypeList,
  5736.                     'consumptionTypeListArray' => $consumptionTypeListArray,
  5737.                     'company_name' => $company_data->getName(),
  5738.                     'company_data' => $company_data,
  5739.                     'company_address' => $company_data->getAddress(),
  5740.                     'company_image' => $company_data->getImage(),
  5741.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5742.                     'red' => 0
  5743.                 )
  5744.             );
  5745.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5746. //                'orientation' => 'landscape',
  5747. //                'enable-javascript' => true,
  5748. //                'javascript-delay' => 1000,
  5749.                 'no-stop-slow-scripts' => false,
  5750.                 'no-background' => false,
  5751.                 'lowquality' => false,
  5752.                 'encoding' => 'utf-8',
  5753. //            'images' => true,
  5754. //            'cookie' => array(),
  5755.                 'dpi' => 300,
  5756.                 'image-dpi' => 300,
  5757. //                'enable-external-links' => true,
  5758. //                'enable-internal-links' => true
  5759.             ));
  5760.             return new Response(
  5761.                 $pdf_response,
  5762.                 200,
  5763.                 array(
  5764.                     'Content-Type' => 'application/pdf',
  5765.                     'Content-Disposition' => 'attachment; filename="stock_consumption_note_' $id '.pdf"'
  5766.                 )
  5767.             );
  5768.         }
  5769.         return $this->render('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  5770.             array(
  5771.                 'page_title' => 'Stock Consumption',
  5772.                 'export' => 'pdf,print',
  5773.                 'data' => $dt,
  5774.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5775.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5776.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5777.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5778.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5779.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5780.                     $id,
  5781.                     $dt['created_by'],
  5782.                     $dt['edited_by']),
  5783.                 'document_mark_image' => $document_mark['original'],
  5784.                 'consumptionTypeList' => $consumptionTypeList,
  5785.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5786.                 'company_name' => $company_data->getName(),
  5787.                 'company_data' => $company_data,
  5788.                 'company_address' => $company_data->getAddress(),
  5789.                 'company_image' => $company_data->getImage(),
  5790.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5791.                 'red' => 0
  5792.             )
  5793.         );
  5794.     }
  5795.     public function CreateStockReceivedNoteAction(Request $request$id 0)
  5796.     {
  5797.         $em $this->getDoctrine()->getManager();
  5798.         $companyId $this->getLoggedUserCompanyId($request);
  5799.         $extDocData = [];
  5800.         $userId $request->getSession()->get(UserConstants::USER_ID);
  5801.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  5802.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  5803. //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  5804.         $userBranchIdList $request->getSession()->get('branchIdList');
  5805.         if ($userBranchIdList == null$userBranchIdList = [];
  5806.         $userBranchId $request->getSession()->get('branchId');
  5807.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  5808.             $em $this->getDoctrine()->getManager();
  5809.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //change
  5810.             $dochash $request->request->get('docHash'); //change
  5811.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5812.             $approveRole $request->request->get('approvalRole');
  5813.             $approveHash $request->request->get('approvalHash');
  5814.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5815.                 $loginId$approveRole$approveHash$id)
  5816.             ) {
  5817.                 if ($request->request->has('returnJson')) {
  5818.                     return new JsonResponse(array(
  5819.                         'success' => false,
  5820.                         'documentHash' => 0,
  5821.                         'documentId' => 0,
  5822.                         'billIds' => [],
  5823.                         'drIds' => [],
  5824.                         'pmntTransIds' => [],
  5825.                         'viewUrl' => '',
  5826.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  5827.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  5828.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  5829.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  5830.                     ));
  5831.                 } else
  5832.                     $this->addFlash(
  5833.                         'error',
  5834.                         'Sorry Could not insert Data.'
  5835.                     );
  5836.             } else {
  5837.                 if ($request->request->has('check_allowed'))
  5838.                     $check_allowed 1;
  5839.                 $StID Inventory::CreateNewStockReceivedNote(
  5840.                     $this->getDoctrine()->getManager(),
  5841.                     $request->request,
  5842.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5843.                     $this->getLoggedUserCompanyId($request)
  5844.                 );
  5845.                 //now add Approval info
  5846.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5847.                 $approveRole 1;  //created
  5848.                 $options = array(
  5849.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5850.                     'notification_server' => $this->container->getParameter('notification_server'),
  5851.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5852.                     'url' => $this->generateUrl(
  5853.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  5854.                         ['entity_view_route_path_name']
  5855.                     )
  5856.                 );
  5857.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5858.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5859.                     $StID,
  5860.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5861.                 );
  5862.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  5863.                     $loginId,
  5864.                     $approveRole,
  5865.                     $request->request->get('approvalHash'));
  5866.                 $url $this->generateUrl(
  5867.                     'view_srcv'
  5868.                 );
  5869.                 if ($request->request->has('returnJson')) {
  5870.                     return new JsonResponse(array(
  5871.                         'success' => true,
  5872.                         'documentHash' => $dochash,
  5873.                         'documentId' => $StID,
  5874.                         'viewUrl' => $url "/" $StID,
  5875.                     ));
  5876.                 } else {
  5877.                     $this->addFlash(
  5878.                         'success',
  5879.                         'Stock Received Note Added.'
  5880.                     );
  5881.                     return $this->redirect($url "/" $StID);
  5882.                 }
  5883.             }
  5884.         }
  5885.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5886.             array(
  5887.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5888.             )
  5889.         );
  5890.         if ($id == 0) {
  5891.         } else {
  5892.             $extDoc $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  5893.                 array(
  5894.                     'salesOrderId' => $id///material
  5895.                 )
  5896.             );
  5897.             //now if its not editable, redirect to view
  5898.             if ($extDoc) {
  5899.                 if ($extDoc->getEditFlag() != 1) {
  5900.                     $url $this->generateUrl(
  5901.                         'view_srcv'
  5902.                     );
  5903.                     return $this->redirect($url "/" $id);
  5904.                 } else {
  5905.                     $extDocData $extDoc;
  5906.                     $extDocDataDetails $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findOneBy(
  5907.                         array(
  5908.                             'stockReceivedNoteId' => $id///material
  5909.                         )
  5910.                     );
  5911.                 }
  5912.             } else {
  5913.             }
  5914.         }
  5915.         $INVLIST = [];
  5916.         foreach ($slotList as $slot) {
  5917.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5918.         }
  5919.         $dataArray = array(
  5920.             'page_title' => 'Stock Received Note',
  5921. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  5922.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  5923.             'users' => Users::getUserListById($em),
  5924.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  5925.             'warehouseList' => Inventory::WarehouseList($em),
  5926.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  5927.             'warehouseActionList' => $warehouse_action_list,
  5928.             'warehouseActionListArray' => $warehouse_action_list_array,
  5929.             'extDocData' => $extDocData,
  5930.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  5931.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5932.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5933.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5934. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5935. //            'product_list' => Inventory::ProductList($em, $companyId),
  5936.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  5937.             'prefix_list' => array(
  5938.                 [
  5939.                     'id' => 1,
  5940.                     'value' => 'GN',
  5941.                     'text' => 'GN'
  5942.                 ]
  5943.             ),
  5944.             'assoc_list' => array(
  5945.                 [
  5946.                     'id' => 1,
  5947.                     'value' => 1,
  5948.                     'text' => 'GN'
  5949.                 ]
  5950.             ),
  5951.             'INVLIST' => $INVLIST,
  5952.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  5953.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  5954.             'userBranchIdList' => $userBranchIdList,
  5955.             'userBranchId' => $userBranchId,
  5956. //            'headList' => Accounts::HeadList($em),
  5957.         );
  5958.         //json
  5959.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  5960.         {
  5961.             $dataArray['success'] = true;
  5962.             return new JsonResponse(
  5963.                 $dataArray
  5964.             );
  5965.         }
  5966.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  5967.             $dataArray
  5968.         );
  5969.     }
  5970.     public function GetItemListForStockReceivedAction(Request $request)
  5971.     {
  5972.         if ($request->isMethod('POST')) {
  5973.             $em $this->getDoctrine();
  5974.             $receiveType 1;//transfer
  5975.             if ($request->request->has('receiveType'))
  5976.                 $receiveType $request->request->get('receiveType');
  5977.             $QD = [];
  5978.             if ($receiveType == 1)
  5979.                 $QD $this->getDoctrine()
  5980.                     ->getRepository('ApplicationBundle:StockTransferItem')
  5981.                     ->findBy(
  5982.                         array(
  5983. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  5984.                             'stockTransferId' => $request->request->get('stId')
  5985.                         ),
  5986.                         array()
  5987.                     );
  5988.             if ($receiveType == 2)
  5989.                 $QD $this->getDoctrine()
  5990.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  5991.                     ->findBy(
  5992.                         array(
  5993. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  5994.                             'salesOrderId' => $request->request->get('soId')
  5995.                         ),
  5996.                         array()
  5997.                     );
  5998. //            if($request->request->get('wareHouseId')!='')
  5999. //
  6000. //            $DO=$this->getDoctrine()
  6001. //                ->getRepository('ApplicationBundle:DeliveryOrder')
  6002. //                ->findOneBy(
  6003. //                    $find_array,
  6004. //                    array(
  6005. //
  6006. //                    )
  6007. //                );
  6008.             $sendData = array(
  6009. //                'salesType'=>$SO->getSalesType(),
  6010. //                'packageData'=>[],
  6011.                 'productList' => [],
  6012. //                'productListByPackage'=>[],
  6013.             );
  6014.             $productList Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request));
  6015.             $pckg_item_cross_match_data = [];
  6016.             foreach ($QD as $product) {
  6017. //                $b_code=json_decode($product->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  6018.                 $b_code = [];
  6019.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  6020.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6021.                     if ($to_analyze_codes_str != null)
  6022.                         $b_code json_decode($to_analyze_codes_strtrue512JSON_BIGINT_AS_STRING);
  6023.                     else
  6024.                         $b_code = [];
  6025.                 } else {
  6026.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6027.                     if ($to_analyze_codes_str != null) {
  6028.                         $max_int_length strlen((string)PHP_INT_MAX) - 1;
  6029.                         $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$to_analyze_codes_str);
  6030.                         $b_code json_decode($json_without_bigintstrue);
  6031.                     } else {
  6032.                         $b_code = [];
  6033.                     }
  6034.                 }
  6035.                 $b_code_data = [];
  6036.                 foreach ($b_code as $d) {
  6037.                     $b_code_data[] = array(
  6038.                         'id' => $d,
  6039.                         'name' => str_pad($d13'0'STR_PAD_LEFT),
  6040.                     );
  6041.                 }
  6042.                 $p_data = array(
  6043.                     'details_id' => $product->getId(),
  6044.                     'productId' => $product->getProductId(),
  6045.                     'product_name' => $productList[$product->getProductId()]['name'],
  6046.                     'product_barcodes' => $b_code_data,
  6047. //                    'available_inventory'=>$inventory_by_warehouse?$inventory_by_warehouse->getQty():0,
  6048. //                        'package_id'=>$product->getPackageId(),
  6049.                     'qty' => $receiveType == $product->getQty() : $product->getToBeReceived(),
  6050.                     'unit_price' => $receiveType == $product->getPrice() : $productList[$product->getProductId()]['purchase_price'],
  6051.                     'balance' => $receiveType == $product->getBalance() : ($product->getToBeReceived() - $product->getReceived()),
  6052. //                        'delivered'=>$product->getDelivered(),
  6053.                 );
  6054.                 $sendData['productList'][] = $p_data;
  6055.             }
  6056.             //now package data
  6057.             if ($sendData) {
  6058.                 return new JsonResponse(array("success" => true"content" => $sendData));
  6059.             }
  6060.             return new JsonResponse(array("success" => false));
  6061.         }
  6062.         return new JsonResponse(array("success" => false));
  6063.     }
  6064.     public function StockReceivedNoteListAction(Request $request)
  6065.     {
  6066.         $q $this->getDoctrine()
  6067.             ->getRepository('ApplicationBundle:StockReceivedNote')
  6068.             ->findBy(
  6069.                 array(
  6070.                     'status' => GeneralConstant::ACTIVE,
  6071.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  6072. //                    'approved' =>  GeneralConstant::APPROVED,
  6073.                 )
  6074.             );
  6075.         $stage_list = array(
  6076.             => 'Pending',
  6077.             => 'Pending',
  6078.             => 'Complete',
  6079.             => 'Partial',
  6080.         );
  6081.         $data = [];
  6082.         foreach ($q as $entry) {
  6083.             $data[] = array(
  6084.                 'doc_date' => $entry->getStockReceivedNoteDate(),
  6085.                 'id' => $entry->getStockReceivedNoteId(),
  6086.                 'doc_hash' => $entry->getDocumentHash(),
  6087.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  6088.                 'stage' => $stage_list[$entry->getStage()]
  6089.             );
  6090.         }
  6091.         return $this->render('@Inventory/pages/views/stock_received_note_list.html.twig',
  6092.             array(
  6093.                 'page_title' => 'Stock Received List',
  6094.                 'data' => $data
  6095.             )
  6096.         );
  6097.     }
  6098.     public function ViewStockReceivedNoteAction(Request $request$id)
  6099.     {
  6100.         $em $this->getDoctrine()->getManager();
  6101.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6102.         return $this->render(
  6103.             '@Inventory/pages/views/view_stock_received_note.html.twig',
  6104.             array(
  6105.                 'page_title' => 'Stock Received Note',
  6106.                 'data' => $dt,
  6107.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  6108.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6109.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6110.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6111.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6112.                     $id,
  6113.                     $dt['created_by'],
  6114.                     $dt['edited_by'])
  6115.             )
  6116.         );
  6117.     }
  6118.     public function PrintStockReceivedNoteAction(Request $request$id)
  6119.     {
  6120.         $em $this->getDoctrine()->getManager();
  6121.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6122.         $company_data Company::getCompanyData($em1);
  6123.         $document_mark = array(
  6124.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6125.             'copy' => ''
  6126.         );
  6127.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6128.             $html $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
  6129.                 array(
  6130.                     //full array here
  6131.                     'pdf' => true,
  6132.                     'page_title' => 'Stock Received Note',
  6133.                     'export' => 'pdf,print',
  6134.                     'data' => $dt,
  6135.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6136.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6137.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6138.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6139.                         $id,
  6140.                         $dt['created_by'],
  6141.                         $dt['edited_by']),
  6142.                     'document_mark_image' => $document_mark['original'],
  6143.                     'company_name' => $company_data->getName(),
  6144.                     'company_data' => $company_data,
  6145.                     'company_address' => $company_data->getAddress(),
  6146.                     'company_image' => $company_data->getImage(),
  6147.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6148.                     'red' => 0
  6149.                 )
  6150.             );
  6151.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6152. //                'orientation' => 'landscape',
  6153. //                'enable-javascript' => true,
  6154. //                'javascript-delay' => 1000,
  6155.                 'no-stop-slow-scripts' => false,
  6156.                 'no-background' => false,
  6157.                 'lowquality' => false,
  6158.                 'encoding' => 'utf-8',
  6159. //            'images' => true,
  6160. //            'cookie' => array(),
  6161.                 'dpi' => 300,
  6162.                 'image-dpi' => 300,
  6163. //                'enable-external-links' => true,
  6164. //                'enable-internal-links' => true
  6165.             ));
  6166.             return new Response(
  6167.                 $pdf_response,
  6168.                 200,
  6169.                 array(
  6170.                     'Content-Type' => 'application/pdf',
  6171.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  6172.                 )
  6173.             );
  6174.         }
  6175.         return $this->render('@Inventory/pages/print/print_stock_received_note.html.twig',
  6176.             array(
  6177.                 'page_title' => 'Stock Received Note',
  6178.                 'export' => 'pdf,print',
  6179.                 'data' => $dt,
  6180.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6181.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6182.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6183.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6184.                     $id,
  6185.                     $dt['created_by'],
  6186.                     $dt['edited_by']),
  6187.                 'document_mark_image' => $document_mark['original'],
  6188.                 'company_name' => $company_data->getName(),
  6189.                 'company_data' => $company_data,
  6190.                 'company_address' => $company_data->getAddress(),
  6191.                 'company_image' => $company_data->getImage(),
  6192.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6193.                 'red' => 0
  6194.             )
  6195.         );
  6196.     }
  6197.     public function CreateStoreRequisitionSlipAction(Request $request$id 0)
  6198.     {
  6199.         $em $this->getDoctrine()->getManager();
  6200. //        $id;
  6201.         if ($request->isMethod('POST')) {
  6202.             $em $this->getDoctrine()->getManager();
  6203.             $entity_id array_flip(GeneralConstant::$Entity_list)['StoreRequisition']; //change
  6204.             $dochash $request->request->get('voucherNumber'); //change
  6205.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6206.             $approveRole $request->request->get('approvalRole');
  6207.             $approveHash $request->request->get('approvalHash');
  6208.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6209.                 $loginId$approveRole$approveHash$id)
  6210.             ) {
  6211.                 $this->addFlash(
  6212.                     'error',
  6213.                     'Sorry, could not insert Data.'
  6214.                 );
  6215.             } else {
  6216.                 if ($request->request->has('check_allowed'))
  6217.                     $check_allowed 1;
  6218.                 $IrID Inventory::CreateNewStoreRequisition($id,
  6219.                     $this->getDoctrine()->getManager(),
  6220.                     $request->request,
  6221.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6222.                     $this->getLoggedUserCompanyId($request)
  6223.                 );
  6224.                 //now add Approval info
  6225.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6226.                 $approveRole $request->request->get('approvalRole');
  6227.                 $options = array(
  6228.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6229.                     'notification_server' => $this->container->getParameter('notification_server'),
  6230.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6231.                     'url' => $this->generateUrl(
  6232.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StoreRequisition']]
  6233.                         ['entity_view_route_path_name']
  6234.                     )
  6235.                 );
  6236.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6237.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  6238.                     $IrID,
  6239.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6240.                 );
  6241.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StoreRequisition'], $IrID,
  6242.                     $loginId,
  6243.                     $approveRole,
  6244.                     $request->request->get('approvalHash'));
  6245.                 $this->addFlash(
  6246.                     'success',
  6247.                     'New Indent Added.'
  6248.                 );
  6249.                 $url $this->generateUrl(
  6250.                     'view_ir'
  6251.                 );
  6252.                 return $this->redirect($url "/" $IrID);
  6253.             }
  6254.         }
  6255.         $extDocData = [];
  6256.         $extDocDetailsData = [];
  6257.         if ($id == 0) {
  6258.         } else {
  6259.             $extDoc $em->getRepository('ApplicationBundle:StoreRequisition')->findOneBy(
  6260.                 array(
  6261.                     'storeRequisitionId' => $id///material
  6262.                 )
  6263.             );
  6264.             //now if its not editable, redirect to view
  6265.             if ($extDoc) {
  6266.                 if ($extDoc->getEditFlag() != 1) {
  6267.                     $url $this->generateUrl(
  6268.                         'view_ir'
  6269.                     );
  6270.                     return $this->redirect($url "/" $id);
  6271.                 } else {
  6272.                     $extDocData $extDoc;
  6273.                     $extDocDetailsData $em->getRepository('ApplicationBundle:StoreRequisitionItem')->findBy(
  6274.                         array(
  6275.                             'storeRequisitionId' => $id///material
  6276.                         )
  6277.                     );;
  6278.                 }
  6279.             } else {
  6280.             }
  6281.         }
  6282.         $companyId $this->getLoggedUserCompanyId($request);
  6283.         $productListArray = [];
  6284.         $subCategoryListArray = [];
  6285.         $categoryListArray = [];
  6286.         $igListArray = [];
  6287.         $unitListArray = [];
  6288.         $brandListArray = [];
  6289.         $productList Inventory::ProductList($em$companyId);
  6290.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6291.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6292.         $igList Inventory::ItemGroupList($em$companyId);
  6293.         $unitList Inventory::UnitTypeList($em);
  6294.         $brandList Inventory::GetBrandList($em$companyId);
  6295.         foreach ($productList as $product$productListArray[] = $product;
  6296.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6297.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6298.         foreach ($igList as $product$igListArray[] = $product;
  6299.         foreach ($unitList as $product$unitListArray[] = $product;
  6300.         foreach ($brandList as $product$brandListArray[] = $product;
  6301.         $sr_list = [];
  6302.         $QD $this->getDoctrine()
  6303.             ->getRepository('ApplicationBundle:StockRequisition')
  6304.             ->findBy(
  6305.                 array(
  6306.                     'indentTagged' => 0,
  6307.                     'approved' => 1
  6308.                 )
  6309.             );
  6310.         foreach ($QD as $dt) {
  6311.             $sr_list[$dt->getStockRequisitionId()] = array(
  6312.                 'id' => $dt->getStockRequisitionId(),
  6313.                 'name' => $dt->getDocumentHash(),
  6314.                 'text' => $dt->getDocumentHash(),
  6315.             );
  6316.         }
  6317.         return $this->render('@Inventory/pages/input_forms/store_requisition.html.twig',
  6318.             array(
  6319.                 'page_title' => 'Indent Requisition Slip',
  6320.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6321.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6322.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6323.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6324.                 'sr_list' => $sr_list,
  6325.                 'productList' => $productList,
  6326.                 'subCategoryList' => $subCategoryList,
  6327.                 'categoryList' => $categoryList,
  6328.                 'igList' => $igList,
  6329.                 'extId' => $id,
  6330.                 'extDocDetailsData' => $extDocDetailsData,
  6331.                 'extDocData' => $extDocData,
  6332.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6333.                 'unitList' => $unitList,
  6334.                 'brandList' => $brandList,
  6335.                 'brandListArray' => $brandListArray,
  6336.                 'productListArray' => $productListArray,
  6337.                 'subCategoryListArray' => $subCategoryListArray,
  6338.                 'categoryListArray' => $categoryListArray,
  6339.                 'igListArray' => $igListArray,
  6340.                 'unitListArray' => $unitListArray,
  6341.                 'prefix_list' => array(
  6342.                     [
  6343.                         'id' => 1,
  6344.                         'value' => 'GN',
  6345.                         'text' => 'General'
  6346.                     ],
  6347.                     [
  6348.                         'id' => 1,
  6349.                         'value' => 'SD',
  6350.                         'text' => 'For Sales Demand'
  6351.                     ]
  6352.                 ),
  6353.                 'assoc_list' => array(
  6354.                     [
  6355.                         'id' => 1,
  6356.                         'value' => 1,
  6357.                         'text' => 'GN'
  6358.                     ]
  6359.                 )
  6360.             )
  6361.         );
  6362.     }
  6363.     public function CreateStockRequisitionSlipAction(Request $request$id 0)
  6364.     {
  6365.         $em $this->getDoctrine()->getManager();
  6366.         if ($request->isMethod('POST')) {
  6367.             $em $this->getDoctrine()->getManager();
  6368.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockRequisition']; //change
  6369.             $dochash $request->request->get('voucherNumber'); //change
  6370.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6371.             $approveRole $request->request->get('approvalRole');
  6372.             $approveHash $request->request->get('approvalHash');
  6373.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6374.                 $loginId$approveRole$approveHash$id)
  6375.             ) {
  6376.                 $this->addFlash(
  6377.                     'error',
  6378.                     'Sorry, could not insert Data.'
  6379.                 );
  6380.             } else {
  6381.                 if ($request->request->has('check_allowed'))
  6382.                     $check_allowed 1;
  6383.                 $SrID Inventory::CreateNewStockRequisition($id,
  6384.                     $this->getDoctrine()->getManager(),
  6385.                     $request->request,
  6386.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6387.                     $this->getLoggedUserCompanyId($request)
  6388.                 );
  6389.                 //now add Approval info
  6390.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6391.                 $approveRole $request->request->get('approvalRole');
  6392.                 $options = array(
  6393.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6394.                     'notification_server' => $this->container->getParameter('notification_server'),
  6395.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6396.                     'url' => $this->generateUrl(
  6397.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockRequisition']]
  6398.                         ['entity_view_route_path_name']
  6399.                     )
  6400.                 );
  6401.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6402.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  6403.                     $SrID,
  6404.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6405.                 );
  6406.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockRequisition'], $SrID,
  6407.                     $loginId,
  6408.                     $approveRole,
  6409.                     $request->request->get('approvalHash'));
  6410.                 $this->addFlash(
  6411.                     'success',
  6412.                     'New Requisition Added.'
  6413.                 );
  6414.                 $url $this->generateUrl(
  6415.                     'view_sr'
  6416.                 );
  6417. //                return $this->redirect($url . "/" . $SrID);
  6418.             }
  6419.         }
  6420.         $extDocData = [];
  6421.         $extDocDetailsData = [];
  6422.         if ($id == 0) {
  6423.         } else {
  6424.             $extDoc $em->getRepository('ApplicationBundle:StockRequisition')->findOneBy(
  6425.                 array(
  6426.                     'stockRequisitionId' => $id///material
  6427.                 )
  6428.             );
  6429.             //now if its not editable, redirect to view
  6430.             if ($extDoc) {
  6431.                 if ($extDoc->getEditFlag() != 1) {
  6432.                     $url $this->generateUrl(
  6433.                         'view_sr'
  6434.                     );
  6435.                     return $this->redirect($url "/" $id);
  6436.                 } else {
  6437.                     $extDocData $extDoc;
  6438.                     $extDocDetailsData $em->getRepository('ApplicationBundle:StockRequisitionItem')->findBy(
  6439.                         array(
  6440.                             'stockRequisitionId' => $id///material
  6441.                         )
  6442.                     );;
  6443.                 }
  6444.             } else {
  6445.             }
  6446.         }
  6447.         $companyId $this->getLoggedUserCompanyId($request);
  6448.         $productListArray = [];
  6449.         $subCategoryListArray = [];
  6450.         $categoryListArray = [];
  6451.         $igListArray = [];
  6452.         $unitListArray = [];
  6453.         $brandListArray = [];
  6454.         $productList Inventory::ProductList($em$companyId);
  6455.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6456.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6457.         $igList Inventory::ItemGroupList($em$companyId);
  6458.         $unitList Inventory::UnitTypeList($em);
  6459.         $brandList Inventory::GetBrandList($em$companyId);
  6460.         foreach ($productList as $product$productListArray[] = $product;
  6461.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6462.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6463.         foreach ($igList as $product$igListArray[] = $product;
  6464.         foreach ($unitList as $product$unitListArray[] = $product;
  6465.         foreach ($brandList as $product$brandListArray[] = $product;
  6466.         return $this->render('@Inventory/pages/input_forms/stock_requisition_slip.html.twig',
  6467.             array(
  6468.                 'page_title' => 'Stock Requisition Slip',
  6469.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6470.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6471.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6472.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6473.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  6474.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6475.                 'productList' => $productList,
  6476.                 'extId' => $id,
  6477.                 'extDocDetailsData' => $extDocDetailsData,
  6478.                 'extDocData' => $extDocData,
  6479.                 'subCategoryList' => $subCategoryList,
  6480.                 'categoryList' => $categoryList,
  6481.                 'igList' => $igList,
  6482.                 'unitList' => $unitList,
  6483.                 'brandList' => $brandList,
  6484.                 'brandListArray' => $brandListArray,
  6485.                 'productListArray' => $productListArray,
  6486.                 'subCategoryListArray' => $subCategoryListArray,
  6487.                 'categoryListArray' => $categoryListArray,
  6488.                 'igListArray' => $igListArray,
  6489.                 'unitListArray' => $unitListArray,
  6490.                 'productionBomList' => ProductionM::ProductionBomList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6491.                 'productionScheduleList' => ProductionM::ProductionScheduleList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6492.                 'prefix_list' => array(
  6493.                     [
  6494.                         'id' => 1,
  6495.                         'value' => 'GN',
  6496.                         'text' => 'General'
  6497.                     ],
  6498.                     [
  6499.                         'id' => 1,
  6500.                         'value' => 'SD',
  6501.                         'text' => 'For Sales Demand'
  6502.                     ]
  6503.                 ),
  6504.                 'projectList' => $em->getRepository('ApplicationBundle:Project')->findBy(
  6505.                     array(
  6506.                         'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  6507.                     ), array('projectDate' => 'desc')
  6508.                 ),
  6509.                 'salesOrderList' => SalesOrderM::SalesOrderListPendingDelivery($em),
  6510.                 'assoc_list' => array(
  6511.                     [
  6512.                         'id' => 1,
  6513.                         'value' => 'GN',
  6514.                         'text' => 'General'
  6515.                     ]
  6516.                 )
  6517.             )
  6518.         );
  6519.     }
  6520.     public function CreateStockReturnAction(Request $request)
  6521.     {
  6522.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  6523.             array(
  6524.                 'page_title' => 'Stock Return',
  6525. //                'dataList'=>$dta_list
  6526.             )
  6527.         );
  6528.     }
  6529.     public function MaterialInwardAction(Request $request)
  6530.     {
  6531.         $data = [];
  6532.         if ($request->isMethod('POST')) {
  6533.             //first of all resolve the transport costs
  6534.             $total_price_value 0;
  6535.             $data_list $dt $this->getDoctrine()
  6536.                 ->getRepository('ApplicationBundle:PurchaseOrderItem')
  6537.                 ->findBy(
  6538.                     array(
  6539.                         'purchaseOrderId' => $request->request->get('poId'),
  6540.                         'productId' => $request->request->get('products')
  6541.                     )
  6542.                 );
  6543.             $purchase_items = [];
  6544.             foreach ($data_list as $key => $value) {
  6545.                 $purchase_items[$value->getProductId()] = $value;
  6546.             }
  6547.             foreach ($request->request->get('products') as $key => $entry) {
  6548.                 $total_price_value $total_price_value + ($request->request->get('receivedQty')[$key]) * ($purchase_items[$entry]->getPrice());
  6549.             }
  6550.             $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$request->request->get('poId')];
  6551.             $supplier_id $po_data['supplier_id'];
  6552.             $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6553.             foreach ($request->request->get('products') as $key => $entry) {
  6554.                 if ($request->request->get('receivedQty')[$key] > 0)
  6555.                     Inventory::NewMaterialInward($this->getDoctrine()->getManager(),
  6556.                         $request->request,
  6557.                         $key,
  6558.                         $request->request->get('poId'),
  6559.                         $request->request->get('purchaseOrderItemId'),
  6560.                         $supplier_id,
  6561.                         $request->request->get('warehouseId'),
  6562.                         $request->request->get('lotNumber'),
  6563.                         $request->request->get('type_hash'),
  6564.                         $request->request->get('prefix_hash'),
  6565.                         $request->request->get('assoc_hash'),
  6566.                         $request->request->get('number_hash'),
  6567.                         $request->request->get('docHash'),
  6568.                         $request->request->get('docDate'),
  6569.                         $purchase_items[$entry],
  6570.                         $total_price_value,
  6571.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6572.             }
  6573.             $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$request->request->get('warehouseId')]['name'];
  6574. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6575.             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),
  6576.                 "A stack of material Has Arrived at The " $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6577.                 'all',
  6578.                 "",
  6579.                 'information',
  6580.                 "",
  6581.                 "Inbound Material"
  6582.             );
  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),"Eco is the best",'all','','success',null);
  6584.         }
  6585.         return $this->render('@Inventory/pages/input_forms/material_inward.html.twig',
  6586.             array(
  6587.                 'page_title' => 'Material Inward',
  6588.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6589.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  6590.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  6591.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  6592.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  6593.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  6594.                 "unitList" => Inventory::UnitTypeList($this->getDoctrine()->getManager())
  6595. //                'po'=>Inventory::getPurchaseOrderList
  6596.             )
  6597.         );
  6598.     }
  6599.     public function QualityControlAction(Request $request)
  6600.     {
  6601.         $checked_qc_list_flag 0;
  6602.         if ($request->query->has('checked_qc_list_flag'))
  6603.             $checked_qc_list_flag $request->query->has('checked_qc_list_flag');
  6604.         if ($request->isMethod('POST')) {
  6605.             foreach ($request->request->get('qc_checked', []) as $key => $entry) {
  6606.                 $em $this->getDoctrine()->getManager();
  6607.                 $data $this->getDoctrine()
  6608.                     ->getRepository('ApplicationBundle:MaterialInward')
  6609.                     ->findOneBy(
  6610.                         array(
  6611.                             'qcId' => $entry
  6612.                         )
  6613.                     );
  6614.                 if ($request->request->get('approvedQty')[$entry] <= 0) {
  6615.                     $em->remove($data);
  6616.                     $em->flush();
  6617.                 } else {
  6618.                     $data->setApprovedQty($request->request->get('approvedQty')[$entry]);
  6619.                     $data->setRejectedQty($data->getInwardQty() - $request->request->get('approvedQty')[$entry]);
  6620.                     $data->setQcDate(new \DateTime($request->request->get('qcDate')));
  6621.                     $data->setStage(GeneralConstant::STAGE_PENDING_TAG);
  6622.                     $em->flush();
  6623.                 }
  6624.                 //notification
  6625.                 $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$data->getPurchaseOrderId()];
  6626.                 $supplier_id $po_data['supplier_id'];
  6627.                 $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6628.                 $product_name Inventory::ProductList($this->getDoctrine()->getManager())[$data->getProductId()]['name'];
  6629.                 $qty $request->request->get('approvedQty')[$entry];
  6630.                 $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$data->getWarehouseId()]['name'];
  6631. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6632.                 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),
  6633.                     $qty " among " $data->getInwardQty() . " units of " $product_name " has passed the Quality Control in " .
  6634.                     $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6635.                     'all',
  6636.                     "",
  6637.                     'success',
  6638.                     "",
  6639.                     "Quality Control"
  6640.                 );
  6641.             }
  6642.         }
  6643.         return $this->render('@Inventory/pages/input_forms/qc.html.twig',
  6644.             array(
  6645.                 'page_title' => 'Quality Control',
  6646.                 'checked_qc_list_flag' => $checked_qc_list_flag,
  6647.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6648.                 'warehouse_indexed' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6649.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  6650.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  6651.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  6652.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  6653.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6654.                 'material_inward' => $this->getDoctrine()
  6655.                     ->getRepository('ApplicationBundle:MaterialInward')
  6656.                     ->findBy(
  6657.                         array(
  6658.                             'stage' => $checked_qc_list_flag == GeneralConstant::STAGE_PENDING GeneralConstant::STAGE_PENDING_TAG
  6659.                         )
  6660.                     )
  6661. //                'po'=>Inventory::getPurchaseOrderList
  6662.             )
  6663.         );
  6664.     }
  6665.     public function InventoryTransactionViewAction(Request $request)
  6666.     {
  6667.         $em $this->getDoctrine()->getManager();
  6668.         $qry_data = array(
  6669.             'warehouseId' => [0],
  6670.             'igId' => [0],
  6671.             'brandId' => [0],
  6672.             'categoryId' => [0],
  6673.             'actionTagId' => [0],
  6674.         );
  6675.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6676.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6677.         $data_searched = [];
  6678.         $em $this->getDoctrine()->getManager();
  6679.         $companyId $this->getLoggedUserCompanyId($request);
  6680.         $company_data Company::getCompanyData($em$companyId);
  6681.         $data = [];
  6682.         $print_title "Inventory Report";
  6683.         $document_mark = array(
  6684.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6685.             'copy' => ''
  6686.         );
  6687.         if ($request->isMethod('POST'))
  6688.             $method 'POST';
  6689.         else
  6690.             $method 'GET';
  6691.         {
  6692.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  6693.                 $request->request$method,
  6694.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6695.                 $companyId);
  6696.             if ($request->query->has('returnJson') || $request->request->has('returnJson')) {
  6697.                 return new JsonResponse(
  6698.                     array(
  6699.                         'success' => true,
  6700. //                    'page_title' => 'Product Details',
  6701. //                    'company_data' => $company_data,
  6702.                         'page_title' => 'Inventory Transactions',
  6703.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6704.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6705.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6706.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6707.                         'data_products' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6708.                         'action_tag' => $warehouse_action_list,
  6709.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6710.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6711.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6712.                         'data_searched' => $data_searched
  6713.                     )
  6714.                 );
  6715.             } else if ($request->request->get('print_data_enabled') == 1) {
  6716.                 $print_sub_title "";
  6717.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  6718.                     array(
  6719.                         'page_title' => 'Inventory Report',
  6720.                         'page_header' => 'Report',
  6721.                         'print_title' => $print_title,
  6722.                         'document_type' => 'Journal voucher',
  6723.                         'document_mark_image' => $document_mark['original'],
  6724.                         'page_header_sub' => 'Add',
  6725.                         'item_data' => [],
  6726.                         'received' => 2,
  6727.                         'return' => 1,
  6728.                         'total_w_vat' => 1,
  6729.                         'total_vat' => 1,
  6730.                         'total_wo_vat' => 1,
  6731.                         'invoice_id' => 'abcd1234',
  6732.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6733.                         'created_by' => 'created by',
  6734.                         'created_at' => '',
  6735.                         'red' => 0,
  6736.                         'company_name' => $company_data->getName(),
  6737.                         'company_data' => $company_data,
  6738.                         'company_address' => $company_data->getAddress(),
  6739.                         'company_image' => $company_data->getImage(),
  6740.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6741.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6742.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6743.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6744.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6745.                         'action_tag' => $warehouse_action_list,
  6746.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6747.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6748.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6749.                         'data_searched' => $data_searched
  6750.                     )
  6751.                 );
  6752.             }
  6753.         }
  6754.         return $this->render('@Inventory/pages/report/inventory_transaction_view.html.twig',
  6755.             array(
  6756.                 'page_title' => 'Inventory Transactions',
  6757.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6758.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6759.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6760.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6761.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6762.                 'action_tag' => $warehouse_action_list,
  6763.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6764.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6765.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6766.                 'data_searched' => $data_searched
  6767.             )
  6768.         );
  6769.     }
  6770.     public function StockConsumptionViewAction(Request $request)
  6771.     {
  6772.         $em $this->getDoctrine()->getManager();
  6773.         $start_date $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
  6774.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : new \DateTime();
  6775.         $qry_data = array(
  6776.             'warehouseId' => [0],
  6777.             'igId' => [0],
  6778.             'brandId' => [0],
  6779.             'categoryId' => [0],
  6780.             'actionTagId' => [0],
  6781.         );
  6782.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6783.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6784.         $data_searched = [];
  6785.         $em $this->getDoctrine()->getManager();
  6786.         $company_data Company::getCompanyData($em1);
  6787.         $data = [];
  6788.         $print_title "Inventory Report";
  6789.         $document_mark = array(
  6790.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6791.             'copy' => ''
  6792.         );
  6793.         if ($request->isMethod('POST'))
  6794.             $method 'POST';
  6795.         else
  6796.             $method 'GET';
  6797.         $post_data $method == 'POST' $request->request $request->query;
  6798.         $data_searched Inventory::GetStockConsumptionData($this->getDoctrine()->getManager(),
  6799.             $post_data,
  6800.             $method,
  6801.             $start_date,
  6802.             $end_date,
  6803.             $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6804.         if ($post_data->get('print_data_enabled') == 1) {
  6805.             $print_sub_title "";
  6806.             if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6807.                 $html $this->renderView('@Inventory/pages/print/print_stock_consumption.html.twig',
  6808.                     array(
  6809.                         'pdf' => 'true',
  6810.                         'page_title' => 'Inventory Report',
  6811.                         'page_header' => 'Report',
  6812.                         'print_title' => $print_title,
  6813.                         'document_type' => 'Journal voucher',
  6814.                         'document_mark_image' => $document_mark['original'],
  6815.                         'page_header_sub' => 'Add',
  6816.                         'item_data' => [],
  6817.                         'received' => 2,
  6818.                         'return' => 1,
  6819.                         'total_w_vat' => 1,
  6820.                         'total_vat' => 1,
  6821.                         'total_wo_vat' => 1,
  6822.                         'invoice_id' => 'abcd1234',
  6823.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6824.                         'created_by' => 'created by',
  6825.                         'created_at' => '',
  6826.                         'red' => 0,
  6827.                         'start_date' => $start_date,
  6828.                         'end_date' => $end_date,
  6829.                         'openFilter' => empty($post_data->keys()) ? 0,
  6830.                         'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6831.                         'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6832.                         'company_name' => $company_data->getName(),
  6833.                         'company_data' => $company_data,
  6834.                         'company_address' => $company_data->getAddress(),
  6835.                         'company_image' => $company_data->getImage(),
  6836.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6837.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6838.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6839.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6840.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6841.                         'action_tag' => $warehouse_action_list,
  6842.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6843.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6844.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6845.                         'data_searched' => $data_searched,
  6846.                         'export' => 'all'
  6847.                     )
  6848.                 );
  6849.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6850.                     'orientation' => count($data_searched['query_columns_filter']) > 'landscape' 'portrait',
  6851.                     'no-stop-slow-scripts' => true,
  6852.                     'no-background' => false,
  6853.                     'lowquality' => false,
  6854.                     'encoding' => 'utf-8',
  6855.                     'dpi' => 300,
  6856.                     'image-dpi' => 300,
  6857.                 ));
  6858.                 return new Response(
  6859.                     $pdf_response,
  6860.                     200,
  6861.                     array(
  6862.                         'Content-Type' => 'application/pdf',
  6863.                         'Content-Disposition' => 'attachment; filename="Stock_Consumption.pdf"'
  6864.                     )
  6865.                 );
  6866.             }
  6867.             return $this->render('@Inventory/pages/print/print_stock_consumption.html.twig',
  6868.                 array(
  6869.                     'page_title' => 'Inventory Report',
  6870.                     'page_header' => 'Report',
  6871.                     'print_title' => $print_title,
  6872.                     'document_type' => 'Journal voucher',
  6873.                     'document_mark_image' => $document_mark['original'],
  6874.                     'page_header_sub' => 'Add',
  6875.                     'item_data' => [],
  6876.                     'received' => 2,
  6877.                     'return' => 1,
  6878.                     'total_w_vat' => 1,
  6879.                     'total_vat' => 1,
  6880.                     'total_wo_vat' => 1,
  6881.                     'invoice_id' => 'abcd1234',
  6882.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6883.                     'created_by' => 'created by',
  6884.                     'created_at' => '',
  6885.                     'red' => 0,
  6886.                     'start_date' => $start_date,
  6887.                     'end_date' => $end_date,
  6888.                     'openFilter' => empty($post_data->keys()) ? 0,
  6889.                     'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6890.                     'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6891.                     'company_name' => $company_data->getName(),
  6892.                     'company_data' => $company_data,
  6893.                     'company_address' => $company_data->getAddress(),
  6894.                     'company_image' => $company_data->getImage(),
  6895.                     'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6896.                     'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6897.                     'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6898.                     'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6899.                     'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6900.                     'action_tag' => $warehouse_action_list,
  6901.                     'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6902.                     'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6903.                     'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6904.                     'data_searched' => $data_searched,
  6905.                     'export' => 'all'
  6906.                 )
  6907.             );
  6908.         }
  6909. //        return new JsonResponse(Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()));
  6910.         return $this->render('@Inventory/pages/report/stock_consumption.html.twig',
  6911.             array(
  6912.                 'page_title' => 'Stock Consumption',
  6913.                 'start_date' => $start_date,
  6914.                 'end_date' => $end_date,
  6915.                 'openFilter' => empty($post_data->keys()) ? 0,
  6916.                 'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6917.                 'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6918.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6919.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6920.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6921.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6922.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6923.                 'action_tag' => $warehouse_action_list,
  6924.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6925.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6926.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6927.                 'data_searched' => $data_searched
  6928.             )
  6929.         );
  6930.     }
  6931.     public function ItemViewAction(Request $request)
  6932.     {
  6933.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  6934.             array(
  6935.                 'page_title' => 'Stock Return'
  6936.             )
  6937.         );
  6938.     }
  6939.     public function ProductViewAction(Request $request$id 0)
  6940.     {
  6941.         $em $this->getDoctrine()->getManager();
  6942.         $companyId $this->getLoggedUserCompanyId($request);
  6943.         $company_data Company::getCompanyData($em$companyId);
  6944.         $data = [];
  6945.         $specData =[];
  6946.         $specIds=[];
  6947.         $productData $em->getRepository('ApplicationBundle:InvProducts')
  6948.             ->findOneBy(
  6949.                 array(
  6950.                     'id' => $id
  6951.                 )
  6952.             );
  6953.         if($productData){
  6954.             $tempSpecData json_decode($productData->getSpecData(),true);
  6955.             if($tempSpecData == null ){
  6956.                 $tempSpecData=[];
  6957.             }
  6958.             foreach ($tempSpecData as $indSpecData)
  6959.             {
  6960. //                $specId = $indSpecData['id'];
  6961.                 $specData[]=[
  6962.                     'id'=> $indSpecData['id'],
  6963.                     'value'=> $indSpecData['value']
  6964.                 ];
  6965.                 $specIds[]= $indSpecData['id'];
  6966.             }
  6967.         }
  6968.         $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  6969.             ->findBy(
  6970.                 array(
  6971.                     'productId' => $id
  6972.                 )
  6973.             );
  6974.         $trans_history $em->getRepository('ApplicationBundle:InvItemTransaction')
  6975.             ->findBy(
  6976.                 array(
  6977.                     'productId' => $id
  6978.                 ), array(
  6979.                     'transactionDate' => 'ASC',
  6980.                     'id' => 'ASC'
  6981.                 )
  6982.             );
  6983. //        $specId = array_keys($specData);
  6984.         $finSpecData=[];
  6985. //        if($productData){
  6986. //            $tempSpec = json_decode($productData->getSpecData(),true);
  6987. //
  6988. //            if($tempSpec == null){
  6989. //                $tempSpecName=[];
  6990. //            }
  6991. //            foreach ($tempSpec as $indSpec)
  6992. //            {
  6993. //                $specIds[]=$indSpec['id'];
  6994. //
  6995. //                $spec = $em->getRepository('ApplicationBundle:SpecType')
  6996. //                    ->findOneBy(
  6997. //                        array(
  6998. //                            'id' => $indSpec['id']
  6999. //                        )
  7000. //                    );
  7001. //
  7002. //                if($spec)
  7003. //                    $indSpec['name']=$spec->getName();
  7004. //                else
  7005. //                    $indSpec['name']='';
  7006. ////                $specId = $indSpecData['id'];
  7007. //
  7008. //                $finSpecData[]=$indSpec;
  7009. //
  7010. //            }
  7011. //        }
  7012.         $specList $em->getRepository('ApplicationBundle:SpecType')
  7013.             ->findBy(
  7014.                 array(
  7015.                     'id' =>$specIds
  7016.                 )
  7017.             );
  7018.         $specListById=[];
  7019.         foreach ($specList as $specHere)
  7020.         {
  7021.             $specListById[$specHere->getId()]=$specHere->getName();
  7022.         }
  7023.         foreach ($specData as $specDatum){
  7024.             $finSpecData[]=[
  7025.                 'id' => $specDatum['id'],
  7026.                 'name' => isset($specListById[$specDatum['id']])?$specListById[$specDatum['id']]:'',
  7027.                 'value' => $specDatum['value']
  7028.             ];
  7029.         }
  7030.         $productDataObj = array();
  7031.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  7032.             $getters array_filter(get_class_methods($productData), function ($method) {
  7033.                 return 'get' === substr($method03);
  7034.             });
  7035.             foreach ($getters as $getter) {
  7036.                 if ($getter == 'getGlobalId')
  7037.                     continue;
  7038. //                    if ($getter == 'getId')
  7039. //                        continue;
  7040.                 $Fieldname str_replace('get'''$getter);
  7041.                 $productDataObj[$Fieldname] = $productData->{$getter}(); // `foo!`
  7042.             }
  7043.             if ($request->request->has('genInfoOnly') && $request->request->get('genInfoOnly') == 1) {
  7044.                 $dataArray = array(
  7045.                     'success' => true,
  7046.                     'page_title' => 'Product Details',
  7047.                     'company_data' => $company_data,
  7048.                     'productData' => $productData,
  7049.                     'productDataObj' => $productDataObj,
  7050.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7051.                 );
  7052.             } else {
  7053.                 $dataArray = array(
  7054.                     'success' => true,
  7055.                     'page_title' => 'Product Details',
  7056.                     'company_data' => $company_data,
  7057.                     'productData' => $productData,
  7058.                     'productDataObj' => $productDataObj,
  7059.                     'currInvList' => $currInvList,
  7060.                     'finSpecData' => $finSpecData,
  7061.                     'specList' => $specList,
  7062.                     'trans_history' => $trans_history,
  7063.                     'entityList' => GeneralConstant::$Entity_list_details,
  7064. //                    'productList' => Inventory::ProductList($em, $companyId),
  7065.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7066.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7067.                     'igList' => Inventory::ItemGroupList($em$companyId),
  7068.                     'unitList' => Inventory::UnitTypeList($em),
  7069.                     'brandList' => Inventory::GetBrandList($em$companyId),
  7070.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7071.                     'warehouseList' => Inventory::WarehouseList($em),
  7072.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7073.                 );
  7074.             }
  7075.             return new JsonResponse(
  7076.                 $dataArray
  7077.             );
  7078.         }
  7079.         $dataArray = array(
  7080.             'page_title' => 'Product Details',
  7081.             'company_data' => $company_data,
  7082.             'productData' => $productData,
  7083.             'currInvList' => $currInvList,
  7084.             'specData' => $specData,
  7085. //            'specListById' => $specListById,
  7086.             'finSpecData' => $finSpecData,
  7087.             'trans_history' => $trans_history,
  7088.             'entityList' => GeneralConstant::$Entity_list_details,
  7089. //            'productList' => Inventory::ProductList($em, $companyId),
  7090.             'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7091.             'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7092.             'igList' => Inventory::ItemGroupList($em$companyId),
  7093.             'unitList' => Inventory::UnitTypeList($em),
  7094.             'brandList' => Inventory::GetBrandList($em$companyId),
  7095.             'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7096.             'warehouseList' => Inventory::WarehouseList($em),
  7097.         );
  7098.         return $this->render('@Inventory/pages/views/product_view.html.twig'$dataArray
  7099.         );
  7100.     }
  7101.     public function CheckForProductInWarehouseAction(Request $request$queryStr '')
  7102.     {
  7103.         $em $this->getDoctrine()->getManager();
  7104.         $companyId $this->getLoggedUserCompanyId($request);
  7105.         $data = [
  7106.             'availableQty' => 0,
  7107.             'productByCodesArray' => [],
  7108.             'indRowId' => 0
  7109.         ];
  7110.         $html '';
  7111.         $productByCodeData = [];
  7112.         if ($request->isMethod('POST')) {
  7113.             $warehouseId $request->request->get('warehouseId'0);
  7114.             $warehouseActionId $request->request->get('warehouseActionId'0);
  7115.             $productId $request->request->get('productId'0);
  7116.             $indRowId $request->request->get('indRowId'0);
  7117.             $data['indRowId'] = $indRowId;
  7118.             $inStorage $em->getRepository('ApplicationBundle:InventoryStorage')
  7119.                 ->findBy(
  7120.                     array(
  7121.                         'productId' => $productId,
  7122.                         'warehouseId' => $warehouseId,
  7123.                         'actionTagId' => $warehouseActionId,
  7124.                         'CompanyId' => $companyId,
  7125.                     )
  7126.                 );
  7127.             foreach ($inStorage as $strg) {
  7128.                 $data['availableQty'] += $strg->getQty();
  7129.             }
  7130.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  7131.                 ->findBy(
  7132.                     array(
  7133.                         'productId' => $productId,
  7134.                         'warehouseId' => $warehouseId,
  7135.                         'warehouseActionId' => $warehouseActionId,
  7136.                         'CompanyId' => $companyId,
  7137.                     )
  7138.                 );
  7139.             foreach ($productByCodeData as $pbc) {
  7140.                 $data['productByCodesArray'][] = array(
  7141.                     'id' => $pbc->getProductByCodeId(),
  7142.                     'productId' => $pbc->getProductId(),
  7143.                     'warehouseId' => $pbc->getWarehouseId(),
  7144.                     'warehouseActionId' => $pbc->getWarehouseActionId(),
  7145. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7146.                     'sales_code' => str_pad($pbc->getSalesCode(), 13'0'STR_PAD_LEFT),
  7147. //                'sales_code'=>$d['sales_code'],
  7148.                 );
  7149.             }
  7150.             return new JsonResponse(array(
  7151.                     'success' => true,
  7152.                     'data' => $data,
  7153.                 )
  7154.             );
  7155.         }
  7156.         return new JsonResponse(
  7157.             array(
  7158.                 'success' => false,
  7159.                 'data' => $data,
  7160.             )
  7161.         );
  7162.     }
  7163.     public function ProductByCodeListAjaxAction(Request $request$queryStr '')
  7164.     {
  7165.         $em $this->getDoctrine()->getManager();
  7166.         $companyId $this->getLoggedUserCompanyId($request);
  7167.         $company_data Company::getCompanyData($em$companyId);
  7168.         $data = [];
  7169.         $html '';
  7170.         $productByCodeData = [];
  7171.         if ($request->request->has('query') && $queryStr == '')
  7172.             $queryStr $request->request->get('queryStr');
  7173.         $get_kids_sql "select product_by_code_id id, product_id, warehouse_id, warehouse_action_id,
  7174.                             sales_code ,
  7175.                             serial_no,
  7176.                             imei1,
  7177.                             imei2,
  7178.                             imei3,
  7179.                             imei4
  7180.                             from product_by_code
  7181.                             where ( CONVERT(sales_code,char)  like '%" $queryStr "%'
  7182.                                     or  CONVERT(serial_no,char)  like '%" $queryStr "%'
  7183.                                     or  CONVERT(imei1,char)  like '%" $queryStr "%'
  7184.                                     or  CONVERT(imei2,char)  like '%" $queryStr "%'
  7185.                                     or  CONVERT(imei3,char)  like '%" $queryStr "%'
  7186.                                     or  CONVERT(imei4,char)  like '%" $queryStr "%'
  7187.                                     ) ";
  7188.         if ($request->query->has('warehouseId'))
  7189.             $get_kids_sql .= " and warehouse_id=" $request->query->get('warehouseId') . " ";
  7190.         if ($request->query->has('position'))
  7191.             $get_kids_sql .= " and position=" $request->query->get('position') . " ";
  7192.         if ($request->query->has('deliveryReceiptId'))
  7193.             $get_kids_sql .= " and deliveryReceiptId=" $request->query->get('deliveryReceiptId') . " ";
  7194.         if ($request->query->has('warehouseActionId'))
  7195.             $get_kids_sql .= " and warehouse_action_id=" $request->query->get('warehouseActionId') . " ";
  7196.         if ($request->query->has('productId'))
  7197.             $get_kids_sql .= " and product_id=" $request->query->get('productId') . " ";
  7198.         $get_kids_sql .= " and company_id=" $companyId " limit 25";
  7199.         $stmt $em->getConnection()->prepare($get_kids_sql);
  7200.         $stmt->execute();
  7201.         $get_kids $stmt->fetchAll();
  7202.         if (!empty($get_kids)) {
  7203.             foreach ($get_kids as $d) {
  7204.                 $dt = array(
  7205.                     'id' => $d['id'],
  7206.                     'productId' => $d['product_id'],
  7207.                     'warehouseId' => $d['warehouse_id'],
  7208.                     'warehouseActionId' => $d['warehouse_action_id'],
  7209. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7210.                     'sales_code' => str_pad($d['sales_code'], 13'0'STR_PAD_LEFT),
  7211.                     'serial_no' => str_pad($d['serial_no'], 13'0'STR_PAD_LEFT),
  7212.                     'imei1' => str_pad($d['imei1'], 13'0'STR_PAD_LEFT),
  7213.                     'imei2' => str_pad($d['imei2'], 13'0'STR_PAD_LEFT),
  7214.                     'imei3' => str_pad($d['imei3'], 13'0'STR_PAD_LEFT),
  7215.                     'imei4' => str_pad($d['imei4'], 13'0'STR_PAD_LEFT),
  7216. //                'sales_code'=>$d['sales_code'],
  7217.                 );
  7218.                 $data[] = $dt;
  7219.             }
  7220.         }
  7221. //        if($request->query->has('returnJson'))
  7222.         {
  7223.             return new JsonResponse(
  7224.                 array(
  7225.                     'success' => true,
  7226. //                    'page_title' => 'Product Details',
  7227. //                    'company_data' => $company_data,
  7228.                     'data' => $data,
  7229. //                    'exId'=>$id,
  7230. //                'productByCodeData' => $productByCodeData,
  7231. //                'productData' => $productData,
  7232. //                'currInvList' => $currInvList,
  7233. //                'productList' => Inventory::ProductList($em, $companyId),
  7234. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  7235. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  7236. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  7237. //                'unitList' => Inventory::UnitTypeList($em),
  7238. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  7239. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  7240. //                'warehouseList' => Inventory::WarehouseList($em),
  7241.                 )
  7242.             );
  7243.         }
  7244.     }
  7245.     public function selectDataAjaxAction(Request $request$queryStr '',
  7246.                                                  $version 'latest',
  7247.                                                  $identifier '_default_',
  7248.                                                  $apiKey '_ignore_'
  7249.     )
  7250.     {
  7251.         $em $this->getDoctrine()->getManager();
  7252.         $em_goc $this->getDoctrine()->getManager('company_group');
  7253.         $companyId 0;
  7254.         $skipCurrentUserIdRestriction $request->get('skipCurrentUserIdRestriction'0);
  7255.         $skipCurrentEmployeeIdRestriction $request->get('skipCurrentEmployeeIdRestriction'0);
  7256.         $skipCurrentUserLoginIdRestriction $request->get('skipCurrentUserLoginIdRestriction'0);
  7257.         $currentUserId $request->getSession()->get(UserConstants::USER_ID0);
  7258.         $currentEmployeeId $request->getSession()->get(UserConstants::USER_EMPLOYEE_ID0);
  7259.         $currentUserLoginIds = [];
  7260.         if ($request->request->get('entity_group'0)) {
  7261.             $companyId 0;
  7262.             $em $this->getDoctrine()->getManager('company_group');
  7263.         } else {
  7264.             if ($request->request->get('appId'0) != 0) {
  7265.                 $gocEnabled 0;
  7266.                 if ($this->container->hasParameter('entity_group_enabled'))
  7267.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7268.                 else
  7269.                     $gocEnabled 1;
  7270.                 if ($gocEnabled == 1) {
  7271.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7272.                         $this->getDoctrine()->getManager('company_group'),
  7273.                         $gocEnabled,
  7274.                         $request->request->get('appId'0)
  7275.                     );
  7276.                     if (!empty($dataToConnect)) {
  7277.                         $connector $this->container->get('application_connector');
  7278.                         $connector->resetConnection(
  7279.                             'default',
  7280.                             $dataToConnect['dbName'],
  7281.                             $dataToConnect['dbUser'],
  7282.                             $dataToConnect['dbPass'],
  7283.                             $dataToConnect['dbHost'],
  7284.                             $reset true
  7285.                         );
  7286.                         $em $this->getDoctrine()->getManager();
  7287.                     }
  7288.                 }
  7289.             } else if ($request->getSession()->get(UserConstants::USER_APP_ID) != && $request->getSession()->get(UserConstants::USER_APP_ID) != null) {
  7290.                 $gocEnabled 0;
  7291.                 if ($this->container->hasParameter('entity_group_enabled'))
  7292.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7293.                 else
  7294.                     $gocEnabled 1;
  7295.                 if ($gocEnabled == 1) {
  7296.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7297.                         $this->getDoctrine()->getManager('company_group'),
  7298.                         $gocEnabled,
  7299.                         $request->getSession()->get(UserConstants::USER_APP_ID)
  7300.                     );
  7301.                     if (!empty($dataToConnect)) {
  7302.                         $connector $this->container->get('application_connector');
  7303.                         $connector->resetConnection(
  7304.                             'default',
  7305.                             $dataToConnect['dbName'],
  7306.                             $dataToConnect['dbUser'],
  7307.                             $dataToConnect['dbPass'],
  7308.                             $dataToConnect['dbHost'],
  7309.                             $reset true
  7310.                         );
  7311.                         $em $this->getDoctrine()->getManager();
  7312.                     }
  7313.                 }
  7314.             }
  7315.             $companyId $this->getLoggedUserCompanyId($request);
  7316.         }
  7317.         $configData = [];
  7318.         $isSingleDataset 1;
  7319.         $dataSet $request->request->has('dataset') ? $request->request->get('dataset') : [];
  7320.         if (is_string($dataSet)) $dataSet json_decode($dataSettrue);
  7321.         $valuePairs $request->get('valuePairs', []);
  7322.         if (is_string($valuePairs)) $valuePairs json_decode($valuePairstrue);
  7323.         $allResult = [];
  7324.         $datasetFromConfig = [];
  7325.         if ($identifier != '_default_') {
  7326.             $config_file $this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' $identifier 'Config.json';
  7327.             if (!file_exists($config_file)) {
  7328.             } else {
  7329.                 $fileText file_get_contents($config_file);
  7330.                 //now replace any value pairs
  7331.                 foreach ($valuePairs as $kkeeyy => $vvaalluuee) {
  7332.                     if (is_array($vvaalluuee)) {
  7333.                         if (isset($vvaalluuee['value']) && isset($vvaalluuee['type'])) {
  7334.                             if ($vvaalluuee['type'] == 'array'$fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee['value']), $fileText);
  7335.                             if ($vvaalluuee['type'] == 'value'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7336.                             if ($vvaalluuee['type'] == 'text'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7337.                         } else {
  7338.                             $fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee), $fileText);
  7339.                         }
  7340.                     }
  7341.                     $fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee$fileText);
  7342.                 }
  7343.                 $fileText str_ireplace('_query_'$request->get('query'$queryStr), $fileText);
  7344.                 if (!(strpos($fileText'_CURRENT_USER_LOGIN_IDS_') === false) && $skipCurrentUserLoginIdRestriction == 0) {
  7345.                     $userInfo = [];
  7346.                     if ($request->getSession()->get(UserConstants::USER_TYPE0) == UserConstants::USER_TYPE_APPLICANT) {
  7347.                         $userInfo $em_goc->getRepository('CompanyGroupBundle:EntityLoginLog')->findBy(
  7348.                             array('userId' => $currentUserId)
  7349.                         );
  7350.                     } else {
  7351.                         $userInfo $em->getRepository('ApplicationBundle:SysLoginLog')->findBy(
  7352.                             array('userId' => $currentUserId)
  7353.                         );
  7354.                     }
  7355.                     foreach ($userInfo as $uLogininfo) {
  7356.                         $currentUserLoginIds[] = $uLogininfo->getLoginId();
  7357.                     }
  7358.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_'json_encode($currentUserLoginIds), $fileText);
  7359.                 } else {
  7360.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_''_EMPTY_'$fileText);
  7361.                 }
  7362.                 if (!(strpos($fileText'_CURRENT_USER_ID_') === false) && $skipCurrentUserIdRestriction == 0) {
  7363.                     $fileText str_ireplace('_CURRENT_USER_ID_'$currentUserId$fileText);
  7364.                 } else {
  7365.                     $fileText str_ireplace('_CURRENT_USER_ID_''_EMPTY_'$fileText);
  7366.                 }
  7367.                 if (!(strpos($fileText'_CURRENT_USER_EMPLOYEE_ID_') === false) && $skipCurrentEmployeeIdRestriction == 0) {
  7368.                     if ((strpos($fileText'skipCurrentEmployeeIdRestriction') === false)) {
  7369.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_'$currentEmployeeId$fileText);
  7370.                     } else {
  7371.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  7372.                     }
  7373.                 } else {
  7374.                     $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  7375.                 }
  7376.                 if ($fileText)
  7377.                     $datasetFromConfig json_decode($fileTexttrue);
  7378.                 $skipCurrentUserIdRestriction = isset($datasetFromConfig['skipCurrentUserIdRestriction']) ? $datasetFromConfig['skipCurrentUserIdRestriction'] : $skipCurrentUserIdRestriction;
  7379.                 $skipCurrentEmployeeIdRestriction = isset($datasetFromConfig['skipCurrentEmployeeIdRestriction']) ? $datasetFromConfig['skipCurrentEmployeeIdRestriction'] : $skipCurrentEmployeeIdRestriction;
  7380.                 $skipCurrentUserLoginIdRestriction = isset($datasetFromConfig['skipCurrentUserLoginIdRestriction']) ? $datasetFromConfig['skipCurrentUserLoginIdRestriction'] : $skipCurrentUserLoginIdRestriction;
  7381.             }
  7382.         }
  7383.         if ($dataSet == null$dataSet = [];
  7384. //        return new JsonResponse(array(
  7385. //            'queryStr'=>$queryStr
  7386. //        ));
  7387.         if (!empty($datasetFromConfig)) {
  7388.             if (isset($datasetFromConfig['tableName'])) {
  7389.                 $isSingleDataset 1;
  7390.                 $dataSet[] = $datasetFromConfig;
  7391.             } else {
  7392.                 if (count($datasetFromConfig) == 1)
  7393.                     $isSingleDataset 1;
  7394.                 $dataSet $datasetFromConfig;
  7395.             }
  7396.         }
  7397.         if (empty($dataSet)) {
  7398.             $isSingleDataset 1;
  7399.             $singleDataSet = array(
  7400.                 "valueField" => $request->request->has('valueField') ? $request->request->get('valueField') : 'id',
  7401.                 "query" => $request->get('query'$queryStr),
  7402.                 "headMarkers" => $request->get('headMarkers'''),
  7403.                 "headMarkersStrictMatch" => $request->get('headMarkersStrictMatch'0),
  7404.                 "itemLimit" => $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25,
  7405.                 "selectorId" => $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_',
  7406.                 "textField" => $request->request->has('textField') ? $request->request->get('textField') : 'name',
  7407.                 "tableName" => $request->request->has('tableName') ? $request->request->get('tableName') : '',
  7408.                 "isMultiple" => $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0,
  7409.                 "orConditions" => $request->request->has('orConditions') ? $request->request->get('orConditions') : [],
  7410.                 "andConditions" => $request->request->has('andConditions') ? $request->request->get('andConditions') : [],
  7411.                 "andOrConditions" => $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [],
  7412.                 "mustConditions" => $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [],
  7413.                 "joinTableData" => $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [],
  7414.                 "renderTextFormat" => $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '',
  7415.                 "setDataForSingle" => $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0,
  7416.                 "dataId" => $request->request->has('dataId') ? $request->request->get('dataId') : 0,
  7417.                 "lastChildrenOnly" => $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0,
  7418.                 "parentOnly" => $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0,
  7419.                 "parentIdField" => $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id',
  7420.                 "skipDefaultCompanyId" => $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1,
  7421.                 "offset" => $request->request->has('offset') ? $request->request->get('offset') : 0,
  7422.                 "returnTotalMatchedEntriesFlag" => $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0,
  7423.                 "nextOffset" => 0,
  7424.                 "totalMatchedEntries" => 0,
  7425.                 "convertToObject" => $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [],
  7426.                 "convertDateToStringFieldList" => $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [],
  7427.                 "orderByConditions" => $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [],
  7428.                 "convertToUrl" => $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [],
  7429.                 "fullPathList" => $request->request->has('fullPathList') ? $request->request->get('fullPathList') : [],
  7430.                 "ret_data" => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  7431.             );
  7432.             $dataSet[] = $singleDataSet;
  7433.         }
  7434. //        $lastResult = [
  7435. //            'identifier' => $identifier,
  7436. //            'dataSet' => $dataSet,
  7437. //        ];
  7438. //        return new JsonResponse($lastResult);
  7439.         $userId $request->getSession()->get(UserConstants::USER_ID);
  7440. //        public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [],$userId=0)
  7441.         foreach ($dataSet as $dsIndex => $dataConfig) {
  7442.             $companyId 0;
  7443.             $queryStringIndividual $queryStr;
  7444.             $data = [];
  7445.             $data_by_id = [];
  7446.             $setValueArray = [];
  7447.             $silentChangeSelectize 0;
  7448.             $setValue 0;
  7449.             $setValueType 0;// 0 for id , 1 for query
  7450.             $selectAll 0;
  7451.             if ($queryStringIndividual == '_EMPTY_')
  7452.                 $queryStringIndividual '';
  7453.             if (isset($dataConfig['query']))
  7454.                 $queryStringIndividual $dataConfig['query'];
  7455.             if ($queryStringIndividual == '_EMPTY_')
  7456.                 $queryStringIndividual '';
  7457.             $queryStringIndividual str_replace('_FSLASH_''/'$queryStringIndividual);
  7458.             if ($queryStringIndividual === '#setValue:') {
  7459.                 $queryStringIndividual '';
  7460.             }
  7461.             if (!(strpos($queryStringIndividual'_silent_change_') === false)) {
  7462.                 $silentChangeSelectize 1;
  7463.                 $queryStringIndividual str_ireplace('_silent_change_'''$queryStringIndividual);
  7464.             }
  7465.             if (!(strpos($queryStringIndividual'#setValue:') === false)) {
  7466.                 $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStringIndividual));
  7467.                 foreach ($setValueArrayBeforeFilter as $svf) {
  7468.                     if ($svf == '_ALL_') {
  7469.                         $selectAll 1;
  7470.                         $setValueArray = [];
  7471.                         continue;
  7472.                     }
  7473.                     if (is_numeric($svf)) {
  7474.                         $setValueArray[] = ($svf 1);
  7475.                         $setValue $svf 1;
  7476.                     }
  7477.                 }
  7478.                 $queryStringIndividual '';
  7479.             }
  7480.             $valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
  7481.             $headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''//Special Field
  7482.             $headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0//Special Field
  7483.             $itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
  7484.             $selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
  7485.             $textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
  7486.             $table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
  7487.             $isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
  7488.             $orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
  7489.             $andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
  7490.             $andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
  7491.             $mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
  7492.             $joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
  7493.             $renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
  7494.             $setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
  7495.             $dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
  7496.             $lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
  7497.             $parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
  7498.             $parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
  7499.             $skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
  7500.             $offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
  7501.             $returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
  7502.             $nextOffset 0;
  7503.             $totalMatchedEntries 0;
  7504.             $convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
  7505.             $convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
  7506.             $orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
  7507.             $convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
  7508.             $fullPathList = isset($dataConfig['fullPathList']) ? $dataConfig['fullPathList'] : [];
  7509.             if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  7510.             if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  7511.             if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  7512.             if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  7513.             if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  7514.             if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  7515.             if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  7516.             if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  7517.             if (is_string($fullPathList)) $fullPathList json_decode($fullPathListtrue);
  7518. //            return new JsonResponse(array(
  7519. //                'dataSet'=>$dataSet,
  7520. //                'dataConfig'=>$dataConfig,
  7521. //                'hi'=>$this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json',
  7522. //                'hiD'=>file_get_contents($this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json')
  7523. //            ));
  7524.             if ($table == '') {
  7525.                 $lastResult = array(
  7526.                     'success' => false,
  7527.                     'currentTs' => (new \Datetime())->format('U'),
  7528.                     'isMultiple' => $isMultiple,
  7529.                     'setValueArray' => $setValueArray,
  7530.                     'setValue' => $setValue,
  7531.                     'data' => $data,
  7532.                     'dataId' => $dataId,
  7533.                     'selectorId' => $selectorId,
  7534.                     'dataById' => $data_by_id,
  7535.                     'selectedId' => 0,
  7536.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  7537.                 );
  7538.             } else {
  7539.                 $restrictionData = array(
  7540. //            'table'=>'relevantField in restriction'
  7541.                     'warehouse_action' => 'warehouseActionIds',
  7542.                     'branch' => 'branchIds',
  7543.                     'warehouse' => 'warehouseIds',
  7544.                     'production_process_settings' => 'productionProcessIds',
  7545.                 );
  7546.                 $restrictionIdList = [];
  7547.                 $filterQryForCriteria "select ";
  7548.                 $selectQry "";
  7549. //        $selectQry=" `$table`.* ";
  7550.                 $selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
  7551.                 $selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
  7552.                 if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  7553.                 foreach ($selectFieldList as $selField) {
  7554.                     if ($selectQry != '')
  7555.                         $selectQry .= ", ";
  7556.                     if ($selField == '*')
  7557.                         $selectQry .= " `$table`.$selField ";
  7558.                     else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7559.                         if ($selectPrefix == '')
  7560.                             $selectQry .= " count(*)  ";
  7561.                         else
  7562.                             $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  7563.                     } else {
  7564.                         if ($selectPrefix == '')
  7565.                             $selectQry .= " `$table`.`$selField` ";
  7566.                         else
  7567.                             $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  7568.                     }
  7569.                 }
  7570.                 $joinQry " from $table ";
  7571. //        $filterQryForCriteria = "select * from $table ";
  7572.                 foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  7573. //            $conditionStr.=' 1=1 ';
  7574.                     $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  7575.                     $joinTableAlias $joinTableName '_' $joinIndex;
  7576.                     $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  7577.                     $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  7578.                     $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  7579.                     $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  7580.                     $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  7581.                     $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  7582.                     $joinMustConditions = isset($joinTableDatum['joinMustConditions']) ? $joinTableDatum['joinMustConditions'] : [];
  7583.                     $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  7584.                     $joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
  7585.                     $joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
  7586.                     if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  7587.                     if (is_string($joinMustConditions)) $joinMustConditions json_decode($joinMustConditionstrue);
  7588.                     if (is_string($joinAndOrConditions)) $joinAndOrConditions json_decode($joinAndOrConditionstrue);
  7589.                     if (is_string($joinOrConditions)) $joinOrConditions json_decode($joinOrConditionstrue);
  7590.                     foreach ($selectFieldList as $selField) {
  7591.                         if ($selField == '*')
  7592.                             $selectQry .= ", `$joinTableAlias`.$selField ";
  7593.                         else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7594.                             if ($selectPrefix == '')
  7595.                                 $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  7596.                             else
  7597.                                 $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  7598.                         } else {
  7599.                             if ($selectPrefix == '')
  7600.                                 $selectQry .= ", `$joinTableAlias`.`$selField`  ";
  7601.                             else
  7602.                                 $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  7603.                         }
  7604.                     }
  7605.                     $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  7606. //            if($joinTablePrimaryField!='')
  7607. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7608. //            $joinAndString = '';
  7609.                     $joinMustString '';
  7610.                     if ($joinTablePrimaryField != '')
  7611.                         $joinQry .= "  `$joinTableAlias`.`$joinTableOnField$fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7612.                     foreach ($joinMustConditions as $mustCondition) {
  7613. //            $conditionStr.=' 1=1 ';
  7614.                         $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  7615.                         $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  7616.                         $aliasInCondition $table;
  7617.                         if (!(strpos($cfield'.') === false)) {
  7618.                             $fullCfieldArray explode('.'$cfield);
  7619.                             $aliasInCondition $fullCfieldArray[0];
  7620.                             $cfield $fullCfieldArray[1];
  7621.                         }
  7622.                         $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  7623.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7624.                             if ($joinMustString != '')
  7625.                                 $joinMustString .= " and ";
  7626.                             if ($ctype == 'like') {
  7627.                                 $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7628.                                 $wordsBySpaces explode(' '$cvalue);
  7629.                                 foreach ($wordsBySpaces as $word) {
  7630.                                     if ($joinMustString != '')
  7631.                                         $joinMustString .= " and ";
  7632.                                     $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7633.                                 }
  7634.                             } else if ($ctype == 'not like') {
  7635.                                 $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7636.                                 $wordsBySpaces explode(' '$cvalue);
  7637.                                 foreach ($wordsBySpaces as $word) {
  7638.                                     if ($joinMustString != '')
  7639.                                         $joinMustString .= " and ";
  7640.                                     $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7641.                                 }
  7642.                             } else if ($ctype == 'not_in') {
  7643.                                 $joinMustString .= " ( ";
  7644.                                 if (in_array('null'$cvalue)) {
  7645.                                     $joinMustString .= " `$joinTableAlias`.$cfield is not null";
  7646.                                     $cvalue array_diff($cvalue, ['null']);
  7647.                                     if (!empty($cvalue))
  7648.                                         $joinMustString .= " and ";
  7649.                                 }
  7650.                                 if (in_array(''$cvalue)) {
  7651.                                     $joinMustString .= "`$joinTableAlias`.$cfield != '' ";
  7652.                                     $cvalue array_diff($cvalue, ['']);
  7653.                                     if (!empty($cvalue))
  7654.                                         $joinMustString .= " and ";
  7655.                                 }
  7656.                                 $joinMustString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7657.                             } else if ($ctype == 'in') {
  7658.                                 if (in_array('null'$cvalue)) {
  7659.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null";
  7660.                                     $cvalue array_diff($cvalue, ['null']);
  7661.                                     if (!empty($cvalue))
  7662.                                         $joinMustString .= " and ";
  7663.                                 }
  7664.                                 if (in_array(''$cvalue)) {
  7665.                                     $joinMustString .= "`$joinTableAlias`.$cfield = '' ";
  7666.                                     $cvalue array_diff($cvalue, ['']);
  7667.                                     if (!empty($cvalue))
  7668.                                         $joinMustString .= " and ";
  7669.                                 }
  7670.                                 $joinMustString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7671.                             } else if ($ctype == '=') {
  7672. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7673. //                            $fullCfieldArray = explode('.', $cfield);
  7674. //                            $aliasInCondition = $fullCfieldArray[0];
  7675. //                            $cfield = $fullCfieldArray[1];
  7676. //                        }
  7677.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7678.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null ";
  7679.                                 else
  7680.                                     $joinMustString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7681.                             } else if ($ctype == '!=') {
  7682.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7683.                                     $joinMustString .= "`$joinTableAlias`.$cfield is not null ";
  7684.                                 else
  7685.                                     $joinMustString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7686.                             } else {
  7687.                                 if (is_string($cvalue))
  7688.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7689.                                 else
  7690.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7691.                             }
  7692.                         }
  7693.                     }
  7694. //            if ($joinMustString != '') {
  7695. //                if ($conditionStr != '')
  7696. //                    $conditionStr .= (" and (" . $joinMustString . ") ");
  7697. //                else
  7698. //                    $conditionStr .= ("  (" . $joinMustString . ") ");
  7699. //            }
  7700.                     if ($joinMustString != '') {
  7701.                         $joinQry .= (' and ' $joinMustString);
  7702. //                        $joinQry.=' and (';
  7703.                     }
  7704.                     $mustBracketDone 0;
  7705.                     $joinAndString '';
  7706. //                    if ($joinTablePrimaryField != '')
  7707. //                        $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7708.                     foreach ($joinAndConditions as $andCondition) {
  7709. //            $conditionStr.=' 1=1 ';
  7710.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  7711.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  7712.                         $aliasInCondition $table;
  7713.                         if (!(strpos($cfield'.') === false)) {
  7714.                             $fullCfieldArray explode('.'$cfield);
  7715.                             $aliasInCondition $fullCfieldArray[0];
  7716.                             $cfield $fullCfieldArray[1];
  7717.                         }
  7718.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  7719.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7720.                             if ($joinAndString != '')
  7721.                                 $joinAndString .= " and ";
  7722.                             if ($ctype == 'like') {
  7723.                                 $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7724.                                 $wordsBySpaces explode(' '$cvalue);
  7725.                                 foreach ($wordsBySpaces as $word) {
  7726.                                     if ($joinAndString != '')
  7727.                                         $joinAndString .= " and ";
  7728.                                     $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7729.                                 }
  7730.                             } else if ($ctype == 'not like') {
  7731.                                 $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7732.                                 $wordsBySpaces explode(' '$cvalue);
  7733.                                 foreach ($wordsBySpaces as $word) {
  7734.                                     if ($joinAndString != '')
  7735.                                         $joinAndString .= " and ";
  7736.                                     $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7737.                                 }
  7738.                             } else if ($ctype == 'not_in') {
  7739.                                 $joinAndString .= " ( ";
  7740.                                 if (in_array('null'$cvalue)) {
  7741.                                     $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  7742.                                     $cvalue array_diff($cvalue, ['null']);
  7743.                                     if (!empty($cvalue))
  7744.                                         $joinAndString .= " and ";
  7745.                                 }
  7746.                                 if (in_array(''$cvalue)) {
  7747.                                     $joinAndString .= "`$joinTableAlias`.$cfield != '' ";
  7748.                                     $cvalue array_diff($cvalue, ['']);
  7749.                                     if (!empty($cvalue))
  7750.                                         $joinAndString .= " and ";
  7751.                                 }
  7752.                                 $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7753.                             } else if ($ctype == 'in') {
  7754.                                 if (in_array('null'$cvalue)) {
  7755.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null";
  7756.                                     $cvalue array_diff($cvalue, ['null']);
  7757.                                     if (!empty($cvalue))
  7758.                                         $joinAndString .= " and ";
  7759.                                 }
  7760.                                 if (in_array(''$cvalue)) {
  7761.                                     $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  7762.                                     $cvalue array_diff($cvalue, ['']);
  7763.                                     if (!empty($cvalue))
  7764.                                         $joinAndString .= " and ";
  7765.                                 }
  7766.                                 $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7767.                             } else if ($ctype == '=') {
  7768. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7769. //                            $fullCfieldArray = explode('.', $cfield);
  7770. //                            $aliasInCondition = $fullCfieldArray[0];
  7771. //                            $cfield = $fullCfieldArray[1];
  7772. //                        }
  7773.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7774.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  7775.                                 else
  7776.                                     $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7777.                             } else if ($ctype == '!=') {
  7778.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7779.                                     $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  7780.                                 else
  7781.                                     $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7782.                             } else {
  7783.                                 if (is_string($cvalue))
  7784.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7785.                                 else
  7786.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7787.                             }
  7788.                         }
  7789.                     }
  7790. //            if ($joinAndString != '') {
  7791. //                if ($conditionStr != '')
  7792. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  7793. //                else
  7794. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  7795. //            }
  7796.                     if ($joinAndString != '') {
  7797.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7798.                             $joinQry .= ' and (';
  7799.                             $mustBracketDone 1;
  7800.                         }
  7801.                         if ($joinQry != '')
  7802.                             $joinQry .= (" and (" $joinAndString ") ");
  7803.                         else
  7804.                             $joinQry .= ("  (" $joinAndString ") ");
  7805.                     }
  7806.                     $joinAndOrString "";
  7807.                     foreach ($joinAndOrConditions as $andOrCondition) {
  7808. //            $conditionStr.=' 1=1 ';
  7809.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  7810.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  7811.                         $aliasInCondition $table;
  7812.                         if (!(strpos($cfield'.') === false)) {
  7813.                             $fullCfieldArray explode('.'$cfield);
  7814.                             $aliasInCondition $fullCfieldArray[0];
  7815.                             $cfield $fullCfieldArray[1];
  7816.                         }
  7817.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  7818.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7819.                             if ($joinAndOrString != '')
  7820.                                 $joinAndOrString .= " or ";
  7821.                             if ($ctype == 'like') {
  7822.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7823.                                 $wordsBySpaces explode(' '$cvalue);
  7824.                                 foreach ($wordsBySpaces as $word) {
  7825.                                     if ($joinAndOrString != '')
  7826.                                         $joinAndOrString .= " or ";
  7827.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7828.                                 }
  7829.                             } else if ($ctype == 'not like') {
  7830.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7831.                                 $wordsBySpaces explode(' '$cvalue);
  7832.                                 foreach ($wordsBySpaces as $word) {
  7833.                                     if ($joinAndOrString != '')
  7834.                                         $joinAndOrString .= " or ";
  7835.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7836.                                 }
  7837.                             } else if ($ctype == 'not_in') {
  7838.                                 $joinAndOrString .= " ( ";
  7839.                                 if (in_array('null'$cvalue)) {
  7840.                                     $joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
  7841.                                     $cvalue array_diff($cvalue, ['null']);
  7842.                                     if (!empty($cvalue))
  7843.                                         $joinAndOrString .= " or ";
  7844.                                 }
  7845.                                 if (in_array(''$cvalue)) {
  7846.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != '' ";
  7847.                                     $cvalue array_diff($cvalue, ['']);
  7848.                                     if (!empty($cvalue))
  7849.                                         $joinAndOrString .= " or ";
  7850.                                 }
  7851.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7852.                             } else if ($ctype == 'in') {
  7853.                                 if (in_array('null'$cvalue)) {
  7854.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null";
  7855.                                     $cvalue array_diff($cvalue, ['null']);
  7856.                                     if (!empty($cvalue))
  7857.                                         $joinAndOrString .= " or ";
  7858.                                 }
  7859.                                 if (in_array(''$cvalue)) {
  7860.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  7861.                                     $cvalue array_diff($cvalue, ['']);
  7862.                                     if (!empty($cvalue))
  7863.                                         $joinAndOrString .= " or ";
  7864.                                 }
  7865.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7866.                             } else if ($ctype == '=') {
  7867. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7868. //                            $fullCfieldArray = explode('.', $cfield);
  7869. //                            $aliasInCondition = $fullCfieldArray[0];
  7870. //                            $cfield = $fullCfieldArray[1];
  7871. //                        }
  7872.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7873.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
  7874.                                 else
  7875.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7876.                             } else if ($ctype == '!=') {
  7877.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7878.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
  7879.                                 else
  7880.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7881.                             } else {
  7882.                                 if (is_string($cvalue))
  7883.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7884.                                 else
  7885.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7886.                             }
  7887.                         }
  7888.                     }
  7889. //            if ($joinAndOrString != '')
  7890. //                $joinQry .= $joinAndOrString;
  7891.                     if ($joinAndOrString != '') {
  7892.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7893.                             $joinQry .= ' and (';
  7894.                             $mustBracketDone 1;
  7895.                         }
  7896.                         if ($joinQry != '')
  7897.                             $joinQry .= (" and (" $joinAndOrString ") ");
  7898.                         else
  7899.                             $joinQry .= ("  (" $joinAndOrString ") ");
  7900.                     }
  7901.                     //pika
  7902.                     $joinOrString "";
  7903.                     foreach ($joinOrConditions as $orCondition) {
  7904. //            $conditionStr.=' 1=1 ';
  7905.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  7906.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  7907.                         $aliasInCondition $table;
  7908.                         if (!(strpos($cfield'.') === false)) {
  7909.                             $fullCfieldArray explode('.'$cfield);
  7910.                             $aliasInCondition $fullCfieldArray[0];
  7911.                             $cfield $fullCfieldArray[1];
  7912.                         }
  7913.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  7914.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7915.                             if ($joinOrString != '' || $joinAndString != '' || $joinMustString != '')
  7916.                                 $joinOrString .= " or ";
  7917.                             if ($ctype == 'like') {
  7918.                                 $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7919.                                 $wordsBySpaces explode(' '$cvalue);
  7920.                                 foreach ($wordsBySpaces as $word) {
  7921.                                     if ($joinOrString != '')
  7922.                                         $joinOrString .= " or ";
  7923.                                     $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7924.                                 }
  7925.                             } else if ($ctype == 'not like') {
  7926.                                 $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7927.                                 $wordsBySpaces explode(' '$cvalue);
  7928.                                 foreach ($wordsBySpaces as $word) {
  7929.                                     if ($joinOrString != '')
  7930.                                         $joinOrString .= " or ";
  7931.                                     $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7932.                                 }
  7933.                             } else if ($ctype == 'not_in') {
  7934.                                 $joinOrString .= " ( ";
  7935.                                 if (in_array('null'$cvalue)) {
  7936.                                     $joinOrString .= " `$joinTableAlias`.$cfield is not null";
  7937.                                     $cvalue array_diff($cvalue, ['null']);
  7938.                                     if (!empty($cvalue))
  7939.                                         $joinOrString .= " or ";
  7940.                                 }
  7941.                                 if (in_array(''$cvalue)) {
  7942.                                     $joinOrString .= "`$joinTableAlias`.$cfield != '' ";
  7943.                                     $cvalue array_diff($cvalue, ['']);
  7944.                                     if (!empty($cvalue))
  7945.                                         $joinOrString .= " or ";
  7946.                                 }
  7947.                                 $joinOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7948.                             } else if ($ctype == 'in') {
  7949.                                 if (in_array('null'$cvalue)) {
  7950.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null";
  7951.                                     $cvalue array_diff($cvalue, ['null']);
  7952.                                     if (!empty($cvalue))
  7953.                                         $joinOrString .= " or ";
  7954.                                 }
  7955.                                 if (in_array(''$cvalue)) {
  7956.                                     $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  7957.                                     $cvalue array_diff($cvalue, ['']);
  7958.                                     if (!empty($cvalue))
  7959.                                         $joinOrString .= " or ";
  7960.                                 }
  7961.                                 $joinOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7962.                             } else if ($ctype == '=') {
  7963. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7964. //                            $fullCfieldArray = explode('.', $cfield);
  7965. //                            $aliasInCondition = $fullCfieldArray[0];
  7966. //                            $cfield = $fullCfieldArray[1];
  7967. //                        }
  7968.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7969.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null ";
  7970.                                 else
  7971.                                     $joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7972.                             } else if ($ctype == '!=') {
  7973.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7974.                                     $joinOrString .= "`$joinTableAlias`.$cfield is not null ";
  7975.                                 else
  7976.                                     $joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7977.                             } else {
  7978.                                 if (is_string($cvalue))
  7979.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7980.                                 else
  7981.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7982.                             }
  7983.                         }
  7984.                     }
  7985. //            if ($joinOrString != '')
  7986. //                $joinQry .= $joinOrString;
  7987.                     if ($joinOrString != '') {
  7988.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7989.                             $joinQry .= ' and (';
  7990.                             $mustBracketDone 1;
  7991.                         }
  7992.                         if ($joinQry != '')
  7993.                             $joinQry .= (" or (" $joinOrString ") ");
  7994.                         else
  7995.                             $joinQry .= ("  (" $joinOrString ") ");
  7996.                     }
  7997.                     if ($joinMustString != '' && $mustBracketDone == 1) {
  7998.                         $joinQry .= ' ) ';
  7999.                     }
  8000. //
  8001. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8002.                 }
  8003.                 $filterQryForCriteria .= $selectQry;
  8004.                 $filterQryForCriteria .= $joinQry;
  8005.                 if ($skipDefaultCompanyId == && $companyId != && !isset($dataConfig['entity_group']))
  8006.                     $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  8007.                 else
  8008.                     $filterQryForCriteria .= " where 1=1 ";
  8009.                 $conditionStr "";
  8010.                 $aliasInCondition $table;
  8011.                 if ($headMarkers != '' && $table == 'acc_accounts_head') {
  8012.                     $markerList explode(','$headMarkers);
  8013.                     $spMarkerQry "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
  8014.                     $markerPassedHeads = [];
  8015.                     foreach ($markerList as $mrkr) {
  8016.                         $spMarkerQry .= " and marker_hash like '%" $mrkr "%'";
  8017.                     }
  8018.                     $spStmt $em->getConnection()->prepare($spMarkerQry);
  8019.                     $spStmt->execute();
  8020.                     $spStmtResults $spStmt->fetchAll();
  8021.                     foreach ($spStmtResults as $ggres) {
  8022.                         $markerPassedHeads[] = $ggres['accounts_head_id'];
  8023.                     }
  8024.                     if (!empty($markerPassedHeads)) {
  8025.                         if ($conditionStr != '')
  8026.                             $conditionStr .= " and (";
  8027.                         else
  8028.                             $conditionStr .= " (";
  8029.                         if ($headMarkersStrictMatch != 1) {
  8030.                             foreach ($markerPassedHeads as $mh) {
  8031.                                 $conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" $mh "/%' or ";
  8032.                             }
  8033.                         }
  8034.                         $conditionStr .= "  `$aliasInCondition`.`accounts_head_id` in (" implode(','$markerPassedHeads) . ") ";
  8035.                         $conditionStr .= " )";
  8036.                     }
  8037.                 }
  8038.                 if (isset($restrictionData[$table])) {
  8039.                     $userRestrictionData Users::getUserApplicationAccessSettings($em$userId)['options'];
  8040.                     if (isset($userRestrictionData[$restrictionData[$table]])) {
  8041.                         $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  8042.                         if ($restrictionIdList == null)
  8043.                             $restrictionIdList = [];
  8044.                     }
  8045.                     if (!empty($restrictionIdList)) {
  8046.                         if ($conditionStr != '')
  8047.                             $conditionStr .= " and ";
  8048.                         $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  8049.                     }
  8050.                 }
  8051. //        $aliasInCondition = $table;
  8052.                 if (!empty($setValueArray) || $selectAll == 1) {
  8053.                     if (!empty($setValueArray)) {
  8054.                         if ($conditionStr != '')
  8055.                             $conditionStr .= " and ";
  8056.                         $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  8057.                     }
  8058.                 } else {
  8059.                     $andString '';
  8060.                     foreach ($andConditions as $andCondition) {
  8061. //            $conditionStr.=' 1=1 ';
  8062.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  8063.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  8064.                         $aliasInCondition $table;
  8065.                         if (!(strpos($cfield'.') === false)) {
  8066.                             $fullCfieldArray explode('.'$cfield);
  8067.                             $aliasInCondition $fullCfieldArray[0];
  8068.                             $cfield $fullCfieldArray[1];
  8069.                         }
  8070.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  8071.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8072.                             if ($andString != '')
  8073.                                 $andString .= " and ";
  8074.                             if ($ctype == 'like') {
  8075.                                 $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8076.                                 $wordsBySpaces explode(' '$cvalue);
  8077.                                 foreach ($wordsBySpaces as $word) {
  8078.                                     if ($andString != '')
  8079.                                         $andString .= " and ";
  8080.                                     $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8081.                                 }
  8082.                             } else if ($ctype == 'not like') {
  8083.                                 $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8084.                                 $wordsBySpaces explode(' '$cvalue);
  8085.                                 foreach ($wordsBySpaces as $word) {
  8086.                                     if ($andString != '')
  8087.                                         $andString .= " and ";
  8088.                                     $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8089.                                 }
  8090.                             } else if ($ctype == 'not_in') {
  8091.                                 $andString .= " ( ";
  8092.                                 if (in_array('null'$cvalue)) {
  8093.                                     $andString .= " `$aliasInCondition`.$cfield is not null";
  8094.                                     $cvalue array_diff($cvalue, ['null']);
  8095.                                     if (!empty($cvalue))
  8096.                                         $andString .= " and ";
  8097.                                 }
  8098.                                 if (in_array(''$cvalue)) {
  8099.                                     $andString .= "`$aliasInCondition`.$cfield != '' ";
  8100.                                     $cvalue array_diff($cvalue, ['']);
  8101.                                     if (!empty($cvalue))
  8102.                                         $andString .= " and ";
  8103.                                 }
  8104.                                 $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8105.                             } else if ($ctype == 'in') {
  8106.                                 if (in_array('null'$cvalue)) {
  8107.                                     $andString .= "`$aliasInCondition`.$cfield is null";
  8108.                                     $cvalue array_diff($cvalue, ['null']);
  8109.                                     if (!empty($cvalue))
  8110.                                         $andString .= " and ";
  8111.                                 }
  8112.                                 if (in_array(''$cvalue)) {
  8113.                                     $andString .= "`$aliasInCondition`.$cfield = '' ";
  8114.                                     $cvalue array_diff($cvalue, ['']);
  8115.                                     if (!empty($cvalue))
  8116.                                         $andString .= " and ";
  8117.                                 }
  8118.                                 $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  8119.                             } else if ($ctype == '=') {
  8120.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8121.                                     $andString .= "`$aliasInCondition`.$cfield is null ";
  8122.                                 else
  8123.                                     $andString .= "`$aliasInCondition`.$cfield = $cvalue ";
  8124.                             } else if ($ctype == '!=') {
  8125.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8126.                                     $andString .= "`$aliasInCondition`.$cfield is not null ";
  8127.                                 else
  8128.                                     $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8129.                             } else {
  8130.                                 if (is_string($cvalue))
  8131.                                     $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8132.                                 else
  8133.                                     $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8134.                             }
  8135.                         }
  8136.                     }
  8137.                     if ($andString != '') {
  8138.                         if ($conditionStr != '')
  8139.                             $conditionStr .= (" and (" $andString ") ");
  8140.                         else
  8141.                             $conditionStr .= ("  (" $andString ") ");
  8142.                     }
  8143.                     $orString '';
  8144.                     foreach ($orConditions as $orCondition) {
  8145.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  8146.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  8147.                         $aliasInCondition $table;
  8148.                         if (!(strpos($cfield'.') === false)) {
  8149.                             $fullCfieldArray explode('.'$cfield);
  8150.                             $aliasInCondition $fullCfieldArray[0];
  8151.                             $cfield $fullCfieldArray[1];
  8152.                         }
  8153.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  8154.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8155.                             if ($orString != '')
  8156.                                 $orString .= " or ";
  8157.                             if ($ctype == 'like') {
  8158.                                 $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8159.                                 $wordsBySpaces explode(' '$cvalue);
  8160.                                 foreach ($wordsBySpaces as $word) {
  8161.                                     if ($orString != '')
  8162.                                         $orString .= " or ";
  8163.                                     $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8164.                                 }
  8165.                             } else if ($ctype == 'not like') {
  8166.                                 $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8167.                                 $wordsBySpaces explode(' '$cvalue);
  8168.                                 foreach ($wordsBySpaces as $word) {
  8169.                                     if ($orString != '')
  8170.                                         $orString .= " or ";
  8171.                                     $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8172.                                 }
  8173.                             } else if ($ctype == 'not_in') {
  8174.                                 $orString .= " ( ";
  8175.                                 if (in_array('null'$cvalue)) {
  8176.                                     $orString .= " `$aliasInCondition`.$cfield is not null";
  8177.                                     $cvalue array_diff($cvalue, ['null']);
  8178.                                     if (!empty($cvalue))
  8179.                                         $orString .= " or ";
  8180.                                 }
  8181.                                 if (in_array(''$cvalue)) {
  8182.                                     $orString .= "`$aliasInCondition`.$cfield != '' ";
  8183.                                     $cvalue array_diff($cvalue, ['']);
  8184.                                     if (!empty($cvalue))
  8185.                                         $orString .= " or ";
  8186.                                 }
  8187.                                 $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8188.                             } else if ($ctype == 'in') {
  8189.                                 $orString .= " ( ";
  8190.                                 if (in_array('null'$cvalue)) {
  8191.                                     $orString .= " `$aliasInCondition`.$cfield is null";
  8192.                                     $cvalue array_diff($cvalue, ['null']);
  8193.                                     if (!empty($cvalue))
  8194.                                         $orString .= " or ";
  8195.                                 }
  8196.                                 if (in_array(''$cvalue)) {
  8197.                                     $orString .= "`$aliasInCondition`.$cfield = '' ";
  8198.                                     $cvalue array_diff($cvalue, ['']);
  8199.                                     if (!empty($cvalue))
  8200.                                         $orString .= " or ";
  8201.                                 }
  8202.                                 $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8203.                             } else if ($ctype == '=') {
  8204.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8205.                                     $orString .= "`$aliasInCondition`.$cfield is null ";
  8206.                                 else
  8207.                                     $orString .= "`$aliasInCondition`.$cfield = $cvalue ";
  8208.                             } else if ($ctype == '!=') {
  8209.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8210.                                     $orString .= "`$aliasInCondition`.$cfield is not null ";
  8211.                                 else
  8212.                                     $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8213.                             } else {
  8214.                                 if (is_string($cvalue))
  8215.                                     $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8216.                                 else
  8217.                                     $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8218.                             }
  8219.                         }
  8220.                     }
  8221.                     if ($orString != '') {
  8222.                         if ($conditionStr != '')
  8223.                             $conditionStr .= (" or (" $orString ") ");
  8224.                         else
  8225.                             $conditionStr .= ("  (" $orString ") ");
  8226.                     }
  8227.                     $andOrString '';
  8228.                     foreach ($andOrConditions as $andOrCondition) {
  8229.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  8230.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  8231.                         $aliasInCondition $table;
  8232.                         if (!(strpos($cfield'.') === false)) {
  8233.                             $fullCfieldArray explode('.'$cfield);
  8234.                             $aliasInCondition $fullCfieldArray[0];
  8235.                             $cfield $fullCfieldArray[1];
  8236.                         }
  8237.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  8238.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8239.                             if ($andOrString != '')
  8240.                                 $andOrString .= " or ";
  8241.                             if ($ctype == 'like') {
  8242.                                 $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8243.                                 $wordsBySpaces explode(' '$cvalue);
  8244.                                 foreach ($wordsBySpaces as $word) {
  8245.                                     if ($andOrString != '')
  8246.                                         $andOrString .= " or ";
  8247.                                     $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8248.                                 }
  8249.                             } else if ($ctype == 'not like') {
  8250.                                 $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8251.                                 $wordsBySpaces explode(' '$cvalue);
  8252.                                 foreach ($wordsBySpaces as $word) {
  8253.                                     if ($andOrString != '')
  8254.                                         $andOrString .= " or ";
  8255.                                     $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8256.                                 }
  8257.                             } else if ($ctype == 'in') {
  8258.                                 $andOrString .= " ( ";
  8259.                                 if (in_array('null'$cvalue)) {
  8260.                                     $andOrString .= " `$aliasInCondition`.$cfield is null";
  8261.                                     $cvalue array_diff($cvalue, ['null']);
  8262.                                     if (!empty($cvalue))
  8263.                                         $andOrString .= " or ";
  8264.                                 }
  8265.                                 if (in_array(''$cvalue)) {
  8266.                                     $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  8267.                                     $cvalue array_diff($cvalue, ['']);
  8268.                                     if (!empty($cvalue))
  8269.                                         $andOrString .= " or ";
  8270.                                 }
  8271.                                 if (!empty($cvalue))
  8272.                                     $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8273.                                 else
  8274.                                     $andOrString .= "  ) ";
  8275.                             } else if ($ctype == 'not_in') {
  8276.                                 $andOrString .= " ( ";
  8277.                                 if (in_array('null'$cvalue)) {
  8278.                                     $andOrString .= " `$aliasInCondition`.$cfield is not null";
  8279.                                     $cvalue array_diff($cvalue, ['null']);
  8280.                                     if (!empty($cvalue))
  8281.                                         $andOrString .= " or ";
  8282.                                 }
  8283.                                 if (in_array(''$cvalue)) {
  8284.                                     $andOrString .= "`$aliasInCondition`.$cfield != '' ";
  8285.                                     $cvalue array_diff($cvalue, ['']);
  8286.                                     if (!empty($cvalue))
  8287.                                         $andOrString .= " or ";
  8288.                                 }
  8289.                                 if (!empty($cvalue))
  8290.                                     $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8291.                                 else
  8292.                                     $andOrString .= "  ) ";
  8293.                             } else if ($ctype == '=') {
  8294.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8295.                                     $andOrString .= "`$aliasInCondition`.$cfield is null ";
  8296.                                 else
  8297.                                     $andOrString .= "`$aliasInCondition`.$cfield = $cvalue ";
  8298.                             } else if ($ctype == '!=') {
  8299.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8300.                                     $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  8301.                                 else
  8302.                                     $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8303.                             } else {
  8304.                                 if (is_string($cvalue))
  8305.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8306.                                 else
  8307.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8308.                             }
  8309.                         }
  8310.                     }
  8311.                     if ($andOrString != '') {
  8312.                         if ($conditionStr != '')
  8313.                             $conditionStr .= (" and (" $andOrString ") ");
  8314.                         else
  8315.                             $conditionStr .= ("  (" $andOrString ") ");
  8316.                     }
  8317.                 }
  8318.                 $mustStr '';
  8319. ///now must conditions
  8320.                 foreach ($mustConditions as $mustCondition) {
  8321. //            $conditionStr.=' 1=1 ';
  8322.                     $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  8323.                     $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  8324.                     $aliasInCondition $table;
  8325.                     if (!(strpos($cfield'.') === false)) {
  8326.                         $fullCfieldArray explode('.'$cfield);
  8327.                         $aliasInCondition $fullCfieldArray[0];
  8328.                         $cfield $fullCfieldArray[1];
  8329.                     }
  8330.                     $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  8331.                     if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8332.                         if ($mustStr != '')
  8333.                             $mustStr .= " and ";
  8334.                         if ($ctype == 'like') {
  8335.                             $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8336.                             $wordsBySpaces explode(' '$cvalue);
  8337.                             foreach ($wordsBySpaces as $word) {
  8338.                                 if ($mustStr != '')
  8339.                                     $mustStr .= " or ";
  8340.                                 $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8341.                             }
  8342.                             $mustStr .= " )";
  8343.                         } else if ($ctype == 'not like') {
  8344.                             $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8345.                             $wordsBySpaces explode(' '$cvalue);
  8346.                             foreach ($wordsBySpaces as $word) {
  8347.                                 if ($mustStr != '')
  8348.                                     $mustStr .= " and ";
  8349.                                 $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8350.                             }
  8351.                         } else if ($ctype == 'in') {
  8352.                             $mustStr .= " ( ";
  8353.                             if (in_array('null'$cvalue)) {
  8354.                                 $mustStr .= " `$aliasInCondition`.$cfield is null";
  8355.                                 $cvalue array_diff($cvalue, ['null']);
  8356.                                 if (!empty($cvalue))
  8357.                                     $mustStr .= " or ";
  8358.                             }
  8359.                             if (in_array(''$cvalue)) {
  8360.                                 $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  8361.                                 $cvalue array_diff($cvalue, ['']);
  8362.                                 if (!empty($cvalue))
  8363.                                     $mustStr .= " or ";
  8364.                             }
  8365.                             $mustStr .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8366.                         } else if ($ctype == 'not_in') {
  8367.                             $mustStr .= " ( ";
  8368.                             if (in_array('null'$cvalue)) {
  8369.                                 $mustStr .= " `$aliasInCondition`.$cfield is not null";
  8370.                                 $cvalue array_diff($cvalue, ['null']);
  8371.                                 if (!empty($cvalue))
  8372.                                     $mustStr .= " and ";
  8373.                             }
  8374.                             if (in_array(''$cvalue)) {
  8375.                                 $mustStr .= "`$aliasInCondition`.$cfield != '' ";
  8376.                                 $cvalue array_diff($cvalue, ['']);
  8377.                                 if (!empty($cvalue))
  8378.                                     $mustStr .= " and ";
  8379.                             }
  8380.                             $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8381.                         } else if ($ctype == '=') {
  8382.                             if ($cvalue == 'null' || $cvalue == 'Null')
  8383.                                 $mustStr .= "`$aliasInCondition`.$cfield is null ";
  8384.                             else
  8385.                                 $mustStr .= "`$aliasInCondition`.$cfield = $cvalue ";
  8386.                         } else if ($ctype == '!=') {
  8387.                             if ($cvalue == 'null' || $cvalue == 'Null')
  8388.                                 $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  8389.                             else
  8390.                                 $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  8391.                         } else {
  8392.                             if (is_string($cvalue))
  8393.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8394.                             else
  8395.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8396.                         }
  8397.                     }
  8398.                 }
  8399.                 if ($mustStr != '') {
  8400.                     if ($conditionStr != '')
  8401.                         $conditionStr .= (" and (" $mustStr ") ");
  8402.                     else
  8403.                         $conditionStr .= ("  (" $mustStr ") ");
  8404.                 }
  8405.                 if ($conditionStr != '')
  8406.                     $filterQryForCriteria .= (" and (" $conditionStr ") ");
  8407.                 if ($lastChildrenOnly == 1) {
  8408.                     if ($filterQryForCriteria != '')
  8409.                         $filterQryForCriteria .= ' and';
  8410.                     $filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  8411.                 } else if ($parentOnly == 1) {
  8412.                     if ($filterQryForCriteria != '')
  8413.                         $filterQryForCriteria .= ' and';
  8414.                     $filterQryForCriteria .= "`$table`.`$valueField`  in ( select distinct $parentIdField from  $table)";
  8415.                 }
  8416.                 if (!empty($orderByConditions)) {
  8417.                     $filterQryForCriteria .= "  order by ";
  8418.                     $fone 1;
  8419.                     foreach ($orderByConditions as $orderByCondition) {
  8420.                         if ($fone != 1) {
  8421.                             $filterQryForCriteria .= " , ";
  8422.                         }
  8423.                         if (isset($orderByCondition['valueList'])) {
  8424.                             if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  8425.                             if ($orderByCondition['valueList'] == null)
  8426.                                 $orderByCondition['valueList'] = [];
  8427.                             $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  8428.                         } else
  8429.                             $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  8430.                         $fone 0;
  8431.                     }
  8432.                 }
  8433.                 if ($returnTotalMatchedEntriesFlag == 1) {
  8434. //            $stmt = $em->getConnection()->prepare($get_kids_sql);
  8435. //            $stmt->execute();
  8436. //            $get_kids = $stmt->fetchAll();
  8437.                 }
  8438.                 if ($filterQryForCriteria != '')
  8439.                     if (!empty($setValueArray) || $selectAll == 1) {
  8440.                     } else {
  8441.                         if ($itemLimit != '_ALL_')
  8442.                             $filterQryForCriteria .= "  limit $offset$itemLimit ";
  8443.                         else
  8444.                             $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  8445.                     }
  8446.                 $get_kids_sql $filterQryForCriteria;
  8447.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  8448.                 $stmt->execute();
  8449.                 $get_kids $stmt->fetchAll();
  8450.                 $selectedId 0;
  8451.                 if ($table == 'warehouse_action') {
  8452.                     if (empty($get_kids)) {
  8453.                         $get_kids_sql_2 "select * from warehouse_action";
  8454.                         $stmt $em->getConnection()->prepare($get_kids_sql_2);
  8455.                         $stmt->execute();
  8456.                         $get_kids2 $stmt->fetchAll();
  8457.                         if (empty($get_kids2))
  8458.                             $get_kids GeneralConstant::$warehouse_action_list;
  8459.                     }
  8460.                 }
  8461.                 if (!empty($get_kids)) {
  8462.                     $nextOffset $offset count($get_kids);
  8463.                     $nextOffset++;
  8464.                     foreach ($get_kids as $pa) {
  8465.                         if (!empty($setValueArray) && $selectAll == 0) {
  8466.                             if (!in_array($pa[$valueField], $setValueArray))
  8467.                                 continue;
  8468.                         }
  8469.                         if (!empty($restrictionIdList)) {
  8470.                             if (!in_array($pa[$valueField], $restrictionIdList))
  8471.                                 continue;
  8472.                         }
  8473.                         if ($selectAll == 1) {
  8474.                             $setValueArray[] = $pa[$valueField];
  8475.                             $setValue $pa[$valueField];
  8476.                         } else if (count($get_kids) == && $setDataForSingle == 1) {
  8477.                             $setValueArray[] = $pa[$valueField];
  8478.                             $setValue $pa[$valueField];
  8479.                         }
  8480.                         if ($valueField != '')
  8481.                             $pa['value'] = $pa[$valueField];
  8482.                         $renderedText $renderTextFormat;
  8483.                         $compare_array = [];
  8484.                         if ($renderTextFormat != '') {
  8485.                             $renderedText $renderTextFormat;
  8486.                             $compare_arrayFull = [];
  8487.                             $compare_array = [];
  8488.                             $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  8489.                             );
  8490.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  8491.                             if (isset($compare_arrayFull[0]))
  8492.                                 $compare_array $compare_arrayFull[0];
  8493. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  8494.                             foreach ($compare_array as $cmpdt) {
  8495.                                 $tbr str_replace("__"""$cmpdt);
  8496.                                 if ($tbr != '') {
  8497.                                     if (isset($pa[$tbr])) {
  8498.                                         if ($pa[$tbr] == null)
  8499.                                             $renderedText str_replace($cmpdt''$renderedText);
  8500.                                         else
  8501.                                             $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  8502.                                     } else {
  8503.                                         $renderedText str_replace($cmpdt''$renderedText);
  8504.                                     }
  8505.                                 }
  8506.                             }
  8507.                         }
  8508.                         $pa['rendered_text'] = $renderedText;
  8509.                         $pa['text'] = ($textField != '' $pa[$textField] : '');
  8510. //                $pa['compare_array'] = $compare_array;
  8511.                         foreach ($convertToObjectFieldList as $convField) {
  8512.                             if (isset($pa[$convField])) {
  8513.                                 $taA json_decode($pa[$convField], true);
  8514.                                 if ($taA == null$taA = [];
  8515.                                 $pa[$convField] = $taA;
  8516.                             } else {
  8517.                                 $pa[$convField] = [];
  8518.                             }
  8519.                         }
  8520.                         foreach ($convertDateToStringFieldList as $convField) {
  8521.                             if (is_array($convField)) {
  8522.                                 $fld $convField['field'];
  8523.                                 $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  8524.                             } else {
  8525.                                 $fld $convField;
  8526.                                 $frmt 'Y-m-d H:i:s';
  8527.                             }
  8528.                             if (isset($pa[$fld])) {
  8529.                                 $taA = new \DateTime($pa[$fld]);
  8530.                                 $pa[$fld] = $taA->format($frmt);
  8531.                             }
  8532.                         }
  8533.                         foreach ($convertToUrl as $convField) {
  8534. //
  8535. //                            $fld = $convField;
  8536. //
  8537. //
  8538. //                            if (isset($pa[$fld])) {
  8539. //
  8540. //
  8541. //                                $pa[$fld] =
  8542. //                                    $this->generateUrl(
  8543. //                                        'dashboard', [
  8544. //
  8545. //                                    ], UrlGenerator::ABSOLUTE_URL
  8546. //                                    ).'/'.$pa[$fld];
  8547. //
  8548. //                            }
  8549.                         }
  8550.                         foreach ($fullPathList as $pathField) {
  8551.                             $fld $pathField;
  8552.                             if (isset($pa[$fld])) {
  8553.                             if ($pa[$fld] !='' && $pa[$fld] !=null) {
  8554.                                 $pa[$fld]=($this->generateUrl(
  8555.                                     'dashboard', [
  8556.                                 ], UrlGenerator::ABSOLUTE_URL
  8557.                                 ).$pa[$fld]);
  8558.                             }
  8559.                             }
  8560.                         }
  8561.                         $pa['currentTs'] = (new \Datetime())->format('U');
  8562.                         $data[] = $pa;
  8563.                         if ($valueField != '') {
  8564.                             $data_by_id[$pa[$valueField]] = $pa;
  8565.                             $selectedId $pa[$valueField];
  8566.                         }
  8567.                     }
  8568.                 }
  8569.                 $lastResult = array(
  8570.                     'success' => true,
  8571.                     'data' => $data,
  8572.                     'tableName' => $table,
  8573.                     'setValue' => $setValue,
  8574.                     'currentTs' => (new \Datetime())->format('U'),
  8575.                     'restrictionIdList' => $restrictionIdList,
  8576.                     'andConditions' => $andConditions,
  8577.                     'queryStr' => $queryStringIndividual,
  8578.                     'isMultiple' => $isMultiple,
  8579.                     'nextOffset' => $nextOffset,
  8580.                     'totalMatchedEntries' => $totalMatchedEntries,
  8581.                     'selectorId' => $selectorId,
  8582.                     'setValueArray' => $setValueArray,
  8583.                     'silentChangeSelectize' => $silentChangeSelectize,
  8584.                     'convertToObjectFieldList' => $convertToObjectFieldList,
  8585.                     'conditionStr' => $conditionStr,
  8586. //                    'andStr' => $andString,
  8587. //                    'andOrStr' => $andOrString,
  8588.                     'dataById' => $data_by_id,
  8589.                     'selectedId' => $selectedId,
  8590.                     'dataId' => $dataId,
  8591.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8592.                 );
  8593.             }
  8594.             $allResult[] = $lastResult;
  8595.         }
  8596.         if ($isSingleDataset == 1)
  8597.             return new JsonResponse($lastResult);
  8598.         else
  8599.             return new JsonResponse($allResult);
  8600.     }
  8601.     public function updatePlanningItemSequenceAction(Request $request$queryStr '')
  8602.     {
  8603.         $em $this->getDoctrine()->getManager();
  8604.         $stmt $em->getConnection()->prepare("select  `id` , parent_id, sequence from planning_item where sequence is null 
  8605.             ORDER BY parent_id ASC, id ASC
  8606.                         ");
  8607.         $stmt->execute();
  8608.         $query_output $stmt->fetchAll();
  8609.         foreach ($query_output as $dupe) {
  8610.             System::updatePlanningItemSequence($em$dupe["id"]);
  8611.         }
  8612.         System::updatePlanningItemSequence(
  8613.             $em,
  8614.             $request->request->get('planningItemId'0),
  8615.             $request->request->get('assignType''_ASSIGN_')   ///can be _MOVE_UP_ or _MOVE_DOWN_
  8616.         );
  8617. //        if($request->query->has('returnJson'))
  8618.         return new JsonResponse(
  8619.             array(
  8620.                 'success' => true,
  8621.                 'data' => [],
  8622.             )
  8623.         );
  8624.     }
  8625.     public function insertDataAjaxAction(Request $request$queryStr '')
  8626.     {
  8627.         $em $this->getDoctrine()->getManager();
  8628. //        if($request->query->has('big_data_test'))
  8629. //        {
  8630. //            for($t=0;$t<$request->request->get('big_data_test',10000);$t++) {
  8631. //                $em = $this->getDoctrine()->getManager('company_group');
  8632. //                $NOTIFICATION = new EntityNotification();
  8633. //                $NOTIFICATION->setAppId(1);
  8634. //                $NOTIFICATION->setCompanyId(0);
  8635. //                $NOTIFICATION->setCompanyId(0);
  8636. //                $NOTIFICATION->setBody('Test Description'.$t);
  8637. //                $NOTIFICATION->setTitle('Test Title'.$t);
  8638. //                $NOTIFICATION->setExpireTs(0);
  8639. //                $NOTIFICATION->setIsBuddybee(0);
  8640. //                $NOTIFICATION->setType(0);
  8641. //                $em->persist($NOTIFICATION);
  8642. //                $em->flush();
  8643. //            }
  8644. //
  8645. //            return new JsonResponse(
  8646. //                array(
  8647. //                    'success' => true,
  8648. //                    'data' => [],
  8649. //
  8650. //
  8651. //                )
  8652. //            );
  8653. //
  8654. //
  8655. //        }
  8656.         if ($request->request->get('entity_group'0)) {
  8657.             $companyId 0;
  8658.             $em $this->getDoctrine()->getManager('company_group');
  8659.         } else
  8660.             $companyId $this->getLoggedUserCompanyId($request);
  8661.         if ($companyId) {
  8662.             $company_data = [];
  8663. //            $company_data = Company::getCompanyData($em, $companyId);
  8664.         } else {
  8665.             $companyId 0;
  8666.             $company_data = [];
  8667.         }
  8668. //        $theEntity= new EntityNotification();
  8669. //        $entityName = 'EntityNotification';
  8670. //
  8671. //        $className='\\CompanyGroupBundle\\Entity\\'.$entityName;
  8672. //
  8673. //
  8674. //            $theEntity= new $className();
  8675.         $dataToAdd $request->request->has('dataToAdd') ? $request->request->get('dataToAdd') : [];
  8676.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8677.         if ($dataToAdd == null$dataToAdd = [];
  8678.         $dataToRemove $request->request->has('dataToRemove') ? $request->request->get('dataToRemove') : [];
  8679.         if (is_string($dataToRemove)) $dataToAdd json_decode($dataToRemovetrue);
  8680.         if ($dataToRemove == null$dataToRemove = [];
  8681.         $relData = [];
  8682.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8683.         $updatedDataList = [];
  8684.         foreach ($dataToAdd as $dataInd => $dat) {
  8685.             $entityName $dat['entityName'];
  8686.             $idField $dat['idField'];
  8687.             $findByField = isset($dat['findByField']) ? $dat['findByField'] : '';
  8688.             $findByValue = isset($dat['findByValue']) ? $dat['findByValue'] : '';
  8689.             $returnRefIndex $dat['returnRefIndex'];
  8690.             $findById $dat['findId'];
  8691.             $dataFields = isset($dat['dataFields']) ? $dat['dataFields'] : [];
  8692.             $noCreation = isset($dat['noCreation']) ? $dat['noCreation'] : 0;
  8693.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  8694.             $preAdditionalSql = isset($dat['preAdditionalSql']) ? $dat['preAdditionalSql'] : '';
  8695.             if ($preAdditionalSql != '') {
  8696. //            if ($entityName == 'PlanningItem') {
  8697. //
  8698. //                $stmt='select disctinct parent_id from planning_item;';
  8699. //                $stmt->execute();
  8700. //                $get_kids = $stmt->fetchAll();
  8701. //                $p_ids=[];
  8702. //                foreach($get_kids as $g)
  8703. //                {
  8704. //                    $p_ids[]=$g['parent_id'];
  8705. //                }
  8706. //
  8707. //
  8708. //
  8709.                 $stmt $em->getConnection()->prepare($preAdditionalSql);
  8710.                 $stmt->execute();
  8711.                 $stmt->closeCursor();
  8712. //
  8713. //
  8714.             }
  8715.             if ($entityName == 'PlanningItem') {
  8716.                 $stmt $em->getConnection()->prepare("select  `id` , parent_id, sequence from planning_item where sequence is null
  8717.             ORDER BY parent_id ASC, id ASC
  8718.                         ");
  8719.                 $stmt->execute();
  8720.                 $query_output $stmt->fetchAll();
  8721.                 foreach ($query_output as $dupe) {
  8722.                     System::updatePlanningItemSequence($em$dupe["id"]);
  8723.                 }
  8724.             }
  8725.             $className = ($request->request->get('entity_group'0) ? '\\CompanyGroupBundle\\Entity\\' '\\ApplicationBundle\\Entity\\') . $entityName;
  8726.             if (
  8727.                 ($findById == || $findById == '_NA_') && $findByField == '' && $noCreation == 0
  8728.             ) {
  8729.                 $theEntity = new $className();
  8730. //                $theEntity= new EntityNotification();
  8731.             } else {
  8732.                 if ($findByField != '') {
  8733.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findOneBy(
  8734.                         array
  8735.                         (
  8736.                             $findByField => $findByValue,
  8737.                         )
  8738.                     );
  8739.                 } else {
  8740.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findOneBy(
  8741.                         array
  8742.                         (
  8743.                             $idField => $findById,
  8744.                         )
  8745.                     );
  8746.                 }
  8747.             }
  8748.             if (!$theEntity && $noCreation == 0)
  8749.                 $theEntity = new $className();
  8750.             foreach ($dataFields as $dt) {
  8751.                 $setMethod 'set' ucfirst($dt['field']);
  8752.                 $getMethod 'get' ucfirst($dt['field']);
  8753.                 $type = isset($dt['type']) ? $dt['type'] : '_VALUE_';
  8754.                 $action = isset($dt['action']) ? $dt['action'] : '_REPLACE_';
  8755.                 if (method_exists($theEntity$setMethod)) {
  8756.                     $oldValue $theEntity->{$getMethod}();
  8757.                     $newValue $oldValue;
  8758.                     if ($type == '_VALUE_') {
  8759.                         $newValue $dt['value'];
  8760.                     }
  8761.                     if ($type == '_DECIMAL_') {
  8762.                         $newValue $dt['value'];
  8763.                     }
  8764.                     if ($type == '_DATE_') {
  8765.                         $newValue = new \DateTime($dt['value']);
  8766.                     }
  8767.                     if ($type == '_ARRAY_') {
  8768.                         $oldValue json_decode($oldValue);
  8769.                         if ($oldValue == null$oldValue = [];
  8770.                         if ($action == '_REPLACE_') {
  8771.                             $newValue json_encode($dt['value']);
  8772.                         }
  8773.                         if ($action == '_APPEND_') {
  8774.                             $newValue array_merge($oldValuearray_values(array_diff([$dt['value']], $oldValue)));
  8775.                         }
  8776.                         if ($action == '_MERGE_') {
  8777.                             $newValue array_merge($oldValuearray_values(array_diff($dt['value'], $oldValue)));
  8778.                         }
  8779.                         if ($action == '_EXCLUDE_') {
  8780.                             $newValue array_values(array_diff($oldValue, [$dt['value']]));
  8781.                         }
  8782.                         if ($action == '_EXCLUDE_ARRAY_') {
  8783.                             $newValue array_values(array_diff($oldValue$dt['value']));
  8784.                         }
  8785.                         $newValue json_encode($newValue);
  8786.                     }
  8787.                     $theEntity->{$setMethod}($newValue); // `foo!`
  8788. //                    $theEntity->setCompletionPercentage(78); // `foo!`
  8789.                 }
  8790.             }
  8791.             if ($additionalSql != '') {
  8792. //            if ($entityName == 'PlanningItem') {
  8793. //
  8794. //                $stmt='select disctinct parent_id from planning_item;';
  8795. //                $stmt->execute();
  8796. //                $get_kids = $stmt->fetchAll();
  8797. //                $p_ids=[];
  8798. //                foreach($get_kids as $g)
  8799. //                {
  8800. //                    $p_ids[]=$g['parent_id'];
  8801. //                }
  8802. //
  8803. //
  8804. //
  8805.                 $stmt $em->getConnection()->prepare($additionalSql);
  8806.                 $stmt->execute();
  8807.                 $stmt->closeCursor();
  8808. //
  8809. //
  8810.             }
  8811.             if (($findById == || $findById == '_NA_') && $noCreation == 0) {
  8812.                 $em->persist($theEntity);
  8813.                 $em->flush();
  8814.                 $getMethod 'get' ucfirst($idField);
  8815.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8816.             } else if ($theEntity) {
  8817.                 $em->flush();
  8818.                 $getMethod 'get' ucfirst($idField);
  8819.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8820.             }
  8821.             if ($entityName == 'PlanningItem') {
  8822.                 $stmt $em->getConnection()->prepare('select distinct parent_id from planning_item;');
  8823.                 $stmt->execute();
  8824.                 $get_kids $stmt->fetchAll();
  8825.                 $p_ids = [];
  8826.                 foreach ($get_kids as $g) {
  8827.                     $p_ids[] = $g['parent_id'];
  8828.                 }
  8829.                 $stmt $em->getConnection()->prepare('UPDATE planning_item d SET d.`has_child` =0 WHERE d.id NOT IN (' implode(','$p_ids) . '); 
  8830.                           UPDATE planning_item d SET d.`has_child` =1 WHERE d.id  IN (' implode(','$p_ids) . ')');
  8831.                 $stmt->execute();
  8832.                 $stmt->closeCursor();
  8833.                 $updatedData System::updatePlanningItemSequence($em$theEntity->getId());
  8834.                 $theEntity $updatedData['primaryOne'];
  8835.                 $theEntityUpdated $theEntity;
  8836.                 if ($theEntityUpdated->getEntryType() == 4)///cashflow
  8837.                 {
  8838.                     MiscActions::AddCashFlowProjection($em0, [
  8839.                         'planningItemId' => $theEntityUpdated->getId(),
  8840.                         'fundRequisitionId' => 0,
  8841.                         'concernedPersonId' => 0,
  8842.                         'type' => 1//exp
  8843.                         'subType' => 1//1== khoroch hobe 2: ashbe
  8844.                         'cashFlowType' => 1//2== RCV /in  1: Payment/out
  8845.                         'creationType' => 1//auto
  8846.                         'amountType' => 1//fund
  8847.                         'cashFlowAmount' => 0,
  8848.                         'expAstAmount' => 0,
  8849.                         'accumulatedCashFlowAmount' => 0,
  8850.                         'accumulatedCashFlowBalance' => 0,
  8851.                         'accumulatedExpAstAmount' => 0,
  8852.                         'relevantExpAstHeadId' => 0,
  8853.                         'balancingHeadId' => 0,
  8854.                         'cashFlowHeadId' => 0,
  8855.                         'cashFlowHeadType' => 1,
  8856.                         'relevantProductIds' => [],
  8857.                         'reminderDateTs' => 0,
  8858.                         'cashFlowDateTs' => 0,
  8859.                         'expAstRealizationDateTs' => 0,
  8860.                     ]);
  8861.                 }
  8862.             } else if ($entityName == 'TaskLog') {
  8863.                 $session $request->getSession();
  8864.                 if ($theEntity) {
  8865.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  8866.                     $currTime = new \DateTime();
  8867.                     $options = array(
  8868.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8869.                         'notification_server' => $this->container->getParameter('notification_server'),
  8870.                     );
  8871.                     $positionsArray = [
  8872.                         array(
  8873.                             'employeeId' => $empId,
  8874.                             'userId' => $session->get(UserConstants::USER_ID0),
  8875.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  8876.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  8877.                             'lat' => 23.8623834,
  8878.                             'lng' => 90.3979294,
  8879.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING,
  8880. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  8881.                         )
  8882.                     ];
  8883.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  8884.                     if ($positionsArray == null$positionsArray = [];
  8885.                     $dataByAttId = [];
  8886.                     $workPlaceType '_UNSET_';
  8887.                     foreach ($positionsArray as $findex => $d) {
  8888.                         $sysUserId 0;
  8889.                         $userId 0;
  8890.                         $empId 0;
  8891.                         $dtTs 0;
  8892.                         $timeZoneStr '+0000';
  8893.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  8894.                         if (isset($d['userId'])) $userId $d['userId'];
  8895.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  8896.                         if (isset($d['tsMilSec'])) {
  8897.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  8898.                         }
  8899.                         if ($dtTs == 0) {
  8900.                             $currTsTime = new \DateTime();
  8901.                             $dtTs $currTsTime->format('U');
  8902.                         } else {
  8903.                             $currTsTime = new \DateTime('@' $dtTs);
  8904.                         }
  8905.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  8906.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  8907.                         $EmployeeAttendance $this->getDoctrine()
  8908.                             ->getRepository(EmployeeAttendance::class)
  8909.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  8910.                         if (!$EmployeeAttendance) {
  8911.                             $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8912.                             $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8913.                             $EmployeeAttendance = new EmployeeAttendance;
  8914.                         } else {
  8915.                             if ($EmployeeAttendance->getCurrentLocation() == 'out') {
  8916.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8917.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8918.                             } else {
  8919.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8920.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8921.                             }
  8922.                         }
  8923.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  8924.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  8925.                             $workPlaceType '_STATIC_';
  8926.                         }
  8927.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  8928.                             $dataByAttId[$attendanceInfo->getId()] = array(
  8929.                                 'attendanceInfo' => $attendanceInfo,
  8930.                                 'empId' => $empId,
  8931.                                 'lat' => 0,
  8932.                                 'lng' => 0,
  8933.                                 'address' => 0,
  8934.                                 'sysUserId' => $sysUserId,
  8935.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8936.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8937.                                 'positionArray' => []
  8938.                             );
  8939.                         $posData = array(
  8940.                             'ts' => $dtTs,
  8941.                             'lat' => $d['lat'],
  8942.                             'lng' => $d['lng'],
  8943.                             'marker' => $d['markerId'],
  8944.                             'src' => 2,
  8945.                         );
  8946.                         $posDataArray = array(
  8947.                             $dtTs,
  8948.                             $d['lat'],
  8949.                             $d['lng'],
  8950.                             $d['markerId'],
  8951.                             2
  8952.                         );
  8953.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  8954.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  8955.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  8956.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  8957.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  8958.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  8959.                         if (isset($d['address']))
  8960.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  8961. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  8962.                     }
  8963.                     $response = array(
  8964.                         'success' => true,
  8965.                     );
  8966.                     foreach ($dataByAttId as $attInfoId => $d) {
  8967.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  8968.                             $d['empId'],
  8969.                             $d['sysUserId'],
  8970.                             $d['companyId'],
  8971.                             $d['appId'],
  8972.                             $request,
  8973.                             $d['attendanceInfo'],
  8974.                             $options,
  8975.                             $d['positionArray'],
  8976.                             $d['lat'],
  8977.                             $d['lng'],
  8978.                             $d['address'],
  8979.                             $d['markerId']
  8980.                         );
  8981.                     }
  8982.                     $session->set(UserConstants::USER_CURRENT_TASK_ID$theEntity->getId());
  8983.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$theEntity->getPlanningItemId());
  8984.                 } else {
  8985.                     $session->set(UserConstants::USER_CURRENT_TASK_ID0);
  8986.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID0);
  8987.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  8988.                     $currTime = new \DateTime();
  8989.                     $options = array(
  8990.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8991.                         'notification_server' => $this->container->getParameter('notification_server'),
  8992.                     );
  8993.                     $positionsArray = [
  8994.                         array(
  8995.                             'employeeId' => $empId,
  8996.                             'userId' => $session->get(UserConstants::USER_ID0),
  8997.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  8998.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  8999.                             'lat' => 23.8623834,
  9000.                             'lng' => 90.3979294,
  9001.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT,
  9002. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  9003.                         )
  9004.                     ];
  9005.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  9006.                     if ($positionsArray == null$positionsArray = [];
  9007.                     $dataByAttId = [];
  9008.                     $workPlaceType '_UNSET_';
  9009.                     foreach ($positionsArray as $findex => $d) {
  9010.                         $sysUserId 0;
  9011.                         $userId 0;
  9012.                         $empId 0;
  9013.                         $dtTs 0;
  9014.                         $timeZoneStr '+0000';
  9015.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  9016.                         if (isset($d['userId'])) $userId $d['userId'];
  9017.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  9018.                         if (isset($d['tsMilSec'])) {
  9019.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  9020.                         }
  9021.                         if ($dtTs == 0) {
  9022.                             $currTsTime = new \DateTime();
  9023.                             $dtTs $currTsTime->format('U');
  9024.                         } else {
  9025.                             $currTsTime = new \DateTime('@' $dtTs);
  9026.                         }
  9027.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  9028.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  9029.                         $EmployeeAttendance $this->getDoctrine()
  9030.                             ->getRepository(EmployeeAttendance::class)
  9031.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  9032.                         if (!$EmployeeAttendance) {
  9033.                             continue;
  9034.                         } else {
  9035.                         }
  9036.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  9037.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT) {
  9038.                             $workPlaceType '_STATIC_';
  9039.                         }
  9040.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  9041.                             $dataByAttId[$attendanceInfo->getId()] = array(
  9042.                                 'attendanceInfo' => $attendanceInfo,
  9043.                                 'empId' => $empId,
  9044.                                 'lat' => 0,
  9045.                                 'lng' => 0,
  9046.                                 'address' => 0,
  9047.                                 'sysUserId' => $sysUserId,
  9048.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  9049.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  9050.                                 'positionArray' => []
  9051.                             );
  9052.                         $posData = array(
  9053.                             'ts' => $dtTs,
  9054.                             'lat' => $d['lat'],
  9055.                             'lng' => $d['lng'],
  9056.                             'marker' => $d['markerId'],
  9057.                             'src' => 2,
  9058.                         );
  9059.                         $posDataArray = array(
  9060.                             $dtTs,
  9061.                             $d['lat'],
  9062.                             $d['lng'],
  9063.                             $d['markerId'],
  9064.                             2
  9065.                         );
  9066.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  9067.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  9068.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  9069.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  9070.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  9071.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  9072.                         if (isset($d['address']))
  9073.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  9074. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  9075.                     }
  9076.                     $response = array(
  9077.                         'success' => true,
  9078.                     );
  9079.                     foreach ($dataByAttId as $attInfoId => $d) {
  9080.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  9081.                             $d['empId'],
  9082.                             $d['sysUserId'],
  9083.                             $d['companyId'],
  9084.                             $d['appId'],
  9085.                             $request,
  9086.                             $d['attendanceInfo'],
  9087.                             $options,
  9088.                             $d['positionArray'],
  9089.                             $d['lat'],
  9090.                             $d['lng'],
  9091.                             $d['address'],
  9092.                             $d['markerId']
  9093.                         );
  9094.                     }
  9095.                 }
  9096.                 $theEntityUpdated $theEntity;
  9097.             } else
  9098.                 $theEntityUpdated $theEntity;
  9099. //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  9100.             $getters = [];
  9101.             if ($theEntityUpdated)
  9102.                 $getters array_filter(get_class_methods($theEntityUpdated), function ($method) {
  9103.                     return 'get' === substr($method03);
  9104.                 });
  9105.             $updatedData = [];
  9106.             foreach ($getters as $getter) {
  9107.                 $indForThis str_replace('get'''$getter);
  9108.                 $indForThis lcfirst($indForThis);
  9109.                 $updatedData[$indForThis] = $theEntityUpdated->{$getter}();
  9110.             }
  9111.             $updatedDataList[$dataInd] = $updatedData;
  9112.         }
  9113.         foreach ($dataToRemove as $dataInd => $dat) {
  9114.             $entityName $dat['entityName'];
  9115.             $idField $dat['idField'];
  9116.             $findById $dat['findId'];
  9117.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  9118.             $theEntityList $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findBy(
  9119.                 array
  9120.                 (
  9121.                     $idField => $findById,
  9122.                 )
  9123.             );
  9124.             foreach ($theEntityList as $dt) {
  9125.                 $em->remove($dt);
  9126.                 $em->flush();
  9127.             }
  9128.             if ($additionalSql != '') {
  9129. //            if ($entityName == 'PlanningItem') {
  9130. //
  9131. //                $stmt='select disctinct parent_id from planning_item;';
  9132. //                $stmt->execute();
  9133. //                $get_kids = $stmt->fetchAll();
  9134. //                $p_ids=[];
  9135. //                foreach($get_kids as $g)
  9136. //                {
  9137. //                    $p_ids[]=$g['parent_id'];
  9138. //                }
  9139. //
  9140. //
  9141. //
  9142.                 $stmt $em->getConnection()->prepare($additionalSql);
  9143.                 $stmt->execute();
  9144.                 $stmt->closeCursor();
  9145. //
  9146. //
  9147.             }
  9148.             $updatedDataList[$dataInd] = [];
  9149.         }
  9150. //        if ($table == '') {
  9151. //            return new JsonResponse(
  9152. //                array(
  9153. //                    'success' => false,
  9154. ////                    'page_title' => 'Product Details',
  9155. ////                    'company_data' => $company_data,
  9156. //                    'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9157. //
  9158. //                )
  9159. //            );
  9160. //        }
  9161. //        if($request->query->has('returnJson'))
  9162.         return new JsonResponse(
  9163.             array(
  9164.                 'success' => true,
  9165.                 'data' => $relData,
  9166.                 'updatedDataList' => $updatedDataList,
  9167.             )
  9168.         );
  9169.     }
  9170.     public function GetAvailableQtyAction(Request $request$id 0)
  9171.     {
  9172.         $em $this->getDoctrine()->getManager();
  9173.         $productId $request->request->has('productId') ? $request->request->get('productId') : 0;
  9174.         $colorId $request->request->has('colorId') ? $request->request->get('colorId') : 0;
  9175.         $dataId $request->request->has('dataId') ? $request->request->get('dataId') : 0;
  9176.         $allowedWarehouseIds $request->request->has('warehouseId') ? [$request->request->get('warehouseId')] : [];
  9177.         $allowedWarehouseActionIds $request->request->has('warehouseActionId') ? [$request->request->get('warehouseActionId')] : [];
  9178.         $qty Inventory::getProductQty($em$productId$allowedWarehouseIds$allowedWarehouseActionIds$colorId);
  9179.         return new JsonResponse(array("success" => true,
  9180.             "qty" => $qty,
  9181.             "dataId" => $dataId,
  9182.         ));
  9183.     }
  9184.     public
  9185.     function ProductListSelectAjaxAction(Request $request$queryStr '')
  9186.     {
  9187.         $em $this->getDoctrine()->getManager();
  9188.         $companyId $this->getLoggedUserCompanyId($request);
  9189.         $company_data Company::getCompanyData($em$companyId);
  9190.         $data = [];
  9191.         $data_by_id = [];
  9192.         $html '';
  9193.         $productByCodeData = [];
  9194.         if ($queryStr == '_EMPTY_')
  9195.             $queryStr '';
  9196.         if ($request->request->has('query') && $queryStr == '')
  9197.             $queryStr $request->request->get('queryStr');
  9198.         if ($queryStr == '_EMPTY_')
  9199.             $queryStr '';
  9200. //        $queryStr=urldecode($queryStr);
  9201.         $queryStr str_replace('_FSLASH_''/'$queryStr);
  9202.         $filterQryForCriteria "select * from inv_products where 1=1 ";
  9203.         if ($request->request->has('sellableOnly') && $request->request->get('sellableOnly') != 0)
  9204.             $filterQryForCriteria .= " and sellable=1";
  9205.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9206.             $filterQryForCriteria .= " and sub_category_id=" $request->request->get('subCategoryId');
  9207.         else if ($request->request->has('categoryId') && $request->request->get('categoryId') != '')
  9208.             $filterQryForCriteria .= " and category_id=" $request->request->get('categoryId');
  9209.         else if ($request->request->has('igId') && $request->request->get('igId') != '')
  9210.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  9211.         if ($request->request->has('brandId') && $request->request->get('brandId') != '')
  9212.             $filterQryForCriteria .= " and brand_company=" $request->request->get('brandId');
  9213.         if ($request->request->has('restrictedBrandIds') && $request->request->get('restrictedBrandIds') != [])
  9214.             $filterQryForCriteria .= " and brand_company in (" implode(','$request->request->get('restrictedBrandIds')) . ")";
  9215.         if ($request->request->has('productIds'))
  9216.             $filterQryForCriteria .= " and id in (" implode(','$request->request->get('productIds')) . ") ";
  9217.         else if ($request->request->has('productCode'))
  9218.             $filterQryForCriteria .= " and product_code  like '%" $request->request->get('productCode') . "%'  ";
  9219.         else if ($queryStr != '')
  9220.             $filterQryForCriteria .= " and  (product_code  like '%" $queryStr "%' or `name`   like '%" $queryStr "%' or model_no like '%" $queryStr "%') ";
  9221.         if ($filterQryForCriteria != '')
  9222.             $filterQryForCriteria .= "  limit 25";
  9223.         $get_kids_sql $filterQryForCriteria;
  9224. //        if ($request->request->has('productIds'))
  9225. //
  9226. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9227. //        else if ($request->request->has('productCode'))
  9228. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9229. //        else if ($filterQryForCriteria!='')
  9230. //            $get_kids_sql = $filterQryForCriteria;
  9231. //
  9232. //        else
  9233. //               $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";
  9234.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9235.         $stmt->execute();
  9236.         $get_kids $stmt->fetchAll();
  9237.         $productId 0;
  9238.         if (!empty($get_kids)) {
  9239.             foreach ($get_kids as $product) {
  9240.                 $pa = array();
  9241.                 $pa['id'] = $product['id'];
  9242.                 $pa['name'] = $product['name'];
  9243.                 $pa['id_name'] = $product['id'] . '. ' $product['name'];
  9244.                 $pa['id_mn'] = $product['id'] . '. ' $product['model_no'];;
  9245.                 $pa['id_name_mn'] = $product['id'] . '. ' $product['name'] . ' ( ' $product['model_no'] . ' )';
  9246.                 $pa['globalId'] = $product['global_id'];
  9247.                 $pa['classSuffix'] = $product['class_suffix'];
  9248.                 $pa['productFdm'] = $product['product_fdm'];
  9249.                 $pa['modelNo'] = $product['model_no'];
  9250.                 $pa['partId'] = $product['part_id'];
  9251.                 $pa['hsCode'] = $product['hs_code'];
  9252.                 $pa['productCode'] = $product['product_code'];
  9253.                 $pa['text'] = $product['name'];
  9254.                 $pa['value'] = $product['id'];
  9255.                 $pa['tac'] = $product['tac'];
  9256.                 $pa['igId'] = $product['ig_id'];
  9257.                 $pa['categoryId'] = $product['category_id'];
  9258.                 $pa['subCategoryId'] = $product['sub_category_id'];
  9259.                 $pa['brandCompany'] = $product['brand_company'];
  9260.                 $pa['sales_price'] = $product['curr_sales_price'];
  9261.                 $pa['purchase_price'] = $product['curr_purchase_price'];
  9262.                 $pa['unit_type'] = $product['unit_type_id'];
  9263.                 $pa['single_weight'] = $product['single_weight'];
  9264.                 $pa['single_weight_variance_type'] = $product['single_weight_variance_type'];
  9265.                 $pa['single_weight_variance_value'] = $product['single_weight_variance_value'];
  9266.                 $pa['weight'] = $product['weight'];
  9267.                 $pa['weight_variance_type'] = $product['weight_variance_type'];
  9268.                 $pa['weight_variance_value'] = $product['weight_variance_value'];
  9269.                 $pa['carton_capacity_count'] = $product['carton_capacity_count'];
  9270.                 $pa['type'] = $product['type'];
  9271.                 $pa['qty'] = $product['qty'];
  9272. //                $pa['alias'] = '';
  9273.                 $pa['alias'] = $product['alias'];
  9274.                 $pa['note'] = $product['note'];
  9275.                 $pa['defaultTaxConfigId'] = $product['default_tax_config_id'] == null $product['default_tax_config_id'];
  9276.                 $pa['defaultPurchaseTaxConfigId'] = $product['default_purchase_tax_config_id'] == null $product['default_purchase_tax_config_id'];
  9277.                 $tax_config_ids json_decode($product['tax_config_ids'], true);
  9278.                 if ($tax_config_ids == null)
  9279.                     $tax_config_ids = [];
  9280.                 $pa['taxConfigIds'] = $tax_config_ids;
  9281.                 $purchase_tax_config_ids json_decode($product['purchase_tax_config_ids'], true);
  9282.                 if ($purchase_tax_config_ids == null)
  9283.                     $purchase_tax_config_ids = [];
  9284.                 $pa['purchaseTaxConfigIds'] = $tax_config_ids;
  9285.                 $inco_terms json_decode($product['inco_terms'], true);
  9286.                 if ($inco_terms == null)
  9287.                     $inco_terms = [];
  9288.                 $pa['incoTerms'] = $inco_terms;
  9289.                 $pa['defaultIncoTerm'] = $product['default_inco_term'] == null $product['default_inco_term'];
  9290.                 $pa['has_serial'] = $product['has_serial'];
  9291.                 $pa['expiry_days'] = $product['expiry_days'];
  9292.                 $pa['image'] = $product['default_image'];
  9293.                 $pa['sales_warranty'] = $product['sales_warranty_months'];;
  9294.                 $pa['defaultColorId'] = $product['default_color_id'];;
  9295.                 $allowedColorIds json_decode($product['colors'], true);
  9296.                 if ($allowedColorIds == null$allowedColorIds = [];
  9297.                 if (!in_array($product['default_color_id'], $allowedColorIds))
  9298.                     $allowedColorIds[] = $product['default_color_id'];
  9299.                 $pa['allowedColorIds'] = $allowedColorIds;;
  9300.                 $data[] = $pa;
  9301.                 $data_by_id[$product['id']] = $pa;
  9302.                 $productId $product['id'];
  9303.             }
  9304.         }
  9305. //        if($request->query->has('returnJson'))
  9306.         {
  9307.             return new JsonResponse(
  9308.                 array(
  9309.                     'success' => true,
  9310. //                    'page_title' => 'Product Details',
  9311. //                    'company_data' => $company_data,
  9312.                     'data' => $data,
  9313.                     'dataById' => $data_by_id,
  9314.                     'productId' => $productId,
  9315.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9316. //                    'exId'=>$id,
  9317. //                'productByCodeData' => $productByCodeData,
  9318. //                'productData' => $productData,
  9319. //                'currInvList' => $currInvList,
  9320. //                'productList' => Inventory::ProductList($em, $companyId),
  9321. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9322. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9323. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9324. //                'unitList' => Inventory::UnitTypeList($em),
  9325. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9326. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9327. //                'warehouseList' => Inventory::WarehouseList($em),
  9328.                 )
  9329.             );
  9330.         }
  9331.     }
  9332.     public
  9333.     function labelFormatSelectAjaxAction(Request $request$queryStr '')
  9334.     {
  9335.         $em $this->getDoctrine()->getManager();
  9336.         $companyId $this->getLoggedUserCompanyId($request);
  9337.         $company_data Company::getCompanyData($em$companyId);
  9338.         $data = [];
  9339.         $data_by_id = [];
  9340.         $html '';
  9341.         $productByCodeData = [];
  9342.         if ($queryStr == '_EMPTY_')
  9343.             $queryStr '';
  9344.         if ($request->request->has('query') && $queryStr == '')
  9345.             $queryStr $request->request->get('queryStr');
  9346.         if ($queryStr == '_EMPTY_')
  9347.             $queryStr '';
  9348.         $filterQryForCriteria "select * from label_format where company_id=" $companyId " ";
  9349.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  9350.             $filterQryForCriteria .= " and label_type=" $request->request->get('dataType');
  9351.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  9352.             $filterQryForCriteria .= " and format_id=" $request->request->get('formatId');
  9353.         else if ($queryStr != '')
  9354.             $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' or `format_code` like '%" $queryStr "%') ";
  9355.         if ($filterQryForCriteria != '')
  9356.             $filterQryForCriteria .= "  limit 25";
  9357.         $get_kids_sql $filterQryForCriteria;
  9358. //        if ($request->request->has('productIds'))
  9359. //
  9360. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9361. //        else if ($request->request->has('productCode'))
  9362. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9363. //        else if ($filterQryForCriteria!='')
  9364. //            $get_kids_sql = $filterQryForCriteria;
  9365. //
  9366. //        else
  9367. //               $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";
  9368.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9369.         $stmt->execute();
  9370.         $get_kids $stmt->fetchAll();
  9371.         $productId 0;
  9372.         if (!empty($get_kids)) {
  9373.             foreach ($get_kids as $product) {
  9374.                 $pa = array();
  9375.                 $pa['id'] = $product['format_id'];
  9376.                 $pa['name'] = $product['name'];
  9377.                 $pa['format_code'] = $product['format_code'] . '. ' $product['name'];
  9378.                 $pa['id_code_name'] = $product['format_id'] . '. ' $product['format_code'] . ' - ' $product['name'] . ' ';
  9379.                 $pa['text'] = $product['name'];
  9380.                 $pa['value'] = $product['format_id'];
  9381.                 $data[] = $pa;
  9382.                 $data_by_id[$product['format_id']] = $pa;
  9383.                 $productId $product['format_id'];
  9384.             }
  9385.         }
  9386. //        if($request->query->has('returnJson'))
  9387.         {
  9388.             return new JsonResponse(
  9389.                 array(
  9390.                     'success' => true,
  9391. //                    'page_title' => 'Product Details',
  9392. //                    'company_data' => $company_data,
  9393.                     'data' => $data,
  9394.                     'dataById' => $data_by_id,
  9395.                     'productId' => $productId,
  9396.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9397. //                    'exId'=>$id,
  9398. //                'productByCodeData' => $productByCodeData,
  9399. //                'productData' => $productData,
  9400. //                'currInvList' => $currInvList,
  9401. //                'productList' => Inventory::ProductList($em, $companyId),
  9402. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9403. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9404. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9405. //                'unitList' => Inventory::UnitTypeList($em),
  9406. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9407. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9408. //                'warehouseList' => Inventory::WarehouseList($em),
  9409.                 )
  9410.             );
  9411.         }
  9412.     }
  9413.     public
  9414.     function CategoryListSelectAjaxAction(Request $request$queryStr '')
  9415.     {
  9416.         $em $this->getDoctrine()->getManager();
  9417.         $companyId $this->getLoggedUserCompanyId($request);
  9418.         $company_data Company::getCompanyData($em$companyId);
  9419.         $data = [];
  9420.         $data_by_id = [];
  9421.         $html '';
  9422.         $productByCodeData = [];
  9423.         if ($queryStr == '_EMPTY_')
  9424.             $queryStr '';
  9425.         if ($request->request->has('query') && $queryStr == '')
  9426.             $queryStr $request->request->get('queryStr');
  9427.         if ($queryStr == '_EMPTY_')
  9428.             $queryStr '';
  9429.         $filterQryForCriteria "select * from inv_product_categories where company_id=" $companyId " ";
  9430.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  9431.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  9432.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  9433.         if ($filterQryForCriteria != '')
  9434.             $filterQryForCriteria .= "  limit 25";
  9435.         $get_kids_sql $filterQryForCriteria;
  9436. //        if ($request->request->has('productIds'))
  9437. //
  9438. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9439. //        else if ($request->request->has('productCode'))
  9440. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9441. //        else if ($filterQryForCriteria!='')
  9442. //            $get_kids_sql = $filterQryForCriteria;
  9443. //
  9444. //        else
  9445. //               $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";
  9446.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9447.         $stmt->execute();
  9448.         $get_kids $stmt->fetchAll();
  9449.         $productId 0;
  9450.         if (!empty($get_kids)) {
  9451.             foreach ($get_kids as $product) {
  9452.                 $pa = array();
  9453.                 $pa['id'] = $product['id'];
  9454.                 $pa['name'] = $product['name'];
  9455.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  9456.                 $pa['globalId'] = $product['global_id'];
  9457.                 $pa['text'] = $product['name'];
  9458.                 $pa['value'] = $product['id'];
  9459.                 $pa['igId'] = $product['ig_id'];
  9460. //                $pa['categoryId'] = $product['category_id'];
  9461. //                $pa['subCategoryId'] = $product['sub_category_id'];
  9462.                 $data[] = $pa;
  9463.                 $data_by_id[$product['id']] = $pa;
  9464.                 $productId $product['id'];
  9465.             }
  9466.         }
  9467. //        if($request->query->has('returnJson'))
  9468.         {
  9469.             return new JsonResponse(
  9470.                 array(
  9471.                     'success' => true,
  9472. //                    'page_title' => 'Product Details',
  9473. //                    'company_data' => $company_data,
  9474.                     'data' => $data,
  9475.                     'dataById' => $data_by_id,
  9476.                     'productId' => $productId,
  9477.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9478. //                    'exId'=>$id,
  9479. //                'productByCodeData' => $productByCodeData,
  9480. //                'productData' => $productData,
  9481. //                'currInvList' => $currInvList,
  9482. //                'productList' => Inventory::ProductList($em, $companyId),
  9483. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9484. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9485. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9486. //                'unitList' => Inventory::UnitTypeList($em),
  9487. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9488. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9489. //                'warehouseList' => Inventory::WarehouseList($em),
  9490.                 )
  9491.             );
  9492.         }
  9493.     }
  9494.     public
  9495.     function SubCategoryListSelectAjaxAction(Request $request$queryStr '')
  9496.     {
  9497.         $em $this->getDoctrine()->getManager();
  9498.         $companyId $this->getLoggedUserCompanyId($request);
  9499.         $company_data Company::getCompanyData($em$companyId);
  9500.         $data = [];
  9501.         $data_by_id = [];
  9502.         $html '';
  9503.         $productByCodeData = [];
  9504.         if ($queryStr == '_EMPTY_')
  9505.             $queryStr '';
  9506.         if ($request->request->has('query') && $queryStr == '')
  9507.             $queryStr $request->request->get('queryStr');
  9508.         if ($queryStr == '_EMPTY_')
  9509.             $queryStr '';
  9510.         $filterQryForCriteria "select * from inv_product_sub_categories where company_id=" $companyId " ";
  9511.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9512.             $filterQryForCriteria .= " and sub_category_id=" $request->request->get('subCategoryId');
  9513.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  9514.             $filterQryForCriteria .= " and category_id=" $request->request->get('categoryId');
  9515.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  9516.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  9517.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  9518.             if ($request->request->get('parentId') != 0)
  9519.                 $filterQryForCriteria .= " and  parent_id=" $request->request->get('parentId');
  9520.             else
  9521.                 $filterQryForCriteria .= " and ( parent_id =0 or parent_id is null ) ";
  9522.         if ($request->request->has('level') && $request->request->get('level') != '')
  9523.             if ($request->request->get('level') != 0)
  9524.                 $filterQryForCriteria .= " and level=" $request->request->get('level');
  9525.             else
  9526.                 $filterQryForCriteria .= " and ( level =0 or level is null) ";
  9527.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  9528.         if ($filterQryForCriteria != '')
  9529.             $filterQryForCriteria .= "  limit 25";
  9530.         $get_kids_sql $filterQryForCriteria;
  9531. //        if ($request->request->has('productIds'))
  9532. //
  9533. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9534. //        else if ($request->request->has('productCode'))
  9535. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9536. //        else if ($filterQryForCriteria!='')
  9537. //            $get_kids_sql = $filterQryForCriteria;
  9538. //
  9539. //        else
  9540. //               $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";
  9541.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9542.         $stmt->execute();
  9543.         $get_kids $stmt->fetchAll();
  9544.         $productId 0;
  9545.         if (!empty($get_kids)) {
  9546.             foreach ($get_kids as $product) {
  9547.                 $pa = array();
  9548.                 $pa['id'] = $product['id'];
  9549.                 $pa['name'] = $product['name'];
  9550.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  9551.                 $pa['globalId'] = $product['global_id'];
  9552.                 $pa['parentId'] = $product['parent_id'];
  9553.                 $pa['text'] = $product['name'];
  9554.                 $pa['value'] = $product['id'];
  9555.                 $pa['igId'] = $product['ig_id'];
  9556.                 $pa['categoryId'] = $product['category_id'];
  9557. //                $pa['subCategoryId'] = $product['sub_category_id'];
  9558.                 $data[] = $pa;
  9559.                 $data_by_id[$product['id']] = $pa;
  9560.                 $productId $product['id'];
  9561.             }
  9562.         }
  9563. //        if($request->query->has('returnJson'))
  9564.         {
  9565.             return new JsonResponse(
  9566.                 array(
  9567.                     'success' => true,
  9568. //                    'page_title' => 'Product Details',
  9569. //                    'company_data' => $company_data,
  9570.                     'data' => $data,
  9571.                     'dataById' => $data_by_id,
  9572.                     'productId' => $productId,
  9573.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9574. //                    'exId'=>$id,
  9575. //                'productByCodeData' => $productByCodeData,
  9576. //                'productData' => $productData,
  9577. //                'currInvList' => $currInvList,
  9578. //                'productList' => Inventory::ProductList($em, $companyId),
  9579. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9580. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9581. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9582. //                'unitList' => Inventory::UnitTypeList($em),
  9583. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9584. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9585. //                'warehouseList' => Inventory::WarehouseList($em),
  9586.                 )
  9587.             );
  9588.         }
  9589.     }
  9590.     public
  9591.     function ProductByCodeViewAction(Request $request$id 0)
  9592.     {
  9593.         $em $this->getDoctrine()->getManager();
  9594.         $companyId $this->getLoggedUserCompanyId($request);
  9595.         $company_data Company::getCompanyData($em$companyId);
  9596.         $data = [];
  9597.         $html '';
  9598.         $productByCodeData = [];
  9599.         if ($id != 0) {
  9600.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9601.                 ->findOneBy(
  9602.                     array(
  9603.                         'productByCodeId' => $id
  9604.                     )
  9605.                 );
  9606.         } else {
  9607.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9608.                 ->findOneBy(
  9609.                     array(
  9610. //                        'productByCodeId' => $id,
  9611.                         'CompanyId' => $companyId
  9612.                     ), array(
  9613.                         'productByCodeId' => 'DESC'
  9614.                     )
  9615.                 );
  9616.             if ($productByCodeData)
  9617.                 $id $productByCodeData->getProductByCodeId();
  9618.         }
  9619.         if ($id != 0) {
  9620.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9621.                 ->findOneBy(
  9622.                     array(
  9623.                         'id' => $productByCodeData->getProductId()
  9624.                     )
  9625.                 );
  9626.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9627.                 ->findBy(
  9628.                     array(
  9629.                         'productId' => $id
  9630.                     )
  9631.                 );
  9632.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  9633.                 array(
  9634.                     'page_title' => 'Product Details',
  9635.                     'company_data' => $company_data,
  9636.                     'productByCodeData' => $productByCodeData,
  9637.                     'productData' => $productData,
  9638.                     'currInvList' => $currInvList,
  9639.                     'exId' => $id,
  9640.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9641.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9642.                     'productList' => Inventory::ProductList($em$companyId),
  9643.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9644.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9645.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9646.                     'unitList' => Inventory::UnitTypeList($em),
  9647.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9648.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9649.                     'warehouseList' => Inventory::WarehouseList($em),
  9650.                 )
  9651.             );
  9652.         } else {
  9653.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  9654.                 array(
  9655.                     'exId' => $id,
  9656.                 )
  9657.             );
  9658.         }
  9659.         if ($request->query->has('returnJson')) {
  9660.             return new JsonResponse(
  9661.                 array(
  9662.                     'success' => true,
  9663.                     'page_title' => 'Product Details',
  9664.                     'company_data' => $company_data,
  9665.                     'renderedHtml' => $html,
  9666.                     'exId' => $id,
  9667. //                'productByCodeData' => $productByCodeData,
  9668. //                'productData' => $productData,
  9669. //                'currInvList' => $currInvList,
  9670. //                'productList' => Inventory::ProductList($em, $companyId),
  9671. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9672. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9673. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9674. //                'unitList' => Inventory::UnitTypeList($em),
  9675. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9676. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9677. //                'warehouseList' => Inventory::WarehouseList($em),
  9678.                 )
  9679.             );
  9680.         } else {
  9681. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9682. //                ->findBy(
  9683. //                    array(
  9684. ////                        'productByCodeId' => $id,
  9685. //                    'CompanyId'=>$companyId
  9686. //                    )
  9687. //                );
  9688.             $productByCodeList = []; //called by ajax
  9689.             return $this->render('@Inventory/pages/views/product_by_code_view.html.twig',
  9690.                 array(
  9691.                     'page_title' => 'Product Details',
  9692.                     'company_data' => $company_data,
  9693.                     'renderedHtml' => $html,
  9694.                     'exId' => $id,
  9695.                     'productByCodeList' => $productByCodeList,
  9696. //                'productByCodeData' => $productByCodeData,
  9697. //                'productData' => $productData,
  9698. //                'currInvList' => $currInvList,
  9699. //                'productList' => Inventory::ProductList($em, $companyId),
  9700. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9701. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9702. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9703. //                'unitList' => Inventory::UnitTypeList($em),
  9704. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9705. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9706. //                'warehouseList' => Inventory::WarehouseList($em),
  9707.                 )
  9708.             );
  9709.         }
  9710.     }
  9711.     public
  9712.     function ConsumptionSettingsAction(Request $request$id)
  9713.     {
  9714.         $cc_id '';
  9715.         $cc_name '';
  9716.         $em $this->getDoctrine()->getManager();
  9717.         $companyId $this->getLoggedUserCompanyId($request);
  9718.         $consumptionTypeId 0;
  9719.         if ($request->isMethod('POST')) {
  9720.             $new_cc = [];
  9721.             if ($request->request->get('consumptionTypeId') != '' && $request->request->get('consumptionTypeId') != 0) {
  9722.                 $em $this->getDoctrine()->getManager();
  9723.                 $new_cc $this->getDoctrine()
  9724.                     ->getRepository('ApplicationBundle:ConsumptionType')
  9725.                     ->findOneBy(
  9726.                         array(
  9727.                             'consumptionTypeId' => $request->request->get('consumptionTypeId'),
  9728.                         )
  9729.                     );
  9730.                 $new_cc->setName($request->request->get('name'));
  9731.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9732.                 $new_cc->setCompanyId($companyId);
  9733.                 $em->flush();
  9734.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9735.                 $this->addFlash(
  9736.                     'success',
  9737.                     'Consumption Information Updated'
  9738.                 );
  9739.             } else {
  9740.                 $new_cc = new ConsumptionType();
  9741.                 $new_cc->setName($request->request->get('name'));
  9742.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9743.                 $new_cc->setCompanyId($companyId);
  9744.                 $em->persist($new_cc);
  9745.                 $em->flush();
  9746.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9747.                 $em->flush();
  9748.                 $this->addFlash(
  9749.                     'success',
  9750.                     'New Consumption Type Added'
  9751.                 );
  9752.             }
  9753.         }
  9754.         $extData = [];
  9755.         if ($id != 0) {
  9756.             $extData $this->getDoctrine()
  9757.                 ->getRepository('ApplicationBundle:ConsumptionType')
  9758.                 ->findOneBy(
  9759.                     array(
  9760.                         'consumptionTypeId' => $id
  9761.                     )
  9762.                 );
  9763. //            $cc_data_list = [];
  9764. //            foreach ($cc_data as $value) {
  9765. //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  9766. //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  9767. //
  9768. //                if ($value->getSupplierCategoryId() == $id) {
  9769. //                    $cc_id = $value->getSupplierCategoryId();
  9770. //                    $cc_name = $value->getName();
  9771. //                }
  9772. //            }
  9773.         }
  9774.         return $this->render('@Inventory/pages/input_forms/consumption_settings.html.twig',
  9775.             array(
  9776.                 'page_title' => 'Consumption Settings',
  9777.                 'consumptionTypeList' => $this->getDoctrine()
  9778.                     ->getRepository('ApplicationBundle:ConsumptionType')
  9779.                     ->findBy(
  9780.                         array(
  9781.                             'CompanyId' => $companyId
  9782.                         )
  9783.                     ),
  9784.                 'extData' => $extData,
  9785.                 'headList' => Accounts::getParentLedgerHeads($em),
  9786. //                'countryList'=>SalesOrderM::Co
  9787.             )
  9788.         );
  9789.     }
  9790.     public
  9791.     function ProductByCodeCheckAssignPrintAction(Request $request$id 0)
  9792.     {
  9793.         $em $this->getDoctrine()->getManager();
  9794.         $companyId $this->getLoggedUserCompanyId($request);
  9795.         $company_data Company::getCompanyData($em$companyId);
  9796.         $data = [];
  9797.         $html '';
  9798.         $productByCodeData = [];
  9799.         $productDataWeightPackageGm '';
  9800.         $productDataWeightVarianceValue 0;
  9801.         $productDataWeightVarianceType 0;
  9802.         $productByCodeDataObj = [];
  9803.         $dr_id 0;//for dr_id
  9804.         $skipRenderData 0;
  9805.         if ($request->query->has('skipRenderData'))
  9806.             $skipRenderData $request->query->get('skipRenderData');
  9807.         if ($id != 0) {
  9808.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9809.                 ->findOneBy(
  9810.                     array(
  9811.                         'productByCodeId' => $id
  9812.                     )
  9813.                 );
  9814.         } else {
  9815.             if ($request->query->has('scanCode')) {
  9816.                 $query $em->getRepository('ApplicationBundle:ProductByCode')
  9817.                     ->createQueryBuilder('p');
  9818.                 if ($request->query->has('assigned')) {
  9819.                     $query->where('p.assigned > :av')
  9820.                         ->setParameter('av'$request->query->get('assigned'));
  9821.                 } else
  9822.                     $query->where("1=0");
  9823.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  9824.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  9825.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  9826.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  9827.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  9828.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  9829.                 $query->setMaxResults(1);
  9830.                 $results $query->getQuery()->getResult();
  9831.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  9832.             } else
  9833.                 $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9834.                     ->findOneBy(
  9835.                         array(
  9836. //                        'productByCodeId' => $id,
  9837.                             'CompanyId' => $companyId
  9838.                         ), array(
  9839.                             'productByCodeId' => 'DESC'
  9840.                         )
  9841.                     );
  9842.             if ($productByCodeData)
  9843.                 $id $productByCodeData->getProductByCodeId();
  9844.         }
  9845.         if ($id != 0) {
  9846.             $productByCodeDataObj = array(
  9847.                 'salesCode' => $productByCodeData->getSalesCode(),
  9848.                 'sales_code' => $productByCodeData->getSalesCode(),
  9849.                 'sn' => $productByCodeData->getSerialNo(),
  9850.                 'serialNo' => $productByCodeData->getSerialNo(),
  9851.                 'imei1' => $productByCodeData->getImei1(),
  9852.                 'imei2' => $productByCodeData->getImei2(),
  9853.                 'soId' => $productByCodeData->getSalesOrderId(),
  9854.                 'poId' => $productByCodeData->getPurchaseOrderId(),
  9855.                 'irrId' => $productByCodeData->getIrrId(),
  9856.                 'productId' => $productByCodeData->getProductId(),
  9857.                 'productByCodeId' => $productByCodeData->getProductByCodeId(),
  9858.                 'warehouseId' => $productByCodeData->getWarehouseId(),
  9859.                 'warehouseActionId' => $productByCodeData->getWarehouseActionId(),
  9860.                 'stId' => $productByCodeData->getStockTransferId(),
  9861.                 'srId' => $productByCodeData->getStockReceivedNoteId(),
  9862.                 'scmpId' => $productByCodeData->getStockConsumptionNoteId(),
  9863.                 'clientId' => $productByCodeData->getClientId(),
  9864.                 'supplierId' => $productByCodeData->getSupplierId(),
  9865.                 'drId' => $productByCodeData->getDeliveryReceiptId(),
  9866.                 'consumerName' => $productByCodeData->getConsumerName(),
  9867.                 'drItemData' => [],
  9868. //                'salesCodes' => $productByCodeData->getDeliveryReceiptId(),
  9869.             );
  9870.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9871.                 ->findOneBy(
  9872.                     array(
  9873.                         'id' => $productByCodeData->getProductId()
  9874.                     )
  9875.                 );
  9876.             if ($productByCodeData->getProductionId() != null) {
  9877.                 $productionDataHere $em->getRepository('ApplicationBundle:Production')
  9878.                     ->findOneBy(
  9879.                         array(
  9880.                             'productionId' => $productByCodeData->getProductionId()
  9881.                         )
  9882.                     );
  9883.                 if ($productionDataHere) {
  9884.                     $productDataWeightPackageGm $productionDataHere->getPackageWeight();
  9885.                     $productDataWeightVarianceValue $productionDataHere->getPackageWeightVarianceValue();
  9886.                     $productDataWeightVarianceType $productionDataHere->getPackageWeightVarianceType();
  9887.                 }
  9888.             } else {
  9889.                 if ($productData) {
  9890.                     $productDataWeightPackageGm $productData->getWeight();
  9891.                     $productDataWeightVarianceValue $productData->getWeightVarianceValue();
  9892.                     $productDataWeightVarianceType $productData->getWeightVarianceType();
  9893.                 }
  9894.             }
  9895.             if ($productData) {
  9896.                 $productByCodeDataObj['unitTypeId'] = $productData->getUnitTypeId();
  9897.                 $productByCodeDataObj['purchasePrice'] = $productData->getPurchasePrice();
  9898.                 $productByCodeDataObj['productFdm'] = $productData->getProductFdm();
  9899.                 $productByCodeDataObj['productName'] = $productData->getName();
  9900.                 if ($request->request->has('forSalesReturn') || $request->query->has('forSalesReturn')) {
  9901.                     $QD $this->getDoctrine()
  9902.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  9903.                         ->findOneBy(
  9904.                             array(
  9905.                                 'deliveryReceiptId' => $productByCodeData->getDeliveryReceiptId(),
  9906.                                 'productId' => $productByCodeData->getProductId(),
  9907.                             )
  9908.                         );
  9909. //            if($request->request->get('wareHouseId')!='')
  9910.                     if ($QD) {
  9911.                         $new_pid $QD->getProductId();
  9912.                         $sales_code_range = [];
  9913.                         if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  9914.                             $sales_code_range json_decode($QD->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  9915.                         } else {
  9916.                             $max_int_length strlen((string)PHP_INT_MAX) - 1;
  9917.                             $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$QD->getSalesCodeRange());
  9918.                             $sales_code_range json_decode($json_without_bigintstrue);
  9919.                         }
  9920.                         $p_data = array(
  9921.                             'details_id' => $QD->getId(),
  9922.                             'productId' => $new_pid,
  9923.                             'dr_id' => $productByCodeData->getDeliveryReceiptId(),
  9924.                             'product_name' => $productData->getName(),
  9925.                             'qty' => $QD->getQty(),
  9926.                             'delivered' => $QD->getDelivered(),
  9927.                             'unitTypeId' => $QD->getUnitTypeId(),
  9928.                             'deliverable' => $QD->getDeliverable(),
  9929.                             'balance' => $QD->getBalance(),
  9930.                             'salesCodeRangeStr' => $QD->getSalesCodeRange(),
  9931.                             'salesCodeRange' => $sales_code_range,
  9932.                             'sales_codes' => $sales_code_range,
  9933.                             'sales_price' => $QD->getPrice(),
  9934.                             'purchase_price' => $QD->getCurrentPurchasePrice()
  9935. //                        'delivered'=>$product->getDelivered(),
  9936.                         );
  9937.                         $productByCodeDataObj['drItemData'][] = $p_data;
  9938.                     }
  9939.                 }
  9940.             }
  9941.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9942.                 ->findBy(
  9943.                     array(
  9944.                         'productId' => $id
  9945.                     )
  9946.                 );
  9947.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  9948.                 array(
  9949.                     'page_title' => 'Details',
  9950.                     'company_data' => $company_data,
  9951.                     'productByCodeData' => $productByCodeData,
  9952.                     'productByCodeDataObj' => $productByCodeDataObj,
  9953.                     'productData' => $productData,
  9954.                     'currInvList' => $currInvList,
  9955.                     'productDataWeightPackageGm' => $productDataWeightPackageGm,
  9956.                     'productDataWeightVarianceValue' => $productDataWeightVarianceValue,
  9957.                     'productDataWeightVarianceType' => $productDataWeightVarianceType,
  9958.                     'exId' => $id,
  9959.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9960.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9961.                     'productList' => Inventory::ProductList($em$companyId),
  9962.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9963.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9964.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9965.                     'unitList' => Inventory::UnitTypeList($em),
  9966.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9967.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9968.                     'warehouseList' => Inventory::WarehouseList($em),
  9969.                 )
  9970.             ));
  9971.         } else {
  9972.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  9973.                 array(
  9974.                     'exId' => $id,
  9975.                 )
  9976.             ));
  9977.         }
  9978.         if ($request->query->has('returnJson')) {
  9979.             return new JsonResponse(
  9980.                 array(
  9981.                     'success' => true,
  9982.                     'page_title' => 'Product Details',
  9983.                     'company_data' => $company_data,
  9984.                     'renderedHtml' => $html,
  9985.                     'exId' => $id,
  9986.                     'productByCodeDataObj' => $productByCodeDataObj,
  9987. //                'productData' => $productData,
  9988. //                'currInvList' => $currInvList,
  9989. //                'productList' => Inventory::ProductList($em, $companyId),
  9990. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9991. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9992. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9993. //                'unitList' => Inventory::UnitTypeList($em),
  9994. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9995. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9996. //                'warehouseList' => Inventory::WarehouseList($em),
  9997.                 )
  9998.             );
  9999.         } else {
  10000. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  10001. //                ->findBy(
  10002. //                    array(
  10003. ////                        'productByCodeId' => $id,
  10004. //                    'CompanyId'=>$companyId
  10005. //                    )
  10006. //                );
  10007.             $productByCodeList = []; //called by ajax
  10008.             return $this->render('@Inventory/pages/views/product_by_code_assign_check_print.html.twig',
  10009.                 array(
  10010.                     'page_title' => 'Serial Manager',
  10011.                     'company_data' => $company_data,
  10012.                     'renderedHtml' => $html,
  10013.                     'exId' => $id,
  10014.                     'productByCodeList' => $productByCodeList,
  10015.                     'productByCodeDataObj' => $productByCodeDataObj,
  10016. //                'productByCodeData' => $productByCodeData,
  10017. //                'productData' => $productData,
  10018. //                'currInvList' => $currInvList,
  10019. //                'productList' => Inventory::ProductList($em, $companyId),
  10020. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10021. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10022. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10023. //                'unitList' => Inventory::UnitTypeList($em),
  10024. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10025. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10026. //                'warehouseList' => Inventory::WarehouseList($em),
  10027.                 )
  10028.             );
  10029.         }
  10030.     }
  10031.     public
  10032.     function TestProductByCodeCheckAssignPrintAction(Request $request$id 0)
  10033.     {
  10034.         $em $this->getDoctrine()->getManager();
  10035.         $companyId $this->getLoggedUserCompanyId($request);
  10036.         $company_data Company::getCompanyData($em$companyId);
  10037.         $data = [];
  10038.         $html '';
  10039.         $productByCodeData = [];
  10040.         $productByCodeDataObj = [];
  10041.         if ($id != 0) {
  10042.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  10043.                 ->findOneBy(
  10044.                     array(
  10045.                         'productByCodeId' => $id
  10046.                     )
  10047.                 );
  10048.         } else {
  10049.             if ($request->query->has('scanCode')) {
  10050.                 $query $em->getRepository('ApplicationBundle:ProductByCode')
  10051.                     ->createQueryBuilder('p');
  10052.                 if ($request->query->has('assigned')) {
  10053.                     $query->where('p.assigned > :av')
  10054.                         ->setParameter('av'$request->query->get('assigned'));
  10055.                 } else
  10056.                     $query->where("1=0");
  10057.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  10058.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  10059.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  10060.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  10061.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  10062.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  10063.                 $query->setMaxResults(1);
  10064.                 $results $query->getQuery()->getResult();
  10065.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  10066.             } else
  10067.                 $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  10068.                     ->findOneBy(
  10069.                         array(
  10070. //                        'productByCodeId' => $id,
  10071.                             'CompanyId' => $companyId
  10072.                         ), array(
  10073.                             'productByCodeId' => 'DESC'
  10074.                         )
  10075.                     );
  10076.             if ($productByCodeData)
  10077.                 $id $productByCodeData->getProductByCodeId();
  10078.         }
  10079.         if ($id != 0) {
  10080.             $productByCodeDataObj = array(
  10081.                 'sn' => $productByCodeData->getSalesCode(),
  10082.                 'imei1' => $productByCodeData->getImei1(),
  10083.                 'imei2' => $productByCodeData->getImei2(),
  10084.                 'colorId' => $productByCodeData->getColorId(),
  10085.             );
  10086.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  10087.                 ->findOneBy(
  10088.                     array(
  10089.                         'id' => $productByCodeData->getProductId()
  10090.                     )
  10091.                 );
  10092.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  10093.                 ->findBy(
  10094.                     array(
  10095.                         'productId' => $id
  10096.                     )
  10097.                 );
  10098.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  10099.                 array(
  10100.                     'page_title' => 'Details',
  10101.                     'company_data' => $company_data,
  10102.                     'productByCodeData' => $productByCodeData,
  10103.                     'productData' => $productData,
  10104.                     'currInvList' => $currInvList,
  10105.                     'exId' => $id,
  10106.                     'clientList' => Client::GetExistingClientList($em$companyId),
  10107.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  10108.                     'productList' => Inventory::ProductList($em$companyId),
  10109.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10110.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10111.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10112.                     'unitList' => Inventory::UnitTypeList($em),
  10113.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10114.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10115.                     'warehouseList' => Inventory::WarehouseList($em),
  10116.                 )
  10117.             );
  10118.         } else {
  10119.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  10120.                 array(
  10121.                     'exId' => $id,
  10122.                 )
  10123.             );
  10124.         }
  10125.         if ($request->query->has('returnJson')) {
  10126.             return new JsonResponse(
  10127.                 array(
  10128.                     'success' => true,
  10129.                     'page_title' => 'Product Details',
  10130.                     'company_data' => $company_data,
  10131.                     'renderedHtml' => $html,
  10132.                     'exId' => $id,
  10133.                     'productByCodeDataObj' => $productByCodeDataObj,
  10134. //                'productData' => $productData,
  10135. //                'currInvList' => $currInvList,
  10136. //                'productList' => Inventory::ProductList($em, $companyId),
  10137. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10138. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10139. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10140. //                'unitList' => Inventory::UnitTypeList($em),
  10141. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10142. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10143. //                'warehouseList' => Inventory::WarehouseList($em),
  10144.                 )
  10145.             );
  10146.         } else {
  10147. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  10148. //                ->findBy(
  10149. //                    array(
  10150. ////                        'productByCodeId' => $id,
  10151. //                    'CompanyId'=>$companyId
  10152. //                    )
  10153. //                );
  10154.             $productByCodeList = []; //called by ajax
  10155.             return $this->render('@Inventory/pages/views/test_product_by_code_assign_check_print.html.twig',
  10156.                 array(
  10157.                     'page_title' => ' Test Serial Manager',
  10158.                     'company_data' => $company_data,
  10159.                     'renderedHtml' => $html,
  10160.                     'exId' => $id,
  10161.                     'productByCodeList' => $productByCodeList,
  10162.                     'productByCodeDataObj' => $productByCodeDataObj,
  10163. //                'productByCodeData' => $productByCodeData,
  10164. //                'productData' => $productData,
  10165. //                'currInvList' => $currInvList,
  10166. //                'productList' => Inventory::ProductList($em, $companyId),
  10167. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10168. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10169. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10170. //                'unitList' => Inventory::UnitTypeList($em),
  10171. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10172. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10173. //                'warehouseList' => Inventory::WarehouseList($em),
  10174.                 )
  10175.             );
  10176.         }
  10177.     }
  10178.     public
  10179.     function DeleteProductAction(Request $request$id '')
  10180.     {
  10181.         $em $this->getDoctrine()->getManager();
  10182.         $idListArray = [];
  10183.         if ($request->isMethod('POST')) {
  10184.             if ($id == 0)
  10185.                 $id $request->request->get('productId');
  10186.             //now check the product closing , if nothing then we cna remove it
  10187.             $query_here $this->getDoctrine()
  10188.                 ->getRepository('ApplicationBundle:InvClosingBalance')
  10189.                 ->findBy(
  10190.                     array(
  10191.                         'productId' => $request->request->get('productId')
  10192.                     )
  10193.                 );
  10194.             if (!empty($query_here)) {
  10195.                 return new JsonResponse(
  10196.                     array(
  10197.                         'success' => false,
  10198.                     )
  10199.                 );
  10200.             } else {
  10201.                 $qry $em->getRepository('ApplicationBundle:ProductByCode')->findBy(array(
  10202.                     'productId' => $id
  10203.                 ));
  10204.                 foreach ($qry as $det) {
  10205.                     //remove any barcoded products
  10206.                     $em->remove($det);
  10207.                     $em->flush();
  10208.                 }
  10209.                 $qry $em->getRepository('ApplicationBundle:InvProducts')->findBy(array(
  10210.                     'id' => $id
  10211.                 ));
  10212.                 foreach ($qry as $det) {
  10213.                     //remove any barcoded products
  10214.                     $em->remove($det);
  10215.                     $em->flush();
  10216.                 }
  10217.                 $qry $em->getRepository('ApplicationBundle:InvItemTransaction')->findBy(array(
  10218.                     'productId' => $id
  10219.                 ));
  10220.                 foreach ($qry as $det) {
  10221.                     //remove any barcoded products
  10222.                     $em->remove($det);
  10223.                     $em->flush();
  10224.                 }
  10225.                 return new JsonResponse(
  10226.                     array(
  10227.                         'success' => true,
  10228.                     )
  10229.                 );
  10230.             }
  10231.         }
  10232.         return new JsonResponse(
  10233.             array(
  10234.                 'success' => false,
  10235.             )
  10236.         );
  10237.     }
  10238.     public
  10239.     function RegisterProductAction(Request $request$idListStr '')
  10240.     {
  10241.         $em $this->getDoctrine()->getManager();
  10242.         $companyId $this->getLoggedUserCompanyId($request);
  10243.         $company_data Company::getCompanyData($em$companyId);
  10244.         $session $request->getSession();
  10245. //        System::setSessionForUser($session );
  10246.         $idListArray = [];
  10247.         if ($idListStr != '')
  10248.             $idListArray explode(','$idListStr);
  10249.         $data = [];
  10250. //        if ($request->isMethod('POST')) {
  10251. //            $post = $request->request;
  10252. //            if ($request->request->get('formatId') != '') {
  10253. //                $query_here = $this->getDoctrine()
  10254. //                    ->getRepository('ApplicationBundle:CheckFormat')
  10255. //                    ->findOneBy(
  10256. //                        array(
  10257. //                            'formatId' => $request->request->get('formatId')
  10258. //                        )
  10259. //                    );
  10260. //                if (!empty($query_here))
  10261. //                    $new = $query_here;
  10262. //            } else
  10263. //                $new = new CheckFormat();
  10264. //            $new->setName($request->request->get('name'));
  10265. //            $new->setWidth($request->request->get('width'));
  10266. //            $new->setHeight($request->request->get('height'));
  10267. //            $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
  10268. //            $new->setCheckPayToTop($request->request->get('checkPayToTop'));
  10269. //            $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
  10270. //            $new->setCheckAmountTop($request->request->get('checkAmountTop'));
  10271. //            $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
  10272. //            $new->setCheckAiWTop($request->request->get('checkAiWTop'));
  10273. //            $new->setCheckDateLeft($request->request->get('checkDateLeft'));
  10274. //            $new->setCheckDateTop($request->request->get('checkDateTop'));
  10275. //            $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
  10276. //            $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
  10277. //            $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
  10278. //            $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
  10279. //            $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
  10280. //            $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
  10281. //            $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
  10282. //            $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
  10283. //            $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
  10284. //            $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
  10285. //            $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 1 : 0);
  10286. //            $new->setCheckImage($request->request->get('checkImage'));
  10287. //
  10288. //            $em = $this->getDoctrine()->getManager();
  10289. //            $em->persist($new);
  10290. //            $em->flush();
  10291. //
  10292. //        }
  10293. //        if (!empty($idListArray)) {
  10294. //            $query_here = $this->getDoctrine()
  10295. //                ->getRepository('ApplicationBundle:ProductByCode')
  10296. //                ->findBy(
  10297. //                    array(
  10298. //                        'productByCodeId' => $idListArray
  10299. //                    )
  10300. //                );
  10301. //            if (!empty($query_here))
  10302. //                $data = $query_here;
  10303. //
  10304. //        }
  10305. //        else if ($request->query->has('formatId')) {
  10306. //            $query_here = $this->getDoctrine()
  10307. //                ->getRepository('ApplicationBundle:CheckFormat')
  10308. //                ->findOneBy(
  10309. //                    array(
  10310. //                        'formatId' => $request->query->get('formatId')
  10311. //                    )
  10312. //                );
  10313. //            if (!empty($query_here))
  10314. //                $data = $query_here;
  10315. //        }
  10316.         $data = [];
  10317.         $html '';
  10318.         $productByCodeData = [];
  10319.         if ($request->query->has('returnJson')) {
  10320.             return new JsonResponse(
  10321.                 array(
  10322.                     'success' => true,
  10323.                     'page_title' => 'Product Details',
  10324.                     'company_data' => $company_data,
  10325.                     'renderedHtml' => $html,
  10326.                     'data' => $data,
  10327.                     'idListArray' => $idListArray,
  10328. //                    'exId'=>$id,
  10329. //                'productByCodeData' => $productByCodeData,
  10330. //                'productData' => $productData,
  10331. //                'currInvList' => $currInvList,
  10332. //                'productList' => Inventory::ProductList($em, $companyId),
  10333. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10334. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10335. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10336. //                'unitList' => Inventory::UnitTypeList($em),
  10337. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10338. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10339. //                'warehouseList' => Inventory::WarehouseList($em),
  10340.                 )
  10341.             );
  10342.         } else {
  10343.             return $this->render('@Inventory/pages/input_forms/register_product.html.twig',
  10344.                 array(
  10345.                     'page_title' => 'Register Product',
  10346.                     'company_data' => $company_data,
  10347.                     'renderedHtml' => $html,
  10348. //                    'exIdList'=>$i,
  10349.                     'idListArray' => $idListArray,
  10350.                     'data' => $data,
  10351.                     'productByCodeList' => [],
  10352.                     'productByCodeData' => [],
  10353.                     'productList' => Inventory::ProductList($em$companyId),
  10354.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10355.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10356.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10357.                     'unitList' => Inventory::UnitTypeList($em),
  10358.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10359.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10360.                     'warehouseList' => Inventory::WarehouseList($em),
  10361.                 )
  10362.             );
  10363.         }
  10364.     }
  10365.     public
  10366.     function BrandViewAction(Request $request)
  10367.     {
  10368.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  10369.             array(
  10370.                 'page_title' => 'Stock Return'
  10371.             )
  10372.         );
  10373.     }
  10374.     public
  10375.     function PrintTableDataAction(Request $request)
  10376.     {
  10377.         $em $this->getDoctrine()->getManager();
  10378.         $company_data Company::getCompanyData($em1);
  10379.         $data = [];
  10380.         $print_title "test";
  10381.         $document_mark = array(
  10382.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10383.             'copy' => ''
  10384.         );
  10385.         $mis_data = [];
  10386.         $p 1;
  10387.         return $this->render('@Inventory/pages/print/print_table_data.html.twig',
  10388.             array(
  10389.                 'page_title' => 'Data Report',
  10390.                 'data' => $data,
  10391.                 'page_header' => 'Report',
  10392.                 'print_title' => $print_title,
  10393.                 'document_type' => 'Journal voucher',
  10394.                 'document_mark_image' => $document_mark['original'],
  10395.                 'page_header_sub' => 'Add',
  10396. //                'type_list'=>$type_list,
  10397.                 'mis_data' => $mis_data,
  10398.                 'item_data' => [],
  10399.                 'received' => 2,
  10400.                 'return' => 1,
  10401.                 'total_w_vat' => 1,
  10402.                 'total_vat' => 1,
  10403.                 'total_wo_vat' => 1,
  10404.                 'invoice_id' => 'abcd1234',
  10405.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10406.                 'created_by' => 'created by',
  10407.                 'created_at' => '',
  10408.                 'red' => 0,
  10409.                 'company_name' => $company_data->getName(),
  10410.                 'company_data' => $company_data,
  10411.                 'company_address' => $company_data->getAddress(),
  10412.                 'company_image' => $company_data->getImage(),
  10413.                 'p' => $p
  10414.             )
  10415.         );
  10416.     }
  10417.     public
  10418.     function ReplacementReportAction(Request $request)
  10419.     {
  10420.         $qry_data = array(
  10421.             'warehouseId' => [0],
  10422.             'igId' => [0],
  10423.             'brandId' => [0],
  10424.             'categoryId' => [0],
  10425.             'actionTagId' => [0],
  10426.         );
  10427.         $em $this->getDoctrine()->getManager();
  10428.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  10429.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  10430.         $data_searched = [];
  10431.         $companyId $this->getLoggedUserCompanyId($request);
  10432.         $company_data Company::getCompanyData($em$companyId);
  10433.         $data = [];
  10434.         $print_title "Inventory Report";
  10435.         $document_mark = array(
  10436.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10437.             'copy' => ''
  10438.         );
  10439.         $post_data $request->request;
  10440.         $start_date $post_data->has('start_date') ? $post_data->get('start_date') : '';
  10441.         $end_date $post_data->has('end_date') ? $post_data->get('end_date') : '';
  10442.         if ($request->isMethod('POST'))
  10443.             $method 'POST';
  10444.         else
  10445.             $method 'GET';
  10446.         {
  10447. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  10448.             $data_searched Inventory::GetReplacementReportData($this->getDoctrine()->getManager(),
  10449.                 $request->request$method,
  10450.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  10451.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  10452.                 return new JsonResponse(
  10453.                     array(
  10454.                         'page_title' => 'Inventory ',
  10455.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10456.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10457.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10458.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10459.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10460.                         'action_tag' => $warehouse_action_list,
  10461.                         'start_date' => $start_date,
  10462.                         'end_date' => $end_date,
  10463.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10464.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10465.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10466.                         'data_searched' => $data_searched,
  10467.                         'success' => empty($data_searched['query_result']) ? false true
  10468.                     )
  10469.                 );
  10470.             }
  10471.             if ($request->request->get('print_data_enabled') == 1) {
  10472.                 $print_sub_title "";
  10473.                 return $this->render('@Inventory/pages/print/print_replacement_report.html.twig',
  10474.                     array(
  10475.                         'page_title' => 'Replacement Report',
  10476.                         'page_header' => 'Report',
  10477.                         'print_title' => $print_title,
  10478.                         'document_type' => 'Journal voucher',
  10479.                         'document_mark_image' => $document_mark['original'],
  10480.                         'page_header_sub' => 'Add',
  10481.                         'item_data' => [],
  10482.                         'received' => 2,
  10483.                         'return' => 1,
  10484.                         'total_w_vat' => 1,
  10485.                         'total_vat' => 1,
  10486.                         'total_wo_vat' => 1,
  10487.                         'invoice_id' => 'abcd1234',
  10488.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  10489.                         'created_by' => 'created by',
  10490.                         'created_at' => '',
  10491.                         'red' => 0,
  10492.                         'company_name' => $company_data->getName(),
  10493.                         'company_data' => $company_data,
  10494.                         'company_address' => $company_data->getAddress(),
  10495.                         'company_image' => $company_data->getImage(),
  10496.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10497.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10498.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10499.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10500.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10501.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10502.                         'action_tag' => $warehouse_action_list,
  10503.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10504.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10505.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10506.                         'start_date' => $start_date,
  10507.                         'end_date' => $end_date,
  10508.                         'data_searched' => $data_searched
  10509.                     )
  10510.                 );
  10511.             }
  10512.         }
  10513.         return $this->render('@Inventory/pages/report/replacement_report.html.twig',
  10514.             array(
  10515.                 'page_title' => 'Replacement Report',
  10516.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10517.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10518.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10519.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10520.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10521. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10522.                 'action_tag' => $warehouse_action_list,
  10523.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10524.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10525.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10526.                 'start_date' => $start_date,
  10527.                 'end_date' => $end_date,
  10528.                 'data_searched' => $data_searched,
  10529.                 'success' => empty($data_searched['query_result']) ? false true
  10530.             )
  10531.         );
  10532.     }
  10533.     public
  10534.     function InventoryViewAction(Request $request)
  10535.     {
  10536.         $qry_data = array(
  10537.             'warehouseId' => [0],
  10538.             'igId' => [0],
  10539.             'brandId' => [0],
  10540.             'categoryId' => [0],
  10541.             'actionTagId' => [0],
  10542.         );
  10543.         $em $this->getDoctrine()->getManager();
  10544.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  10545.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  10546.         $data_searched = [];
  10547.         $companyId $this->getLoggedUserCompanyId($request);
  10548.         $company_data Company::getCompanyData($em$companyId);
  10549.         $data = [];
  10550.         $print_title "Inventory Report";
  10551.         $document_mark = array(
  10552.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10553.             'copy' => ''
  10554.         );
  10555.         if ($request->isMethod('POST'))
  10556.             $method 'POST';
  10557.         else
  10558.             $method 'GET';
  10559.         {
  10560. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  10561.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  10562.                 $request->request$method,
  10563.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  10564.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  10565.                 return new JsonResponse(
  10566.                     array(
  10567.                         'page_title' => 'Inventory ',
  10568.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10569.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10570.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10571.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10572.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10573.                         'action_tag' => $warehouse_action_list,
  10574.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10575.                         'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  10576.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10577.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10578.                         'data_searched' => $data_searched,
  10579.                         'success' => empty($data_searched['query_result']) ? false true
  10580.                     )
  10581.                 );
  10582.             }
  10583.             if ($request->request->get('print_data_enabled') == 1) {
  10584.                 $print_sub_title "";
  10585.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  10586.                     array(
  10587.                         'page_title' => 'Inventory Report',
  10588.                         'page_header' => 'Report',
  10589.                         'print_title' => $print_title,
  10590.                         'document_type' => 'Journal voucher',
  10591.                         'document_mark_image' => $document_mark['original'],
  10592.                         'page_header_sub' => 'Add',
  10593.                         'item_data' => [],
  10594.                         'received' => 2,
  10595.                         'return' => 1,
  10596.                         'total_w_vat' => 1,
  10597.                         'total_vat' => 1,
  10598.                         'total_wo_vat' => 1,
  10599.                         'invoice_id' => 'abcd1234',
  10600.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  10601.                         'created_by' => 'created by',
  10602.                         'created_at' => '',
  10603.                         'red' => 0,
  10604.                         'company_name' => $company_data->getName(),
  10605.                         'company_data' => $company_data,
  10606.                         'company_address' => $company_data->getAddress(),
  10607.                         'company_image' => $company_data->getImage(),
  10608.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10609.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10610.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10611.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10612.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10613.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10614.                         'action_tag' => $warehouse_action_list,
  10615.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10616.                         'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  10617.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10618.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10619.                         'data_searched' => $data_searched
  10620.                     )
  10621.                 );
  10622.             }
  10623.         }
  10624.         return $this->render('@Inventory/pages/report/inventory_view.html.twig',
  10625.             array(
  10626.                 'page_title' => 'Inventory',
  10627.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10628.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10629.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10630.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10631.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10632. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10633.                 'action_tag' => $warehouse_action_list,
  10634.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10635.                 'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  10636.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10637.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10638.                 'data_searched' => $data_searched
  10639.             )
  10640.         );
  10641.     }
  10642.     public
  10643.     function GrnListAction(Request $request)
  10644.     {
  10645.         $q $this->getDoctrine()
  10646.             ->getRepository('ApplicationBundle:Grn')
  10647.             ->findBy(
  10648.                 array(
  10649.                     'status' => GeneralConstant::ACTIVE,
  10650. //                    'approved' =>  GeneralConstant::APPROVED,
  10651.                 )
  10652.             );
  10653.         $stage_list = array(
  10654.             => 'Pending',
  10655.             => 'Pending',
  10656.             => 'Complete',
  10657.             => 'Partial',
  10658.         );
  10659.         $data = [];
  10660.         foreach ($q as $entry) {
  10661.             $data[] = array(
  10662.                 'doc_date' => $entry->getGrnDate(),
  10663.                 'id' => $entry->getGrnId(),
  10664.                 'doc_hash' => $entry->getDocumentHash(),
  10665.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  10666.                 'stage' => $stage_list[$entry->getStage()]
  10667.             );
  10668.         }
  10669.         return $this->render('@Inventory/pages/views/grn_list.html.twig',
  10670.             array(
  10671.                 'page_title' => 'Grn List',
  10672.                 'data' => $data
  10673.             )
  10674.         );
  10675.     }
  10676.     public
  10677.     function ViewGrnAction(Request $request$id)
  10678.     {
  10679.         $em $this->getDoctrine()->getManager();
  10680.         $dt Inventory::GetGrnDetails($em$id);
  10681.         return $this->render(
  10682.                                     '@Inventory/pages/views/view_grn.html.twig',
  10683.             array(
  10684.                 'page_title' => 'View',
  10685.                 'data' => $dt,
  10686.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  10687.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10688.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10689.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10690.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10691.                     $id,
  10692.                     $dt['created_by'],
  10693.                     $dt['edited_by'])
  10694.             )
  10695.         );
  10696.     }
  10697.     public
  10698.     function PrintGrnAction(Request $request$id)
  10699.     {
  10700.         $em $this->getDoctrine()->getManager();
  10701.         $dt Inventory::GetGrnDetails($em$id);
  10702.         $company_data Company::getCompanyData($em1);
  10703.         $document_mark = array(
  10704.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10705.             'copy' => ''
  10706.         );
  10707.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10708.             $html $this->renderView('@Inventory/pages/print/print_received_note.html.twig',
  10709.                 array(
  10710.                     //full array here
  10711.                     'pdf' => true,
  10712.                     'page_title' => 'Grn',
  10713.                     'export' => 'pdf,print',
  10714.                     'data' => $dt,
  10715.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10716.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10717.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10718.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10719.                         $id,
  10720.                         $dt['created_by'],
  10721.                         $dt['edited_by']),
  10722.                     'document_mark_image' => $document_mark['original'],
  10723.                     'company_name' => $company_data->getName(),
  10724.                     'company_data' => $company_data,
  10725.                     'company_address' => $company_data->getAddress(),
  10726.                     'company_image' => $company_data->getImage(),
  10727.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10728.                     'red' => 0
  10729.                 )
  10730.             );
  10731.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10732. //                'orientation' => 'landscape',
  10733. //                'enable-javascript' => true,
  10734. //                'javascript-delay' => 1000,
  10735.                 'no-stop-slow-scripts' => false,
  10736.                 'no-background' => false,
  10737.                 'lowquality' => false,
  10738.                 'encoding' => 'utf-8',
  10739. //            'images' => true,
  10740. //            'cookie' => array(),
  10741.                 'dpi' => 300,
  10742.                 'image-dpi' => 300,
  10743. //                'enable-external-links' => true,
  10744. //                'enable-internal-links' => true
  10745.             ));
  10746.             return new Response(
  10747.                 $pdf_response,
  10748.                 200,
  10749.                 array(
  10750.                     'Content-Type' => 'application/pdf',
  10751.                     'Content-Disposition' => 'attachment; filename="grn.pdf"'
  10752.                 )
  10753.             );
  10754.         }
  10755.         return $this->render('@Inventory/pages/print/print_received_note.html.twig',
  10756.             array(
  10757.                 'page_title' => 'Grn',
  10758.                 'export' => 'pdf,print',
  10759.                 'data' => $dt,
  10760.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10761.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10762.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10763.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10764.                     $id,
  10765.                     $dt['created_by'],
  10766.                     $dt['edited_by']),
  10767.                 'document_mark_image' => $document_mark['original'],
  10768.                 'company_name' => $company_data->getName(),
  10769.                 'company_data' => $company_data,
  10770.                 'company_address' => $company_data->getAddress(),
  10771.                 'company_image' => $company_data->getImage(),
  10772.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10773.                 'red' => 0
  10774.             )
  10775.         );
  10776.     }
  10777.     public
  10778.     function PrintGrnBarcodeAction(Request $request$id)
  10779.     {
  10780.         $em $this->getDoctrine()->getManager();
  10781.         $dt Inventory::GetGrnDetails($em$id);
  10782.         $company_data Company::getCompanyData($em1);
  10783.         $repeatCount 1;
  10784.         if ($request->query->has('repeatCount'))
  10785.             $repeatCount $request->query->get('repeatCount');
  10786.         $document_mark = array(
  10787.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10788.             'copy' => ''
  10789.         );
  10790.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10791.             $html $this->renderView('@Inventory/pages/print/print_grn_barcodes.html.twig',
  10792.                 array(
  10793.                     //full array here
  10794.                     'pdf' => true,
  10795.                     'page_title' => 'Grn Barcodes',
  10796.                     'export' => 'print',
  10797.                     'data' => $dt,
  10798.                     'repeatCount' => $repeatCount,
  10799.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10800.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10801.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10802.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10803.                         $id,
  10804.                         $dt['created_by'],
  10805.                         $dt['edited_by']),
  10806.                     'document_mark_image' => $document_mark['original'],
  10807.                     'company_name' => $company_data->getName(),
  10808.                     'company_data' => $company_data,
  10809.                     'company_address' => $company_data->getAddress(),
  10810.                     'company_image' => $company_data->getImage(),
  10811.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10812.                     'red' => 0
  10813.                 )
  10814.             );
  10815.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10816. //                'orientation' => 'landscape',
  10817.                 'enable-javascript' => true,
  10818. //                'javascript-delay' => 1000,
  10819.                 'no-stop-slow-scripts' => false,
  10820.                 'no-background' => false,
  10821.                 'lowquality' => false,
  10822.                 'encoding' => 'utf-8',
  10823. //            'images' => true,
  10824. //            'cookie' => array(),
  10825.                 'dpi' => 300,
  10826.                 'image-dpi' => 300,
  10827. //                'enable-external-links' => true,
  10828. //                'enable-internal-links' => true
  10829.             ));
  10830.             return new Response(
  10831.                 $pdf_response,
  10832.                 200,
  10833.                 array(
  10834.                     'Content-Type' => 'application/pdf',
  10835.                     'Content-Disposition' => 'attachment; filename="grn_barcodes.pdf"'
  10836.                 )
  10837.             );
  10838.         }
  10839.         return $this->render('@Inventory/pages/print/print_grn_barcodes.html.twig',
  10840.             array(
  10841.                 'page_title' => 'Grn barcodes',
  10842. //                'export'=>'pdf,print',
  10843.                 'data' => $dt,
  10844.                 'repeatCount' => $repeatCount,
  10845.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10846.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10847.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10848.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10849.                     $id,
  10850.                     $dt['created_by'],
  10851.                     $dt['edited_by']),
  10852.                 'document_mark_image' => $document_mark['original'],
  10853.                 'company_name' => $company_data->getName(),
  10854.                 'company_data' => $company_data,
  10855.                 'company_address' => $company_data->getAddress(),
  10856.                 'company_image' => $company_data->getImage(),
  10857.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10858.                 'red' => 0
  10859.             )
  10860.         );
  10861.     }
  10862.     public
  10863.     function GenerateBarcodeAction(Request $request$type$id$item_id)
  10864.     {
  10865.         $em $this->getDoctrine()->getManager();
  10866.         $repeatCount 1;
  10867.         $spec_item_id 0;
  10868.         $skip_ids = [];
  10869.         $clearUnnecessaryOnly 0;
  10870.         if ($request->query->has('skipIds'))
  10871.             $skip_ids $request->query->get('skipIds');
  10872.         if ($request->query->has('clearUnnecessaryOnly'))
  10873.             $clearUnnecessaryOnly $request->query->get('clearUnnecessaryOnly');
  10874.         if ($type == 'srcv') {
  10875.             $doc_data $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  10876.                 array(
  10877.                     'stockReceivedNoteId' => $id
  10878.                 )
  10879.             );
  10880.             if ($item_id == '_single_') {
  10881.                 $doc_item_data $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
  10882.                     array(
  10883.                         'stockReceivedNoteId' => $id,
  10884. //                        'id' => $item_id
  10885.                     )
  10886.                 );
  10887.             } else {
  10888.                 $doc_item_data $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
  10889.                     array(
  10890.                         'stockReceivedNoteId' => $id,
  10891.                         'id' => $item_id
  10892.                     )
  10893.                 );
  10894.             }
  10895.             $inv_acc_data = [
  10896.                 'fa_amount' => 0,
  10897.                 'tg_amount' => 0,
  10898.             ];
  10899.             $inv_acc_data_by_head = [
  10900.             ];
  10901.             $new_non_delivered_sales_code_range = [];
  10902.             foreach ($doc_item_data as $entry) {
  10903.                 //adding transaction
  10904.                 $sales_code_range_ser = [];
  10905.                 if (in_array($entry->getId(), $skip_ids))
  10906.                     continue;
  10907.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10908.                     ->findOneBy(
  10909.                         array(
  10910.                             'id' => $entry->getProductId()
  10911.                         )
  10912.                     );
  10913.                 $stitem $em->getRepository('ApplicationBundle:StockTransferItem')
  10914.                     ->findOneBy(
  10915.                         array(
  10916.                             'id' => $entry->getStockTransferItemId(),
  10917.                             'productId' => $entry->getProductId()
  10918.                         )
  10919.                     );
  10920.                 if ($product) {
  10921.                     if ($product->getHasSerial() == 1) {
  10922.                         //clear if exists
  10923.                         if ($clearUnnecessaryOnly == 1) {
  10924.                             $get_kids_sql "DELETE FROM product_by_code
  10925.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10926. //                $get_kids_sql .=' ORDER BY name ASC';
  10927.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  10928.                             $stmt->execute();
  10929.                             $em->flush();
  10930.                         } else {
  10931.                             $get_kids_sql "DELETE FROM product_by_code
  10932.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10933. //                $get_kids_sql .=' ORDER BY name ASC';
  10934.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  10935.                             $stmt->execute();
  10936.                             $em->flush();
  10937.                         }
  10938. //                        $check_here = $stmt->fetchAll();
  10939.                         //now addng product by code
  10940.                         $sales_code_range = [];
  10941.                         if ($doc_data->getType() == || $doc_data->getType() == 4) {
  10942. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10943. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10944.                             $product_action_tag_id $entry->getWarehouseActionId();
  10945.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getQty(),
  10946.                                 $doc_data->getStockReceivedNoteDate(), $entry->getWarrantyMon(), 0$doc_data->getCompanyId(), $entry->getWarehouseId(),
  10947.                                 $entry->getWarehouseActionId(), $entry->getPurchaseCodeRange(), nullnullnullnull$doc_data->getStockReceivedNoteId()
  10948.                             );
  10949.                             $sales_code_range $barcodeData['sales_code_range'];
  10950.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  10951.                             $em->flush();
  10952.                         }
  10953. //                        else {
  10954. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10955. //
  10956. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10957. //                            } else {
  10958. //
  10959. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10960. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10961. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10962. //                            }
  10963. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10964. //
  10965. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10966. //                            } else {
  10967. //
  10968. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10969. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10970. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10971. //                            }
  10972. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10973. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10974. //                            $new_non_delivered_sales_code_range = [];
  10975. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10976. //                                if (!(in_array($ndsc, $sales_code_range)))
  10977. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10978. //                            }
  10979. //                            if ($sales_code_range != null) {
  10980. //                                foreach ($sales_code_range as $ind => $dt) {
  10981. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  10982. //                                        ->findOneBy(
  10983. //                                            array(
  10984. //                                                'salesCode' => [$dt],
  10985. //                                                'productId' => $entry->getProductId()
  10986. //                                            )
  10987. //                                        );
  10988. //
  10989. //                                    if ($np) {
  10990. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10991. //                                        $np->setProductId($entry->getProductId());
  10992. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10993. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10994. //                                        $np->setPosition(1);//in warehouse
  10995. //                                        $np->setStockReceivedNoteId($id);
  10996. //
  10997. //
  10998. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10999. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  11000. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  11001. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  11002. //                                            'direction' => 'in',
  11003. //                                            'warehouseId' => $entry->getWarehouseId(),
  11004. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  11005. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  11006. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  11007. //                                        );
  11008. //                                        $np->setTransactionHistory(json_encode(
  11009. //                                            $trans_history
  11010. //                                        ));
  11011. //
  11012. //
  11013. //                                        $em->persist($np);
  11014. //                                        $em->flush();
  11015. //                                    }
  11016. //                                }
  11017. //                            }
  11018. //                        }
  11019.                     }
  11020.                 }
  11021.                 //adding transaction
  11022.                 if ($stitem) {
  11023.                     $stitem->setNonDeliveredSalesCodeRange(json_encode($new_non_delivered_sales_code_range));
  11024.                 }
  11025.                 $spec_item_id $entry->getId();
  11026.                 if ($item_id == '_single_') {
  11027.                     break;
  11028.                 }
  11029.             }
  11030.         }
  11031.         if ($type == 'irr') {
  11032.             $doc_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacement')->findOneBy(
  11033.                 array(
  11034.                     'itemReceivedAndReplacementId' => $id
  11035.                 )
  11036.             );
  11037.             if ($item_id == '_single_') {
  11038.                 $doc_item_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
  11039.                     array(
  11040.                         'itemReceivedAndReplacementId' => $id,
  11041. //                        'id' => $item_id
  11042.                     )
  11043.                 );
  11044.             } else {
  11045.                 $doc_item_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
  11046.                     array(
  11047.                         'itemReceivedAndReplacementId' => $id,
  11048.                         'id' => $item_id
  11049.                     )
  11050.                 );
  11051.             }
  11052.             $inv_acc_data = [
  11053.                 'fa_amount' => 0,
  11054.                 'tg_amount' => 0,
  11055.             ];
  11056.             $inv_acc_data_by_head = [
  11057.             ];
  11058.             $new_non_delivered_sales_code_range = [];
  11059.             foreach ($doc_item_data as $entry) {
  11060.                 //adding transaction
  11061.                 $sales_code_range_ser = [];
  11062.                 if (in_array($entry->getId(), $skip_ids))
  11063.                     continue;
  11064.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  11065.                     ->findOneBy(
  11066.                         array(
  11067.                             'id' => $entry->getReceivedProductId()
  11068.                         )
  11069.                     );
  11070.                 if ($product) {
  11071.                     if ($product->getHasSerial() == 1) {
  11072.                         //clear if exists
  11073. //                        if($clearUnnecessaryOnly==1) {
  11074. //                            $get_kids_sql = "DELETE FROM product_by_code
  11075. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  11076. ////                $get_kids_sql .=' ORDER BY name ASC';
  11077. //
  11078. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  11079. //                            $stmt->execute();
  11080. //                            $em->flush();
  11081. //                        }
  11082. //                        else{
  11083. //                            $get_kids_sql = "DELETE FROM product_by_code
  11084. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  11085. ////                $get_kids_sql .=' ORDER BY name ASC';
  11086. //
  11087. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  11088. //                            $stmt->execute();
  11089. //                            $em->flush();
  11090. //                        }
  11091. //                        $check_here = $stmt->fetchAll();
  11092.                         //now addng product by code
  11093.                         $sales_code_range = [];
  11094.                         if ($entry->getReceivedQty() > 0) {
  11095. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  11096. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  11097. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  11098.                             $barcodeData Inventory::GenerateBarcode($em$entry->getReceivedProductId(), $entry->getReceivedQty(),
  11099.                                 $doc_data->getItemReceivedAndReplacementDate(), 00$doc_data->getCompanyId(), $entry->getReceivedWarehouseId(),
  11100.                                 $entry->getReceivedWarehouseActionId(), nullnullnullnullnullnullnullnull$doc_data->getItemReceivedAndReplacementId()
  11101.                             );
  11102.                             $sales_code_range $barcodeData['sales_code_range'];
  11103.                             $entry->setReceivedCodeRange(json_encode($sales_code_range));
  11104.                             $em->flush();
  11105.                         }
  11106. //                        else {
  11107. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11108. //
  11109. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11110. //                            } else {
  11111. //
  11112. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11113. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  11114. //                                $sales_code_range = json_decode($json_without_bigints, true);
  11115. //                            }
  11116. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11117. //
  11118. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11119. //                            } else {
  11120. //
  11121. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11122. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  11123. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  11124. //                            }
  11125. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  11126. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  11127. //                            $new_non_delivered_sales_code_range = [];
  11128. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  11129. //                                if (!(in_array($ndsc, $sales_code_range)))
  11130. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  11131. //                            }
  11132. //                            if ($sales_code_range != null) {
  11133. //                                foreach ($sales_code_range as $ind => $dt) {
  11134. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  11135. //                                        ->findOneBy(
  11136. //                                            array(
  11137. //                                                'salesCode' => [$dt],
  11138. //                                                'productId' => $entry->getProductId()
  11139. //                                            )
  11140. //                                        );
  11141. //
  11142. //                                    if ($np) {
  11143. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  11144. //                                        $np->setProductId($entry->getProductId());
  11145. //                                        $np->setWarehouseId($entry->getWarehouseId());
  11146. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  11147. //                                        $np->setPosition(1);//in warehouse
  11148. //                                        $np->setStockReceivedNoteId($id);
  11149. //
  11150. //
  11151. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  11152. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  11153. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  11154. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  11155. //                                            'direction' => 'in',
  11156. //                                            'warehouseId' => $entry->getWarehouseId(),
  11157. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  11158. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  11159. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  11160. //                                        );
  11161. //                                        $np->setTransactionHistory(json_encode(
  11162. //                                            $trans_history
  11163. //                                        ));
  11164. //
  11165. //
  11166. //                                        $em->persist($np);
  11167. //                                        $em->flush();
  11168. //                                    }
  11169. //                                }
  11170. //                            }
  11171. //                        }
  11172.                     }
  11173.                 }
  11174.                 //adding transaction
  11175.                 $spec_item_id $entry->getId();
  11176.                 if ($item_id == '_single_') {
  11177.                     break;
  11178.                 }
  11179.             }
  11180.         }
  11181.         if ($type == 'prdcn') {
  11182.             $doc_data $em->getRepository('ApplicationBundle:Production')->findOneBy(
  11183.                 array(
  11184.                     'productionId' => $id
  11185.                 )
  11186.             );
  11187.             if ($item_id == '_single_') {
  11188.                 $doc_item_data $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
  11189.                     array(
  11190.                         'productionId' => $id,
  11191. //                        'id' => $item_id
  11192.                     )
  11193.                 );
  11194.             } else {
  11195.                 $doc_item_data $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
  11196.                     array(
  11197.                         'productionId' => $id,
  11198.                         'id' => $item_id
  11199.                     )
  11200.                 );
  11201.             }
  11202.             $inv_acc_data = [
  11203.                 'fa_amount' => 0,
  11204.                 'tg_amount' => 0,
  11205.             ];
  11206.             $inv_acc_data_by_head = [
  11207.             ];
  11208.             $new_non_delivered_sales_code_range = [];
  11209.             foreach ($doc_item_data as $entry) {
  11210.                 //adding transaction
  11211.                 $sales_code_range_ser = [];
  11212.                 if (in_array($entry->getId(), $skip_ids))
  11213.                     continue;
  11214.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  11215.                     ->findOneBy(
  11216.                         array(
  11217.                             'id' => $entry->getProductId()
  11218.                         )
  11219.                     );
  11220.                 if ($product) {
  11221.                     if ($product->getHasSerial() == 1) {
  11222.                         //clear if exists
  11223. //                        if($clearUnnecessaryOnly==1) {
  11224. //                            $get_kids_sql = "DELETE FROM product_by_code
  11225. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  11226. ////                $get_kids_sql .=' ORDER BY name ASC';
  11227. //
  11228. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  11229. //                            $stmt->execute();
  11230. //                            $em->flush();
  11231. //                        }
  11232. //                        else{
  11233. //                            $get_kids_sql = "DELETE FROM product_by_code
  11234. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  11235. ////                $get_kids_sql .=' ORDER BY name ASC';
  11236. //
  11237. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  11238. //                            $stmt->execute();
  11239. //                            $em->flush();
  11240. //                        }
  11241. //                        $check_here = $stmt->fetchAll();
  11242.                         //now addng product by code
  11243.                         $sales_code_range = [];
  11244.                         if ($entry->getProducedQty() > 0) {
  11245. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  11246. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  11247. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  11248.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getProducedQty(),
  11249.                                 $doc_data->getProductionDate(), 00$doc_data->getCompanyId(), $entry->getWarehouseId(),
  11250.                                 $entry->getProducedItemActionTagId(), nullnullnullnullnullnullnull$doc_data->getProductionId(), null
  11251.                             );
  11252.                             $sales_code_range $barcodeData['sales_code_range'];
  11253.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  11254.                             $em->flush();
  11255.                         }
  11256. //                        else {
  11257. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11258. //
  11259. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11260. //                            } else {
  11261. //
  11262. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11263. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  11264. //                                $sales_code_range = json_decode($json_without_bigints, true);
  11265. //                            }
  11266. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11267. //
  11268. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11269. //                            } else {
  11270. //
  11271. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11272. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  11273. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  11274. //                            }
  11275. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  11276. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  11277. //                            $new_non_delivered_sales_code_range = [];
  11278. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  11279. //                                if (!(in_array($ndsc, $sales_code_range)))
  11280. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  11281. //                            }
  11282. //                            if ($sales_code_range != null) {
  11283. //                                foreach ($sales_code_range as $ind => $dt) {
  11284. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  11285. //                                        ->findOneBy(
  11286. //                                            array(
  11287. //                                                'salesCode' => [$dt],
  11288. //                                                'productId' => $entry->getProductId()
  11289. //                                            )
  11290. //                                        );
  11291. //
  11292. //                                    if ($np) {
  11293. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  11294. //                                        $np->setProductId($entry->getProductId());
  11295. //                                        $np->setWarehouseId($entry->getWarehouseId());
  11296. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  11297. //                                        $np->setPosition(1);//in warehouse
  11298. //                                        $np->setStockReceivedNoteId($id);
  11299. //
  11300. //
  11301. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  11302. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  11303. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  11304. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  11305. //                                            'direction' => 'in',
  11306. //                                            'warehouseId' => $entry->getWarehouseId(),
  11307. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  11308. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  11309. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  11310. //                                        );
  11311. //                                        $np->setTransactionHistory(json_encode(
  11312. //                                            $trans_history
  11313. //                                        ));
  11314. //
  11315. //
  11316. //                                        $em->persist($np);
  11317. //                                        $em->flush();
  11318. //                                    }
  11319. //                                }
  11320. //                            }
  11321. //                        }
  11322.                     }
  11323.                 }
  11324.                 //adding transaction
  11325.                 $spec_item_id $entry->getId();
  11326.                 if ($item_id == '_single_') {
  11327.                     break;
  11328.                 }
  11329.             }
  11330.         }
  11331.         return new JsonResponse(array(
  11332.             'success' => $spec_item_id != true false,
  11333.             'skipIds' => [],
  11334.             'spec_item_id' => $spec_item_id
  11335.         ));
  11336. //        return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  11337. //            array(
  11338. //                'page_title' => 'Srcv barcodes',
  11339. ////                'export'=>'pdf,print',
  11340. //                'data' => $dt,
  11341. //                'repeatCount' => $repeatCount,
  11342. //                'item_id' => $item_id,
  11343. //                'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11344. //                    $id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11345. //                'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11346. //                    array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11347. //                    $id,
  11348. //                    $dt['created_by'],
  11349. //                    $dt['edited_by']),
  11350. //                'document_mark_image' => $document_mark['original'],
  11351. //                                    'company_name' => $company_data->getName(),
  11352. //                    'company_data'=>$company_data,
  11353. //                'company_address' => $company_data->getAddress(),
  11354. //                'company_image' => $company_data->getImage(),
  11355. //                'invoice_footer' => $company_data->getInvoiceFooter(),
  11356. //                'red' => 0
  11357. //
  11358. //            )
  11359. //        );
  11360.     }
  11361.     public
  11362.     function PrintLabelAction(Request $request$id)
  11363.     {
  11364.         $em $this->getDoctrine()->getManager();
  11365. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11366.         $repeatCount 1;
  11367.         $assignProductId '';
  11368.         $productByCodeIds = [];
  11369.         $print_selection_type 1;
  11370.         $print_selection_string 1;
  11371.         $assignLabelFormatId 0;
  11372.         $assignColorId 0;
  11373.         $assignProductionScheduleId 0;
  11374.         $warehouseId '';
  11375.         $warehouseActionId '';
  11376.         $toAssignPosition '';
  11377.         $printFlag $request->request->has('printFlag') ? $request->request->get('printFlag') : 1;
  11378.         $returnJson $request->request->has('returnJson') ? $request->request->get('returnJson') : 0;
  11379.         if ($returnJson == 1)
  11380.             $printFlag 0;
  11381.         $companyId $this->getLoggedUserCompanyId($request);
  11382.         if ($request->query->has('repeatCount'))
  11383.             $repeatCount $request->query->get('repeatCount');
  11384.         if ($request->request->has('print_selection_type'))
  11385.             $print_selection_type $request->request->get('print_selection_type');
  11386.         if ($request->request->has('print_selection_string'))
  11387.             $print_selection_string $request->request->get('print_selection_string');
  11388.         if ($request->request->has('productByCodeIds'))
  11389.             $productByCodeIds json_decode($request->request->get('productByCodeIds'), true);
  11390.         if ($request->request->has('formatId'))
  11391.             $assignLabelFormatId $request->request->get('formatId');
  11392.         if ($printFlag == 0) {
  11393.             if ($request->request->has('productSelector'))
  11394.                 $assignProductId $request->request->get('productSelector');
  11395.             if ($request->request->has('colorId'))
  11396.                 $assignColorId $request->request->get('colorId');
  11397.             if ($request->request->has('productionScheduleId'))
  11398.                 $assignProductionScheduleId $request->request->get('productionScheduleId');
  11399.             if ($request->request->has('warehouseId'))
  11400.                 $warehouseId $request->request->get('warehouseId');
  11401.             if ($request->request->has('warehouseActionId'))
  11402.                 $warehouseActionId $request->request->get('warehouseActionId');
  11403.             if ($request->request->has('position'))
  11404.                 $toAssignPosition $request->request->get('position');
  11405.             if ($assignColorId == '')
  11406.                 $assignColorId 0;
  11407.         }
  11408.         if ($productByCodeIds == null)
  11409.             $productByCodeIds = [];
  11410.         $productByCodeData = [];
  11411.         $productList = [];
  11412.         $productIds = [];
  11413.         if ($print_selection_type == 2) {
  11414.             //range
  11415.             $productByCodeIds Inventory::getIdsFromIdSelectionStr($print_selection_string);
  11416.         }
  11417.         $labelData = [
  11418.             'formatId' => 0
  11419.         ];
  11420.         $formatId 0;
  11421.         if (!empty($productByCodeIds)) {
  11422.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11423.                 ->findBy(
  11424.                     array(
  11425.                         'productByCodeId' => $productByCodeIds
  11426.                     )
  11427.                 );
  11428.             foreach ($productByCodeData as $d) {
  11429.                 if ($d->getStage() < 10$d->setStage(11);
  11430.                 if ($assignProductId != '') {
  11431.                     $d->setProductId($assignProductId);
  11432.                 }
  11433.                 if ($assignColorId != 0) {
  11434.                     $d->setColorId($assignColorId);
  11435.                 } else {
  11436.                     $productData $em->getRepository('ApplicationBundle:InvProducts')
  11437.                         ->findOneBy(
  11438.                             array(
  11439.                                 'id' => $assignProductId
  11440.                             )
  11441.                         );
  11442.                     if ($productData) {
  11443.                         $d->setColorId($productData->getDefaultColorId());
  11444.                     }
  11445.                 }
  11446.                 if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  11447.                     $d->setDefaultLabelFormatId($assignLabelFormatId);
  11448.                     $d->setDeviceLabelFormatId($assignLabelFormatId);
  11449.                 }
  11450.                 $toAssignPosition != '' $d->setPosition($toAssignPosition) : '';
  11451.                 $warehouseId != '' $d->setWarehouseId($warehouseId) : '';
  11452.                 $warehouseActionId != '' $d->setWarehouseActionId($warehouseActionId) : '';
  11453.                 if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  11454.                     $d->setProductionScheduleId($assignProductionScheduleId);
  11455.                     $productionSchedule $em->getRepository('ApplicationBundle:ProductionSchedule')
  11456.                         ->findOneBy(
  11457.                             array(
  11458.                                 'productionScheduleId' => $assignProductionScheduleId
  11459.                             )
  11460.                         );
  11461.                     if ($productionSchedule) {
  11462.                         if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  11463.                             //becuase it will assigned at previous lines
  11464.                         } else {
  11465.                             $d->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  11466.                             $d->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  11467.                         }
  11468.                         $d->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  11469.                         $d->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  11470.                     }
  11471.                 }
  11472.                 $em->flush();
  11473.                 if ($d->getProductId() != '' || $d->getProductId() != null)
  11474.                     $productIds[] = $d->getProductId();
  11475.                 $formatId $d->getDeviceLabelFormatId();
  11476.             }
  11477.         }
  11478.         $labelFormatHere $em->getRepository('ApplicationBundle:LabelFormat')
  11479.             ->findOneBy(
  11480.                 array(
  11481.                     'formatId' => $formatId,
  11482. //                        'CompanyId' => $companyId
  11483.                 )
  11484.             );
  11485.         if ($labelFormatHere) {
  11486.             $formatData json_decode($labelFormatHere->getFormatData(), true);
  11487.             if ($formatData == null$formatData = [];
  11488.             $labelData = array(
  11489.                 'id' => $labelFormatHere->getFormatId(),
  11490.                 'formatId' => $labelFormatHere->getFormatId(),
  11491.                 'labelType' => $labelFormatHere->getLabelType(),
  11492.                 'name' => $labelFormatHere->getName(),
  11493.                 'width' => $labelFormatHere->getWidth(),
  11494.                 'pageWidth' => $labelFormatHere->getPageWidth(),
  11495.                 'height' => $labelFormatHere->getheight(),
  11496.                 'pageHeight' => $labelFormatHere->getPageHeight(),
  11497.                 'formatData' => $formatData,
  11498.             );
  11499.         }
  11500.         $productList Inventory::ProductList($em$this->getLoggedUserCompanyId($request), 10''$productIds);
  11501.         $company_data Company::getCompanyData($em1);
  11502.         $document_mark = array(
  11503.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11504.             'copy' => ''
  11505.         );
  11506.         $dt $productByCodeData;
  11507.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11508.             $html $this->renderView('@Inventory/pages/print/print_label.html.twig',
  11509.                 array(
  11510.                     //full array here
  11511.                     'pdf' => true,
  11512.                     'page_title' => 'Device Labels',
  11513.                     'export' => 'print',
  11514.                     'repeatCount' => $repeatCount,
  11515.                     'labelData' => $labelData,
  11516.                     'brandList' => Inventory::GetBrandList($em$companyId),
  11517. //                    'item_id' => $item_id,
  11518.                     'data' => $dt,
  11519.                     'productList' => $productList,
  11520.                     'approval_data' => [],
  11521.                     'document_log' => [],
  11522.                     'document_mark_image' => $document_mark['original'],
  11523.                     'company_name' => $company_data->getName(),
  11524.                     'company_data' => $company_data,
  11525.                     'company_address' => $company_data->getAddress(),
  11526.                     'company_image' => $company_data->getImage(),
  11527.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11528.                     'red' => 0
  11529.                 )
  11530.             );
  11531.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11532. //                'orientation' => 'landscape',
  11533.                 'enable-javascript' => true,
  11534. //                'javascript-delay' => 1000,
  11535.                 'no-stop-slow-scripts' => false,
  11536.                 'no-background' => false,
  11537.                 'lowquality' => false,
  11538.                 'encoding' => 'utf-8',
  11539. //            'images' => true,
  11540. //            'cookie' => array(),
  11541.                 'dpi' => 300,
  11542.                 'image-dpi' => 300,
  11543. //                'enable-external-links' => true,
  11544. //                'enable-internal-links' => true
  11545.             ));
  11546.             return new Response(
  11547.                 $pdf_response,
  11548.                 200,
  11549.                 array(
  11550.                     'Content-Type' => 'application/pdf',
  11551.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11552.                 )
  11553.             );
  11554.         }
  11555.         $url $this->generateUrl(
  11556.             'print_label'
  11557.         );
  11558.         if ($returnJson == && $printFlag == 0) {
  11559. //                    $dr = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  11560. //                        array(
  11561. //                            'salesOrderId' => $orderId, ///material
  11562. //
  11563. //                        )
  11564. //                    );
  11565.             return new JsonResponse(array(
  11566.                 'success' => true,
  11567. //                        'documentHash' => $order->getDocumentHash(),
  11568. //                'documentId' => $receiptId,
  11569. //                'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
  11570. //
  11571. //                'viewUrl' => $url . "/" . $receiptId,
  11572.             ));
  11573.         } else return $this->render('@Inventory/pages/print/print_label.html.twig',
  11574.             array(
  11575.                 'page_title' => 'Product Labels',
  11576. //                'export'=>'pdf,print',
  11577.                 'data' => $dt,
  11578.                 'productList' => $productList,
  11579.                 'repeatCount' => $repeatCount,
  11580. //                'item_id' => $item_id,
  11581.                 'labelData' => $labelData,
  11582.                 'brandList' => Inventory::GetBrandList($em$companyId),
  11583.                 'approval_data' => [],
  11584.                 'document_log' => [],
  11585.                 'document_mark_image' => $document_mark['original'],
  11586.                 'company_name' => $company_data->getName(),
  11587.                 'company_data' => $company_data,
  11588.                 'company_address' => $company_data->getAddress(),
  11589.                 'company_image' => $company_data->getImage(),
  11590.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11591.                 'red' => 0
  11592.             )
  11593.         );
  11594.     }
  11595.     public
  11596.     function PrintCartonLabelAction(Request $request$id)
  11597.     {
  11598.         $em $this->getDoctrine()->getManager();
  11599. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11600.         $repeatCount 1;
  11601.         $assignProductId '';
  11602.         $productByCodeIds = [];
  11603.         $cartonId 0;
  11604.         if ($id != 0)
  11605.             $cartonId $id;
  11606.         $colorText '';
  11607.         $weightText '';
  11608.         if ($request->query->has('repeatCount'))
  11609.             $repeatCount $request->query->get('repeatCount');
  11610.         if ($request->request->has('printCartonId'))
  11611.             $cartonId $request->request->get('printCartonId');
  11612.         if ($request->request->has('printCartonColorText'))
  11613.             $colorText $request->request->get('printCartonColorText');
  11614.         if ($request->request->has('printCartonWeightText'))
  11615.             $weightText $request->request->get('printCartonWeightText');
  11616.         $labelData = [
  11617.             'formatId' => 0
  11618.         ];
  11619.         if ($productByCodeIds == null)
  11620.             $productByCodeIds = [];
  11621.         $productByCodeData = [];
  11622.         $cartonData = [];
  11623.         $product = [];
  11624.         if ($cartonId != 0) {
  11625.             $cartonData $em->getRepository('ApplicationBundle:Carton')
  11626.                 ->findOneBy(
  11627.                     array(
  11628.                         'id' => $cartonId
  11629.                     )
  11630.                 );
  11631.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11632.                 ->findBy(
  11633.                     array(
  11634.                         'cartonId' => $cartonId
  11635.                     )
  11636.                 );
  11637. //            if(!empty($productByCodeData))
  11638. //                $product = $em->getRepository('ApplicationBundle:InvProducts')
  11639. //                ->findOneBy(
  11640. //                    array(
  11641. //                        'id' => $productByCodeData[0]->getProductId()
  11642. //                    )
  11643. //                );
  11644. //            else
  11645.             $product $em->getRepository('ApplicationBundle:InvProducts')
  11646.                 ->findOneBy(
  11647.                     array(
  11648.                         'id' => $cartonData->getProductId()
  11649.                     )
  11650.                 );
  11651.             $formatId $cartonData->getCartonLabelFormatId();
  11652.             $labelFormatHere $em->getRepository('ApplicationBundle:LabelFormat')
  11653.                 ->findOneBy(
  11654.                     array(
  11655.                         'formatId' => $formatId,
  11656. //                        'CompanyId' => $companyId
  11657.                     )
  11658.                 );
  11659.             if ($labelFormatHere) {
  11660.                 $formatData json_decode($labelFormatHere->getFormatData(), true);
  11661.                 if ($formatData == null$formatData = [];
  11662.                 $labelData = array(
  11663.                     'id' => $labelFormatHere->getFormatId(),
  11664.                     'formatId' => $labelFormatHere->getFormatId(),
  11665.                     'labelType' => $labelFormatHere->getLabelType(),
  11666.                     'name' => $labelFormatHere->getName(),
  11667.                     'width' => $labelFormatHere->getWidth(),
  11668.                     'pageWidth' => $labelFormatHere->getPageWidth(),
  11669.                     'height' => $labelFormatHere->getheight(),
  11670.                     'pageHeight' => $labelFormatHere->getPageHeight(),
  11671.                     'formatData' => $formatData,
  11672.                 );
  11673.             }
  11674.         }
  11675.         $company_data Company::getCompanyData($em1);
  11676.         $document_mark = array(
  11677.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11678.             'copy' => ''
  11679.         );
  11680.         $dt $productByCodeData;
  11681.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11682.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  11683.                 array(
  11684.                     //full array here
  11685.                     'pdf' => true,
  11686.                     'page_title' => 'Carton Labels',
  11687.                     'export' => 'print',
  11688.                     'labelData' => $labelData,
  11689.                     'repeatCount' => $repeatCount,
  11690. //                    'item_id' => $item_id,
  11691.                     'data' => $dt,
  11692.                     'cartonData' => $cartonData,
  11693.                     'product' => $product,
  11694.                     'colorText' => $colorText,
  11695.                     'weightText' => $weightText,
  11696.                     'approval_data' => [],
  11697.                     'document_log' => [],
  11698.                     'document_mark_image' => $document_mark['original'],
  11699.                     'company_name' => $company_data->getName(),
  11700.                     'company_data' => $company_data,
  11701.                     'company_address' => $company_data->getAddress(),
  11702.                     'company_image' => $company_data->getImage(),
  11703.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11704.                     'red' => 0
  11705.                 )
  11706.             );
  11707.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11708. //                'orientation' => 'landscape',
  11709.                 'enable-javascript' => true,
  11710. //                'javascript-delay' => 1000,
  11711.                 'no-stop-slow-scripts' => false,
  11712.                 'no-background' => false,
  11713.                 'lowquality' => false,
  11714.                 'encoding' => 'utf-8',
  11715. //            'images' => true,
  11716. //            'cookie' => array(),
  11717.                 'dpi' => 300,
  11718.                 'image-dpi' => 300,
  11719. //                'enable-external-links' => true,
  11720. //                'enable-internal-links' => true
  11721.             ));
  11722.             return new Response(
  11723.                 $pdf_response,
  11724.                 200,
  11725.                 array(
  11726.                     'Content-Type' => 'application/pdf',
  11727.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11728.                 )
  11729.             );
  11730.         }
  11731.         if ($request->query->has('previewOnly')) {
  11732.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  11733.                 array(
  11734.                     'page_title' => 'Carton Labels',
  11735. //                'export'=>'pdf,print',
  11736.                     'data' => $dt,
  11737.                     'skip_parameters' => 1,
  11738.                     'labelData' => $labelData,
  11739.                     'cartonData' => $cartonData,
  11740.                     'product' => $product,
  11741.                     'colorText' => $colorText,
  11742.                     'weightText' => $weightText,
  11743.                     'repeatCount' => $repeatCount,
  11744. //                'item_id' => $item_id,
  11745.                     'approval_data' => [],
  11746.                     'document_log' => [],
  11747.                     'document_mark_image' => $document_mark['original'],
  11748.                     'company_name' => $company_data->getName(),
  11749.                     'company_data' => $company_data,
  11750.                     'company_address' => $company_data->getAddress(),
  11751.                     'company_image' => $company_data->getImage(),
  11752.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11753.                     'red' => 0
  11754.                 )
  11755.             );
  11756.             if ($request->query->has('returnJson')) {
  11757.                 return new JsonResponse(
  11758.                     array(
  11759.                         'success' => true,
  11760.                         'page_title' => 'Product Details',
  11761.                         'company_data' => $company_data,
  11762.                         'renderedHtml' => $html,
  11763. //                'productData' => $productData,
  11764. //                'currInvList' => $currInvList,
  11765. //                'productList' => Inventory::ProductList($em, $companyId),
  11766. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11767. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11768. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11769. //                'unitList' => Inventory::UnitTypeList($em),
  11770. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11771. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11772. //                'warehouseList' => Inventory::WarehouseList($em),
  11773.                     )
  11774.                 );
  11775.             }
  11776.         }
  11777.         return $this->render('@Inventory/pages/print/print_carton_label.html.twig',
  11778.             array(
  11779.                 'page_title' => 'Carton Labels',
  11780. //                'export'=>'pdf,print',
  11781.                 'data' => $dt,
  11782.                 'cartonData' => $cartonData,
  11783.                 'product' => $product,
  11784. //                'productByCodeData' => $productByCodeData,
  11785.                 'colorText' => $colorText,
  11786.                 'weightText' => $weightText,
  11787.                 'repeatCount' => $repeatCount,
  11788.                 'labelData' => $labelData,
  11789. //                'item_id' => $item_id,
  11790.                 'approval_data' => [],
  11791.                 'document_log' => [],
  11792.                 'document_mark_image' => $document_mark['original'],
  11793.                 'company_name' => $company_data->getName(),
  11794.                 'company_data' => $company_data,
  11795.                 'company_address' => $company_data->getAddress(),
  11796.                 'company_image' => $company_data->getImage(),
  11797.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11798.                 'red' => 0
  11799.             )
  11800.         );
  11801.     }
  11802.     public
  11803.     function AssignInfoToProductByCodeAction(Request $request$id)
  11804.     {
  11805.         $em $this->getDoctrine()->getManager();
  11806.         $companyId $this->getLoggedUserCompanyId($request);
  11807. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11808.         $cartonId '';
  11809.         $passStatus 5;
  11810.         $assignProductId '';
  11811.         $assignProductionId '';
  11812.         $assignProductionScheduleId '';
  11813.         $gbWeightGm '';
  11814.         $dvWeightGm '';
  11815.         $cartonWeightGm '';
  11816.         if ($request->request->has('cartonId'))
  11817.             $cartonId $request->request->get('cartonId');
  11818.         if ($request->request->has('passStatus'))
  11819.             $passStatus $request->request->get('passStatus');
  11820.         if ($request->request->has('productByCodeId'))
  11821.             $id $request->request->get('productByCodeId');
  11822.         if ($request->request->has('productId'))
  11823.             $assignProductId $request->request->get('productId');
  11824.         if ($request->request->has('productionId'))
  11825.             $assignProductionId $request->request->get('productionId');
  11826.         if ($request->request->has('productionScheduleId'))
  11827.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  11828.         if ($request->request->has('gbWeightGm'))
  11829.             $gbWeightGm $request->request->get('gbWeightGm');
  11830.         if ($request->request->has('dvWeightGm'))
  11831.             $dvWeightGm $request->request->get('dvWeightGm');
  11832.         if ($request->request->has('cartonWeightGm'))
  11833.             $cartonWeightGm $request->request->get('cartonWeightGm');
  11834.         $cartonAssignedAlready 0;
  11835.         $otherData = array(
  11836.             'currentCartonBalance' => 0,
  11837.             'currentCartonCapacity' => 0,
  11838.             'currentCartonAssigned' => 0,
  11839.             'currentCartonFull' => 0,
  11840.         );
  11841.         if ($id != && $id != '') {
  11842.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11843.                 ->findOneBy(
  11844.                     array(
  11845.                         'productByCodeId' => $id
  11846.                     )
  11847.                 );
  11848.             if ($assignProductId != ''$productByCodeData->setProductId($assignProductId);
  11849.             if ($productByCodeData->getCartonId() != '' || $productByCodeData->getCartonId() != null)
  11850.                 $cartonAssignedAlready 1;
  11851.             else if ($cartonId != ''$productByCodeData->setCartonId($cartonId);
  11852.             if ($dvWeightGm != ''$productByCodeData->setSingleWeightGm($dvWeightGm);
  11853.             if ($gbWeightGm != '') {
  11854.                 $productByCodeData->setPackagedWeightGm($gbWeightGm);
  11855.             }
  11856.             $colorText '_NA_';
  11857.             if ($passStatus != 5$productByCodeData->setStage($passStatus);
  11858.             $productByCodeData->setCompanyId($companyId);
  11859.             if ($assignProductionId != '') {
  11860.                 $productByCodeData->setProductionId($assignProductionId);
  11861.                 $productionData $em->getRepository('ApplicationBundle:Production')
  11862.                     ->findOneBy(
  11863.                         array(
  11864.                             'productionId' => $assignProductionId
  11865.                         )
  11866.                     );
  11867.                 if ($assignProductId != '' && $assignProductId != null && $assignProductId != 0)
  11868.                     $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11869.                         array(
  11870.                             'productionId' => $assignProductionId,
  11871.                             'productId' => $assignProductId,
  11872.                             'type' => 1,
  11873.                         )
  11874.                     );
  11875.                 else
  11876.                     $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11877.                         array(
  11878.                             'productionId' => $assignProductionId,
  11879. //                            'productId' => $assignProductId,
  11880.                             'type' => 1,
  11881.                         )
  11882.                     );
  11883.                 $assignProductionScheduleId $productionData->getProductionScheduleId();
  11884.                 if ($productionItemData) {
  11885.                     $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11886.                     $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11887.                     $productByCodeData->setPosition(1);//in inventory
  11888.                     $productByCodeData->setSerialAssigned(1);
  11889.                     $productByCodeData->setColorId($productionItemData->getColorId());
  11890.                     $productByCodeData->setColorText($productionItemData->getColorText());
  11891.                     $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11892.                     $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11893.                     if ($passStatus == 1)//passed
  11894.                     {
  11895. //                    $transDate = new \DateTime();
  11896. //                    Inventory::addItemToInventoryCompact($em,
  11897. //                        $productionItemData->getProductId(),
  11898. //                        $productionItemData->getWarehouseId(),
  11899. //                        $productionItemData->getWarehouseId(),
  11900. //                        $productionData->getProducedItemActionTagId(),
  11901. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11902. //                        $transDate,
  11903. //                        1,
  11904. //                        1,
  11905. //                        $entry['valueAdd'],
  11906. //                        $entry['valueSub'],
  11907. //                        $entry['price'],
  11908. //                        $this->getLoggedUserCompanyId($request),
  11909. //                        0,
  11910. //                        $entry['entity'],
  11911. //                        $entry['entityId'],
  11912. //                        $entry['entityDocHash']
  11913. //                    );
  11914.                     }
  11915.                     $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  11916.                     if ($transHistory == null)
  11917.                         $transHistory = [];
  11918.                     $transHistory[] = array(
  11919.                         'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  11920.                         'direction' => 'in',
  11921.                         'warehouseId' => $productionItemData->getWarehouseId(),
  11922.                         'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  11923.                         'fromWarehouseId' => 0,
  11924.                         'fromWarehouseActionId' => //stock of goods
  11925.                     );
  11926.                     $productByCodeData->setTransactionHistory(json_encode($transHistory));
  11927.                 }
  11928.             }
  11929.             if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  11930.                 $productByCodeData->setProductionScheduleId($assignProductionScheduleId);
  11931.                 $productionSchedule $em->getRepository('ApplicationBundle:ProductionSchedule')
  11932.                     ->findOneBy(
  11933.                         array(
  11934.                             'productionScheduleId' => $assignProductionScheduleId
  11935.                         )
  11936.                     );
  11937.                 if ($productionSchedule) {
  11938.                     $productByCodeData->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  11939.                     $productByCodeData->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  11940.                     $productByCodeData->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  11941.                     $productByCodeData->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  11942.                     if ($productByCodeData->getProductionId() == null || $productByCodeData->getProductionId() == '' || $productByCodeData->getProductionId() == 0) {
  11943.                         $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11944.                             array(
  11945.                                 'productionScheduleId' => $assignProductionScheduleId,
  11946.                                 'productId' => $productionSchedule->getProducedProductId(),
  11947.                                 'type' => 1,
  11948.                             )
  11949.                         );
  11950. //                        $assignProductionScheduleId=$productionData->getProductionScheduleId();
  11951.                         if ($productionItemData) {
  11952.                             $productByCodeData->setProductionId($productionItemData->getProductionId());
  11953.                             $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11954.                             $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11955.                             $productByCodeData->setPosition(1);//in inventory
  11956.                             $productByCodeData->setSerialAssigned(1);
  11957.                             $productByCodeData->setColorId($productionItemData->getColorId());
  11958.                             $productByCodeData->setColorText($productionItemData->getColorText());
  11959.                             $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11960.                             $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11961.                             if ($passStatus == 1)//passed
  11962.                             {
  11963. //                    $transDate = new \DateTime();
  11964. //                    Inventory::addItemToInventoryCompact($em,
  11965. //                        $productionItemData->getProductId(),
  11966. //                        $productionItemData->getWarehouseId(),
  11967. //                        $productionItemData->getWarehouseId(),
  11968. //                        $productionData->getProducedItemActionTagId(),
  11969. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11970. //                        $transDate,
  11971. //                        1,
  11972. //                        1,
  11973. //                        $entry['valueAdd'],
  11974. //                        $entry['valueSub'],
  11975. //                        $entry['price'],
  11976. //                        $this->getLoggedUserCompanyId($request),
  11977. //                        0,
  11978. //                        $entry['entity'],
  11979. //                        $entry['entityId'],
  11980. //                        $entry['entityDocHash']
  11981. //                    );
  11982.                             }
  11983.                             $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  11984.                             if ($transHistory == null)
  11985.                                 $transHistory = [];
  11986.                             $transHistory[] = array(
  11987.                                 'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  11988.                                 'direction' => 'in',
  11989.                                 'warehouseId' => $productionItemData->getWarehouseId(),
  11990.                                 'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  11991.                                 'fromWarehouseId' => 0,
  11992.                                 'fromWarehouseActionId' => //stock of goods
  11993.                             );
  11994.                             $productByCodeData->setTransactionHistory(json_encode($transHistory));
  11995.                         }
  11996.                     }
  11997.                 }
  11998.             }
  11999. //                $productByCodeData->setPurchaseWarrantyLastDate($new_pwld);
  12000.             $em->flush();
  12001.             //now adding carton
  12002.         }
  12003.         if ($cartonId != '') {
  12004.             $carton $em->getRepository('ApplicationBundle:Carton')
  12005.                 ->findOneBy(
  12006.                     array(
  12007.                         'id' => $cartonId
  12008.                     )
  12009.                 );
  12010.             if ($cartonWeightGm != ''$carton->setCartonWeightGm($cartonWeightGm);
  12011.             $otherData['currentCartonCapacity'] = $carton->getCartonCapacityCount();
  12012.             if ($cartonAssignedAlready == 0)
  12013.                 $carton->setCartonAssignedCount(($carton->getCartonAssignedCount()) + 1);
  12014.             $otherData['currentCartonAssigned'] = $carton->getCartonAssignedCount();
  12015.             $otherData['currentCartonBalance'] = $otherData['currentCartonCapacity'] - $otherData['currentCartonAssigned'];
  12016.             if ($otherData['currentCartonAssigned'] >= $otherData['currentCartonCapacity'])
  12017.                 $otherData['currentCartonFull'] = 1;
  12018.             $em->flush();
  12019.         }
  12020.         if ($cartonId != '') {
  12021. //                    if($cartonAssignedAlready==1)
  12022. //                    {
  12023.             $productByCodeDataListForThisCarton $em->getRepository('ApplicationBundle:ProductByCode')
  12024.                 ->findBy(
  12025.                     array(
  12026.                         'cartonId' => $cartonId
  12027.                     )
  12028.                 );
  12029.             $carton $em->getRepository('ApplicationBundle:Carton')
  12030.                 ->findOneBy(
  12031.                     array(
  12032.                         'id' => $cartonId
  12033.                     )
  12034.                 );
  12035.             $total_carton_predicted_weight 0;
  12036.             $colorTextList = [];
  12037.             $cartonProductByCodeIds = [];
  12038.             foreach ($productByCodeDataListForThisCarton as $pikamaster) {
  12039.                 if (!in_array($pikamaster->getProductByCodeId(), $cartonProductByCodeIds))
  12040.                     $cartonProductByCodeIds[] = $pikamaster->getProductByCodeId();
  12041.                 if (!in_array($pikamaster->getColorText(), $colorTextList) && $pikamaster->getColorText() != null)
  12042.                     $colorTextList[] = $pikamaster->getColorText();
  12043.                 $total_carton_predicted_weight += ($pikamaster->getPackagedWeightGm());
  12044.                 if ($passStatus != 5)
  12045.                     if ($pikamaster->getStage() < $passStatus)
  12046.                         $pikamaster->setStage($passStatus);
  12047.             }
  12048.             if ($carton)
  12049.                 $carton->setCartonCalculatedWeightGm($total_carton_predicted_weight);
  12050.             if ($passStatus != 5)
  12051.                 $carton->setStage($passStatus);
  12052.             $carton->setColors(implode(','$colorTextList));
  12053.             $carton->setCartonProductByCodeIds(json_encode($cartonProductByCodeIds));
  12054.             $em->flush();
  12055.         }
  12056.         return new JsonResponse(array(
  12057.             'success' => true,
  12058.             'otherData' => $otherData,
  12059.         ));
  12060.     }
  12061.     public
  12062.     function RefreshCartonListAction(Request $request$id)
  12063.     {
  12064.         $em $this->getDoctrine()->getManager();
  12065. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12066.         $cartonListArray = [];
  12067.         $cartonList = [];
  12068.         $assignableCartonList = [];
  12069.         $assignableCartonListArray = [];
  12070.         $assignable 0;
  12071.         $cartonId '';
  12072.         $passStatus 5;
  12073.         $assignProductId '';
  12074.         $assignProductionId '';
  12075.         $assignProductionScheduleId '';
  12076.         if ($request->request->has('productionId'))
  12077.             $assignProductionId $request->request->get('productionId');
  12078.         if ($request->request->has('productionScheduleId'))
  12079.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  12080.         if ($request->request->has('assignable'))
  12081.             $assignable $request->request->get('assignable');
  12082.         $cartonAssignedAlready 0;
  12083.         $otherData = array(
  12084.             'currentCartonBalance' => 0,
  12085.             'currentCartonCapacity' => 0,
  12086.             'currentCartonAssigned' => 0,
  12087.             'currentCartonFull' => 0,
  12088.         );
  12089.         //1st get all cartons for this production id
  12090.         $cartonList $em->getRepository('ApplicationBundle:Carton')
  12091.             ->findBy(
  12092.                 array(
  12093. //                    'productionId' => $assignProductionId,
  12094.                     'productionScheduleId' => $assignProductionScheduleId
  12095.                 )
  12096.             );
  12097.         $foundAssignable 0;
  12098.         $setId 0;
  12099.         $lastdmySer '';
  12100.         foreach ($cartonList as $carton) {
  12101.             $cartonData = array(
  12102.                 'id' => $carton->getId(),
  12103.                 'name' => $carton->getCartonNumber(),
  12104.                 'colors' => $carton->getColors(),
  12105.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  12106.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  12107.             );
  12108.             $cartonListArray[] = $cartonData;
  12109.             $cartonList[$cartonData['id']] = $cartonData;
  12110.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  12111.                 $foundAssignable 1;
  12112.                 $setId $cartonData['id'];
  12113.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  12114.                 $assignableCartonListArray[] = $cartonData;
  12115.             }
  12116.         }
  12117.         if ($assignable == && $foundAssignable == 0) {
  12118. //            $productionData = $em->getRepository('ApplicationBundle:Production')
  12119. //                ->findOneBy(
  12120. //                    array(
  12121. //                        'productionId' => $assignProductionId
  12122. //                    )
  12123. //                );
  12124.             $productionScheduleData $em->getRepository('ApplicationBundle:ProductionSchedule')
  12125.                 ->findOneBy(
  12126.                     array(
  12127.                         'productionScheduleId' => $assignProductionScheduleId
  12128.                     )
  12129.                 );
  12130.             $productId 0;
  12131.             $product = [];
  12132.             $productModel '';
  12133.             if ($productionScheduleData)
  12134.                 $productId $productionScheduleData->getProducedProductId();
  12135. //            $productionItem = $em->getRepository('ApplicationBundle:ProductionEntryItem')
  12136. //                ->findOneBy(
  12137. //                    array(
  12138. //                        'productionId' => $assignProductionId,
  12139. //                        'type' => 1
  12140. //                    )
  12141. //                );
  12142.             if ($productId != 0) {
  12143. //                    $productId = $productionItem->getProductId();
  12144.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  12145.                     ->findOneBy(
  12146.                         array(
  12147.                             'id' => $productId,
  12148.                         )
  12149.                     );
  12150.                 $productModel $product->getModelNo();
  12151.             }
  12152.             $carton = new Carton();
  12153.             $carton_capacity $productionScheduleData->getCartonCapacity();
  12154.             $carton->setProductId($productId);
  12155.             $carton->setProductionId($assignProductionId);
  12156.             $carton->setProductionScheduleId($assignProductionScheduleId);
  12157.             if ($productionScheduleData) {
  12158.                 $carton->setCartonLabelFormatId($productionScheduleData->getCartonLabelFormatId());
  12159.             }
  12160.             $carton->setCartonCapacityCount($carton_capacity == null $carton_capacity);
  12161.             $carton->setCartonAssignedCount(0);
  12162.             $carton->setCompanyId($this->getLoggedUserCompanyId($request));
  12163.             $today = new \DateTime();
  12164.             $dmy $productModel '-' . ($today->format('m')) . '-' . ($today->format('Y')) . '-' $productionScheduleData->getBatchNumber();
  12165.             $ser 0;
  12166.             $carton->setCartonNumberDmy($dmy);
  12167.             $carton->setCartonNumberLastSer(* (($today->format('h')) . '' . ($today->format('i'))));
  12168.             $carton->setCartonNumber($dmy '-' . ($today->format('h')) . '' . ($today->format('i')));
  12169.             $em->persist($carton);
  12170.             $em->flush();
  12171.             $cartonData = array(
  12172.                 'id' => $carton->getId(),
  12173.                 'name' => $carton->getCartonNumber(),
  12174.                 'colors' => $carton->getColors(),
  12175.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  12176.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  12177.             );
  12178.             $cartonListArray[] = $cartonData;
  12179.             $cartonList[$cartonData['id']] = $cartonData;
  12180.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  12181.                 $foundAssignable 1;
  12182.                 $setId $cartonData['id'];
  12183.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  12184.                 $assignableCartonListArray[] = $cartonData;
  12185.             }
  12186.         }
  12187.         return new JsonResponse(array(
  12188.             'success' => true,
  12189.             'cartonList' => $cartonList,
  12190.             'cartonListArray' => $cartonListArray,
  12191.             'assignableCartonList' => $assignableCartonList,
  12192.             'assignableCartonListArray' => $assignableCartonListArray,
  12193.             'setId' => $setId,
  12194.         ));
  12195.     }
  12196.     public
  12197.     function PrintDrBarcodeAction(Request $request$id$item_id)
  12198.     {
  12199.         $em $this->getDoctrine()->getManager();
  12200.         $dt Inventory::GetDrDetails($em$id$item_id);
  12201.         $repeatCount 1;
  12202.         if ($request->query->has('repeatCount'))
  12203.             $repeatCount $request->query->get('repeatCount');
  12204.         $company_data Company::getCompanyData($em1);
  12205.         $document_mark = array(
  12206.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12207.             'copy' => ''
  12208.         );
  12209.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12210.             $html $this->renderView('@Inventory/pages/print/print_dr_barcodes.html.twig',
  12211.                 array(
  12212.                     //full array here
  12213.                     'pdf' => true,
  12214.                     'page_title' => 'Challan Barcodes',
  12215.                     'export' => 'print',
  12216.                     'repeatCount' => $repeatCount,
  12217.                     'item_id' => $item_id,
  12218.                     'data' => $dt,
  12219.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12220.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12221.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12222.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12223.                         $id,
  12224.                         $dt['created_by'],
  12225.                         $dt['edited_by']),
  12226.                     'document_mark_image' => $document_mark['original'],
  12227.                     'company_name' => $company_data->getName(),
  12228.                     'company_data' => $company_data,
  12229.                     'company_address' => $company_data->getAddress(),
  12230.                     'company_image' => $company_data->getImage(),
  12231.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12232.                     'red' => 0
  12233.                 )
  12234.             );
  12235.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12236. //                'orientation' => 'landscape',
  12237.                 'enable-javascript' => true,
  12238. //                'javascript-delay' => 1000,
  12239.                 'no-stop-slow-scripts' => false,
  12240.                 'no-background' => false,
  12241.                 'lowquality' => false,
  12242.                 'encoding' => 'utf-8',
  12243. //            'images' => true,
  12244. //            'cookie' => array(),
  12245.                 'dpi' => 300,
  12246.                 'image-dpi' => 300,
  12247. //                'enable-external-links' => true,
  12248. //                'enable-internal-links' => true
  12249.             ));
  12250.             return new Response(
  12251.                 $pdf_response,
  12252.                 200,
  12253.                 array(
  12254.                     'Content-Type' => 'application/pdf',
  12255.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  12256.                 )
  12257.             );
  12258.         }
  12259.         return $this->render('@Inventory/pages/print/print_dr_barcodes.html.twig',
  12260.             array(
  12261.                 'page_title' => 'Challan barcodes',
  12262. //                'export'=>'pdf,print',
  12263.                 'data' => $dt,
  12264.                 'repeatCount' => $repeatCount,
  12265.                 'item_id' => $item_id,
  12266.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12267.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12268.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12269.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12270.                     $id,
  12271.                     $dt['created_by'],
  12272.                     $dt['edited_by']),
  12273.                 'document_mark_image' => $document_mark['original'],
  12274.                 'company_name' => $company_data->getName(),
  12275.                 'company_data' => $company_data,
  12276.                 'company_address' => $company_data->getAddress(),
  12277.                 'company_image' => $company_data->getImage(),
  12278.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12279.                 'red' => 0
  12280.             )
  12281.         );
  12282.     }
  12283.     public
  12284.     function PrintIrrBarcodeAction(Request $request$id$item_id)
  12285.     {
  12286.         $em $this->getDoctrine()->getManager();
  12287.         $dt Inventory::GetIrrDetails($em$id$item_id);
  12288.         $repeatCount 1;
  12289.         if ($request->query->has('repeatCount'))
  12290.             $repeatCount $request->query->get('repeatCount');
  12291.         $company_data Company::getCompanyData($em1);
  12292.         $document_mark = array(
  12293.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12294.             'copy' => ''
  12295.         );
  12296.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12297.             $html $this->renderView('@Inventory/pages/print/print_irr_barcodes.html.twig',
  12298.                 array(
  12299.                     //full array here
  12300.                     'pdf' => true,
  12301.                     'page_title' => 'Sales Return Barcodes',
  12302.                     'export' => 'print',
  12303.                     'repeatCount' => $repeatCount,
  12304.                     'item_id' => $item_id,
  12305.                     'data' => $dt,
  12306.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12307.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12308.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12309.                         array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12310.                         $id,
  12311.                         $dt['created_by'],
  12312.                         $dt['edited_by']),
  12313.                     'document_mark_image' => $document_mark['original'],
  12314.                     'company_name' => $company_data->getName(),
  12315.                     'company_data' => $company_data,
  12316.                     'company_address' => $company_data->getAddress(),
  12317.                     'company_image' => $company_data->getImage(),
  12318.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12319.                     'red' => 0
  12320.                 )
  12321.             );
  12322.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12323. //                'orientation' => 'landscape',
  12324.                 'enable-javascript' => true,
  12325. //                'javascript-delay' => 1000,
  12326.                 'no-stop-slow-scripts' => false,
  12327.                 'no-background' => false,
  12328.                 'lowquality' => false,
  12329.                 'encoding' => 'utf-8',
  12330. //            'images' => true,
  12331. //            'cookie' => array(),
  12332.                 'dpi' => 300,
  12333.                 'image-dpi' => 300,
  12334. //                'enable-external-links' => true,
  12335. //                'enable-internal-links' => true
  12336.             ));
  12337.             return new Response(
  12338.                 $pdf_response,
  12339.                 200,
  12340.                 array(
  12341.                     'Content-Type' => 'application/pdf',
  12342.                     'Content-Disposition' => 'attachment; filename="irr_barcodes.pdf"'
  12343.                 )
  12344.             );
  12345.         }
  12346.         return $this->render('@Inventory/pages/print/print_irr_barcodes.html.twig',
  12347.             array(
  12348.                 'page_title' => 'Sales Return barcodes',
  12349. //                'export'=>'pdf,print',
  12350.                 'data' => $dt,
  12351.                 'repeatCount' => $repeatCount,
  12352.                 'item_id' => $item_id,
  12353.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12354.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12355.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12356.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12357.                     $id,
  12358.                     $dt['created_by'],
  12359.                     $dt['edited_by']),
  12360.                 'document_mark_image' => $document_mark['original'],
  12361.                 'company_name' => $company_data->getName(),
  12362.                 'company_data' => $company_data,
  12363.                 'company_address' => $company_data->getAddress(),
  12364.                 'company_image' => $company_data->getImage(),
  12365.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12366.                 'red' => 0
  12367.             )
  12368.         );
  12369.     }
  12370.     public
  12371.     function PrintSrcvBarcodeAction(Request $request$id$item_id)
  12372.     {
  12373.         $em $this->getDoctrine()->getManager();
  12374.         $dt Inventory::GetSrcvDetails($em$id$item_id);
  12375.         $repeatCount 1;
  12376.         if ($request->query->has('repeatCount'))
  12377.             $repeatCount $request->query->get('repeatCount');
  12378.         $company_data Company::getCompanyData($em1);
  12379.         $document_mark = array(
  12380.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12381.             'copy' => ''
  12382.         );
  12383.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12384.             $html $this->renderView('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12385.                 array(
  12386.                     //full array here
  12387.                     'pdf' => true,
  12388.                     'page_title' => 'Grn Barcodes',
  12389.                     'export' => 'print',
  12390.                     'repeatCount' => $repeatCount,
  12391.                     'item_id' => $item_id,
  12392.                     'data' => $dt,
  12393.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12394.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12395.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12396.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12397.                         $id,
  12398.                         $dt['created_by'],
  12399.                         $dt['edited_by']),
  12400.                     'document_mark_image' => $document_mark['original'],
  12401.                     'company_name' => $company_data->getName(),
  12402.                     'company_data' => $company_data,
  12403.                     'company_address' => $company_data->getAddress(),
  12404.                     'company_image' => $company_data->getImage(),
  12405.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12406.                     'red' => 0
  12407.                 )
  12408.             );
  12409.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12410. //                'orientation' => 'landscape',
  12411.                 'enable-javascript' => true,
  12412. //                'javascript-delay' => 1000,
  12413.                 'no-stop-slow-scripts' => false,
  12414.                 'no-background' => false,
  12415.                 'lowquality' => false,
  12416.                 'encoding' => 'utf-8',
  12417. //            'images' => true,
  12418. //            'cookie' => array(),
  12419.                 'dpi' => 300,
  12420.                 'image-dpi' => 300,
  12421. //                'enable-external-links' => true,
  12422. //                'enable-internal-links' => true
  12423.             ));
  12424.             return new Response(
  12425.                 $pdf_response,
  12426.                 200,
  12427.                 array(
  12428.                     'Content-Type' => 'application/pdf',
  12429.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  12430.                 )
  12431.             );
  12432.         }
  12433.         return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12434.             array(
  12435.                 'page_title' => 'Srcv barcodes',
  12436. //                'export'=>'pdf,print',
  12437.                 'data' => $dt,
  12438.                 'repeatCount' => $repeatCount,
  12439.                 'item_id' => $item_id,
  12440.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12441.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12442.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12443.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12444.                     $id,
  12445.                     $dt['created_by'],
  12446.                     $dt['edited_by']),
  12447.                 'document_mark_image' => $document_mark['original'],
  12448.                 'company_name' => $company_data->getName(),
  12449.                 'company_data' => $company_data,
  12450.                 'company_address' => $company_data->getAddress(),
  12451.                 'company_image' => $company_data->getImage(),
  12452.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12453.                 'red' => 0
  12454.             )
  12455.         );
  12456.     }
  12457. //product by code
  12458.     public
  12459.     function ImeiListExcelUploadAction(Request $request)
  12460.     {
  12461.         $lastIndex $request->request->get('lastIndex'0);
  12462.         if ($request->isMethod('POST')) {
  12463.             $post $request->request;
  12464.             if ($request->request->has('chunkData')) {
  12465.                 //now getting the relevant checks
  12466.                 $check_list = [];
  12467.                 $csv_data $request->request->get('chunkData', []);
  12468.                 $em $this->getDoctrine()->getManager();
  12469.                 foreach ($csv_data as $ind => $data_row) {
  12470. //                    if ($ind == 1)
  12471. //                        continue;
  12472.                     $np $this->getDoctrine()
  12473.                         ->getRepository('ApplicationBundle:ProductByCode')
  12474.                         ->findOneBy(
  12475.                             array(
  12476.                                 'salesCode' => isset($data_row[4]) ? $data_row[4] : 0,
  12477. //                    'approved' =>  GeneralConstant::APPROVED,
  12478.                             )
  12479.                         );
  12480.                     if (!$np)
  12481.                         $np = new ProductByCode();
  12482. //                    $np = new ProductByCode();
  12483.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  12484.                     if (isset($data_row[1])) $np->setProductId($data_row[1]);
  12485.                     if (isset($data_row[0])) $np->setLcNumber($data_row[0]);
  12486.                     if (isset($data_row[2])) $np->setCartonNumber($data_row[2]);
  12487.                     if (isset($data_row[3])) $np->setSerialNo($data_row[3]);
  12488.                     $np->setSerialAssigned(isset($data_row[10]) ? $data_row[10] : 0);
  12489.                     if (isset($data_row[4])) $np->setImei1($data_row[4]);
  12490.                     if (isset($data_row[5])) $np->setImei2($data_row[5]);
  12491.                     if (isset($data_row[6])) $np->setImei3($data_row[6]);
  12492.                     if (isset($data_row[7])) $np->setImei4($data_row[7]);
  12493.                     if (isset($data_row[8])) $np->setBtMac($data_row[8]);
  12494.                     if (isset($data_row[9])) $np->setWlanMac($data_row[9]);
  12495.                     $np->setWarehouseId(isset($data_row[11]) ? $data_row[11] : 0);
  12496.                     $np->setWarehouseActionId(isset($data_row[12]) ? $data_row[12] : 0);
  12497.                     $np->setPosition(isset($data_row[13]) ? $data_row[13] : 0);//in inventory
  12498.                     $np->setPurchaseOrderId(0);
  12499.                     $np->setGrnId(0);
  12500.                     $np->setStage(0);
  12501.                     if (isset($data_row[3])) $np->setSalesCodeRange(json_encode([$data_row[3]]));
  12502. //                $np->setSalesCode($data_row[3]);
  12503.                     if (isset($data_row[4])) $np->setSalesCode($data_row[4]); //IMEI
  12504.                     $np->setSalesCodeSer(0);
  12505.                     $np->setSalesCodeDmy('');
  12506.                     $np->setPurchaseCodeRange("");
  12507.                     $np->setPurchaseReceiptDate(null);
  12508.                     $np->setLastInDate(null);
  12509.                     $np->setStatus(GeneralConstant::ACTIVE);
  12510.                     $np->setTransactionHistory(json_encode([
  12511.                         ]
  12512.                     ));
  12513.                     $np->setPurchaseWarrantyLastDate(null);
  12514.                     $em->persist($np);
  12515.                     $em->flush();
  12516.                 }
  12517.                 return new JsonResponse(array(
  12518.                     "success" => true,
  12519.                     "lastIndex" => $lastIndex,
  12520.                     "file_path" => '',
  12521.                     "csv_data" => $csv_data,
  12522.                     //                "debug_data"=>System::encryptSignature($r)
  12523.                 ));
  12524.             } else {
  12525.                 $path "";
  12526.                 $file_path "";
  12527.                 //            var_dump($request->files);
  12528.                 //        var_dump($request->getFile());
  12529.                 foreach ($request->files as $uploadedFile) {
  12530.                     //            if($uploadedFile->getImage())
  12531.                     //                var_dump($uploadedFile->getFile());
  12532.                     //                var_dump($uploadedFile);
  12533.                     if ($uploadedFile != null) {
  12534.                         $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  12535.                         $path $fileName;
  12536.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  12537.                         if (!file_exists($upl_dir)) {
  12538.                             mkdir($upl_dir0777true);
  12539.                         }
  12540.                         $file $uploadedFile->move($upl_dir$path);
  12541.                     }
  12542.                 }
  12543.                 //        print_r($file);
  12544.                 if ($path != "")
  12545.                     $file_path 'uploads/FileUploads/' $path;
  12546.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  12547.                 //
  12548.                 //            $img_file = file_get_contents($g_path);
  12549.                 //            $r=base64_encode($img_file);
  12550.                 $row 1;
  12551.                 $csv_data = [];
  12552.                 if (($handle fopen($g_path"r")) !== FALSE) {
  12553.                     while (($data fgetcsv($handle1000",")) !== FALSE) {
  12554.                         $num count($data);
  12555.                         $csv_data[$row] = $data;
  12556.                         //                    echo "<p> $num fields in line $row: <br /></p>\n";
  12557.                         $row++;
  12558.                         //                    for ($c=0; $c < $num; $c++) {
  12559.                         //                        echo $data[$c] . "<br />\n";
  12560.                         //                    }
  12561.                     }
  12562.                     fclose($handle);
  12563.                 }
  12564.                 //now getting the relevant checks
  12565.                 $check_list = [];
  12566.                 $em $this->getDoctrine()->getManager();
  12567.                 foreach ($csv_data as $ind => $data_row) {
  12568.                     if ($ind == 1)
  12569.                         continue;
  12570.                     $np = new ProductByCode();
  12571.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  12572.                     $np->setProductId($data_row[1]);
  12573.                     $np->setLcNumber($data_row[0]);
  12574.                     $np->setCartonNumber($data_row[2]);
  12575.                     $np->setSerialNo($data_row[3]);
  12576.                     $np->setSerialAssigned(0);
  12577.                     $np->setImei1($data_row[4]);
  12578.                     $np->setImei2($data_row[5]);
  12579.                     $np->setImei3($data_row[6]);
  12580.                     $np->setImei4($data_row[7]);
  12581.                     $np->setBtMac($data_row[8]);
  12582.                     $np->setWlanMac($data_row[9]);
  12583.                     $np->setWarehouseId(0);
  12584.                     $np->setWarehouseActionId(0);
  12585.                     $np->setPosition(0);//in inventory
  12586.                     $np->setPurchaseOrderId(0);
  12587.                     $np->setGrnId(0);
  12588.                     $np->setStage(0);
  12589.                     $np->setSalesCodeRange(json_encode([$data_row[3]]));
  12590. //                $np->setSalesCode($data_row[3]);
  12591.                     $np->setSalesCode($data_row[4]); //IMEI
  12592.                     $np->setSalesCodeSer(0);
  12593.                     $np->setSalesCodeDmy('');
  12594.                     $np->setPurchaseCodeRange("");
  12595.                     $np->setPurchaseReceiptDate(null);
  12596.                     $np->setLastInDate(null);
  12597.                     $np->setStatus(GeneralConstant::ACTIVE);
  12598.                     $np->setTransactionHistory(json_encode([
  12599.                         ]
  12600.                     ));
  12601.                     $np->setPurchaseWarrantyLastDate(null);
  12602.                     $em->persist($np);
  12603.                     $em->flush();
  12604.                 }
  12605.                 return new JsonResponse(array(
  12606.                     "success" => true,
  12607.                     "lastIndex" => $lastIndex,
  12608.                     "file_path" => $file_path,
  12609.                     "csv_data" => $csv_data,
  12610.                     //                "debug_data"=>System::encryptSignature($r)
  12611.                 ));
  12612.             }
  12613.         }
  12614.         return new JsonResponse(array(
  12615.             "success" => false,
  12616.             "file_path" => '',
  12617.             "csv_data" => [],
  12618.             "lastIndex" => $lastIndex,
  12619.         ));
  12620.     }
  12621.     public
  12622.     function ProductByCodeListAction(Request $request)
  12623.     {
  12624.         $em $this->getDoctrine()->getManager();
  12625.         $companyId $this->getLoggedUserCompanyId($request);
  12626.         $listData Inventory::GetProductListForProductByCodeListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  12627.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  12628.             if ($request->query->has('dataTableQry')) {
  12629.                 return new JsonResponse(
  12630.                     $listData
  12631.                 );
  12632.             }
  12633.         }
  12634.         $q = [];
  12635. //        $q = $this->getDoctrine()
  12636. //            ->getRepository('ApplicationBundle:ProductByCode')
  12637. //            ->findBy(
  12638. //                array(
  12639. //                    'status' => GeneralConstant::ACTIVE,
  12640. ////                    'approved' =>  GeneralConstant::APPROVED,
  12641. //                )
  12642. //
  12643. //            );
  12644.         //temp start
  12645. //        foreach($q as $np) {
  12646. //            if($np->getPosition()==1) {   /// only starting ones or in warehouse ones
  12647. //                $temp_obj = json_decode($np->getTransactionHistory());
  12648. //                if ($temp_obj != null) {
  12649. //                    $transHistory = [];
  12650. //                    $transHistory[] = $temp_obj;
  12651. //                    $np->setTransactionHistory(json_encode($transHistory));
  12652. //                }
  12653. //            }
  12654. //            $em->flush();
  12655. //        }
  12656.         ///temp end
  12657.         $stage_list = array(
  12658.             => 'Pending',
  12659.             => 'Pending',
  12660.             => 'Complete',
  12661.             => 'Partial',
  12662.         );
  12663.         $data = [];
  12664. //        foreach($q as $entry)
  12665. //        {
  12666. //            $data[]=array(
  12667. //                'doc_date'=>$entry->getStockRequisitionDate(),
  12668. //                'id'=>$entry->getStockRequisitionId(),
  12669. //                'doc_hash'=>$entry->getDocumentHash(),
  12670. //                'approval_status'=>GeneralConstant::$approvalStatus[$entry->getApproved()],
  12671. //                'stage'=>$stage_list[$entry->getStage()]
  12672. //
  12673. //            );
  12674. //        }
  12675.         return $this->render('@Inventory/pages/views/product_by_code_list.html.twig',
  12676.             array(
  12677.                 'page_title' => 'Product List',
  12678.                 'data' => $q,
  12679. //                'listData' => $listData,
  12680.                 'products' => Inventory::ProductList($em),
  12681.                 'warehouseList' => Inventory::WarehouseList($em)
  12682.             )
  12683.         );
  12684.     }
  12685. //SR
  12686.     public
  12687.     function SrListAction(Request $request)
  12688.     {
  12689.         $q $this->getDoctrine()
  12690.             ->getRepository('ApplicationBundle:StockRequisition')
  12691.             ->findBy(
  12692.                 array(
  12693.                     'status' => GeneralConstant::ACTIVE,
  12694. //                    'approved' =>  GeneralConstant::APPROVED,
  12695.                 )
  12696.                 ,
  12697.                 array(
  12698.                     'stockRequisitionDate' => 'DESC'
  12699.                 )
  12700.             );
  12701.         $stage_list = array(
  12702.             => 'Pending',
  12703.             => 'Pending',
  12704.             => 'Complete',
  12705.             => 'Partial',
  12706.         );
  12707.         $data = [];
  12708.         foreach ($q as $entry) {
  12709.             $data[] = array(
  12710.                 'doc_date' => $entry->getStockRequisitionDate(),
  12711.                 'id' => $entry->getStockRequisitionId(),
  12712.                 'doc_hash' => $entry->getDocumentHash(),
  12713.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12714.                 'stage' => $stage_list[$entry->getStage()],
  12715.                 'indentTagged' => $entry->getIndentTagged(),
  12716.                 'srIds' => $entry->getSrIds(),
  12717.                 'irIds' => $entry->getIrIds(),
  12718.                 'prIds' => $entry->getPrIds(),
  12719.                 'poIds' => $entry->getPoIds(),
  12720.             );
  12721.         }
  12722.         return $this->render('@Inventory/pages/views/sr_list.html.twig',
  12723.             array(
  12724.                 'page_title' => 'Stock Requisition List',
  12725.                 'data' => $data
  12726.             )
  12727.         );
  12728.     }
  12729.     public
  12730.     function ViewSrAction(Request $request$id)
  12731.     {
  12732.         $em $this->getDoctrine()->getManager();
  12733.         $dt Inventory::GetSrDetails($em$id);
  12734.         return $this->render(
  12735.             '@Inventory/pages/views/view_stock_requisition.html.twig',
  12736.             array(
  12737.                 'page_title' => 'Stock requisition',
  12738.                 'data' => $dt,
  12739.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12740.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12741.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12742.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12743.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12744.                     $id,
  12745.                     $dt['created_by'],
  12746.                     $dt['edited_by'])
  12747.             )
  12748.         );
  12749.     }
  12750.     public
  12751.     function PrintSrAction(Request $request$id)
  12752.     {
  12753.         $em $this->getDoctrine()->getManager();
  12754.         $dt Inventory::GetSrDetails($em$id);
  12755.         $company_data Company::getCompanyData($em1);
  12756.         $document_mark = array(
  12757.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12758.             'copy' => ''
  12759.         );
  12760.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12761.             $html $this->renderView('@Inventory/pages/print/print_sr.html.twig',
  12762.                 array(
  12763.                     //full array here
  12764.                     'pdf' => true,
  12765.                     'page_title' => 'Stock Requisition',
  12766.                     'export' => 'pdf,print',
  12767.                     'data' => $dt,
  12768.                     'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12769.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12770.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12771.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12772.                         array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12773.                         $id,
  12774.                         $dt['created_by'],
  12775.                         $dt['edited_by']),
  12776.                     'document_mark_image' => $document_mark['original'],
  12777.                     'company_name' => $company_data->getName(),
  12778.                     'company_data' => $company_data,
  12779.                     'company_address' => $company_data->getAddress(),
  12780.                     'company_image' => $company_data->getImage(),
  12781.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12782.                     'red' => 0
  12783.                 )
  12784.             );
  12785.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12786.             //     'orientation' => 'landscape',
  12787.             //     'enable-javascript' => true,
  12788.             //     'javascript-delay' => 1000,
  12789.                 'no-stop-slow-scripts' => false,
  12790.                 'no-background' => false,
  12791.                 'lowquality' => false,
  12792.                 'encoding' => 'utf-8',
  12793.             //    'images' => true,
  12794.             //    'cookie' => array(),
  12795.                 'dpi' => 300,
  12796.                 'image-dpi' => 300,
  12797.             //    'enable-external-links' => true,
  12798.             //    'enable-internal-links' => true
  12799.         ));
  12800.             return new Response(
  12801.                 $pdf_response,
  12802.                 200,
  12803.                 array(
  12804.                     'Content-Type' => 'application/pdf',
  12805.                     'Content-Disposition' => 'attachment; filename="stock_requisition_' $id '.pdf"'
  12806.                 )
  12807.             );
  12808.         }
  12809.         return $this->render('@Inventory/pages/print/print_sr.html.twig',
  12810.             array(
  12811.                 'page_title' => 'Stock Requisition',
  12812.                 'export' => 'pdf,print',
  12813.                 'data' => $dt,
  12814.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12815.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12816.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12817.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12818.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12819.                     $id,
  12820.                     $dt['created_by'],
  12821.                     $dt['edited_by']),
  12822.                 'document_mark_image' => $document_mark['original'],
  12823.                 'company_name' => $company_data->getName(),
  12824.                 'company_data' => $company_data,
  12825.                 'company_address' => $company_data->getAddress(),
  12826.                 'company_image' => $company_data->getImage(),
  12827.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12828.                 'red' => 0
  12829.             )
  12830.         );
  12831.     }
  12832. //IR
  12833.     public
  12834.     function IrListAction(Request $request)
  12835.     {
  12836.         $q $this->getDoctrine()
  12837.             ->getRepository('ApplicationBundle:StoreRequisition')
  12838.             ->findBy(
  12839.                 array(
  12840.                     'status' => GeneralConstant::ACTIVE,
  12841. //                    'approved' =>  GeneralConstant::APPROVED,
  12842.                 ),
  12843.                 array(
  12844.                     'storeRequisitionDate' => 'DESC'
  12845.                 )
  12846.             );
  12847.         $stage_list = array(
  12848.             => 'Pending',
  12849.             => 'Pending',
  12850.             => 'Complete',
  12851.             => 'Partial',
  12852.         );
  12853.         $data = [];
  12854.         foreach ($q as $entry) {
  12855.             $data[] = array(
  12856.                 'doc_date' => $entry->getStoreRequisitionDate(),
  12857.                 'id' => $entry->getStoreRequisitionId(),
  12858.                 'doc_hash' => $entry->getDocumentHash(),
  12859.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12860.                 'stage' => $stage_list[$entry->getStage()],
  12861.                 'prTagged' => $entry->getIndentTagged(),
  12862.                 'srIds' => $entry->getSrIds(),
  12863.                 'irIds' => $entry->getIrIds(),
  12864.                 'prIds' => $entry->getPrIds(),
  12865.                 'poIds' => $entry->getPoIds(),
  12866.             );
  12867.         }
  12868.         return $this->render('@Inventory/pages/views/ir_list.html.twig',
  12869.             array(
  12870.                 'page_title' => 'Indent Requisition List',
  12871.                 'data' => $data
  12872.             )
  12873.         );
  12874.     }
  12875.     public
  12876.     function ViewIrAction(Request $request$id)
  12877.     {
  12878.         $em $this->getDoctrine()->getManager();
  12879.         $dt Inventory::GetIrDetails($em$id);
  12880.         return $this->render(
  12881.             '@Inventory/pages/views/view_indent_requisition.html.twig',
  12882.             array(
  12883.                 'page_title' => 'Indent',
  12884.                 'data' => $dt,
  12885.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12886.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12887.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12888.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12889.                     $id,
  12890.                     $dt['created_by'],
  12891.                     $dt['edited_by'])
  12892.             )
  12893.         );
  12894.     }
  12895.     public
  12896.     function PrintIrAction(Request $request$id)
  12897.     {
  12898.         $em $this->getDoctrine()->getManager();
  12899.         $dt Inventory::GetIrDetails($em$id);
  12900.         $company_data Company::getCompanyData($em1);
  12901.         $document_mark = array(
  12902.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12903.             'copy' => ''
  12904.         );
  12905.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12906.             $html $this->renderView('@Inventory/pages/print/print_ir.html.twig',
  12907.                 array(
  12908.                     //full array here
  12909.                     'pdf' => true,
  12910.                     'page_title' => 'Indent Requisition',
  12911.                     'export' => 'pdf,print',
  12912.                     'data' => $dt,
  12913.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12914.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12915.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12916.                         array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12917.                         $id,
  12918.                         $dt['created_by'],
  12919.                         $dt['edited_by']),
  12920.                     'document_mark_image' => $document_mark['original'],
  12921.                     'company_name' => $company_data->getName(),
  12922.                     'company_data' => $company_data,
  12923.                     'company_address' => $company_data->getAddress(),
  12924.                     'company_image' => $company_data->getImage(),
  12925.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12926.                     'red' => 0
  12927.                 )
  12928.             );
  12929.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12930. //                'orientation' => 'landscape',
  12931. //                'enable-javascript' => true,
  12932. //                'javascript-delay' => 1000,
  12933.                 'no-stop-slow-scripts' => false,
  12934.                 'no-background' => false,
  12935.                 'lowquality' => false,
  12936.                 'encoding' => 'utf-8',
  12937. //            'images' => true,
  12938. //            'cookie' => array(),
  12939.                 'dpi' => 300,
  12940.                 'image-dpi' => 300,
  12941. //                'enable-external-links' => true,
  12942. //                'enable-internal-links' => true
  12943.             ));
  12944.             return new Response(
  12945.                 $pdf_response,
  12946.                 200,
  12947.                 array(
  12948.                     'Content-Type' => 'application/pdf',
  12949.                     'Content-Disposition' => 'attachment; filename="indent_' $id '.pdf"'
  12950.                 )
  12951.             );
  12952.         }
  12953.         return $this->render('@Inventory/pages/print/print_ir.html.twig',
  12954.             array(
  12955.                 'page_title' => 'Indent Requisition',
  12956.                 'export' => 'pdf,print',
  12957.                 'data' => $dt,
  12958.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12959.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12960.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12961.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12962.                     $id,
  12963.                     $dt['created_by'],
  12964.                     $dt['edited_by']),
  12965.                 'document_mark_image' => $document_mark['original'],
  12966.                 'company_name' => $company_data->getName(),
  12967.                 'company_data' => $company_data,
  12968.                 'company_address' => $company_data->getAddress(),
  12969.                 'company_image' => $company_data->getImage(),
  12970.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12971.                 'red' => 0
  12972.             )
  12973.         );
  12974.     }
  12975. //PR
  12976.     public
  12977.     function PrListAction(Request $request)
  12978.     {
  12979.         $q $this->getDoctrine()
  12980.             ->getRepository('ApplicationBundle:PurchaseRequisition')
  12981.             ->findBy(
  12982.                 array(
  12983.                     'status' => GeneralConstant::ACTIVE,
  12984. //                    'approved' =>  GeneralConstant::APPROVED,
  12985.                 ),
  12986.                 array(
  12987.                     'purchaseRequisitionDate' => 'DESC'
  12988.                 )
  12989.             );
  12990.         $stage_list = array(
  12991.             => 'Pending',
  12992.             => 'Pending',
  12993.             => 'Complete',
  12994.             => 'Partial',
  12995.         );
  12996.         $data = [];
  12997.         foreach ($q as $entry) {
  12998.             $data[] = array(
  12999.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  13000.                 'id' => $entry->getPurchaseRequisitionId(),
  13001.                 'doc_hash' => $entry->getDocumentHash(),
  13002.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13003.                 'acquisition_status' => $entry->getAcquisitionStatus(),
  13004.                 'acquisition_start_date' => $entry->getAcquisitionStartDate(),
  13005.                 'acquisition_end_date' => $entry->getAcquisitionEndDate(),
  13006.                 'acquisition_method' => $entry->getquotationAcquisitionMethod(),
  13007.                 'poTagged' => $entry->getPoTagged(),
  13008.                 'typeHash' => $entry->getTypehash(),
  13009.                 'srIds' => $entry->getSrIds(),
  13010.                 'irIds' => $entry->getIrIds(),
  13011.                 'prIds' => $entry->getPrIds(),
  13012.                 'poIds' => $entry->getPoIds(),
  13013.             );
  13014.         }
  13015.         return $this->render('@Inventory/pages/views/pr_list.html.twig',
  13016.             array(
  13017.                 'page_title' => 'Purchase Requisition List',
  13018.                 'data' => $data
  13019.             )
  13020.         );
  13021.     }
  13022.     public
  13023.     function ServiceRequisitionListAction(Request $request)
  13024.     {
  13025.         $q $this->getDoctrine()
  13026.             ->getRepository('ApplicationBundle:PurchaseRequisition')
  13027.             ->findBy(
  13028.                 array(
  13029.                     'status' => GeneralConstant::ACTIVE,
  13030. //                    'approved' =>  GeneralConstant::APPROVED,
  13031.                 ),
  13032.                 array(
  13033.                     'purchaseRequisitionDate' => 'DESC'
  13034.                 )
  13035.             );
  13036.         $stage_list = array(
  13037.             => 'Pending',
  13038.             => 'Pending',
  13039.             => 'Complete',
  13040.             => 'Partial',
  13041.         );
  13042.         $data = [];
  13043.         foreach ($q as $entry) {
  13044.             $data[] = array(
  13045.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  13046.                 'id' => $entry->getPurchaseRequisitionId(),
  13047.                 'doc_hash' => $entry->getDocumentHash(),
  13048.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13049.                 'poTagged' => $entry->getPoTagged(),
  13050.                 'typeHash' => $entry->getTypehash(),
  13051.                 'srIds' => $entry->getSrIds(),
  13052.                 'irIds' => $entry->getIrIds(),
  13053.                 'prIds' => $entry->getPrIds(),
  13054.                 'poIds' => $entry->getPoIds(),
  13055.             );
  13056.         }
  13057.         return $this->render('@Inventory/pages/views/service_requisition_list.html.twig',
  13058.             array(
  13059.                 'page_title' => 'Service Requisition List',
  13060.                 'data' => $data
  13061.             )
  13062.         );
  13063.     }
  13064.     public
  13065.     function ViewPrAction(Request $request$id)
  13066.     {
  13067.         $em $this->getDoctrine()->getManager();
  13068.         $dt Inventory::GetPrDetails($em$id);
  13069.         $companyId $this->getLoggedUserCompanyId($request);
  13070.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  13071.             array(
  13072.                 'page_title' => 'Purchase Requisition',
  13073.                 'data' => $dt,
  13074.                 'branchList' => Client::BranchList($em$companyId),
  13075.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  13076.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13077.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13078.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13079.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13080.                     $id,
  13081.                     $dt['created_by'],
  13082.                     $dt['edited_by'])
  13083.             )
  13084.         );
  13085.     }
  13086.     public
  13087.     function ViewServiceRequisitionAction(Request $request$id)
  13088.     {
  13089.         $em $this->getDoctrine()->getManager();
  13090.         $dt Inventory::GetPrDetails($em$id);
  13091.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  13092.             array(
  13093.                 'page_title' => 'Service Requisition',
  13094.                 'data' => $dt,
  13095.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13096.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13097.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13098.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13099.                     $id,
  13100.                     $dt['created_by'],
  13101.                     $dt['edited_by'])
  13102.             )
  13103.         );
  13104.     }
  13105.     public
  13106.     function PrintPrAction(Request $request$id)
  13107.     {
  13108.         $em $this->getDoctrine()->getManager();
  13109.         $dt Inventory::GetPrDetails($em$id);
  13110.         $companyId $this->getLoggedUserCompanyId($request);
  13111.         $company_data Company::getCompanyData($em$companyId);
  13112.         $document_mark = array(
  13113.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13114.             'copy' => ''
  13115.         );
  13116.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13117.             $html $this->renderView('@Inventory/pages/print/print_pr.html.twig',
  13118.                 array(
  13119.                     //full array here
  13120.                     'pdf' => true,
  13121.                     'page_title' => 'Purchase Requisition',
  13122.                     'export' => 'pdf,print',
  13123.                     'data' => $dt,
  13124.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13125.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13126.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13127.                         array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13128.                         $id,
  13129.                         $dt['created_by'],
  13130.                         $dt['edited_by']),
  13131.                     'document_mark_image' => $document_mark['original'],
  13132.                     'branchList' => Client::BranchList($em$companyId),
  13133.                     'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  13134.                     'company_name' => $company_data->getName(),
  13135.                     'company_data' => $company_data,
  13136.                     'company_address' => $company_data->getAddress(),
  13137.                     'company_image' => $company_data->getImage(),
  13138.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13139.                     'red' => 0
  13140.                 )
  13141.             );
  13142.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13143. //                'orientation' => 'landscape',
  13144. //                'enable-javascript' => true,
  13145. //                'javascript-delay' => 1000,
  13146.                 'no-stop-slow-scripts' => false,
  13147.                 'no-background' => false,
  13148.                 'lowquality' => false,
  13149.                 'encoding' => 'utf-8',
  13150. //            'images' => true,
  13151. //            'cookie' => array(),
  13152.                 'dpi' => 300,
  13153.                 'image-dpi' => 300,
  13154. //                'enable-external-links' => true,
  13155. //                'enable-internal-links' => true
  13156.             ));
  13157.             return new Response(
  13158.                 $pdf_response,
  13159.                 200,
  13160.                 array(
  13161.                     'Content-Type' => 'application/pdf',
  13162.                     'Content-Disposition' => 'attachment; filename="purchase_requisition_' $id '.pdf"'
  13163.                 )
  13164.             );
  13165.         }
  13166.         return $this->render('@Inventory/pages/print/print_pr.html.twig',
  13167.             array(
  13168.                 'page_title' => 'Purchase Requisition',
  13169.                 'export' => 'pdf,print',
  13170.                 'data' => $dt,
  13171.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13172.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13173.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13174.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13175.                     $id,
  13176.                     $dt['created_by'],
  13177.                     $dt['edited_by']),
  13178.                 'document_mark_image' => $document_mark['original'],
  13179.                 'company_name' => $company_data->getName(),
  13180.                 'company_data' => $company_data,
  13181.                 'branchList' => Client::BranchList($em$companyId),
  13182.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  13183.                 'company_address' => $company_data->getAddress(),
  13184.                 'company_image' => $company_data->getImage(),
  13185.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13186.                 'red' => 0
  13187.             )
  13188.         );
  13189.     }
  13190.     public
  13191.     function CreateSecondaryDeliveryReceiptAction(Request $request)
  13192.     {
  13193.         $em $this->getDoctrine()->getManager();
  13194.         $companyId $this->getLoggedUserCompanyId($request);
  13195.         $userBranchIdList $request->getSession()->get('branchIdList');
  13196.         if ($userBranchIdList == null$userBranchIdList = [];
  13197.         $userBranchId $request->getSession()->get('branchId');
  13198.         if ($request->isMethod('POST')) {
  13199.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  13200.             $dochash $request->request->get('docHash'); //change
  13201.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13202.             $approveRole 1;  //created
  13203.             $approveHash $request->request->get('approvalHash');
  13204.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  13205.                 $loginId$approveRole$approveHash)
  13206.             ) {
  13207.                 $this->addFlash(
  13208.                     'error',
  13209.                     'Sorry Couldnot insert Data.'
  13210.                 );
  13211.             } else {
  13212.                 $receiptId SalesOrderM::CreateNewSecondaryDeliveryReceipt($this->getDoctrine()->getManager(), $request->request,
  13213.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13214.                     $this->getLoggedUserCompanyId($request));
  13215.                 //now add Approval info
  13216.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13217.                 $approveRole 1;  //created
  13218.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  13219.                     $receiptId,
  13220.                     $loginId,
  13221.                     $approveRole,
  13222.                     $request->request->get('approvalHash'));
  13223.                 $options = array(
  13224.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  13225.                     'notification_server' => $this->container->getParameter('notification_server'),
  13226.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  13227.                     'url' => $this->generateUrl(
  13228.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  13229.                         ['entity_view_route_path_name']
  13230.                     )
  13231.                 );
  13232.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  13233.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  13234.                     $receiptId,
  13235.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  13236.                 );
  13237.                 $this->addFlash(
  13238.                     'success',
  13239.                     'New Delivery Receipt Created'
  13240.                 );
  13241.                 $url $this->generateUrl(
  13242.                     'view_delivery_receipt'
  13243.                 );
  13244.                 return $this->redirect($url "/" $receiptId);
  13245.             }
  13246.         }
  13247.         $debugData = [];
  13248. //        $dr_data=$em->getRepository('ApplicationBundle:DeliveryReceipt')->findOneBy(
  13249. //            array(
  13250. //                'deliveryReceiptId'=>$dr_id
  13251. //            )
  13252. //        );
  13253.         $new_swld = new \DateTime('2017-07-09');
  13254. //        if ($entry->getWarranty() > 0)
  13255. //            $new_swld->modify('+' . $entry->getWarranty() . ' month');
  13256.         $debugData[] = $new_swld->format('Y-m-d');
  13257.         $debugData[] = $new_swld;
  13258. //        $debugData[]=$dr_data->getDeliveryReceiptDate();
  13259.         $debugData[] = '+' '1' ' month';
  13260.         $branchList Client::BranchList($em$companyId, [], $userBranchIdList);
  13261.         $warehouseIds = [];
  13262.         foreach ($branchList as $br) {
  13263.             $warehouseIds[] = $br['warehouseId'];
  13264.         }
  13265.         return $this->render('@Inventory/pages/input_forms/secondaryDeliveryReceipt.html.twig',
  13266.             array(
  13267.                 'page_title' => 'New Delivery Receipt',
  13268.                 'ExistingClients' => Accounts::getClientLedgerHeads($em),
  13269.                 'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($em),
  13270.                 'ClientList' => SalesOrderM::GetSecondaryClientList($em),
  13271.                 'warehouse' => Inventory::WarehouseList($em$companyId$warehouseIds),
  13272.                 'salesOrders' => SalesOrderM::SecondarySalesOrderListPendingDelivery($em$warehouseIds),
  13273.                 'salesOrdersArray' => SalesOrderM::SecondarySalesOrderListPendingDeliveryArray($em$warehouseIds),
  13274.                 'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
  13275.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
  13276.                 'debugData' => $debugData,
  13277.             )
  13278.         );
  13279.     }
  13280.     public function AddUnitTypeAction(Request $request$id 0)
  13281.     {
  13282.         $em $this->getDoctrine()->getManager();
  13283.         $companyId $this->getLoggedUserCompanyId($request);
  13284.         if ($request->isMethod('POST')) {
  13285.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13286.             $unitType = new UnitType();
  13287.             $unitType->setName($request->request->get('name'));
  13288.             $unitType->setStatus(1);
  13289.             $em->persist($unitType);
  13290.             $em->flush();
  13291.             $this->addFlash(
  13292.                 'success',
  13293.                 'Unit Type Added'
  13294.             );
  13295.         }
  13296.         $unitTypeDetails $em->getRepository(UnitType::class)->findAll();
  13297.         return $this->render('@Inventory/pages/input_forms/addUnitType.html.twig',
  13298.             array(
  13299.                 'page_title' => 'Add Unit Type',
  13300.                 'unitTypeDetails' => $unitTypeDetails
  13301.             )
  13302.         );
  13303.     }
  13304.     public
  13305.     function SubcategoryListAction()
  13306.     {
  13307.         return $this->render('@Inventory/pages/input_forms/subCategoryList.html.twig',
  13308.             array(
  13309.                 'page_title' => 'Sub Category List',
  13310.             )
  13311.         );
  13312.     }
  13313. //    public function getInventoryProductList(Request $request)
  13314. //    {
  13315. //        $em = $this->getDoctrine()->getManager();
  13316. //
  13317. //        $page = (int) $request->query->get('page', 1);     // Default page = 1
  13318. //        $limit = (int) $request->query->get('limit', 10);   // Default limit = 10
  13319. //        $offset = ($page - 1) * $limit;
  13320. //
  13321. //        // First, get the total count of products
  13322. //        $totalQuery = $em->createQueryBuilder()
  13323. //            ->select('COUNT(i.id)')
  13324. //            ->from('ApplicationBundle:InventoryStorage', 'i')
  13325. //            ->where('i.qty > :minQty')
  13326. //            ->setParameter('minQty', 0)
  13327. //            ->getQuery();
  13328. //
  13329. //        $totalRecords = (int) $totalQuery->getSingleScalarResult();
  13330. //        $totalPages = $limit > 0 ? (int) ceil($totalRecords / $limit) : 1;
  13331. //
  13332. //        // Then, get the paginated data
  13333. //        $qb = $em->getRepository('ApplicationBundle:InventoryStorage')->createQueryBuilder('i')
  13334. //            ->select([
  13335. //                'i.productId AS productId',
  13336. //                'COALESCE(ig.name, \'\') AS itemGroupName',
  13337. //                'COALESCE(w.name, \'\') AS wareHouseName',
  13338. //                'i.qty AS quantity',
  13339. //                'COALESCE(b.name, \'\') AS brandName',
  13340. //                'COALESCE(u.name, \'\') AS UnitName',
  13341. //                'COALESCE(c.name, \'\') AS color',
  13342. //                'COALESCE(s.name, \'\') AS size',
  13343. //                'COALESCE(i.salesPrice, 0) AS salesPrice',
  13344. //                'COALESCE(p.name, \'\') AS productName'
  13345. //            ])
  13346. //            ->leftJoin('ApplicationBundle:InvProducts', 'p', 'WITH', 'i.productId = p.id')
  13347. //            ->leftJoin('ApplicationBundle:InvItemGroup', 'ig', 'WITH', 'i.igId = ig.id')
  13348. //            ->leftJoin('ApplicationBundle:Warehouse', 'w', 'WITH', 'i.warehouseId = w.id')
  13349. //            ->leftJoin('ApplicationBundle:BrandCompany', 'b', 'WITH', 'i.brandId = b.id')
  13350. //            ->leftJoin('ApplicationBundle:UnitType', 'u', 'WITH', 'i.unitTypeId = u.id')
  13351. //            ->leftJoin('ApplicationBundle:Colors', 'c', 'WITH', 'i.color = c.id')
  13352. //            ->leftJoin('ApplicationBundle:ProductSizes', 's', 'WITH', 'i.size = s.id')
  13353. //            ->where('i.qty > :minQty')
  13354. //            ->setParameter('minQty', 0)
  13355. //            ->setFirstResult($offset)
  13356. //            ->setMaxResults($limit);
  13357. //
  13358. //        $inventoryData = $qb->getQuery()->getResult();
  13359. //
  13360. //        return $this->json([
  13361. //            'page' => $page,
  13362. //            'limit' => $limit,
  13363. //            'totalRecords' => $totalRecords,
  13364. //            'totalPages' => $totalPages,
  13365. //            'data' => $inventoryData,
  13366. //        ]);
  13367. //    }
  13368.     public function getInventoryProductList(Request $request)
  13369.     {
  13370.         $em $this->getDoctrine()->getManager();
  13371.         $page = (int) $request->query->get('page'1);
  13372.         $limit = (int) $request->query->get('limit'10);
  13373.         $offset = ($page 1) * $limit;
  13374.         $totalQuery $em->createQueryBuilder()
  13375.             ->select('COUNT(i.id)')
  13376.             ->from('ApplicationBundle:InventoryStorage''i')
  13377.             ->where('i.qty > :minQty')
  13378.             ->setParameter('minQty'0)
  13379.             ->getQuery();
  13380.         $totalRecords = (int) $totalQuery->getSingleScalarResult();
  13381.         $totalPages $limit ? (int) ceil($totalRecords $limit) : 1;
  13382.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  13383.         $qb $em->getRepository('ApplicationBundle:InventoryStorage')->createQueryBuilder('i')
  13384.             ->select([
  13385.                 'i.productId AS productId',
  13386.                 'COALESCE(ig.name, \'\') AS itemGroupName',
  13387.                 'COALESCE(w.name, \'\') AS wareHouseName',
  13388.                 'COALESCE(wa.name, \'\') AS subWareHouseName',
  13389.                 'i.qty AS quantity',
  13390.                 'i.qty AS lastSold',
  13391.                 'i.qty AS lastPurchase',
  13392.                 'COALESCE(b.name, \'\') AS brandName',
  13393.                 'COALESCE(u.name, \'\') AS UnitName',
  13394.                 'COALESCE(c.name, \'\') AS color',
  13395.                 'COALESCE(s.name, \'\') AS size',
  13396.                 'COALESCE(i.purchasePrice, 0) AS purchasePrice',
  13397.                 'COALESCE(i.salesPrice, 0) AS salesPrice',
  13398.                 'COALESCE(p.name, \'\') AS productName',
  13399.                 'COALESCE(p.productCode, \'\') AS productCode',
  13400.                 "CASE 
  13401.                 WHEN p.images IS NOT NULL AND p.images <> '' 
  13402.                 THEN p.images 
  13403.                 ELSE '$defaultImage
  13404.             END AS image"
  13405.             ])
  13406.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  13407.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''i.igId = ig.id')
  13408.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''i.warehouseId = w.id')
  13409.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''i.actionTagId = wa.id')
  13410.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''i.brandId = b.id')
  13411.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''i.unitTypeId = u.id')
  13412.             ->leftJoin('ApplicationBundle:Colors''c''WITH''i.color = c.id')
  13413.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''i.size = s.id')
  13414.             ->where('i.qty > :minQty')
  13415.             ->setParameter('minQty'0)
  13416.             ->setFirstResult($offset)
  13417.             ->setMaxResults($limit);
  13418.         $inventoryData $qb->getQuery()->getResult();
  13419.         return $this->json([
  13420.             'page' => $page,
  13421.             'limit' => $limit,
  13422.             'totalRecords' => $totalRecords,
  13423.             'totalPages' => $totalPages,
  13424.             'data' => $inventoryData,
  13425.         ]);
  13426.     }
  13427.     public function CreateStockTransferForAppAction(Request $request)
  13428.     {
  13429.         $em $this->getDoctrine()->getManager();
  13430.         $companyId $this->getLoggedUserCompanyId($request);
  13431.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  13432.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  13433.         if ($request->isMethod('POST')) {
  13434.             $em $this->getDoctrine()->getManager();
  13435.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  13436.             $dochash $request->request->get('docHash'); //change
  13437.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13438.             $approveRole $request->request->get('approvalRole');
  13439.             $approveHash $request->request->get('approvalHash');
  13440.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  13441.                 $loginId$approveRole$approveHash)
  13442.             ) {
  13443.                 $this->addFlash(
  13444.                     'error',
  13445.                     'Sorry Couldnot insert Data.'
  13446.                 );
  13447.             } else {
  13448.                 if ($request->request->has('check_allowed'))
  13449.                     $check_allowed 1;
  13450.                 $StID Inventory::CreateNewStockTransferForAPP(
  13451.                     $this->getDoctrine()->getManager(),
  13452.                     $request->request,
  13453.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13454.                     $this->getLoggedUserCompanyId($request)
  13455.                 );
  13456.                 //now add Approval info
  13457.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13458.                 $approveRole 1;  //created
  13459.                 $options = array(
  13460.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  13461.                     'notification_server' => $this->container->getParameter('notification_server'),
  13462.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  13463.                     'url' => $this->generateUrl(
  13464.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  13465.                         ['entity_view_route_path_name']
  13466.                     )
  13467.                 );
  13468.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  13469.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  13470.                     $StID,
  13471.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  13472.                 );
  13473.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  13474.                     $loginId,
  13475.                     $approveRole,
  13476.                     $request->request->get('approvalHash'));
  13477.                 $this->addFlash(
  13478.                     'success',
  13479.                     'Stock Transfer Added.'
  13480.                 );
  13481.                 $url $this->generateUrl(
  13482.                     'view_st'
  13483.                 );
  13484. //                return $this->redirect($url . "/" . $StID);
  13485.                 return $this->json(['success' => true]);
  13486.             }
  13487.         }
  13488.        $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  13489.             array(
  13490.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  13491.            )
  13492.         );
  13493.         $INVLIST = [];
  13494.        foreach ($slotList as $slot) {
  13495.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  13496.        }
  13497.         return $this->json(['success' => true]);
  13498. //       return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  13499. //           array(
  13500. //         'page_title' => 'Stock Transfer Note',
  13501. //               'warehouseList' => Inventory::WarehouseList($em),
  13502. //        'warehouseListArray' => Inventory::WarehouseListArray($em),
  13503. //               'colorList' => Inventory::GetColorList($em),
  13504. //               'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13505. //                'srList' => [],
  13506. //               'warehouseActionList' => $warehouse_action_list,
  13507. //                'warehouseActionListArray' => $warehouse_action_list_array,
  13508. //                'item_list' => Inventory::ItemGroupList($em),
  13509. //                'item_list_array' => Inventory::ItemGroupListArray($em),
  13510. //               'category_list_array' => Inventory::ProductCategoryListArray($em),
  13511. //              'product_list_array' => Inventory::ProductListDetailedArray($em),
  13512. ////               'product_list_array' => [],
  13513. //               'product_list' => Inventory::ProductList($em, $companyId),
  13514. ////                'product_list' => [],
  13515. //               'prefix_list' => array(
  13516. //                   [
  13517. //                       'id' => 1,
  13518. //                       'value' => 'GN',
  13519. //                        'text' => 'GN'
  13520. //
  13521. //                   ]
  13522. //              ),
  13523. //              'assoc_list' => array(
  13524. //                  [
  13525. //                       'id' => 1,
  13526. //                        'value' => 1,
  13527. //                        'text' => 'GN'
  13528. //
  13529. //                  ]
  13530. //               ),
  13531. //              'INVLIST' => $INVLIST
  13532. //           )
  13533. //      );
  13534.     }
  13535.     public function getWarehouseList(Request $request){
  13536.         $em $this->getDoctrine()->getManager();
  13537.         $warehouses $em->getRepository('ApplicationBundle:Warehouse')
  13538.             ->createQueryBuilder('w')
  13539.             ->select('w.id''w.name')
  13540.             ->orderBy('w.name''ASC')
  13541.             ->getQuery()
  13542.             ->getResult();
  13543.         return $this->json($warehouses);
  13544.     }
  13545.     public function getSubWarehouseList(Request $request){
  13546.         $em $this->getDoctrine()->getManager();
  13547.         $warehouses $em->getRepository('ApplicationBundle:WarehouseAction')
  13548.             ->createQueryBuilder('w')
  13549.             ->select('w.id''w.name')
  13550. //            ->orderBy('w.name', 'ASC')
  13551.             ->getQuery()
  13552.             ->getResult();
  13553.         return $this->json($warehouses);
  13554.     }
  13555.     public function getStockReceiveList(Request $request){
  13556.         $list GeneralConstant::$stockReceiveType;
  13557.         return $this->json($list);
  13558.     }
  13559.     public function getOrderListByStockReceiveId(Request $request)
  13560.     {
  13561.         $em $this->getDoctrine()->getManager();
  13562.         $typeName $request->request->get('type');
  13563.         $typeId $request->request->get('id');
  13564.         $document null;
  13565.         if($typeName == 'From Stock Transfer' || $typeId == 1){
  13566.             $document $em->getRepository('ApplicationBundle:StockTransfer')->createQueryBuilder('s')->select('s.stockTransferId','s.documentHash')->where('s.approved !=1')->getQuery()->getResult();
  13567.         } else if($typeName == 'For Stock In' || $typeId == 3){
  13568.             $document $em->getRepository('ApplicationBundle:AccAccountsHead')->createQueryBuilder('a')->select('a.accountsHeadId','a.name')->getQuery()->getResult();
  13569.         }
  13570.         else if($typeName == 'For Opening Entity' || $typeId == 4){
  13571.             $document $em->getRepository('ApplicationBundle:WarehouseAction')
  13572.                 ->createQueryBuilder('w')
  13573.                 ->select('w.id''w.name')
  13574.                 ->getQuery()
  13575.                 ->getResult();
  13576.         }
  13577.         return $this->json($document);
  13578.     }
  13579.     public function GetProductFromInvStorage(Request $request)
  13580.     {
  13581.         $em $this->getDoctrine()->getManager();
  13582.         $searchTerm trim($request->get('name'));
  13583.         // Fetch all or filtered products
  13584.         if ($searchTerm) {
  13585.             $products $em->getRepository('ApplicationBundle:InvProducts')
  13586.                 ->createQueryBuilder('p')
  13587.                 ->where('p.name LIKE :term')
  13588.                 ->setParameter('term''%' $searchTerm '%')
  13589.                 ->getQuery()
  13590.                 ->getResult();
  13591.         } else {
  13592.             $products $em->getRepository('ApplicationBundle:InvProducts')->findAll();
  13593.         }
  13594.         $response = [];
  13595.         foreach ($products as $product) {
  13596.             // All InventoryStorage entries for the product
  13597.             $invStorageItems $em->getRepository('ApplicationBundle:InventoryStorage')->findBy([
  13598.                 'productId' => $product->getId()
  13599.             ]);
  13600.             $inventoryList = [];
  13601.             foreach ($invStorageItems as $item) {
  13602.                 $warehouse $em->getRepository('ApplicationBundle:Warehouse')->find($item->getWarehouseId());
  13603.                 $subWarehouse $em->getRepository('ApplicationBundle:WarehouseAction')->find($item->getActionTagId());
  13604.                 $inventoryList[] = [
  13605.                     'warehouse_id'      => $item->getWarehouseId(),
  13606.                     'warehouse_name'    => $warehouse $warehouse->getName() : '',
  13607.                     'sub_warehouse_id'  => $item->getActionTagId(),
  13608.                     'sub_warehouse_name'=> $subWarehouse $subWarehouse->getName() : '',
  13609.                     'quantity'          => $item->getQty(),
  13610.                     'lastSold'          => $item->getNonInvoicedQty(),
  13611.                     'lastPurchase'      => $item->getPhysicalQty(),
  13612.                     'purchasePrice'     => $item->getPurchasePrice(),
  13613.                     'salesPrice'        => $item->getSalesPrice(),
  13614.                     'brandName'         => $item->getBrandId(),
  13615.                     'unitName'          => 'pcs'// Optional: Resolve via Unit table
  13616.                 ];
  13617.             }
  13618.             $response[] = [
  13619.                 'productId'     => $product->getId(),
  13620.                 'itemGroupName' => $product->getIgId(),
  13621.                 'productName'   => $product->getName(),
  13622.                 'productCode'   => $product->getProductCode(),
  13623.                 'color'         => $product->getColors(),
  13624.                 'size'          => $product->getSizes(),
  13625.                 'image'         => $product->getDefaultImage(),
  13626.                 'inventory'     => $inventoryList
  13627.             ];
  13628.         }
  13629.         return new JsonResponse($response);
  13630.     }
  13631.     public function getProductByDocumentId(Request $request)
  13632.     {
  13633.         $em $this->getDoctrine()->getManager();
  13634.         $documentId $request->request->get('documentId');
  13635.         $accountsHeadId $request->request->get('accountsHeadId');
  13636.         if($documentId){
  13637.             $productIdRows $em->getRepository('ApplicationBundle:StockTransferItem')
  13638.                 ->createQueryBuilder('s')
  13639.                 ->select('s.productId')
  13640.                 ->where('s.stockTransferId = :documentId')
  13641.                 ->setParameter('documentId'$documentId)
  13642.                 ->getQuery()
  13643.                 ->getResult();
  13644.             $fromWarehouseRow $em->getRepository('ApplicationBundle:StockTransferItem')
  13645.                 ->createQueryBuilder('s')
  13646.                 ->select('s.warehouseId''s.toWarehouseId''s.warehouseActionId''s.toWarehouseActionId','s.qty','s.price')
  13647.                 ->where('s.stockTransferId = :documentId')
  13648.                 ->setParameter('documentId'$documentId)
  13649.                 ->setMaxResults(1)
  13650.                 ->getQuery()
  13651.                 ->getOneOrNullResult();
  13652.             $productIds array_map(function($row) {
  13653.                 return $row['productId'];
  13654.             }, $productIdRows);
  13655.             $product $em->getRepository('ApplicationBundle:InvProducts')->findBy([
  13656.                 'id'=>$productIds
  13657.             ]);
  13658.             $productData array_map(function($p) {
  13659.                 return [
  13660.                     'id' => $p->getId(),
  13661.                     'name' => $p->getName(),
  13662.                     'modelNo' => $p->getModelNo(),
  13663.                     'sku' => $p->getSkuCode(),
  13664.                     'productCode' => $p->getProductCode(),
  13665.                     'purchasePrice' => $p->getPurchasePrice(),
  13666.                     'salesPrice' => $p->getSalesPrice(),
  13667.                     'purchasePriceWoExpense' => $p->getPurchasePriceWoExpense(),
  13668.                     'qty' => $p->getQty(),
  13669.                     'nonInvoicedQty' => $p->getNonInvoicedQty(),
  13670.                     'nonSalesInvoicedQty' => $p->getNonSalesInvoicedQty(),
  13671.                     'unitTypeId' => $p->getUnitTypeId(),
  13672.                     'dimension' => $p->getDimension(),
  13673.                     'dimensionUnitTypeId' => $p->getDimensionUnitTypeId(),
  13674.                     'weight' => $p->getWeight(),
  13675.                     'categoryId' => $p->getCategoryId(),
  13676.                     'subCategoryId' => $p->getSubCategoryId(),
  13677.                     'brandCompany' => $p->getBrandCompany(),
  13678.                     'warehouseId' => $p->getWarehouseId(),
  13679.                     'reorderLevel' => $p->getReorderLevel(),
  13680.                     'defaultImage' => $p->getDefaultImage(),
  13681.                     'status' => $p->getStatus()
  13682.                 ];
  13683.             }, $product);
  13684.             return $this->json([
  13685.                 'warehouseId' => $fromWarehouseRow['warehouseId'],
  13686.                 'toWarehouseId' => $fromWarehouseRow['toWarehouseId'],
  13687.                 'warehouseActionId' => $fromWarehouseRow['warehouseActionId'],
  13688.                 'toWarehouseActionId' => $fromWarehouseRow['toWarehouseActionId'],
  13689.                 'quantity'=>$fromWarehouseRow['qty'],
  13690.                 'price'=>$fromWarehouseRow['price'],
  13691.                 'products' => $productData
  13692.             ]);
  13693.         }else if($accountsHeadId){
  13694.             $products $em->getRepository('ApplicationBundle:InvProducts')->findAll();
  13695.             $productData array_map(function($p) {
  13696.                 return [
  13697.                     'id' => $p->getId(),
  13698.                     'name' => $p->getName(),
  13699.                     'modelNo' => $p->getModelNo(),
  13700.                     'sku' => $p->getSkuCode(),
  13701.                     'productCode' => $p->getProductCode(),
  13702.                     'purchasePrice' => $p->getPurchasePrice(),
  13703.                     'salesPrice' => $p->getSalesPrice(),
  13704.                     'purchasePriceWoExpense' => $p->getPurchasePriceWoExpense(),
  13705.                     'qty' => $p->getQty(),
  13706.                     'nonInvoicedQty' => $p->getNonInvoicedQty(),
  13707.                     'nonSalesInvoicedQty' => $p->getNonSalesInvoicedQty(),
  13708.                     'unitTypeId' => $p->getUnitTypeId(),
  13709.                     'dimension' => $p->getDimension(),
  13710.                     'dimensionUnitTypeId' => $p->getDimensionUnitTypeId(),
  13711.                     'weight' => $p->getWeight(),
  13712.                     'categoryId' => $p->getCategoryId(),
  13713.                     'subCategoryId' => $p->getSubCategoryId(),
  13714.                     'brandCompany' => $p->getBrandCompany(),
  13715.                     'warehouseId' => $p->getWarehouseId(),
  13716.                     'reorderLevel' => $p->getReorderLevel(),
  13717.                     'defaultImage' => $p->getDefaultImage(),
  13718.                     'status' => $p->getStatus()
  13719.                 ];
  13720.             }, $products);
  13721.             return $this->json($productData);
  13722.         }else{
  13723.             return new JsonResponse([
  13724.                 "status"=>false,
  13725.                 "message"=>"Please insert valid documentId or accountsHead!"
  13726.             ]);
  13727.         }
  13728.     }
  13729.     public function getQuantityBasedOnSubWareHouse(Request $request)
  13730.     {
  13731.         $em $this->getDoctrine()->getManager();
  13732.         $productId $request->get('product_id');
  13733.         $productName trim($request->get('product_name'));
  13734.         $warehouseId $request->get('warehouse_id');
  13735.         $warehouseActionId $request->get('warehouse_action_id');
  13736.         if (!$productId && $productName) {
  13737.             $product $em->getRepository('ApplicationBundle:InvProducts')
  13738.                 ->createQueryBuilder('p')
  13739.                 ->where('p.name LIKE :name')
  13740.                 ->setParameter('name''%' $productName '%')
  13741.                 ->setMaxResults(1)
  13742.                 ->getQuery()
  13743.                 ->getOneOrNullResult();
  13744.             if ($product) {
  13745.                 $productId $product->getId();
  13746.             }
  13747.         }
  13748.         if (!$productId || !$warehouseId || !$warehouseActionId) {
  13749.             return new JsonResponse(['error' => 'Product ID, Warehouse ID, and Action Tag ID are required'], 400);
  13750.         }
  13751.         $criteria = [
  13752.             'productId'   => $productId,
  13753.             'warehouseId' => $warehouseId,
  13754.             'actionTagId' => $warehouseActionId,
  13755.         ];
  13756.         $invStorageItems $em->getRepository('ApplicationBundle:InventoryStorage')->findBy($criteria);
  13757.         if (empty($invStorageItems)) {
  13758.             return new JsonResponse([
  13759.                 'product_id' => $productId,
  13760.                 'quantities' => []
  13761.             ]);
  13762.         }
  13763.         $totalQty 0;
  13764.         $totalNonInvoicedQty 0;
  13765.         $totalPhysicalQty 0;
  13766.         $purchasePrice null;
  13767.         $salesPrice null;
  13768.         foreach ($invStorageItems as $item) {
  13769.             $totalQty += $item->getQty();
  13770.             $totalNonInvoicedQty += $item->getNonInvoicedQty();
  13771.             $totalPhysicalQty += $item->getPhysicalQty();
  13772.             $purchasePrice $item->getPurchasePrice();
  13773.             $salesPrice $item->getSalesPrice();
  13774.         }
  13775.         $subWarehouse $em->getRepository('ApplicationBundle:WarehouseAction')->find($warehouseActionId);
  13776.         $quantitiesBySubWarehouse = [[
  13777.             'action_tag_id'     => $warehouseActionId,
  13778.             'sub_warehouse'     => $subWarehouse $subWarehouse->getName() : '',
  13779.             'qty'               => $totalQty,
  13780.             'non_invoiced_qty'  => $totalNonInvoicedQty,
  13781.             'physical_qty'      => $totalPhysicalQty,
  13782.             'purchase_price'    => $purchasePrice,
  13783.             'sales_price'       => $salesPrice,
  13784.         ]];
  13785.         return new JsonResponse([
  13786.             'product_id' => $productId,
  13787.             'quantities' => $quantitiesBySubWarehouse
  13788.         ]);
  13789.     }
  13790.     public function getPriceByWareHouseId(Request $request)
  13791.     {
  13792.         $em $this->getDoctrine()->getManager();
  13793.         $warehouseId $request->request->get('warehouseId');
  13794.         $productId $request->request->get('productId');
  13795.         $actionTagId $request->request->get('actionTagId');
  13796.         $unitPrice $em->getRepository('ApplicationBundle:InventoryStorage')->createQueryBuilder('st')
  13797.             ->select('st.purchasePrice AS purchasePrice')
  13798.             ->where('st.productId = :productId')
  13799.             ->andWhere('st.warehouseId = :warehouseId')
  13800.             ->andWhere('st.actionTagId = :actionTagId')
  13801.             ->setParameter('productId'$productId)
  13802.             ->setParameter('warehouseId'$warehouseId)
  13803.             ->setParameter('actionTagId'$actionTagId)
  13804.             ->setMaxResults(1)
  13805.             ->getQuery()
  13806.             ->getOneOrNullResult();
  13807.         return new JsonResponse([
  13808.             'purchasePrice' => $unitPrice $unitPrice['purchasePrice'] : null
  13809.         ]);
  13810.     }
  13811.     public function getStockTransferList(Request $request){
  13812.         $em $this->getDoctrine()->getManager();
  13813.         $warehouses $em->getRepository('ApplicationBundle:StockTransfer')
  13814.             ->createQueryBuilder('s')
  13815.             ->select('s.stockTransferId''s.documentHash')
  13816. //            ->orderBy('s.name', 'ASC')
  13817.             ->getQuery()
  13818.             ->getResult();
  13819.         return $this->json($warehouses);
  13820.     }
  13821.     public function stockTransferItemList(Request $request)
  13822.     {
  13823.         $em $this->getDoctrine()->getManager();
  13824.         $stockTransferId $request->query->get('stockTransferId');
  13825.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  13826.         $qb $em->createQueryBuilder();
  13827.         $qb->select(
  13828.             'sti.id AS id',
  13829.             'sti.productId AS productId',
  13830.             'sti.stockTransferId AS stockTransferId',
  13831.             'p.name AS productName',
  13832.             'sti.price AS price',
  13833.             'p.images AS images',
  13834.             'ig.name AS itemGroupName',
  13835.             'w.name AS wareHouseName',
  13836.             'sti.warehouseId AS warehouseId',
  13837.             'wa.name AS subWareHouseName',
  13838.             'sti.warehouseActionId AS warehouseActionId',
  13839.             'sti.qty AS quantity',
  13840.             'b.name AS brandName',
  13841.             'u.name AS UnitName',
  13842.             'c.name AS color',
  13843.             's.name AS size'
  13844.         )
  13845.             ->from('ApplicationBundle:StockTransferItem''sti')
  13846.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''sti.productId = p.id')
  13847.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''p.igId = ig.id')
  13848.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''sti.warehouseId = w.id')
  13849.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''sti.warehouseActionId = wa.id')
  13850.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''p.brandCompany = b.id')
  13851.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''p.unitTypeId = u.id')
  13852.             ->leftJoin('ApplicationBundle:Colors''c''WITH''sti.colorId = c.id')
  13853.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''sti.sizeId = s.id')
  13854.             ->where('sti.stockTransferId = :stockTransferId')
  13855.             ->setParameter('stockTransferId'$stockTransferId);
  13856.         $results $qb->getQuery()->getResult();
  13857.         $response = [];
  13858.         foreach ($results as $item) {
  13859.             $response[] = [
  13860.                 'id' => $item['id'],
  13861.                 'stockTransferId' => $item['stockTransferId'],
  13862.                 'productId'    => (int) $item['productId'],
  13863.                 'itemGroupName'=> $item['itemGroupName'] ?? '',
  13864.                 'wareHouseName'=> $item['wareHouseName'] ?? '',
  13865.                 'wareHouseId'=> $item['warehouseId'] ?? '',
  13866.                 'subWareHouseName'=> $item['subWareHouseName'] ?? '',
  13867.                 'subWareHouseId'=> $item['warehouseActionId'] ?? '',
  13868.                 'quantity'     => (int) $item['quantity'],
  13869.                 'brandName'    => $item['brandName'] ?? '',
  13870.                 'UnitName'     => $item['UnitName'] ?? '',
  13871.                 'color'        => $item['color'] ?? '',
  13872.                 'size'         => $item['size'] ?? '',
  13873.                 'price'   => (float) $item['price'],
  13874.                 'productName'  => $item['productName'] ?? '',
  13875.                 'image'        => !empty($item['images']) ? $item['images'] : $defaultImage,
  13876.             ];
  13877.         }
  13878.         return $this->json($response);
  13879.     }
  13880.     public function inventoryStorageFilter(Request $request)
  13881.     {
  13882.         $em $this->getDoctrine()->getManager();
  13883.         $qb $em->createQueryBuilder();
  13884.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  13885.         $qb->select(
  13886.             'i.productId',
  13887.             'ig.name AS itemGroupName',
  13888.             'w.name AS wareHouseName',
  13889.             'wa.name AS subWareHouseName',
  13890.             'i.qty AS quantity',
  13891.             'b.name AS brandName',
  13892.             'u.name AS UnitName',
  13893.             'c.name AS color',
  13894.             's.name AS size',
  13895.             'i.purchasePrice AS price',
  13896.             'p.name AS productName',
  13897.             'p.images'
  13898.         )
  13899.             ->from('ApplicationBundle:InventoryStorage''i')
  13900.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  13901.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''i.igId = ig.id')
  13902.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''i.warehouseId = w.id')
  13903.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''i.brandId = b.id')
  13904.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''i.unitTypeId = u.id')
  13905.             ->leftJoin('ApplicationBundle:Colors''c''WITH''i.color = c.id')
  13906.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''i.size = s.id')
  13907.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''i.actionTagId = wa.id');
  13908.         // Define available filters with their mappings
  13909.         $filters = [
  13910.             'itemGroup'    => 'ig.id',
  13911.             'category'     => 'p.categoryId',
  13912.             'warehouse'    => 'w.id',
  13913.             'storageType'  => 'i.actionTagId',
  13914.             'brand'        => 'b.id',
  13915.             'color'        => 'c.id',
  13916.             'colorCode'    => 'c.hexCode',
  13917.             'size'         => 's.id',
  13918.         ];
  13919.         foreach ($filters as $param => $field) {
  13920.             $value $request->query->get($param);
  13921.             if ($value !== null) {
  13922.                 $values array_map('trim'explode(','$value));
  13923.                 if (count($values) > 1) {
  13924.                     $qb->andWhere($qb->expr()->in($field":$param"))
  13925.                         ->setParameter($param$values);
  13926.                 } else {
  13927.                     $qb->andWhere("$field = :$param")
  13928.                         ->setParameter($param$values[0]);
  13929.                 }
  13930.             }
  13931.         }
  13932.         $rawResult $qb->getQuery()->getArrayResult();
  13933.         $finalResult = [];
  13934.         foreach ($rawResult as $row) {
  13935.             $finalResult[] = [
  13936.                 'productId'     => $row['productId'],
  13937.                 'itemGroupName' => $row['itemGroupName'],
  13938.                 'wareHouseName' => $row['wareHouseName'],
  13939.                 'subWareHouseName' => $row['subWareHouseName'],
  13940.                 'quantity'      => $row['quantity'],
  13941.                 'brandName'     => $row['brandName'],
  13942.                 'UnitName'      => $row['UnitName'],
  13943.                 'color'         => $row['color'] ?? '',
  13944.                 'size'          => $row['size'] ?? '',
  13945.                 'price'         => $row['price'],
  13946.                 'productName'   => $row['productName'],
  13947.                 'image'         => !empty($row['images']) ? $row['images'] : $defaultImage,
  13948.             ];
  13949.         }
  13950.         // Check if finalResult is empty
  13951.         if (empty($finalResult)) {
  13952.             return $this->json([
  13953.                 'success' => false,
  13954.                 'message' => 'No inventory items found matching your criteria'
  13955.             ]);
  13956.         }
  13957.         return $this->json([
  13958.             'success' => true,
  13959.             'data' => $finalResult
  13960.         ]);
  13961.     }
  13962. //    public function inventoryStorageFilter(Request $request)
  13963. //    {
  13964. //        $em = $this->getDoctrine()->getManager();
  13965. //        $qb = $em->createQueryBuilder();
  13966. //        $defaultImage = 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  13967. //
  13968. //        $qb->select(
  13969. //            'i.productId',
  13970. //            'ig.name AS itemGroupName',
  13971. //            'w.name AS wareHouseName',
  13972. //            'wa.name AS subWareHouseName',
  13973. //            'i.qty AS quantity',
  13974. //            'b.name AS brandName',
  13975. //            'u.name AS UnitName',
  13976. //            'c.name AS color',
  13977. //            's.name AS size',
  13978. //            'i.purchasePrice AS price',
  13979. //            'p.name AS productName',
  13980. //            'p.images'
  13981. //        )
  13982. //            ->from('ApplicationBundle:InventoryStorage', 'i')
  13983. //            ->leftJoin('ApplicationBundle:InvProducts', 'p', 'WITH', 'i.productId = p.id')
  13984. //            ->leftJoin('ApplicationBundle:InvItemGroup', 'ig', 'WITH', 'i.igId = ig.id')
  13985. //            ->leftJoin('ApplicationBundle:Warehouse', 'w', 'WITH', 'i.warehouseId = w.id')
  13986. //            ->leftJoin('ApplicationBundle:BrandCompany', 'b', 'WITH', 'i.brandId = b.id')
  13987. //            ->leftJoin('ApplicationBundle:UnitType', 'u', 'WITH', 'i.unitTypeId = u.id')
  13988. //            ->leftJoin('ApplicationBundle:Colors', 'c', 'WITH', 'i.color = c.id')
  13989. //            ->leftJoin('ApplicationBundle:ProductSizes', 's', 'WITH', 'i.size = s.id')
  13990. //            ->leftJoin('ApplicationBundle:WarehouseAction', 'wa', 'WITH', 'i.actionTagId = wa.id');
  13991. //
  13992. //        // Define available filters with their mappings
  13993. //        $filters = [
  13994. //            'itemGroup'    => 'ig.id',
  13995. //            'category'     => 'p.categoryId',
  13996. //            'warehouse'    => 'w.id',
  13997. //            'storageType'  => 'i.actionTagId',
  13998. //            'brand'        => 'b.id',
  13999. //            'color'        => 'c.id',
  14000. //            'colorCode'    => 'c.hexCode',
  14001. //            'size'         => 's.id',
  14002. //        ];
  14003. //
  14004. //        foreach ($filters as $param => $field) {
  14005. //            $value = $request->query->get($param);
  14006. //
  14007. //            if ($value !== null) {
  14008. //                $values = array_map('trim', explode(',', $value)); // handle multiple
  14009. //                if (count($values) > 1) {
  14010. //                    $qb->andWhere($qb->expr()->in($field, ":$param"))
  14011. //                        ->setParameter($param, $values);
  14012. //                } else {
  14013. //                    $qb->andWhere("$field = :$param")
  14014. //                        ->setParameter($param, $values[0]);
  14015. //                }
  14016. //            }
  14017. //        }
  14018. //
  14019. //        $rawResult = $qb->getQuery()->getArrayResult();
  14020. //
  14021. //        // Now process for validation (color, size, images)
  14022. //        $finalResult = [];
  14023. //
  14024. //        foreach ($rawResult as $row) {
  14025. //            $finalResult[] = [
  14026. //                'productId'     => $row['productId'],
  14027. //                'itemGroupName' => $row['itemGroupName'],
  14028. //                'wareHouseName' => $row['wareHouseName'],
  14029. //                'subWareHouseName' => $row['subWareHouseName'],
  14030. //                'quantity'      => $row['quantity'],
  14031. //                'brandName'     => $row['brandName'],
  14032. //                'UnitName'      => $row['UnitName'],
  14033. //                'color'         => $row['color'] ?? '',
  14034. //                'size'          => $row['size'] ?? '',
  14035. //                'price'         => $row['price'],
  14036. //                'productName'   => $row['productName'],
  14037. //                'image'         => !empty($row['images']) ? $row['images'] : $defaultImage,
  14038. //            ];
  14039. //        }
  14040. //
  14041. //
  14042. //
  14043. //        return $this->json($finalResult);
  14044. //    }
  14045.     public function getItemGroupList()
  14046.     {
  14047.         $em $this->getDoctrine()->getManager();
  14048.         $itemGroups $em->getRepository('ApplicationBundle:InvItemGroup')
  14049.             ->createQueryBuilder('ig')
  14050.             ->select('ig.id''ig.name')
  14051.             ->getQuery()
  14052.             ->getResult();
  14053.         return $this->json($itemGroups);
  14054.     }
  14055.     public function getProductCategoryList()
  14056.     {
  14057.         $em $this->getDoctrine()->getManager();
  14058.         $categories $em->getRepository('ApplicationBundle:InvProductCategories')
  14059.             ->createQueryBuilder('pc')
  14060.             ->select('pc.id''pc.name')
  14061.             ->getQuery()
  14062.             ->getResult();
  14063.         return $this->json($categories);
  14064.     }
  14065.     public function getBrandList()
  14066.     {
  14067.         $em $this->getDoctrine()->getManager();
  14068.         $brands $em->getRepository('ApplicationBundle:BrandCompany')
  14069.             ->createQueryBuilder('b')
  14070.             ->select('b.id''b.name')
  14071.             ->getQuery()
  14072.             ->getResult();
  14073.         return $this->json($brands);
  14074.     }
  14075.     public function getColorList()
  14076.     {
  14077.         $em $this->getDoctrine()->getManager();
  14078.         $colors $em->getRepository('ApplicationBundle:Colors')
  14079.             ->createQueryBuilder('c')
  14080.             ->select('c.id''c.name')
  14081.             ->getQuery()
  14082.             ->getResult();
  14083.         return $this->json($colors);
  14084.     }
  14085.     public function getColorCodeList()
  14086.     {
  14087.         $em $this->getDoctrine()->getManager();
  14088.         $colorCodes $em->getRepository('ApplicationBundle:Colors')
  14089.             ->createQueryBuilder('c')
  14090.             ->select('c.id''c.hexCode')
  14091.             ->getQuery()
  14092.             ->getResult();
  14093.         return $this->json($colorCodes);
  14094.     }
  14095.     public function getSizeList()
  14096.     {
  14097.         $em $this->getDoctrine()->getManager();
  14098.         $sizes $em->getRepository('ApplicationBundle:ProductSizes')
  14099.             ->createQueryBuilder('s')
  14100.             ->select('s.id''s.name')
  14101.             ->getQuery()
  14102.             ->getResult();
  14103.         if (empty($sizes)) {
  14104.             return $this->json([
  14105.                 'success' => false,
  14106.                 'message' => 'No data found'
  14107.             ]);
  14108.         }
  14109.         return $this->json($sizes);
  14110.     }
  14111.     public function productCodeList()
  14112.     {
  14113.         $em $this->getDoctrine()->getManager();
  14114.         $productCode $em->getRepository('ApplicationBundle:ProductByCode')
  14115.             ->createQueryBuilder('p')
  14116.             ->select('p.productByCodeId''p.productId','p.salesCode')
  14117.             ->getQuery()
  14118.             ->getResult();
  14119.         if (empty($productCode)) {
  14120.             return $this->json([
  14121.                 'success' => false,
  14122.                 'message' => 'No data found'
  14123.             ]);
  14124.         }
  14125.         return $this->json($productCode);
  14126.     }
  14127.     public function getItemInOutHistory(Request $request)
  14128.     {
  14129.         $em $this->getDoctrine()->getManager();
  14130.         $qb $em->getRepository('ApplicationBundle:InvItemTransaction')->createQueryBuilder('i')
  14131.             ->select([
  14132.                 'i.productId AS productId',
  14133.                 'i.transactionType AS transactionType',
  14134.                 'i.transactionDate AS transactionDate',
  14135.                 'toWarehouse.name AS toWarehouseId',
  14136.                 'toSubWarehouse.name AS toSubWarehouseId',
  14137.                 'fromWarehouse.name AS fromWarehouseId',
  14138.                 'fromSubWarehouse.name AS fromSubWarehouseId',
  14139.                 'i.qty AS quantity',
  14140.                 'i.entityDocHash AS document',
  14141.                 'i.entity AS entity',
  14142.                 'i.entityId AS entityId',
  14143.                 'p.name AS productName',
  14144.             ])
  14145.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  14146.             ->leftJoin('ApplicationBundle:Warehouse''toWarehouse''WITH''i.warehouseId = toWarehouse.id')
  14147.             ->leftJoin('ApplicationBundle:WarehouseAction''toSubWarehouse''WITH''i.actionTagId = toSubWarehouse.id')
  14148.             ->leftJoin('ApplicationBundle:Warehouse''fromWarehouse''WITH''i.fromWarehouseId = fromWarehouse.id')
  14149.             ->leftJoin('ApplicationBundle:WarehouseAction''fromSubWarehouse''WITH''i.fromActionTagId = fromSubWarehouse.id');
  14150.         // Parse dd-mm-yyyy to Y-m-d
  14151.         $startDateStr $request->query->get('startDate');
  14152.         $endDateStr   $request->query->get('endDate');
  14153.         if ($startDateStr && $endDateStr) {
  14154.             try {
  14155.                 $startDate = \DateTime::createFromFormat('d-m-Y'$startDateStr)->setTime(000);
  14156.                 $endDate   = \DateTime::createFromFormat('d-m-Y'$endDateStr)->setTime(235959);
  14157.                 $qb->andWhere('i.transactionDate BETWEEN :startDate AND :endDate')
  14158.                     ->setParameter('startDate'$startDate)
  14159.                     ->setParameter('endDate'$endDate);
  14160.             } catch (\Exception $e) {
  14161.                 return $this->json(['error' => 'Invalid date format. Use dd-mm-yyyy.'], 400);
  14162.             }
  14163.         }
  14164.         $results $qb->getQuery()->getResult();
  14165.         $data array_map(function ($item) {
  14166.             return [
  14167.                 'productId'          => $item['productId'],
  14168.                 'transactionType'    => $item['transactionType'] == 'IN' 'OUT',
  14169.                 'transactionDate'    => $item['transactionDate']->format('Y-m-d'),
  14170.                 'toWarehouseId'      => $item['toWarehouseId'] ?? '',
  14171.                 'toSubWarehouseId'   => $item['toSubWarehouseId'] ?? '',
  14172.                 'toSubWarehouseShortName'   => $item['toSubWarehouseId'] ?? '',
  14173.                 'fromWarehouseId'    => $item['fromWarehouseId'] ?? '',
  14174.                 'fromSubWarehouseId' => $item['fromSubWarehouseId'] ?? '',
  14175.                 'fromSubWarehouseShortName' => $item['fromSubWarehouseId'] ?? '',
  14176.                 'quantity'           => $item['quantity'],
  14177.                 'document'           => !empty($item['document']) ? $item['document'] : 0,
  14178.                 'entity'             => !empty($item['entity']) ? $item['entity'] : 0,
  14179.                 'entityId'           => !empty($item['entityId']) ? $item['entityId'] : 0,
  14180.                 'productName'        => $item['productName'],
  14181.             ];
  14182.         }, $results);
  14183.         return $this->json($data);
  14184.     }
  14185.     public function CreateStockReceivedNoteForApp(Request $request$id 0)
  14186.     {
  14187.         $em $this->getDoctrine()->getManager();
  14188.         $companyId $this->getLoggedUserCompanyId($request);
  14189.         $extDocData = [];
  14190.         $userId $request->getSession()->get(UserConstants::USER_ID);
  14191.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  14192.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  14193. //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  14194.         $userBranchIdList $request->getSession()->get('branchIdList');
  14195.         if ($userBranchIdList == null$userBranchIdList = [];
  14196.         $userBranchId $request->getSession()->get('branchId');
  14197.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  14198.             $em $this->getDoctrine()->getManager();
  14199.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //change
  14200.             $dochash $request->request->get('docHash'); //change
  14201.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14202.             $approveRole $request->request->get('approvalRole');
  14203.             $approveHash $request->request->get('approvalHash');
  14204.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  14205.                 $loginId$approveRole$approveHash$id)
  14206.             ) {
  14207.                 if ($request->request->has('returnJson')) {
  14208.                     return new JsonResponse(array(
  14209.                         'success' => false,
  14210.                         'documentHash' => 0,
  14211.                         'documentId' => 0,
  14212.                         'billIds' => [],
  14213.                         'drIds' => [],
  14214.                         'pmntTransIds' => [],
  14215.                         'viewUrl' => '',
  14216.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  14217.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  14218.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  14219.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  14220.                     ));
  14221.                 } else
  14222.                     $this->addFlash(
  14223.                         'error',
  14224.                         'Sorry Could not insert Data.'
  14225.                     );
  14226.             } else {
  14227.                 if ($request->request->has('check_allowed'))
  14228.                     $check_allowed 1;
  14229.                 $StID Inventory::CreateNewStockReceivedNoteForApp(
  14230.                     $this->getDoctrine()->getManager(),
  14231.                     $request->request,
  14232.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  14233.                     $this->getLoggedUserCompanyId($request)
  14234.                 );
  14235.                 //now add Approval info
  14236.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14237.                 $approveRole 1;  //created
  14238.                 $options = array(
  14239.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  14240.                     'notification_server' => $this->container->getParameter('notification_server'),
  14241.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  14242.                     'url' => $this->generateUrl(
  14243.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  14244.                         ['entity_view_route_path_name']
  14245.                     )
  14246.                 );
  14247.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  14248.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  14249.                     $StID,
  14250.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  14251.                 );
  14252.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  14253.                     $loginId,
  14254.                     $approveRole,
  14255.                     $request->request->get('approvalHash'));
  14256.                 $url $this->generateUrl(
  14257.                     'view_srcv'
  14258.                 );
  14259.                 if ($request->request->has('returnJson')) {
  14260.                     return new JsonResponse(array(
  14261.                         'success' => true,
  14262.                         'documentHash' => $dochash,
  14263.                         'documentId' => $StID,
  14264. //                        'viewUrl' => $url . "/" . $StID,
  14265.                     ));
  14266.                 } else {
  14267.                     $this->addFlash(
  14268.                         'success',
  14269.                         'Stock Received Note Added.'
  14270.                     );
  14271.                     return $this->redirect($url "/" $StID);
  14272.                 }
  14273.             }
  14274.         }
  14275.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  14276.             array(
  14277.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  14278.             )
  14279.         );
  14280.         if ($id == 0) {
  14281.         } else {
  14282.             $extDoc $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  14283.                 array(
  14284.                     'salesOrderId' => $id///material
  14285.                 )
  14286.             );
  14287.             //now if its not editable, redirect to view
  14288.             if ($extDoc) {
  14289.                 if ($extDoc->getEditFlag() != 1) {
  14290.                     $url $this->generateUrl(
  14291.                         'view_srcv'
  14292.                     );
  14293.                     return $this->redirect($url "/" $id);
  14294.                 } else {
  14295.                     $extDocData $extDoc;
  14296.                     $extDocDataDetails $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findOneBy(
  14297.                         array(
  14298.                             'stockReceivedNoteId' => $id///material
  14299.                         )
  14300.                     );
  14301.                 }
  14302.             } else {
  14303.             }
  14304.         }
  14305.         $INVLIST = [];
  14306.         foreach ($slotList as $slot) {
  14307.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  14308.         }
  14309.         $dataArray = array(
  14310.             'page_title' => 'Stock Received Note',
  14311. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  14312.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  14313.             'users' => Users::getUserListById($em),
  14314.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  14315.             'warehouseList' => Inventory::WarehouseList($em),
  14316.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  14317.             'warehouseActionList' => $warehouse_action_list,
  14318.             'warehouseActionListArray' => $warehouse_action_list_array,
  14319.             'extDocData' => $extDocData,
  14320.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  14321.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  14322.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  14323.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  14324. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  14325. //            'product_list' => Inventory::ProductList($em, $companyId),
  14326.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  14327.             'prefix_list' => array(
  14328.                 [
  14329.                     'id' => 1,
  14330.                     'value' => 'GN',
  14331.                     'text' => 'GN'
  14332.                 ]
  14333.             ),
  14334.             'assoc_list' => array(
  14335.                 [
  14336.                     'id' => 1,
  14337.                     'value' => 1,
  14338.                     'text' => 'GN'
  14339.                 ]
  14340.             ),
  14341.             'INVLIST' => $INVLIST,
  14342.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  14343.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  14344.             'userBranchIdList' => $userBranchIdList,
  14345.             'userBranchId' => $userBranchId,
  14346. //            'headList' => Accounts::HeadList($em),
  14347.         );
  14348.         //json
  14349.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  14350.         {
  14351.             $dataArray['success'] = true;
  14352.             return new JsonResponse(
  14353.                 $dataArray
  14354.             );
  14355.         }
  14356.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  14357.             $dataArray
  14358.         );
  14359.     }
  14360. }