src/ApplicationBundle/Controller/InventoryController.php line 15299

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Controller;
  3. use ApplicationBundle\Constants\AccountsConstant;
  4. use ApplicationBundle\Constants\GeneralConstant;
  5. use ApplicationBundle\Constants\HumanResourceConstant;
  6. use ApplicationBundle\Constants\InventoryConstant;
  7. use ApplicationBundle\Constants\LabelConstant;
  8. use ApplicationBundle\Entity\BrandCompany;
  9. use ApplicationBundle\Modules\Authentication\Constants\UserConstants; use ApplicationBundle\Modules\Api\Constants\ApiConstants;
  10. use ApplicationBundle\Controller\GenericController;
  11. use ApplicationBundle\Entity\Carton;
  12. use ApplicationBundle\Entity\InvItemInOut;
  13. use ApplicationBundle\Entity\StockReceivedNote;
  14. use ApplicationBundle\Entity\ProductByCode;
  15. use ApplicationBundle\Entity\StockReceivedNoteItem;
  16. use ApplicationBundle\Entity\ConsumptionType;
  17. use ApplicationBundle\Entity\LabelFormat;
  18. use ApplicationBundle\Entity\UnitType;
  19. use ApplicationBundle\Entity\SpecType;
  20. use ApplicationBundle\Entity\EmployeeAttendance;
  21. use ApplicationBundle\Entity\EmployeeAttendanceLog;
  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 ApplicationBundle\Entity\InvProducts;
  41. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  42. use Symfony\Component\HttpFoundation\JsonResponse;
  43. use Symfony\Component\HttpFoundation\Request;
  44. use Symfony\Component\HttpFoundation\Response;
  45. use Symfony\Component\Routing\Generator\UrlGenerator;
  46. class InventoryController extends GenericController implements SessionCheckInterface
  47. {
  48.     public function GetInitialDataForProductSelectVendorAppAction(Request $request)
  49.     {
  50.         $em $this->getDoctrine()->getManager();
  51.         $em_goc $this->getDoctrine()->getManager('company_group');
  52.         $session $request->getSession();
  53.         $companyId $this->getLoggedUserCompanyId($request);
  54.         $userRestrictions = [];
  55.         $selectiveDocumentsFlag 0;
  56.         $allowedLoginIds = [];
  57. //        $salesPersonList = Client::SalesPersonList($this->getDoctrine()->getManager());
  58. //
  59. //        $clientList = SalesOrderM::GetClientList($em, [], $companyId);
  60.         $userType $session->get(UserConstants::USER_TYPE);
  61.         $userId $session->get(UserConstants::USER_ID);
  62.         $productListArray = [];
  63.         $subCategoryListArray = [];
  64.         $categoryListArray = [];
  65.         $igListArray = [];
  66.         $unitListArray = [];
  67.         $skipProductList $request->request->has('skipProductList') ? $request->request->get('skipProductList') : 0;
  68.         $productList = ($skipProductList == 1) ? [] : Inventory::ProductList($em$companyId);
  69.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  70.         $categoryList Inventory::ProductCategoryList($em$companyId);
  71.         $igList Inventory::ItemGroupList($em$companyId);
  72.         $unitList Inventory::UnitTypeList($em);
  73.         $brandList Inventory::GetBrandList($em$companyId);
  74.         $defaultSuffix 'lemon-o';
  75.         $pidsByCategory = [];
  76.         $pidsBySubCategory = [];
  77.         $pidsByIg = [];
  78.         $pidsByBrand = [];
  79.         foreach ($igList as $key => $product) {
  80.             if ($product['classSuffix'] == '') {
  81.                 $product['classSuffix'] = $defaultSuffix;
  82.                 $igList[$key]['classSuffix'] = $defaultSuffix;
  83.             }
  84.             $igListArray[] = $product;
  85.         }
  86.         foreach ($categoryList as $product) {
  87.             if ($product['classSuffix'] == '' && isset($igList[$product['igId']]))
  88.                 $product['classSuffix'] = $igList[$product['igId']]['classSuffix'];
  89.             $categoryListArray[] = $product;
  90.         }
  91.         foreach ($subCategoryList as $product) {
  92.             if ($product['classSuffix'] == '' && isset($igList[$product['igId']]))
  93.                 $product['classSuffix'] = $igList[$product['igId']]['classSuffix'];
  94.             $subCategoryListArray[] = $product;
  95.         }
  96.         foreach ($unitList as $product) {
  97.             $unitListArray[] = $product;
  98.         }
  99.         $brandListArray = [];
  100.         foreach ($brandList as $product) {
  101.             $brandListArray[] = $product;
  102.         }
  103.         foreach ($productList as $key => $product) {
  104. //            $productListArray[] = $product;
  105.             $product['igName'] = $igList[$product['igId']]['name'];
  106.             $product['categoryName'] = $categoryList[$product['categoryId']]['name'];
  107.             $product['subCategoryName'] = $subCategoryList[$product['subCategoryId']]['name'];
  108.             $product['brandName'] = $brandList[$product['brandCompany']]['name'];
  109.             $pidsByCategory[$product['categoryId']][] = $key;
  110.             $pidsBySubCategory[$product['subCategoryId']][] = $key;
  111.             $pidsIg[$product['igId']][] = $key;
  112.             $pidsByBrand[$product['brandCompany']][] = $key;
  113. //            $pidsBySubCategory=[];
  114. //            $pidsByIg=[];
  115.             $productListArray[] = $product;
  116.             $productList[$key] = $product;
  117.         }
  118.         $data = [
  119.             ''
  120.         ];
  121. //        if ($request->request->has('returnJson') || $request->query->has('returnJson'))
  122.         {
  123.             return new JsonResponse(
  124.                 array(
  125.                     'page_title' => ' ',
  126.                     'data' => $data,
  127.                     'productList' => $productList,
  128.                     'subCategoryList' => $subCategoryList,
  129.                     'categoryList' => $categoryList,
  130.                     'igList' => $igList,
  131.                     'unitList' => $unitList,
  132.                     'brandList' => $brandList,
  133.                     'productListArray' => $productListArray,
  134.                     'subCategoryListArray' => $subCategoryListArray,
  135.                     'categoryListArray' => $categoryListArray,
  136.                     'igListArray' => $igListArray,
  137.                     'unitListArray' => $unitListArray,
  138.                     'brandListArray' => $brandListArray,
  139.                     'pidsByCategory' => $pidsByCategory,
  140.                     'pidsBySubCategory' => $pidsBySubCategory,
  141.                     'pidsByBrand' => $pidsByBrand,
  142.                     'pidsByIg' => $pidsByIg,
  143.                     'success' => true
  144.                 )
  145.             );
  146.         }
  147.     }
  148.     public function RefreshTaskOnSessionAction(Request $request)
  149.     {
  150.         $session $request->getSession();
  151.         $em $this->getDoctrine()->getManager();
  152.         $currentPlanningItemId=0;
  153.         $currentTaskId=0;
  154.         $taskActualStartTs=0;
  155.         $currentTask $em->getRepository('ApplicationBundle\\Entity\\TaskLog')
  156.             ->findOneBy(
  157.                 array(
  158.                     'userId' => $session->get(UserConstants::USER_ID),
  159.                     'workingStatus' => 1
  160.                 )
  161.             );
  162.         if ($currentTask) {
  163.             $currentTaskId $currentTask->getId();
  164.             $currentPlanningItemId $currentTask->getPlanningItemId();
  165.             $taskActualStartTs $currentTask->getActualStartTs();
  166.         }
  167.         $session->set(UserConstants::USER_CURRENT_TASK_ID,$currentTaskId);
  168.         $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID,$currentPlanningItemId);
  169.         return new JsonResponse(
  170.             array(
  171.                 'currentPlanningItemId'=>$currentPlanningItemId,
  172.                 'currentTaskId'=>$currentTaskId,
  173.                 'taskActualStartTs'=>$taskActualStartTs,
  174.             )
  175.         );
  176.     }
  177.     public function GetRefreshedItemAction(Request $request$type 0)
  178.     {
  179.         $em $this->getDoctrine()->getManager();
  180.         $companyId $this->getLoggedUserCompanyId($request);
  181.         $productListArray = [];
  182.         $subCategoryListArray = [];
  183.         $categoryListArray = [];
  184.         $igListArray = [];
  185.         $unitListArray = [];
  186.         $skipProductList $request->request->has('skipProductList') ? $request->request->get('skipProductList') : 0;
  187.         $productList = ($skipProductList == 1) ? [] : Inventory::ProductList($em$companyId$type);
  188.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  189.         $categoryList Inventory::ProductCategoryList($em$companyId);
  190.         $igList Inventory::ItemGroupList($em$companyId);
  191.         $unitList Inventory::UnitTypeList($em);
  192.         $brandList Inventory::GetBrandList($em$companyId);
  193.         foreach ($productList as $product) {
  194.             $productListArray[] = $product;
  195.         }
  196.         foreach ($categoryList as $product) {
  197.             $categoryListArray[] = $product;
  198.         }
  199.         foreach ($subCategoryList as $product) {
  200.             $subCategoryListArray[] = $product;
  201.         }
  202.         foreach ($igList as $product) {
  203.             $igListArray[] = $product;
  204.         }
  205.         foreach ($unitList as $product) {
  206.             $unitListArray[] = $product;
  207.         }
  208.         $brandListArray = [];
  209.         foreach ($brandList as $product) {
  210.             $brandListArray[] = $product;
  211.         }
  212.         $qry $em->getRepository("ApplicationBundle\\Entity\\AccService")->findBy(array(
  213.             "status" => GeneralConstant::ACTIVE,
  214.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  215. //            'type'=>1//trade items
  216.         ));
  217.         $sl = [];
  218.         $sl_array = [];
  219.         foreach ($qry as $product) {
  220.             $sl[$product->getServiceId()] = array(
  221.                 'text' => $product->getServiceName(),
  222.                 'value' => $product->getServiceId(),
  223.                 'name' => $product->getServiceName(),
  224.                 'id' => $product->getServiceId(),
  225.             );
  226.             $sl_array[] = array(
  227.                 'text' => $product->getServiceName(),
  228.                 'value' => $product->getServiceId(),
  229.                 'name' => $product->getServiceName(),
  230.                 'id' => $product->getServiceId(),
  231.             );
  232.         }
  233.         $hl Accounts::HeadList($em);
  234.         $hl_array Accounts::getParentLedgerHeads($em"""", [], 1$this->getLoggedUserCompanyId($request));
  235.         return new JsonResponse(
  236.             array(
  237. //                'page_title'=>'BOM',
  238. //                'clients'=>SalesOrderM::GetClientList($em),
  239. //                'clients_by_ac_head'=>SalesOrderM::GetClientListByAcHead($em),
  240.                 'productList' => $productList,
  241.                 'subCategoryList' => $subCategoryList,
  242.                 'categoryList' => $categoryList,
  243.                 'igList' => $igList,
  244.                 'unitList' => $unitList,
  245.                 'brandList' => $brandList,
  246.                 'productListArray' => $productListArray,
  247.                 'subCategoryListArray' => $subCategoryListArray,
  248.                 'categoryListArray' => $categoryListArray,
  249.                 'igListArray' => $igListArray,
  250.                 'unitListArray' => $unitListArray,
  251.                 'brandListArray' => $brandListArray,
  252.                 "success" => true,
  253.                 'users' => Users::getUserListById($em),
  254.                 'stages' => ProjectConstant::$projectStages,
  255.                 'sl' => $sl,
  256.                 'hl' => $hl,
  257.                 'hl_array' => $hl_array,
  258.                 'sl_array' => $sl_array,
  259. //                'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
  260.             )
  261.         );
  262.     }
  263.     public function GetProductListForMisAction(Request $request)
  264.     {
  265.         $em $this->getDoctrine()->getManager();
  266.         $productIds $request->query->get('productId');
  267.         $fdmList = [];
  268.         $find_array = array('id' => $productIds);
  269.         if ($request->query->get('fdmList')) {
  270.             $find_array = array();
  271.             $fdmList $productIds $request->query->get('fdmList');
  272.         }
  273. //            $find_array=array('id' =>  $productIds);
  274.         $products $this->getDoctrine()
  275.             ->getRepository('ApplicationBundle\\Entity\\InvProducts')
  276.             ->findBy(
  277.                 $find_array
  278.             );
  279.         $productList = [];
  280.         $productListForShow = [];
  281.         foreach ($products as $entry) {
  282.             $productList[$entry->getId()] = array(
  283.                 'id' => $entry->getId(),
  284.                 'name' => $entry->getName(),
  285.                 'fdm' => $entry->getProductFdm(),
  286.             );
  287.         }
  288.         $products_in_stock $this->getDoctrine()
  289.             ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  290.             ->findBy(
  291.                 $find_array
  292.             );
  293.         $warehouseList Inventory::WarehouseList($em);
  294.         if (!empty($fdmList)) {
  295.             foreach ($products_in_stock as $dt) {
  296. //            if()
  297.                 $matched_a_product 0;
  298.                 foreach ($fdmList as $fdm) {
  299.                     $matchFdm Inventory::MatchFdm($fdm$productList[$dt->getProductId()]['fdm']);
  300.                     if ($matchFdm['hasMatched'] == 1) {
  301.                         if ($matchFdm['isIdentical'] == || $matchFdm['FirstBelongsToSecond'] == 1) {
  302.                             $matched_a_product 1;
  303.                             if (isset($productListForShow[$dt->getProductId()])) {
  304.                             } else {
  305.                                 $productListForShow[$dt->getProductId()] = array(
  306.                                     'id' => $productList[$dt->getProductId()]['id'],
  307.                                     'name' => $productList[$dt->getProductId()]['name'],
  308.                                     'fdm' => $productList[$dt->getProductId()]['fdm'],
  309.                                 );
  310.                             }
  311.                             if (isset($productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  312.                                 $productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  313.                             else {
  314.                                 $productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  315.                             }
  316.                             break;
  317.                         }
  318.                     }
  319.                 }
  320.                 if ($matched_a_product == 0) {
  321.                     continue;
  322.                 }
  323.                 if (isset($productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  324.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  325.                 else
  326.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  327.             }
  328.         } else {
  329.             foreach ($products_in_stock as $dt) {
  330. //            if()
  331.                 if (isset($productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  332.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  333.                 else
  334.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  335.             }
  336.             $productListForShow $productList;
  337.         }
  338.         $engine $this->container->get('twig');
  339. //        $SD=Supplier::GetSupplierDetailsForMis($em,$supplier_id);
  340.         if ($productList) {
  341.             $Content $engine->render('@Inventory/pages/report/selected_item_stock.html.twig', array("productList" => $productListForShow'warehouseList' => $warehouseList));
  342.             return new JsonResponse(array("success" => true"content" => $Content'productListForShow' => $productListForShow));
  343.         }
  344.         return new JsonResponse(array("success" => false));
  345.     }
  346.     public function ProductListAction(Request $request)
  347.     {
  348.         $em $this->getDoctrine()->getManager();
  349.         $companyId $this->getLoggedUserCompanyId($request);
  350.         $listData Inventory::GetProductListForProductListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  351.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  352.             if ($request->query->has('dataTableQry')) {
  353.                 return new JsonResponse(
  354.                     $listData
  355.                 );
  356.             }
  357.         }
  358.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  359.             'name' => 'warehouse_action_1'//for now for stock of goods
  360.         ));
  361.         return $this->render('@Inventory/pages/views/product_list.html.twig',
  362.             array(
  363.                 'page_title' => 'Product List',
  364.                 'inv_head' => $inv_head $inv_head->getData() : '',
  365. //                'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  366.                 'products' => [],
  367.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  368.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  369.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  370.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  371.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  372. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  373.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  374.             )
  375.         );
  376.     }
  377.     public function SalesVsDeliveryListAction(Request $request)
  378.     {
  379.         $em $this->getDoctrine()->getManager();
  380.         $session $request->getSession();
  381.         $userType $session->get(UserConstants::USER_TYPE);
  382.         $userId $session->get(UserConstants::USER_ID);
  383.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  384.             'approved' => GeneralConstant::APPROVED,
  385. //            'stage' => GeneralConstant::STAGE_PENDING
  386.         );
  387.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  388.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  389.         }
  390. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  391. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  392. //            $selectiveDocumentsFlag=1; //by default will show only selective
  393. //            if(isset($userRestrictions['canSeeAllSo'])) {
  394. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  395. //                    $selectiveDocumentsFlag = 0;
  396. //                }
  397. //            }
  398. //
  399. //            if($selectiveDocumentsFlag==1)
  400. //            {
  401. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  402. //            }
  403. //        }
  404.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  405.             'name' => 'warehouse_action_1'//for now for stock of goods
  406.         ));
  407.         if ($request->query->has('queryDate')) {
  408.             $date = new \DateTime($request->query->get('queryDate'));
  409.         } else {
  410.             $today = new \DateTime();
  411.             $todayStr $today->format('Y-m-d');
  412.             $date = new \DateTime($todayStr);
  413.         }
  414.         $orderQryArray['salesOrderDate'] = $date;
  415.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findBy($orderQryArray);
  416.         $so_ids = [];
  417.         $so_data = [];
  418.         $so_item_ids = [];
  419.         $so_item_data = [];
  420.         foreach ($salesOrders as $salesOrder) {
  421.             if ($salesOrder->getSalesOrderDate() > $date)
  422.                 continue;
  423.             $so_ids[] = $salesOrder->getSalesOrderId();
  424.             $so_data[$salesOrder->getSalesOrderId()] = array(
  425.                 "id" => $salesOrder->getSalesOrderId(),
  426.                 "documentHash" => $salesOrder->getDocumentHash(),
  427.                 "clientId" => $salesOrder->getClientId(),
  428.             );
  429.         }
  430.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findBy(array(
  431.             'salesOrderId' => $so_ids,
  432.         ));
  433.         foreach ($salesOrderItems as $salesOrderItem) {
  434.             $so_item_ids[] = $salesOrderItem->getId();
  435.             $so_item_data[$salesOrderItem->getId()] = array(
  436.                 "id" => $salesOrderItem->getId(),
  437.                 "productId" => $salesOrderItem->getProductId(),
  438.                 "productName" => $salesOrderItem->getProductNameFdm(),
  439.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  440.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  441.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  442. //                "documentHash"=>$salesOrder->getDocumentHash(),
  443.                 "qty" => $salesOrderItem->getQty(),
  444.                 "transitQty" => $salesOrderItem->getTransitQty(),
  445.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  446.             );
  447.         }
  448.         return $this->render('@Inventory/pages/views/sales_vs_delivery_status.html.twig',
  449.             array(
  450.                 'page_title' => 'Order Vs. Disperse',
  451.                 'inv_head' => $inv_head $inv_head->getData() : '',
  452.                 'so_data' => $so_data,
  453.                 'queryDate' => $date,
  454.                 'so_item_data' => $so_item_data,
  455.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  456.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  457.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  458.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  459.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  460.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  461.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  462. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  463.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  464.             )
  465.         );
  466.     }
  467.     public function DeliveryPendingOrderListAction(Request $request)
  468.     {
  469.         $em $this->getDoctrine()->getManager();
  470.         $session $request->getSession();
  471.         $userType $session->get(UserConstants::USER_TYPE);
  472.         $userId $session->get(UserConstants::USER_ID);
  473.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  474.             'approved' => GeneralConstant::APPROVED,
  475.             'stage' => GeneralConstant::STAGE_PENDING
  476.         );
  477.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  478.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  479.         }
  480. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  481. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  482. //            $selectiveDocumentsFlag=1; //by default will show only selective
  483. //            if(isset($userRestrictions['canSeeAllSo'])) {
  484. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  485. //                    $selectiveDocumentsFlag = 0;
  486. //                }
  487. //            }
  488. //
  489. //            if($selectiveDocumentsFlag==1)
  490. //            {
  491. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  492. //            }
  493. //        }
  494.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  495.             'name' => 'warehouse_action_1'//for now for stock of goods
  496.         ));
  497.         if ($request->query->has('queryDate')) {
  498.             $date = new \DateTime($request->query->get('queryDate'));
  499.         } else {
  500.             $today = new \DateTime();
  501.             $todayStr $today->format('Y-m-d');
  502.             $date = new \DateTime($todayStr);
  503.         }
  504. //        $orderQryArray['salesOrderDate'] = $date;
  505.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findBy($orderQryArray);
  506.         $so_ids = [];
  507.         $so_data = [];
  508.         $so_item_ids = [];
  509.         $so_item_data = [];
  510.         foreach ($salesOrders as $salesOrder) {
  511.             if ($salesOrder->getSalesOrderDate() > $date)
  512.                 continue;
  513.             $so_ids[] = $salesOrder->getSalesOrderId();
  514.             $so_data[$salesOrder->getSalesOrderId()] = array(
  515.                 "id" => $salesOrder->getSalesOrderId(),
  516.                 "documentHash" => $salesOrder->getDocumentHash(),
  517.                 "clientId" => $salesOrder->getClientId(),
  518.             );
  519.         }
  520.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findBy(array(
  521.             'salesOrderId' => $so_ids,
  522.         ));
  523.         foreach ($salesOrderItems as $salesOrderItem) {
  524.             $so_item_ids[] = $salesOrderItem->getId();
  525.             $so_item_data[$salesOrderItem->getId()] = array(
  526.                 "id" => $salesOrderItem->getId(),
  527.                 "productId" => $salesOrderItem->getProductId(),
  528.                 "productName" => $salesOrderItem->getProductNameFdm(),
  529.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  530.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  531.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  532. //                "documentHash"=>$salesOrder->getDocumentHash(),
  533.                 "qty" => $salesOrderItem->getQty(),
  534.                 "transitQty" => $salesOrderItem->getTransitQty(),
  535.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  536.             );
  537.         }
  538.         return $this->render('@Inventory/pages/views/delivery_pending_order_list.html.twig',
  539.             array(
  540.                 'page_title' => 'Pending Delivery',
  541.                 'inv_head' => $inv_head $inv_head->getData() : '',
  542.                 'so_data' => $so_data,
  543.                 'queryDate' => $date,
  544.                 'so_item_data' => $so_item_data,
  545.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  546.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  547.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  548.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  549.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  550.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  551.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  552. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  553.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  554.             )
  555.         );
  556.     }
  557.     public function ItemGroupAction(Request $request$id 0)
  558.     {
  559.         $ex_id 0;
  560.         $det = [];
  561.         $em $this->getDoctrine()->getManager();
  562.         $companyId $this->getLoggedUserCompanyId($request);
  563.         $group_type 1;//item
  564.         $route $request->get('_route');
  565.         if ($route == 'service_group')
  566.             $group_type 2;//service
  567.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  568.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  569.         if ($request->isMethod('POST')) {
  570.             Inventory::CreateItemGroup($this->getDoctrine()->getManager(),
  571.                 $request->request->get('ex_id'),
  572.                 $this->getLoggedUserCompanyId($request),
  573.                 $request->request,
  574.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  575.         }
  576.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  577.             'name' => 'warehouse_action_1'//for now for stock of goods
  578.         ));
  579.         if ($id != 0) {
  580.             $ex_id $id;
  581.             $det $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(array(
  582.                 'id' => $id//for now for stock of goods
  583. //                    'opening_locked'=>0
  584.             ));
  585.         }
  586.         return $this->render('@Inventory/pages/input_forms/item_group.html.twig',
  587.             array(
  588.                 'page_title' => $group_type == "Item Groups" "Service Groups",
  589.                 'inv_head' => $inv_head $inv_head->getData() : '',
  590.                 'group_type' => $group_type,
  591.                 'igList' => Inventory::ItemGroupList($em$companyId$group_type),
  592.                 'warehouse_action_list' => $warehouse_action_list,
  593. //                'data'=>Inventory::ItemGroupFormRelatedData($this->getDoctrine()->getManager()),
  594.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  595.                 'ex_id' => $ex_id,
  596.                 'ex_det' => $det
  597.             )
  598.         );
  599.     }
  600.     public function addStartingOpeningInOutAction(Request $request$refreshed_opening 0)
  601.     {
  602.         //be very careful!!
  603.         $em $this->getDoctrine()->getManager();
  604. //        $last_refresh_date="";
  605.         //steps
  606.         //1. set all inventory to their opening position
  607.         $assign_list = array();
  608.         $data = array();
  609.         if ($refreshed_opening == 0) {
  610.             $new_cc $em
  611.                 ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  612.                 ->findOneBy(
  613.                     array(
  614.                         'name' => 'accounting_year_start',
  615.                     )
  616.                 );
  617.             $date_start = new \DateTime($new_cc->getData());
  618.             $date_start_str $date_start->format('Y-m-d');
  619.             $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  620. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  621.             $stmt $em->getConnection()->fetchAllAssociative($closingQuery);
  622.             
  623.             $iniClosing $stmt;
  624. //                $stmt = $em->getConnection()->executeStatement($transQuery);
  625. //                
  626. //                $iniTrans = $stmt;
  627.             $singleClosing_byProductId = array();
  628.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  629.             foreach ($iniClosing as $item) {
  630.                 if (!isset($singleClosing_byProductId[$item['product_id']])) {
  631.                     $singleClosing_byProductId[$item['product_id']] = array(
  632.                         'date' => $item['date'],
  633.                         'qtyAdd' => $item['qty_addition'],
  634.                         'qtySub' => '0',
  635.                         'valueAdd' => $item['addition'],
  636.                         'valueSub' => '0',
  637.                         'fromWarehouse' => 0,
  638.                         'toWarehouse' => $item['warehouse_id'],
  639.                         'fromWarehouseSub' => 0,
  640.                         'toWarehouseSub' => $item['action_tag_id'],
  641.                         'price' => ($item['addition'] / $item['qty_addition'])
  642.                     );
  643.                 }
  644.             }
  645.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  646. //                foreach ($iniTrans as $item) {
  647. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  648. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  649. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  650. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  651. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  652. //                    }
  653. //                }
  654.             foreach ($singleClosing_byProductId as $key => $item) {
  655.                 if (!isset($data[$key])) {
  656.                     $data[$key][] = $item;
  657.                 }
  658.             }
  659.             //now that we go the data we can empty the closing table
  660. //                $get_kids_sql ='UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  661. //    truncate `inv_closing_balance`;
  662. //    truncate `inventory_storage`;
  663. //    truncate `inv_item_transaction`;';
  664. //                $stmt = $em->getConnection()->executeStatement($get_kids_sql);
  665. //                
  666. //                
  667. //                $stmt;
  668.             $total_inv_value_in 0;
  669.             foreach ($data as $key => $item) {
  670.                 if (!empty($item)) {
  671.                     foreach ($item as $entry) {
  672.                         $transDate = new \DateTime($entry['date']);
  673.                         $new = new InvItemInOut();
  674.                         $new->setProductId($key);
  675.                         $new->setWarehouseId($entry['toWarehouse']);
  676.                         $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  677.                         $new->setActionTagId($entry['toWarehouseSub']);
  678.                         $new->setTransactionDate($transDate);
  679.                         $new->setQty($entry['qtyAdd']);
  680.                         $new->setPrice($entry['price']);
  681.                         $new->setAmount($entry['qtyAdd'] * $entry['price']);
  682.                         $new->setEntity(0);// opening =0
  683.                         $new->setEntityId(0);// opening =0
  684.                         $new->setDebitCreditHeadId(0);// opening =0
  685.                         $new->setVoucherIds(null);// opening =0
  686.                         $em->persist($new);
  687.                         $em->flush();
  688.                         $total_inv_value_in += $entry['qtyAdd'] * $entry['price'];
  689.                     }
  690.                 }
  691.             }
  692.             $refreshed_opening 1;
  693. //                $terminate=1;
  694. //                $last_refresh_date=$last_refresh_date_obj->format('Y-m-d');
  695.             return new JsonResponse(array(
  696.                 "success" => true,
  697.             ));
  698.             //now call the function which will add the 1st ever entry or opening entry
  699.         }
  700.         //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  701.         return new JsonResponse(array(
  702.             "success" => false,
  703.         ));
  704.     }
  705.     public function RefreshInventoryAction(Request $request$refreshed_opening 0)
  706.     {
  707.         //be very careful!!
  708.         $em $this->getDoctrine()->getManager();
  709.         $refreshed_opening 0;
  710.         $last_refresh_date "";
  711.         $last_refresh_date_obj "";
  712.         $terminate 0;
  713.         $companyId $this->getLoggedUserCompanyId($request);
  714.         $modifyAccTransaction $request->request->has('modify_acc_trans_flag') ? $request->request->get('modify_acc_trans_flag') : 0;
  715.         $modifyProductionPrice $request->request->has('modify_production_price') ? $request->request->get('modify_production_price') : 0;
  716. //        $last_refresh_date="";
  717.         if ($request->isMethod('POST')) {
  718.             //steps
  719.             //1. set all inventory to their opening position
  720.             $assign_list = array();
  721.             $data = array();
  722.             if ($request->request->has('inventory_refreshed'))
  723.                 $refreshed_opening $request->request->get('inventory_refreshed');
  724.             if ($request->request->has('last_refresh_date'))
  725.                 $last_refresh_date $request->request->get('last_refresh_date');
  726.             if ($refreshed_opening == 0) {
  727. //                System::log_it($this->container->getParameter('kernel.root_dir'), "",
  728. //                    'inventory_refresh_debug', 0); //last er 1 is append
  729.                 $new_cc $em
  730.                     ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  731.                     ->findOneBy(
  732.                         array(
  733.                             'name' => 'accounting_year_start',
  734.                         )
  735.                     );
  736.                 $date_start = new \DateTime($new_cc->getData());
  737.                 $date_start_str $date_start->format('Y-m-d');
  738.                 $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  739. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  740.                 $stmt $em->getConnection()->fetchAllAssociative($closingQuery);
  741.                 
  742.                 $iniClosing $stmt;
  743. //                $stmt = $em->getConnection()->executeStatement($transQuery);
  744. //                
  745. //                $iniTrans = $stmt;
  746.                 $singleClosing_byProductId = array();
  747.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  748.                 foreach ($iniClosing as $item) {
  749.                     if (!isset($singleClosing_byProductId[$item['product_id']])) {
  750.                         $singleClosing_byProductId[$item['product_id']] = array(
  751.                             'date' => $item['date'],
  752.                             'qtyAdd' => $item['qty_addition'],
  753.                             'qtySub' => '0',
  754.                             'valueAdd' => $item['addition'],
  755.                             'valueSub' => '0',
  756.                             'fromWarehouse' => 0,
  757.                             'toWarehouse' => $item['warehouse_id'],
  758.                             'fromWarehouseSub' => 0,
  759.                             'toWarehouseSub' => $item['action_tag_id'],
  760.                             'price' => $item['qty_addition'] != ? ($item['addition'] / $item['qty_addition']) : $item['addition']
  761.                         );
  762.                     }
  763.                 }
  764.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  765. //                foreach ($iniTrans as $item) {
  766. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  767. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  768. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  769. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  770. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  771. //                    }
  772. //                }
  773.                 foreach ($singleClosing_byProductId as $key => $item) {
  774.                     if (!isset($data[$key])) {
  775.                         $data[$key][] = $item;
  776.                     }
  777.                 }
  778.                 //new one
  779.                 //chekc if ultra opening stock received note exists if not create it
  780.                 $mo $em
  781.                     ->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')
  782.                     ->findOneBy(
  783.                         array(
  784.                             'documentHash' => '_MASTER_OPENING_',
  785.                             'typeHash' => 'SR',
  786.                             'prefixHash' => 4,
  787.                             'assocHash' => '_MASTER_OPENING_',
  788.                             'numberHash' => 1,
  789.                         )
  790.                     );
  791.                 if (!$mo) {
  792.                     //doensot exist to add :)
  793. //                    $products = $post_data->get('products');
  794. //                    $qty = $post_data->get('qty');
  795. //                    $note = $post_data->get('note');
  796.                     $new = new StockReceivedNote();
  797.                     $new->setStockReceivedNoteDate(new \DateTime($date_start_str));
  798.                     $new->setCompanyId($companyId);
  799.                     $new->setDocumentHash('_MASTER_OPENING_');
  800.                     $new->setTypeHash('SR');
  801.                     $new->setPrefixHash(4);
  802.                     $new->setAssocHash('_MASTER_OPENING_');
  803.                     $new->setNumberHash(1);
  804.                     $new->setCreditHeadId(0);
  805.                     $new->setStockTransferId(0);
  806.                     $new->setSalesOrderId(0);
  807.                     $new->setType(4);
  808.                     $new->setStatus(GeneralConstant::ACTIVE);
  809.                     $new->setWarehouseId(0);
  810.                     $new->setNote('');
  811.                     $new->setAutoCreated(1);
  812.                     $new->setApproved(GeneralConstant::APPROVED);
  813. //        $new->setIndentTagged(0);
  814.                     $new->setStage(GeneralConstant::STAGE_COMPLETE);
  815.                     $new->setCreatedLoginId(0);
  816.                     $new->setEditedLoginId(0);
  817.                     $em->persist($new);
  818.                     $em->flush();
  819.                     $SRID $new->getStockReceivedNoteId();
  820.                     $last_refresh_date_obj $new->getStockReceivedNoteDate();
  821.                     //now add items to details
  822.                     foreach ($data as $key => $item) {
  823.                         if (!empty($item)) {
  824.                             foreach ($item as $entry) {
  825.                                 $transDate = new \DateTime($entry['date']);
  826.                                 if ($last_refresh_date_obj == '') {
  827.                                     $last_refresh_date_obj $transDate;
  828.                                 } else if ($transDate $last_refresh_date_obj) {
  829.                                     $last_refresh_date_obj $transDate;
  830.                                 }
  831.                                 $new = new StockReceivedNoteItem();
  832.                                 $new->setStockReceivedNoteId($SRID);
  833.                                 $new->setStockTransferItemId(0);
  834.                                 $salesCodeRange = [];
  835.                                 $salesCodeRangeStr '';
  836.                                 $new->setSalesCodeRange("[" $salesCodeRangeStr "]");
  837.                                 $new->setQty($entry['qtyAdd']);
  838.                                 $new->setPrice($entry['price']);
  839.                                 $new->setBalance($entry['qtyAdd']);
  840.                                 $new->setProductId($key);
  841.                                 $new->setWarrantyMon(0);
  842.                                 $new->setWarehouseId($entry['toWarehouse']);
  843.                                 $new->setWarehouseActionId($entry['toWarehouseSub']);
  844.                                 $em->persist($new);
  845.                                 $em->flush();
  846.                             }
  847.                         }
  848.                     }
  849. //                    for ($i = 0; $i < count($products); $i++) {
  850. //
  851. //
  852. //                        $srItem = self::CreateNewStockReceivedNoteItem($em, $post_data, $i, $new->getStockReceivedNoteId(), $LoginID);
  853. //                    }
  854.                 }
  855.                 if ($mo)
  856.                     $last_refresh_date_obj $mo->getStockReceivedNoteDate();
  857.                 $last_refresh_date_obj->modify('-1 day');///new so that it willstart form this day on next call
  858.                 //new ends
  859.                 //now that we go the data we can empty the closing table
  860.                 $get_kids_sql "UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  861. UPDATE `purchase_order` SET expense_amount=0, expense_pending_balance_amount=0, grn_tag_pending_expense_invoice_ids='[]' WHERE 1;
  862.     truncate `inv_closing_balance`;
  863.     truncate `inventory_storage`;
  864.     truncate `inv_item_transaction`;";
  865.                 $stmt $em->getConnection()->executeStatement($get_kids_sql);
  866.                 
  867.                 
  868. //                $stmt;
  869. //                foreach ($data as $key => $item) {
  870. //                    if (!empty($item)) {
  871. //                        foreach ($item as $entry) {
  872. //                            $transDate = new \DateTime($entry['date']);
  873. //                            Inventory::addItemToInventoryCompact($em,
  874. //                                $key,
  875. //                                $entry['fromWarehouse'],
  876. //                                $entry['toWarehouse'],
  877. //                                $entry['fromWarehouseSub'],
  878. //                                $entry['toWarehouseSub'],
  879. //                                $transDate,
  880. //                                $entry['qtyAdd'],
  881. //                                $entry['qtySub'],
  882. //                                $entry['valueAdd'],
  883. //                                $entry['valueSub'],
  884. //                                $entry['price'],
  885. //                                $this->getLoggedUserCompanyId($request));
  886. //                            if ($last_refresh_date_obj == '') {
  887. //                                $last_refresh_date_obj = $transDate;
  888. //                            } else if ($transDate < $last_refresh_date_obj) {
  889. //                                $last_refresh_date_obj = $transDate;
  890. //                            }
  891. //                        }
  892. //                    }
  893. //                }
  894.                 $refreshed_opening 1;
  895. //                $terminate=1;
  896.                 if ($last_refresh_date_obj == "") {
  897.                     $last_refresh_date $date_start_str;
  898.                 } else {
  899.                     $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  900.                 }
  901.                 return new JsonResponse(array(
  902.                     "success" => true,
  903.                     "last_refresh_date" => $last_refresh_date,
  904.                     "inventory_refreshed" => $refreshed_opening
  905.                 ));
  906.                 //now call the function which will add the 1st ever entry or opening entry
  907.             }
  908.             //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  909.             if ($last_refresh_date != '')
  910.                 $last_refresh_date_obj = new \DateTime($last_refresh_date);
  911.             else {
  912.                 $new_cc $em
  913.                     ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  914.                     ->findOneBy(
  915.                         array(
  916.                             'name' => 'accounting_year_start',
  917.                         )
  918.                     );
  919.                 $last_refresh_date_obj = new \DateTime($new_cc->getData());
  920.                 $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  921.             }
  922.             $last_refresh_date_obj->modify('+1 day');
  923.             $today = new \DateTime();
  924.             if ($last_refresh_date_obj $today) {
  925.                 $terminate 1;
  926.             }
  927.             $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  928.             //ok now we got the date so get grn item on this date
  929.             //GRN
  930.             $query "SELECT grn_item.*, grn.grn_date, grn.document_hash from  grn_item
  931.               join grn on grn.grn_id=grn_item.grn_id
  932.             where grn.grn_date ='" $last_refresh_date " 00:00:00' and grn.approved=1";
  933.             $stmt $em->getConnection()->fetchAllAssociative($query);
  934.             
  935.             $queryData $stmt;
  936.             $grn_ids = [];
  937.             foreach ($queryData as $item) {
  938.                 $data[$item['product_id']][] = array(
  939.                     'date' => $last_refresh_date,
  940.                     'entity' => array_flip(GeneralConstant::$Entity_list)['Grn'],
  941.                     'entityId' => $item['grn_id'],
  942.                     'colorId' => $item['color_id'],
  943.                     'sizeId' => $item['size_id'],
  944.                     'entityDocHash' => $item['document_hash'],
  945.                     'qtyAdd' => $item['qty'],
  946.                     'qtySub' => 0,
  947.                     'valueAdd' => ($item['qty'] * $item['price_with_expense']),
  948.                     'valueSub' => 0,
  949.                     'price' => $item['price_with_expense'],
  950.                     'fromWarehouse' => 0,
  951.                     'toWarehouse' => $item['warehouse_id'],
  952.                     'fromWarehouseSub' => 0,
  953. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  954.                     'toWarehouseSub' => $item['warehouse_action_id']
  955.                 );
  956.                 if (!in_array($item['grn_id'], $grn_ids))
  957.                     $grn_ids[] = $item['grn_id'];
  958.             }
  959.             //now add grns
  960.             foreach ($data as $key => $item) {
  961.                 if (!empty($item)) {
  962.                     foreach ($item as $entry) {
  963.                         $transDate = new \DateTime($entry['date']);
  964.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  965.                             $key,
  966.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  967.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  968.                             $entry['fromWarehouse'],
  969.                             $entry['toWarehouse'],
  970.                             $entry['fromWarehouseSub'],
  971.                             $entry['toWarehouseSub'],
  972.                             $transDate,
  973.                             $entry['qtyAdd'],
  974.                             $entry['qtySub'],
  975.                             $entry['valueAdd'],
  976.                             $entry['valueSub'],
  977.                             $entry['price'],
  978.                             $this->getLoggedUserCompanyId($request),
  979.                             0,
  980.                             $entry['entity'],
  981.                             $entry['entityId'],
  982.                             $entry['entityDocHash'],
  983.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_SUPPLER
  984.                         );
  985.                         if ($last_refresh_date_obj == '') {
  986.                             $last_refresh_date_obj $transDate;
  987.                         } else if ($transDate $last_refresh_date_obj) {
  988.                             $last_refresh_date_obj $transDate;
  989.                         }
  990.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  991.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  992.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  993.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  994.                             "",
  995.                             'inventory_refresh_debug'1); //last er 1 is append
  996.                     }
  997.                 }
  998.             }
  999.             ///adding grn vouhcer mod here too incase it wasnot in the distributed IG for heads
  1000. //            $grn=$em->getRepository('ApplicationBundle\\Entity\\Grn')->findBy(array(
  1001. //                'grnId'=>$grn_ids,
  1002. //                'modifyVoucherFlag'=>1 //have to add this flag
  1003. //            ));
  1004.             foreach ($grn_ids as $grn_id) {
  1005.                 if ($modifyAccTransaction == 1)
  1006.                     Inventory::ModifyGrnTransactions($em$grn_id1);
  1007.                 else
  1008.                     Inventory::ModifyGrnTransactions($em$grn_id);
  1009.             }
  1010.             //adding voucher ends
  1011.             $inv_head_list_by_wa = [];
  1012.             $inv_head_list = [];
  1013.             $cogs_head 0;
  1014.             $cogs_head 0;
  1015.             $internal_proj 0;
  1016. //            if ($project) {
  1017. //                if ($project->getProjectType() == 2) {
  1018. //                    $cogs_head = $project->getInternalProjectAssetHeadId();
  1019. //                    $internal_proj = 1;
  1020. //                } else {
  1021. //                    $cogs_head_qry = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1022. //                        'name' => 'cogs'
  1023. //                    ));
  1024. //                    $cogs_head = $cogs_head_qry->getData();
  1025. //                }
  1026. //            } else {
  1027.             $cogs_head_qry $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1028.                 'name' => 'cogs'
  1029.             ));
  1030.             $cogs_head $cogs_head_qry->getData();
  1031. //            }
  1032.             $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');
  1033.             foreach ($warehouse_action_list as $wa) {
  1034.                 $inv_head_data $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1035.                         'name' => 'warehouse_action_' $wa['id'])
  1036.                 );
  1037.                 if ($inv_head_data) {
  1038.                     $inv_head_list_by_wa[$wa['id']] = $inv_head_data->getData();
  1039.                     $inv_head_list[] = $inv_head_data->getData();
  1040.                 }
  1041.             }
  1042.             $data = [];
  1043.             //____________STOCK_RECEIVED___________________
  1044.             $docEntity "StockReceivedNote";
  1045.             $docEntityIdField "stockReceivedNoteId";
  1046.             $accTransactionDataByDocId = [];
  1047.             $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
  1048.               join stock_received_note on stock_received_note.stock_received_note_id=stock_received_note_item.stock_received_note_id
  1049.             where stock_received_note.stock_received_note_date ='" $last_refresh_date " 00:00:00' and stock_received_note.approved=1";
  1050.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1051.             
  1052.             $queryData $stmt;
  1053.             $grn_ids = [];
  1054.             foreach ($queryData as $item) {
  1055.                 $data[$item['product_id']][] = array(
  1056.                     'date' => $last_refresh_date,
  1057.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  1058.                     'entityId' => $item['stock_received_note_id'],
  1059.                     'colorId' => $item['color_id'],
  1060.                     'sizeId' => $item['size_id'],
  1061.                     'type' => $item['type'],
  1062.                     'entityDocHash' => $item['document_hash'],
  1063.                     'qtyAdd' => $item['qty'],
  1064.                     'qtySub' => 0,
  1065.                     'valueAdd' => ($item['qty'] * $item['price']),
  1066.                     'valueSub' => 0,
  1067.                     'price' => $item['price'],
  1068.                     'fromWarehouse' => 0,
  1069.                     'toWarehouse' => $item['warehouse_id'],
  1070.                     'fromWarehouseSub' => 0,
  1071. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1072.                     'toWarehouseSub' => $item['warehouse_action_id']
  1073.                 );
  1074. //                if (!in_array($item['grn_id'], $grn_ids))
  1075. //                    $grn_ids[] = $item['grn_id'];
  1076.             }
  1077.             foreach ($data as $key => $item) {
  1078.                 if (!empty($item)) {
  1079.                     foreach ($item as $entry) {
  1080.                         $transDate = new \DateTime($entry['date']);
  1081.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1082.                             $key,
  1083.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1084.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1085.                             $entry['fromWarehouse'],
  1086.                             $entry['toWarehouse'],
  1087.                             $entry['fromWarehouseSub'],
  1088.                             $entry['toWarehouseSub'],
  1089.                             $transDate,
  1090.                             $entry['qtyAdd'],
  1091.                             $entry['qtySub'],
  1092.                             $entry['valueAdd'],
  1093.                             $entry['valueSub'],
  1094.                             $entry['price'],
  1095.                             $this->getLoggedUserCompanyId($request),
  1096.                             0,
  1097.                             $entry['entity'],
  1098.                             $entry['entityId'],
  1099.                             $entry['entityDocHash'],
  1100.                             $entry['type'] == ?
  1101.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_OPENING :
  1102.                                 ($entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_STOCK_IN :
  1103.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT)
  1104.                         );
  1105.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1106.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1107.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1108.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1109.                             "",
  1110.                             'inventory_refresh_debug'1); //last er 1 is append
  1111.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1112.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1113.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  1114.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  1115.                         else
  1116.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  1117.                         if ($last_refresh_date_obj == '') {
  1118.                             $last_refresh_date_obj $transDate;
  1119.                         } else if ($transDate $last_refresh_date_obj) {
  1120.                             $last_refresh_date_obj $transDate;
  1121.                         }
  1122.                     }
  1123.                 }
  1124.             }
  1125.             if ($modifyAccTransaction == 1) {
  1126.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1127.                     $docHere $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  1128.                         $docEntityIdField => $docId,
  1129.                     ));;
  1130.                     if ($docHere) {
  1131.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1132.                         if ($curr_v_ids == null)
  1133.                             $curr_v_ids = [];
  1134.                         $skipVids = [];
  1135.                         $toChangeVid 0;
  1136.                         $voucher null;
  1137.                         foreach ($curr_v_ids as $vid) {
  1138.                             if (in_array($vid$skipVids))
  1139.                                 continue;
  1140.                             $skipVids[] = $vid//to prevent duplicate query
  1141.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  1142.                                 'transactionId' => $vid,
  1143.                             ));;
  1144.                             if ($voucher) {
  1145.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1146.                                     $toChangeVid $vid;
  1147.                                 } else {
  1148.                                     continue;
  1149.                                 }
  1150.                             }
  1151.                         }
  1152.                         if ($toChangeVid == 0) {
  1153.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1154.                                 $em,
  1155.                                 $docHere->getStockReceivedNoteDate()->format('Y-m-d'),
  1156.                                 0,
  1157.                                 AccountsConstant::VOUCHER_JOURNAL,
  1158.                                 'Journal For Stock Received Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  1159.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1160.                                 'JV',
  1161.                                 'GN',
  1162.                                 0,
  1163.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1164.                                 0,
  1165.                                 $docHere->getCreatedLoginId(),
  1166.                                 $docHere->getCompanyId(),
  1167.                                 '',
  1168.                                 0,
  1169.                                 1
  1170.                             );
  1171.                             $em->flush();
  1172.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  1173.                                 'transactionId' => $toChangeVid,
  1174.                             ));;
  1175.                         }
  1176.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  1177.                         $tot_inv_amount 0;
  1178.                         foreach ($transData as $k => $v) {
  1179.                             $tot_inv_amount += ($v);
  1180.                             Accounts::CreateNewTransactionDetails($em,
  1181.                                 '',
  1182.                                 $toChangeVid,
  1183.                                 Generic::CurrToInt($v),
  1184.                                 $k,
  1185.                                 'Inventory Inward For - ' $docHere->getDocumentHash(),
  1186.                                 AccountsConstant::DEBIT,
  1187.                                 0,
  1188.                                 [],
  1189.                                 [],
  1190.                                 $docHere->getCreatedLoginId()
  1191.                             );
  1192.                         }
  1193.                         $stockReceivedType $docHere->getType();
  1194.                         $to_balance_head 0;
  1195.                         if (in_array($stockReceivedType, [23]))
  1196.                             $to_balance_head $docHere->getCreditHeadId();
  1197.                         else {
  1198.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1199.                                     'name' => 'inv_on_transit_head')
  1200.                             );
  1201.                             if ($inv_transit_head)
  1202.                                 $to_balance_head $inv_transit_head->getData();
  1203.                         }
  1204.                         Accounts::CreateNewTransactionDetails($em,
  1205.                             '',
  1206.                             $toChangeVid,
  1207.                             Generic::CurrToInt($tot_inv_amount),
  1208.                             $to_balance_head,
  1209.                             in_array($stockReceivedType, [23]) ? 'Balancing of Stock in Items for -' $docHere->getDocumentHash() : 'In Transit Items for -' $docHere->getDocumentHash(),
  1210.                             AccountsConstant::CREDIT,
  1211.                             0,
  1212.                             [],
  1213.                             [],
  1214.                             $docHere->getCreatedLoginId()
  1215.                         );
  1216.                         if ($voucher)
  1217.                             $voucher->setTransactionAmount($tot_inv_amount);
  1218.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1219.                         if ($curr_v_ids != null)
  1220.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1221.                         else
  1222.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1223.                         $em->flush();
  1224. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  1225.                     }
  1226.                 }
  1227.             }
  1228.             $data = [];
  1229.             $query "SELECT purchase_invoice.* from  purchase_invoice
  1230. where purchase_invoice.purchase_invoice_date ='" $last_refresh_date " 00:00:00' and purchase_invoice.approved=1
  1231.             ";
  1232.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1233.             
  1234.             $queryData $stmt;
  1235.             foreach ($queryData as $pi) {
  1236.                 $transDate = new \DateTime($pi['purchase_invoice_date']);
  1237.                 if ($last_refresh_date_obj == '') {
  1238.                     $last_refresh_date_obj $transDate;
  1239.                 } else if ($transDate $last_refresh_date_obj) {
  1240.                     $last_refresh_date_obj $transDate;
  1241.                 }
  1242.                 Accounts::CalibrateProductPriceWithPi($em$pi['purchase_invoice_id'], 1);
  1243.             }
  1244.             $data = [];
  1245.             $query "SELECT expense_invoice.* from  expense_invoice
  1246. where expense_invoice.expense_invoice_date ='" $last_refresh_date " 00:00:00' and expense_invoice.approved=1 and
  1247.             expense_invoice_type_id=1";
  1248.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1249.             
  1250.             $queryData $stmt;
  1251.             foreach ($queryData as $ei) {
  1252.                 $transDate = new \DateTime($ei['expense_invoice_date']);
  1253.                 if ($last_refresh_date_obj == '') {
  1254.                     $last_refresh_date_obj $transDate;
  1255.                 } else if ($transDate $last_refresh_date_obj) {
  1256.                     $last_refresh_date_obj $transDate;
  1257.                 }
  1258.                 $grn_ids json_decode($ei['grn_id_list'], true);
  1259.                 if ($grn_ids == null)
  1260.                     $grn_ids = [];
  1261. //                if (!empty($grn_ids)) {
  1262. //
  1263. //
  1264. //                        if ($ei->getExpenseInvocationStrategyOnGrn() != 2) {
  1265. //                            $grn = $em->getRepository('ApplicationBundle\\Entity\\Grn')->findBy(array(
  1266. //                                'purchaseOrderId' => $ei->getPurchaseOrderId()
  1267. //                            ));
  1268. //
  1269. //                        }
  1270. //                        else
  1271. //                        {
  1272. //                            $po = $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(array(
  1273. //                                'purchaseOrderId' => $ei['purchase_order_id']
  1274. //                            ));
  1275. //
  1276. //                            if ($po) {
  1277. //                                $po->setExpenseAmount($po->getExpenseAmount() + $ei['invoice_amount']);
  1278. //                            }
  1279. //                            continue; //grn expense will be there anyway
  1280. //                        }
  1281. //
  1282. //
  1283. //
  1284. //                }
  1285.                 Accounts::CalibrateProductPriceWithExpense($em$ei['expense_invoice_id']);
  1286. //                $po = $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(array(
  1287. //                    'purchaseOrderId' => $ei['purchase_order_id']
  1288. //                ));
  1289. //
  1290. //
  1291. //                //first get the total valuation
  1292. //                if ($po) {
  1293. //                    $total_product_value = 0;
  1294. //                    $total_pending_expense = 0;
  1295. //                    $po_item_data = $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(array(
  1296. ////                'productId' => $item->getProductId(),
  1297. //                        'purchaseOrderId' => $ei['purchase_order_id']
  1298. //                    ));
  1299. //
  1300. //
  1301. //                    foreach ($po_item_data as $it) {
  1302. ////                    $product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(array(
  1303. ////                        'id' => $item->getProductId()
  1304. ////                    ));
  1305. //
  1306. //                        $poqty = $it->getReceived();
  1307. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);
  1308. //                        $total_product_value += (1 * $po_price);
  1309. //
  1310. //
  1311. //                    }
  1312. //
  1313. //
  1314. //                    //now we know the total grn price value. lets get the fraction increase
  1315. //                    $total_pending_expense = $ei['invoice_amount'];
  1316. //                    if ($total_product_value != 0)
  1317. //                        $fraction_increase = ($total_pending_expense) / ($total_product_value);
  1318. //                    else
  1319. //                        $fraction_increase = 0;
  1320. //
  1321. //                    foreach ($po_item_data as $it) {
  1322. //                        $item = $it;
  1323. //                        $product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(array(
  1324. //                            'id' => $it->getProductId()
  1325. //                        ));
  1326. //                        if (!$product)
  1327. //                            continue;
  1328. //
  1329. ////                    $items_in_inventory=$em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(array(
  1330. ////                        'productId'=>$item->getProductId()
  1331. ////                    ));
  1332. //
  1333. //                        $poqty = $it->getReceived();
  1334. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);;
  1335. //
  1336. //                        $existing_qty = $product->getQty();;
  1337. //
  1338. //
  1339. //                        $increased_po_price = ($po_price * $fraction_increase);
  1340. //
  1341. //                        //now lets see homuch is the total price
  1342. //                        $new_purchase_price = $product->getPurchasePrice();
  1343. //
  1344. //                        if ($increased_po_price != 0) {
  1345. //                            $last_grn_item = $em->getRepository('ApplicationBundle\\Entity\\GrnItem')->findOneBy(array(
  1346. //                                'purchaseOrderItemId' => $item->getId()
  1347. //                            ));
  1348. //                            if ($last_grn_item) {
  1349. //
  1350. //                                $data[$last_grn_item->getProductId()][] = array(
  1351. //                                    'date' => $last_refresh_date,
  1352. //
  1353. //                                    'entity' => array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  1354. //                                    'entityId' => $ei['expense_invoice_id'],
  1355. //                                    'colorId' => $last_grn_item->getColorId(),
  1356. //                                    'sizeId' => $last_grn_item->getSizeId(),
  1357. //                                    'entityDocHash' => $ei['document_hash'],
  1358. //                                    'qtyAdd' => 0,
  1359. //                                    'qtySub' => 0,
  1360. //                                    'valueAdd' => $increased_po_price,
  1361. ////                                    'valueAdd' => $increased_po_price>=0?$increased_po_price:0,
  1362. ////                    'valueSub' => ($item['qty'] * $item['price']),
  1363. ////                                    'valueSub' => $increased_po_price<0?((-1)*$increased_po_price):0,
  1364. //                                    'valueSub' => 0,
  1365. //                                    'price' => '_UNSET_',
  1366. //                                    'fromWarehouse' => 0,
  1367. //                                    'toWarehouse' => $last_grn_item->getWarehouseId(),
  1368. //                                    'fromWarehouseSub' => 0,
  1369. ////                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1370. //                                    'toWarehouseSub' => $last_grn_item->getWarehouseActionId()
  1371. //                                );
  1372. //
  1373. ////                                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);
  1374. ////
  1375. ////                                $total_item_price = $increased_po_price + ($product->getPurchasePrice() * ($existing_qty));
  1376. ////                                if ($existing_qty != 0)
  1377. ////                                    $new_purchase_price = $total_item_price / $existing_qty;
  1378. //
  1379. //
  1380. //                                $total_pending_expense -= $increased_po_price;
  1381. //                            }
  1382. //                        }
  1383. //                    }
  1384. //
  1385. //
  1386. //
  1387. //
  1388. //
  1389. //
  1390. //                } else {
  1391. //                    continue;
  1392. //                }
  1393.             }
  1394.             $data = [];
  1395.             //____________STOCK_TRANSFER___________________
  1396.             $docEntity "StockTransfer";
  1397.             $docEntityIdField "stockTransferId";
  1398.             $accTransactionDataByDocId = [];
  1399.             $query "SELECT stock_transfer_item.*,  stock_transfer.stock_transfer_date, stock_transfer.document_hash, stock_transfer.transfer_action_type from  stock_transfer_item
  1400.               join stock_transfer on stock_transfer.stock_transfer_id=stock_transfer_item.stock_transfer_id
  1401.             where stock_transfer.stock_transfer_date ='" $last_refresh_date " 00:00:00' and stock_transfer.approved=1";
  1402.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1403.             
  1404.             $queryData $stmt;
  1405.             $grn_ids = [];
  1406.             foreach ($queryData as $item) {
  1407.                 $data[$item['product_id']][] = array(
  1408.                     'date' => $last_refresh_date,
  1409.                     'transfer_action_type' => $item['transfer_action_type'],
  1410.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  1411.                     'entityId' => $item['stock_transfer_id'],
  1412.                     'colorId' => $item['color_id'],
  1413.                     'sizeId' => $item['size_id'],
  1414.                     'entityDocHash' => $item['document_hash'],
  1415.                     'qtyAdd' => $item['transfer_action_type'] == $item['qty'] : 0,
  1416.                     'qtySub' => $item['qty'],
  1417.                     'valueAdd' => 0,
  1418. //                    'valueSub' => ($item['qty'] * $item['price']),
  1419.                     'valueSub' => '_AUTO_',
  1420.                     'price' => $item['price'],
  1421.                     'fromWarehouse' => $item['warehouse_id'],
  1422.                     'toWarehouse' => $item['transfer_action_type'] == $item['to_warehouse_id'] : 0,
  1423.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  1424. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1425.                     'toWarehouseSub' => $item['transfer_action_type'] == $item['to_warehouse_action_id'] : 0
  1426.                 );
  1427. //                if (!in_array($item['grn_id'], $grn_ids))
  1428. //                    $grn_ids[] = $item['grn_id'];
  1429.             }
  1430.             //now add grns
  1431.             foreach ($data as $key => $item) {
  1432.                 if (!empty($item)) {
  1433.                     foreach ($item as $entry) {
  1434.                         $transDate = new \DateTime($entry['date']);
  1435.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1436.                             $key,
  1437.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1438.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1439.                             $entry['fromWarehouse'],
  1440.                             $entry['toWarehouse'],
  1441.                             $entry['fromWarehouseSub'],
  1442.                             $entry['toWarehouseSub'],
  1443.                             $transDate,
  1444.                             $entry['qtyAdd'],
  1445.                             $entry['qtySub'],
  1446.                             $entry['valueAdd'],
  1447.                             $entry['valueSub'],
  1448.                             $entry['price'],
  1449.                             $this->getLoggedUserCompanyId($request),
  1450.                             0,
  1451.                             $entry['entity'],
  1452.                             $entry['entityId'],
  1453.                             $entry['entityDocHash'],
  1454.                             $entry['transfer_action_type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_INTER_WAREHOUSE GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT
  1455.                         );
  1456.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1457.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1458.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1459.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1460.                             "",
  1461.                             'inventory_refresh_debug'1); //last er 1 is append
  1462.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1463.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1464.                         if ($entry['transfer_action_type'] == 4) {
  1465.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  1466.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtySub'] * $modifiedData['slot_cost_price'];
  1467.                             else
  1468.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  1469.                         }
  1470.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  1471.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  1472.                         else
  1473.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  1474.                         if ($last_refresh_date_obj == '') {
  1475.                             $last_refresh_date_obj $transDate;
  1476.                         } else if ($transDate $last_refresh_date_obj) {
  1477.                             $last_refresh_date_obj $transDate;
  1478.                         }
  1479.                     }
  1480.                 }
  1481.             }
  1482.             if ($modifyAccTransaction == 1) {
  1483.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1484.                     $docHere $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  1485.                         $docEntityIdField => $docId,
  1486.                     ));;
  1487.                     if ($docHere) {
  1488.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1489.                         if ($curr_v_ids == null)
  1490.                             $curr_v_ids = [];
  1491.                         $skipVids = [];
  1492.                         $toChangeVid 0;
  1493.                         $voucher null;
  1494.                         foreach ($curr_v_ids as $vid) {
  1495.                             if (in_array($vid$skipVids))
  1496.                                 continue;
  1497.                             $skipVids[] = $vid//to prevent duplicate query
  1498.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  1499.                                 'transactionId' => $vid,
  1500.                             ));;
  1501.                             if ($voucher) {
  1502.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1503.                                     $toChangeVid $vid;
  1504.                                 } else {
  1505.                                     continue;
  1506.                                 }
  1507.                             }
  1508.                         }
  1509.                         if ($toChangeVid == 0) {
  1510.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1511.                                 $em,
  1512.                                 $docHere->getStockTransferDate()->format('Y-m-d'),
  1513.                                 0,
  1514.                                 AccountsConstant::VOUCHER_JOURNAL,
  1515.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  1516.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1517.                                 'JV',
  1518.                                 'GN',
  1519.                                 0,
  1520.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1521.                                 0,
  1522.                                 $docHere->getCreatedLoginId(),
  1523.                                 $docHere->getCompanyId(),
  1524.                                 '',
  1525.                                 0,
  1526.                                 1
  1527.                             );
  1528.                             $em->flush();
  1529.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  1530.                                 'transactionId' => $toChangeVid,
  1531.                             ));;
  1532.                         }
  1533.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  1534.                         $tot_inv_amount 0;
  1535.                         foreach ($transData as $k => $v) {
  1536.                             $tot_inv_amount += ($v);
  1537.                             Accounts::CreateNewTransactionDetails($em,
  1538.                                 '',
  1539.                                 $toChangeVid,
  1540.                                 Generic::CurrToInt($v),
  1541.                                 $k,
  1542.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  1543.                                 $v >= AccountsConstant::DEBIT AccountsConstant::CREDIT,
  1544.                                 0,
  1545.                                 [],
  1546.                                 [],
  1547.                                 $docHere->getCreatedLoginId()
  1548.                             );
  1549.                         }
  1550. //                        $stockReceivedType = $docHere->getType();
  1551.                         $to_balance_head 0;
  1552.                         if ($docHere->getTransferActionType() == 4) {
  1553.                         } else {
  1554.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1555.                                     'name' => 'inv_on_transit_head')
  1556.                             );
  1557.                             if ($inv_transit_head)
  1558.                                 $to_balance_head $inv_transit_head->getData();
  1559.                         }
  1560.                         if ($to_balance_head != 0) {
  1561.                             Accounts::CreateNewTransactionDetails($em,
  1562.                                 '',
  1563.                                 $toChangeVid,
  1564.                                 Generic::CurrToInt($tot_inv_amount),
  1565.                                 $to_balance_head,
  1566.                                 'In Transit Items for -' $docHere->getDocumentHash(),
  1567.                                 $tot_inv_amount >= AccountsConstant::CREDIT AccountsConstant::DEBIT,
  1568.                                 0,
  1569.                                 [],
  1570.                                 [],
  1571.                                 $docHere->getCreatedLoginId()
  1572.                             );
  1573.                         }
  1574.                         if ($voucher)
  1575.                             $voucher->setTransactionAmount($tot_inv_amount);
  1576.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1577.                         if ($curr_v_ids != null)
  1578.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1579.                         else
  1580.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1581.                         $em->flush();
  1582. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  1583.                     }
  1584.                 }
  1585.             }
  1586.             $data = [];
  1587.             //____________IRR___________________
  1588.             $docEntity "ItemReceivedAndReplacement";
  1589.             $docEntityIdField "itemReceivedAndReplacementId";
  1590.             $accTransactionDataByDocId = [];
  1591.             $query "SELECT irr_item.*,  item_received_replacement.irr_date, item_received_replacement.document_hash from  irr_item
  1592.               join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  1593.             where item_received_replacement.irr_date ='" $last_refresh_date " 00:00:00' and item_received_replacement.approved=1";
  1594.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1595.             
  1596.             $queryData $stmt;
  1597.             $irr_add_data = [];
  1598.             $irr_replace_data = [];
  1599.             $irr_dispose_data = [];
  1600.             foreach ($queryData as $item) {
  1601.                 $irr_add_data[$item['received_product_id']][] = array(
  1602.                     'date' => $last_refresh_date,
  1603.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1604.                     'entityId' => $item['irr_id'],
  1605.                     'colorId' => $item['received_product_color_id'],
  1606.                     'sizeId' => $item['received_product_color_id'],
  1607.                     'entityDocHash' => $item['document_hash'],
  1608.                     'qtyAdd' => $item['received_qty'],
  1609.                     'qtySub' => 0,
  1610.                     'valueAdd' => ($item['received_qty'] * $item['received_unit_purchase_price']),
  1611.                     'valueSub' => 0,
  1612.                     'price' => $item['received_unit_purchase_price'],
  1613.                     'fromWarehouse' => 0,
  1614.                     'toWarehouse' => $item['received_warehouse_id'],
  1615.                     'fromWarehouseSub' => 0,
  1616.                     'toWarehouseSub' => $item['received_warehouse_action_id']
  1617.                 );
  1618.                 $irr_replace_data[$item['replaced_product_id']][] = array(
  1619.                     'date' => $last_refresh_date,
  1620.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1621.                     'entityId' => $item['irr_id'],
  1622.                     'colorId' => $item['replaced_product_color_id'],
  1623.                     'sizeId' => $item['replaced_product_color_id'],
  1624.                     'entityDocHash' => $item['document_hash'],
  1625.                     'qtyAdd' => 0,
  1626.                     'qtySub' => $item['replaced_qty'],
  1627.                     'valueAdd' => 0,
  1628.                     'valueSub' => ($item['replaced_qty'] * $item['replaced_unit_purchase_price']),
  1629.                     'price' => $item['replaced_unit_purchase_price'],
  1630.                     'fromWarehouse' => $item['replaced_warehouse_id'],
  1631.                     'toWarehouse' => 0,
  1632.                     'fromWarehouseSub' => $item['replaced_warehouse_action_id'],
  1633.                     'toWarehouseSub' => 0
  1634.                 );
  1635.                 $irr_dispose_data[$item['received_product_id']][] = array(
  1636.                     'date' => $last_refresh_date,
  1637.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1638.                     'entityId' => $item['irr_id'],
  1639.                     'colorId' => $item['received_product_color_id'],
  1640.                     'sizeId' => $item['received_product_size_id'],
  1641.                     'entityDocHash' => $item['document_hash'],
  1642.                     'qtyAdd' => 0,
  1643.                     'qtySub' => $item['dispose_qty'],
  1644.                     'valueAdd' => 0,
  1645.                     'valueSub' => ($item['dispose_qty'] * $item['received_unit_purchase_price']),
  1646.                     'price' => $item['received_unit_purchase_price'],
  1647.                     'fromWarehouse' => $item['received_warehouse_id'],
  1648.                     'toWarehouse' => 0,
  1649.                     'fromWarehouseSub' => $item['received_warehouse_id'],
  1650.                     'toWarehouseSub' => 0
  1651.                 );
  1652.             }
  1653.             //now add irrs
  1654.             foreach ($irr_add_data as $key => $item) {
  1655.                 if (!empty($item)) {
  1656.                     foreach ($item as $entry) {
  1657.                         $transDate = new \DateTime($entry['date']);
  1658.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1659.                             $key,
  1660.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1661.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1662.                             $entry['fromWarehouse'],
  1663.                             $entry['toWarehouse'],
  1664.                             $entry['fromWarehouseSub'],
  1665.                             $entry['toWarehouseSub'],
  1666.                             $transDate,
  1667.                             $entry['qtyAdd'],
  1668.                             $entry['qtySub'],
  1669.                             $entry['valueAdd'],
  1670.                             $entry['valueSub'],
  1671.                             $entry['price'],
  1672.                             $this->getLoggedUserCompanyId($request),
  1673.                             0,
  1674.                             $entry['entity'],
  1675.                             $entry['entityId'],
  1676.                             $entry['entityDocHash'],
  1677.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  1678.                         );
  1679.                         if ($modifiedData)
  1680.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1681.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1682.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1683.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1684.                                 "",
  1685.                                 'inventory_refresh_debug'1); //last er 1 is append
  1686.                         if ($last_refresh_date_obj == '') {
  1687.                             $last_refresh_date_obj $transDate;
  1688.                         } else if ($transDate $last_refresh_date_obj) {
  1689.                             $last_refresh_date_obj $transDate;
  1690.                         }
  1691.                     }
  1692.                 }
  1693.             }
  1694.             foreach ($irr_replace_data as $key => $item) {
  1695.                 if (!empty($item)) {
  1696.                     foreach ($item as $entry) {
  1697.                         $transDate = new \DateTime($entry['date']);
  1698.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1699.                             $key,
  1700.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1701.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1702.                             $entry['fromWarehouse'],
  1703.                             $entry['toWarehouse'],
  1704.                             $entry['fromWarehouseSub'],
  1705.                             $entry['toWarehouseSub'],
  1706.                             $transDate,
  1707.                             $entry['qtyAdd'],
  1708.                             $entry['qtySub'],
  1709.                             $entry['valueAdd'],
  1710.                             $entry['valueSub'],
  1711.                             $entry['price'],
  1712.                             $this->getLoggedUserCompanyId($request),
  1713.                             0,
  1714.                             $entry['entity'],
  1715.                             $entry['entityId'],
  1716.                             $entry['entityDocHash']);
  1717.                         if ($modifiedData)
  1718.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1719.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1720.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1721.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1722.                                 "",
  1723.                                 'inventory_refresh_debug'1); //last er 1 is append
  1724.                         if ($last_refresh_date_obj == '') {
  1725.                             $last_refresh_date_obj $transDate;
  1726.                         } else if ($transDate $last_refresh_date_obj) {
  1727.                             $last_refresh_date_obj $transDate;
  1728.                         }
  1729.                     }
  1730.                 }
  1731.             }
  1732.             foreach ($irr_dispose_data as $key => $item) {
  1733.                 if (!empty($item)) {
  1734.                     foreach ($item as $entry) {
  1735.                         $transDate = new \DateTime($entry['date']);
  1736.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1737.                             $key,
  1738.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1739.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1740.                             $entry['fromWarehouse'],
  1741.                             $entry['toWarehouse'],
  1742.                             $entry['fromWarehouseSub'],
  1743.                             $entry['toWarehouseSub'],
  1744.                             $transDate,
  1745.                             $entry['qtyAdd'],
  1746.                             $entry['qtySub'],
  1747.                             $entry['valueAdd'],
  1748.                             $entry['valueSub'],
  1749.                             $entry['price'],
  1750.                             $this->getLoggedUserCompanyId($request),
  1751.                             0,
  1752.                             $entry['entity'],
  1753.                             $entry['entityId'],
  1754.                             $entry['entityDocHash'],
  1755.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  1756.                         );
  1757.                         if ($modifiedData)
  1758.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1759.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1760.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1761.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1762.                                 "",
  1763.                                 'inventory_refresh_debug'1); //last er 1 is append
  1764.                         if ($last_refresh_date_obj == '') {
  1765.                             $last_refresh_date_obj $transDate;
  1766.                         } else if ($transDate $last_refresh_date_obj) {
  1767.                             $last_refresh_date_obj $transDate;
  1768.                         }
  1769.                     }
  1770.                 }
  1771.             }
  1772.             $data = [];
  1773.             //____________DELIVERY_RECEIPT___________________
  1774.             $docEntity "DeliveryReceipt";
  1775.             $docEntityIdField "deliveryReceiptId";
  1776.             $accTransactionDataByDocId = [];
  1777.             $query "SELECT delivery_receipt_item.*, delivery_receipt.delivery_receipt_date, delivery_receipt.document_hash, delivery_receipt.skip_inventory_hit from  delivery_receipt_item
  1778.               join delivery_receipt on delivery_receipt.delivery_receipt_id=delivery_receipt_item.delivery_receipt_id
  1779.             where delivery_receipt.delivery_receipt_date ='" $last_refresh_date " 00:00:00' and delivery_receipt.approved=1";
  1780.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1781.             
  1782.             $queryData $stmt;
  1783.             foreach ($queryData as $item) {
  1784.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  1785.                     ->findOneBy(
  1786.                         array(
  1787.                             'id' => $item['product_id']
  1788.                         )
  1789.                     );
  1790.                 $curr_purchase_price $product->getPurchasePrice();
  1791.                 if ($item['skip_inventory_hit'] != 1) {
  1792.                     $data[$item['product_id']][] = array(
  1793.                         'date' => $last_refresh_date,
  1794.                         'entity' => array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  1795.                         'entityId' => $item['delivery_receipt_id'],
  1796.                         'colorId' => $item['color_id'],
  1797.                         'sizeId' => $item['size_id'],
  1798.                         'entityDocHash' => $item['document_hash'],
  1799.                         'qtyAdd' => 0,
  1800.                         'qtySub' => ($item['qty'] * $item['unit_multiplier']),
  1801.                         'valueAdd' => 0,
  1802.                         'valueSub' => '_AUTO_',
  1803.                         'price' => $curr_purchase_price,
  1804.                         'fromWarehouse' => $item['warehouse_id'],
  1805.                         'toWarehouse' => 0,
  1806.                         'fromWarehouseSub' => $item['warehouse_action_id'] != null $item['warehouse_action_id'] : GeneralConstant::WAREHOUSE_ACTION_GOODS,
  1807.                         'toWarehouseSub' => 0
  1808.                     );
  1809.                 }
  1810.                 $get_kids_sql "UPDATE `delivery_receipt_item` SET current_purchase_price='" $curr_purchase_price "' WHERE id=" $item['id'] . ";";
  1811.                 $stmt $em->getConnection()->executeStatement($get_kids_sql);
  1812.                 
  1813.             }
  1814.             foreach ($data as $key => $item) {
  1815.                 if (!empty($item)) {
  1816.                     foreach ($item as $entry) {
  1817.                         $transDate = new \DateTime($entry['date']);
  1818.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1819.                             $key,
  1820.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1821.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1822.                             $entry['fromWarehouse'],
  1823.                             $entry['toWarehouse'],
  1824.                             $entry['fromWarehouseSub'],
  1825.                             $entry['toWarehouseSub'],
  1826.                             $transDate,
  1827.                             $entry['qtyAdd'],
  1828.                             $entry['qtySub'],
  1829.                             $entry['valueAdd'],
  1830.                             $entry['valueSub'],
  1831.                             $entry['price'],
  1832.                             $this->getLoggedUserCompanyId($request),
  1833.                             0,
  1834.                             $entry['entity'],
  1835.                             $entry['entityId'],
  1836.                             $entry['entityDocHash'],
  1837.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  1838.                         );
  1839.                         if ($modifiedData)
  1840.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1841.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1842.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1843.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1844.                                 "",
  1845.                                 'inventory_refresh_debug'1); //last er 1 is append
  1846.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1847.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1848.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  1849.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  1850.                         else
  1851.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  1852.                         if ($last_refresh_date_obj == '') {
  1853.                             $last_refresh_date_obj $transDate;
  1854.                         } else if ($transDate $last_refresh_date_obj) {
  1855.                             $last_refresh_date_obj $transDate;
  1856.                         }
  1857.                     }
  1858.                 }
  1859.             }
  1860.             if ($modifyAccTransaction == 1) {
  1861.                 //for now we are suuming there is only receipt without confirmation needed
  1862.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1863.                     $docHereDr $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  1864.                         $docEntityIdField => $docId,
  1865.                     ));;
  1866.                     $so $em->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findOneBy(
  1867.                         array(
  1868.                             'salesOrderId' => $docHereDr->getSalesOrderId()
  1869.                         )
  1870.                     );
  1871.                     $query $em->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
  1872.                         ->createQueryBuilder('p');
  1873.                     $query->where('p.salesOrderId = :soID')
  1874.                         ->setParameter('soID'$docHereDr->getSalesOrderId());
  1875.                     $query->andWhere("p.deliveryReceiptIds LIKE '%" $docId "%' ");
  1876.                     $query->setMaxResults(1);
  1877.                     $results $query->getQuery()->getResult();
  1878.                     $docHere null;
  1879.                     if (!empty($results))
  1880.                         $docHere $results[0];
  1881.                     if ($docHere) {
  1882.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1883.                         if ($curr_v_ids == null)
  1884.                             $curr_v_ids = [];
  1885.                         $skipVids = [];
  1886.                         $toChangeVid 0;
  1887.                         $voucher null;
  1888.                         foreach ($curr_v_ids as $vid) {
  1889.                             if (in_array($vid$skipVids))
  1890.                                 continue;
  1891.                             $skipVids[] = $vid//to prevent duplicate query
  1892.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  1893.                                 'transactionId' => $vid,
  1894.                             ));;
  1895.                             if ($voucher) {
  1896.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1897.                                     $toChangeVid $vid;
  1898.                                 } else {
  1899.                                     continue;
  1900.                                 }
  1901.                                 if (strpos($voucher->getDescription(), 'Inventory') !== false) {
  1902. //                                    echo "Word Found!";
  1903.                                     $toChangeVid $vid;
  1904.                                 } else {
  1905.                                     continue;
  1906.                                 }
  1907.                             }
  1908.                         }
  1909.                         if ($toChangeVid == 0) {
  1910.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1911.                                 $em,
  1912.                                 $docHere->getSalesInvoiceDate()->format('Y-m-d'),
  1913.                                 0,
  1914.                                 AccountsConstant::VOUCHER_JOURNAL,
  1915.                                 'Journal For Inventory balance for Sales Invoice ' $docHere->getDocumentHash(),
  1916.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1917.                                 'JV',
  1918.                                 'GN',
  1919.                                 0,
  1920.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1921.                                 0,
  1922.                                 $docHere->getCreatedLoginId(),
  1923.                                 $docHere->getCompanyId(),
  1924.                                 '',
  1925.                                 0,
  1926.                                 1,
  1927.                                 0''$so->getBranchId(),
  1928.                                 AccountsConstant::INVOICE_REVENUE_JOURNAL,
  1929.                                 array_flip(GeneralConstant::$Entity_list)['SalesInvoice'], $docHere->getSalesInvoiceId(), $docHere->getDocumentHash()
  1930.                             );
  1931.                             $em->flush();
  1932.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  1933.                                 'transactionId' => $toChangeVid,
  1934.                             ));;
  1935.                         }
  1936. //                        DeleteDocument::AccTransactions($em, $toChangeVid, 0);
  1937.                         //now remove cogs or inventory related transactions
  1938.                         $voucherDetails $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(array(
  1939.                             'transactionId' => $toChangeVid,
  1940.                         ));;
  1941.                         foreach ($voucherDetails as $vdtls) {
  1942.                             if (in_array($vdtls->getAccountsHeadId(), $inv_head_list)) {
  1943.                                 $em->remove($vdtls);
  1944.                                 $em->flush();
  1945.                             }
  1946.                             if ($cogs_head == $vdtls->getAccountsHeadId()) {
  1947.                                 $em->remove($vdtls);
  1948.                                 $em->flush();
  1949.                             }
  1950.                         }
  1951.                         $tot_inv_amount 0;
  1952.                         foreach ($transData as $k => $v) {
  1953.                             $tot_inv_amount += ($v);
  1954.                             Accounts::CreateNewTransactionDetails($em,
  1955.                                 '',
  1956.                                 $toChangeVid,
  1957.                                 Generic::CurrToInt($v),
  1958.                                 $k,
  1959.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  1960.                                 AccountsConstant::DEBIT,
  1961.                                 0,
  1962.                                 [],
  1963.                                 [],
  1964.                                 $docHere->getCreatedLoginId()
  1965.                             );
  1966.                         }
  1967. //                        $stockReceivedType = $docHere->getType();
  1968.                         $to_balance_head 0;
  1969. //                        if ($docHere->getTransferActionType() == 4)
  1970.                         if (1) {
  1971.                         } else {
  1972.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1973.                                     'name' => 'inv_on_transit_head')
  1974.                             );
  1975.                             if ($inv_transit_head)
  1976.                                 $to_balance_head $inv_transit_head->getData();
  1977.                         }
  1978.                         if ($to_balance_head != 0) {
  1979.                             Accounts::CreateNewTransactionDetails($em,
  1980.                                 '',
  1981.                                 $toChangeVid,
  1982.                                 Generic::CurrToInt($tot_inv_amount),
  1983.                                 $to_balance_head,
  1984.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  1985.                                 AccountsConstant::CREDIT,
  1986.                                 0,
  1987.                                 [],
  1988.                                 [],
  1989.                                 $docHere->getCreatedLoginId()
  1990.                             );
  1991.                         }
  1992.                         if ($voucher)
  1993.                             $voucher->setTransactionAmount($tot_inv_amount);
  1994.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1995.                         if ($curr_v_ids != null)
  1996.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1997.                         else
  1998.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1999.                         $em->flush();
  2000. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2001.                     }
  2002.                 }
  2003.             }
  2004.             $data = [];
  2005.             //____________STOCK_CONSUMPTION___________________
  2006.             $docEntity "StockConsumptionNote";
  2007.             $docEntityIdField "stockConsumptionNoteId";
  2008.             $accTransactionDataByDocId = [];
  2009.             $query "SELECT stock_consumption_note_item.*,  stock_consumption_note.stock_consumption_note_date, stock_consumption_note.document_hash, stock_consumption_note.data
  2010.               from  stock_consumption_note_item
  2011.               join stock_consumption_note on stock_consumption_note.stock_consumption_note_id=stock_consumption_note_item.stock_consumption_note_id
  2012.             where stock_consumption_note.stock_consumption_note_date ='" $last_refresh_date " 00:00:00' and stock_consumption_note.approved=1";
  2013.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2014.             
  2015.             $queryData $stmt;
  2016.             $consumption_data = [];
  2017.             $produced_data = [];
  2018.             $checked_stcm_ids = [];
  2019.             foreach ($queryData as $item) {
  2020. //                $product=$em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  2021. //                    ->findOneBy(
  2022. //                        array(
  2023. //                            'id'=>$item['product_id']
  2024. //                        )
  2025. //                    );
  2026. //
  2027. //                $curr_purchase_price=$product->getPurchasePrice();
  2028.                 if (!in_array($item['stock_consumption_note_id'], $checked_stcm_ids)) {
  2029.                     $conversion_data json_decode($item['data'], true);
  2030.                     if ($conversion_data == null)
  2031.                         $conversion_data = [];
  2032.                     if (isset($conversion_data['conversionData'])) {
  2033.                         if (isset($conversion_data['conversionData']['converted_products'])) {
  2034.                             $curr_spec_data $conversion_data['conversionData'];
  2035.                             foreach ($curr_spec_data['converted_products'] as $pika_key => $val) {
  2036.                                 $consumption_data[$val][] = array(
  2037.                                     'date' => $last_refresh_date,
  2038.                                     'type' => 2,
  2039.                                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2040.                                     'entityId' => $item['stock_consumption_note_id'],
  2041.                                     'colorId' => isset($curr_spec_data['converted_product_colors'][$pika_key]) ? ($curr_spec_data['converted_product_colors'][$pika_key]) : 0,
  2042.                                     'sizeId' => isset($curr_spec_data['converted_product_sizes'][$pika_key]) ? ($curr_spec_data['converted_product_sizes'][$pika_key]) : 0,
  2043.                                     'entityDocHash' => $item['document_hash'],
  2044.                                     'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_units'][$pika_key]) : 0,
  2045.                                     'qtySub' => 0,
  2046.                                     '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,
  2047.                                     'valueSub' => 0,
  2048.                                     'price' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_unit_price'][$pika_key]) : 0,
  2049.                                     'fromWarehouse' => 0,
  2050.                                     'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key]) ? ($curr_spec_data['converted_warehouseId'][$pika_key]) : 0,
  2051.                                     'fromWarehouseSub' => 0,
  2052.                                     'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key]) ? ($curr_spec_data['converted_warehouseActionId'][$pika_key]) : 0
  2053.                                 );
  2054.                             }
  2055.                         }
  2056.                     }
  2057. //                    if(isset($conversion_data['expenseCost'] ))
  2058. //                    if(isset($conversion_data['expenseCost']['expense_heads'] ))
  2059. //                    {
  2060. //                        $curr_spec_data=$conversion_data['expenseCost'];
  2061. //                        foreach($curr_spec_data['expense_heads'] as $pika_key=>$val)
  2062. //                        {
  2063. //
  2064. //                            $consumption_data[$val][] = array(
  2065. //                                'date' => $last_refresh_date,
  2066. //                                'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2067. //                                'entityId' => $item['stock_consumption_note_id'],
  2068. //                                'entityDocHash' => $item['document_hash'],
  2069. //                                'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_units'][$pika_key]):0,
  2070. //                                'qtySub' => 0,
  2071. //                                '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,
  2072. //                                'valueSub' => 0,
  2073. //                                'price' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_unit_price'][$pika_key]):0,
  2074. //                                'fromWarehouse' => 0,
  2075. //                                'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key])?(1*$curr_spec_data['converted_warehouseId'][$pika_key]):0,
  2076. //                                'fromWarehouseSub' => 0,
  2077. //                                'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key])?(1*$curr_spec_data['converted_warehouseActionId'][$pika_key]):0
  2078. //                            );
  2079. //                        }
  2080. //                    }
  2081.                     $checked_stcm_ids[] = $item['stock_consumption_note_id'];
  2082.                 }
  2083.                 $consumption_data[$item['product_id']][] = array(
  2084.                     'date' => $last_refresh_date,
  2085.                     'type' => 1,
  2086.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2087.                     'entityId' => $item['stock_consumption_note_id'],
  2088.                     'colorId' => $item['color_id'],
  2089.                     'sizeId' => $item['size_id'],
  2090.                     'entityDocHash' => $item['document_hash'],
  2091.                     'qtyAdd' => 0,
  2092.                     'qtySub' => ($item['qty'] * 1),
  2093.                     'valueAdd' => 0,
  2094.                     'valueSub' => (($item['qty']) * ($item['price'])),
  2095.                     'price' => $item['price'],
  2096.                     'fromWarehouse' => $item['warehouse_id'],
  2097.                     'toWarehouse' => 0,
  2098.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  2099.                     'toWarehouseSub' => 0
  2100.                 );
  2101. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2102. //                $stmt = $em->getConnection()->executeStatement($get_kids_sql);
  2103. //                
  2104.             }
  2105.             foreach ($consumption_data as $key => $item) {
  2106.                 if (!empty($item)) {
  2107.                     foreach ($item as $entry) {
  2108.                         $transDate = new \DateTime($entry['date']);
  2109.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2110.                             $key,
  2111.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2112.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2113.                             $entry['fromWarehouse'],
  2114.                             $entry['toWarehouse'],
  2115.                             $entry['fromWarehouseSub'],
  2116.                             $entry['toWarehouseSub'],
  2117.                             $transDate,
  2118.                             $entry['qtyAdd'],
  2119.                             $entry['qtySub'],
  2120.                             $entry['valueAdd'],
  2121.                             $entry['valueSub'],
  2122.                             $entry['price'],
  2123.                             $this->getLoggedUserCompanyId($request),
  2124.                             0,
  2125.                             $entry['entity'],
  2126.                             $entry['entityId'],
  2127.                             $entry['entityDocHash'],
  2128.                             $entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION
  2129.                         );
  2130.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2131.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2132.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2133.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2134.                             "",
  2135.                             'inventory_refresh_debug'1); //last er 1 is append
  2136.                         if ($last_refresh_date_obj == '') {
  2137.                             $last_refresh_date_obj $transDate;
  2138.                         } else if ($transDate $last_refresh_date_obj) {
  2139.                             $last_refresh_date_obj $transDate;
  2140.                         }
  2141.                     }
  2142.                 }
  2143.             }
  2144.             $data = [];
  2145.             //____________PRODUCTION___________________
  2146.             $docEntity "Production";
  2147.             $docEntityIdField "productionId";
  2148.             $accTransactionDataByDocId = [];
  2149.             $consumedAmountByProductionId = [];
  2150.             $query "SELECT * from production_process_settings
  2151.             where approved=1 order by production_process_settings_id asc  ";
  2152.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2153.             
  2154.             $processList $stmt;
  2155. //            $processList=[];
  2156.             foreach ($processList as $process) {
  2157.                 $query "SELECT production_entry_item.*,  production.production_date, production.document_hash
  2158.               from  production_entry_item
  2159.               join production on production_entry_item.production_id=production.production_id
  2160.             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  ";
  2161.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  2162.                 
  2163.                 $queryData $stmt;
  2164.                 $produced_data = [];
  2165.                 $rejected_data = [];
  2166.                 $consumed_data = [];
  2167.                 foreach ($queryData as $item) {
  2168. //                $product=$em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  2169. //                    ->findOneBy(
  2170. //                        array(
  2171. //                            'id'=>$item['product_id']
  2172. //                        )
  2173. //                    );
  2174. //
  2175. //                $curr_purchase_price=$product->getPurchasePrice();
  2176.                     if ($item['price'] == '')
  2177.                         $item['price'] = 0;
  2178.                     if ($item['price'] < 0)
  2179.                         $item['price'] = 0;
  2180.                     $item['production_nature_id'];
  2181.                     $consumed_data[$item['product_id']][] = array(
  2182.                         'date' => $last_refresh_date,
  2183.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2184.                         'entityId' => $item['production_id'],
  2185.                         'colorId' => $item['color_id'],
  2186.                         'sizeId' => $item['size_id'],
  2187.                         'entityDocHash' => $item['document_hash'],
  2188.                         'qtyAdd' => 0,
  2189.                         'qtySub' => ($item['additional_consumed_qty'] * 1) + ($item['consumed_qty']),
  2190.                         'valueAdd' => 0,
  2191.                         'valueSub' => '_AUTO_',
  2192.                         'price' => $item['price'],
  2193.                         'fromWarehouse' => $item['warehouse_id'],
  2194.                         'toWarehouse' => 0,
  2195.                         'fromWarehouseSub' => $item['consumed_item_action_tag_id'],
  2196.                         'toWarehouseSub' => 0,
  2197.                         'production_nature_id' => $item['production_nature_id'],
  2198.                     );
  2199.                     $produced_data[$item['product_id']][] = array(
  2200.                         'date' => $last_refresh_date,
  2201.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2202.                         'entityId' => $item['production_id'],
  2203.                         'colorId' => $item['color_id'],
  2204.                         'sizeId' => $item['size_id'],
  2205.                         'entityDocHash' => $item['document_hash'],
  2206.                         'qtyAdd' => ($item['accepted_qty'] * 1),
  2207.                         'qtySub' => 0,
  2208.                         'valueAdd' => (($item['accepted_qty'] * 1) * ($item['price'])),
  2209.                         'valueSub' => 0,
  2210.                         'price' => $item['price'],
  2211.                         'fromWarehouse' => 0,
  2212.                         'toWarehouse' => $item['warehouse_id'],
  2213.                         'fromWarehouseSub' => 0,
  2214.                         'toWarehouseSub' => $item['produced_item_action_tag_id'],
  2215.                         'production_nature_id' => $item['production_nature_id'],
  2216.                     );
  2217.                     $rejected_data[$item['product_id']][] = array(
  2218.                         'date' => $last_refresh_date,
  2219.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2220.                         'entityId' => $item['production_id'],
  2221.                         'colorId' => $item['color_id'],
  2222.                         'sizeId' => $item['size_id'],
  2223.                         'entityDocHash' => $item['document_hash'],
  2224.                         'qtyAdd' => ($item['rejected_qty'] * 1),
  2225.                         'qtySub' => 0,
  2226.                         'valueAdd' => (($item['rejected_qty'] * 1) * ($item['price'])),
  2227.                         'valueSub' => 0,
  2228.                         'price' => $item['price'],
  2229.                         'fromWarehouse' => 0,
  2230.                         'toWarehouse' => $item['warehouse_id'],
  2231.                         'fromWarehouseSub' => 0,
  2232.                         'toWarehouseSub' => $item['rejected_item_action_tag_id'],
  2233.                         'production_nature_id' => $item['production_nature_id'],
  2234.                     );
  2235. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2236. //                $stmt = $em->getConnection()->executeStatement($get_kids_sql);
  2237. //                
  2238.                 }
  2239.                 foreach ($consumed_data as $key => $item) {
  2240.                     if (!empty($item)) {
  2241.                         foreach ($item as $entry) {
  2242.                             $transDate = new \DateTime($entry['date']);
  2243.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2244.                                 $key,
  2245.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2246.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2247.                                 $entry['fromWarehouse'],
  2248.                                 $entry['toWarehouse'],
  2249.                                 $entry['fromWarehouseSub'],
  2250.                                 $entry['toWarehouseSub'],
  2251.                                 $transDate,
  2252.                                 $entry['qtyAdd'],
  2253.                                 $entry['qtySub'],
  2254.                                 $entry['valueAdd'],
  2255.                                 $entry['valueSub'],
  2256.                                 $entry['price'],
  2257.                                 $this->getLoggedUserCompanyId($request),
  2258.                                 0,
  2259.                                 $entry['entity'],
  2260.                                 $entry['entityId'],
  2261.                                 $entry['entityDocHash'],
  2262.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION);
  2263.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2264.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2265.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2266.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2267.                                 "",
  2268.                                 'inventory_refresh_debug'1); //last er 1 is append
  2269.                             if (!isset($consumedAmountByProductionId[$entry['entityId']]))
  2270.                                 $consumedAmountByProductionId[$entry['entityId']] = ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2271.                             else
  2272.                                 $consumedAmountByProductionId[$entry['entityId']] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2273.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2274.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  2275.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2276.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2277.                             else
  2278.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2279.                             if ($last_refresh_date_obj == '') {
  2280.                                 $last_refresh_date_obj $transDate;
  2281.                             } else if ($transDate $last_refresh_date_obj) {
  2282.                                 $last_refresh_date_obj $transDate;
  2283.                             }
  2284.                         }
  2285.                     }
  2286.                 }
  2287.                 foreach ($produced_data as $key => $item) {
  2288.                     if (!empty($item)) {
  2289.                         foreach ($item as $entry) {
  2290.                             $transDate = new \DateTime($entry['date']);
  2291.                             $productionNature $entry['production_nature_id'];
  2292.                             if (in_array($productionNature, [12])) {
  2293.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2294.                                     $key,
  2295.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2296.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2297.                                     $entry['fromWarehouse'],
  2298.                                     $entry['toWarehouse'],
  2299.                                     $entry['fromWarehouseSub'],
  2300.                                     $entry['toWarehouseSub'],
  2301.                                     $transDate,
  2302.                                     $entry['qtyAdd'],
  2303.                                     $entry['qtySub'],
  2304. //                                $entry['valueAdd'],
  2305.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2306.                                     $entry['valueSub'],
  2307.                                     $entry['price'],
  2308.                                     $this->getLoggedUserCompanyId($request),
  2309.                                     0,
  2310.                                     $entry['entity'],
  2311.                                     $entry['entityId'],
  2312.                                     $entry['entityDocHash'],
  2313.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2314.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2315.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2316.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2317.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2318.                                     "",
  2319.                                     'inventory_refresh_debug'1); //last er 1 is append
  2320.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2321.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2322.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2323.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2324.                                 else
  2325.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2326. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2327. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2328. //                            else
  2329. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2330.                             } else {
  2331.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2332.                                     $key,
  2333.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2334.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2335.                                     $entry['fromWarehouse'],
  2336.                                     $entry['toWarehouse'],
  2337.                                     $entry['fromWarehouseSub'],
  2338.                                     $entry['toWarehouseSub'],
  2339.                                     $transDate,
  2340.                                     0,
  2341.                                     0,
  2342. //                                $entry['valueAdd'],
  2343.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2344.                                     0,
  2345.                                     $entry['price'],
  2346.                                     $this->getLoggedUserCompanyId($request),
  2347.                                     0,
  2348.                                     $entry['entity'],
  2349.                                     $entry['entityId'],
  2350.                                     $entry['entityDocHash'],
  2351.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2352.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2353.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2354.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2355.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2356.                                     "",
  2357.                                     'inventory_refresh_debug'1); //last er 1 is append
  2358.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2359.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2360.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2361.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2362.                                 else
  2363.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2364. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2365. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2366. //                            else
  2367. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2368.                             }
  2369.                             if ($last_refresh_date_obj == '') {
  2370.                                 $last_refresh_date_obj $transDate;
  2371.                             } else if ($transDate $last_refresh_date_obj) {
  2372.                                 $last_refresh_date_obj $transDate;
  2373.                             }
  2374.                         }
  2375.                     }
  2376.                 }
  2377.                 foreach ($rejected_data as $key => $item) {
  2378.                     if (!empty($item)) {
  2379.                         foreach ($item as $entry) {
  2380.                             $transDate = new \DateTime($entry['date']);
  2381.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2382.                                 $key,
  2383.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2384.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2385.                                 $entry['fromWarehouse'],
  2386.                                 $entry['toWarehouse'],
  2387.                                 $entry['fromWarehouseSub'],
  2388.                                 $entry['toWarehouseSub'],
  2389.                                 $transDate,
  2390.                                 $entry['qtyAdd'],
  2391.                                 $entry['qtySub'],
  2392.                                 $entry['valueAdd'],
  2393.                                 $entry['valueSub'],
  2394.                                 $entry['price'],
  2395.                                 $this->getLoggedUserCompanyId($request),
  2396.                                 0,
  2397.                                 $entry['entity'],
  2398.                                 $entry['entityId'],
  2399.                                 $entry['entityDocHash'],
  2400.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2401.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2402.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2403.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2404.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2405.                                 "",
  2406.                                 'inventory_refresh_debug'1); //last er 1 is append
  2407.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2408.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  2409.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2410.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = (-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2411.                             else
  2412.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ((-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2413.                             if ($last_refresh_date_obj == '') {
  2414.                                 $last_refresh_date_obj $transDate;
  2415.                             } else if ($transDate $last_refresh_date_obj) {
  2416.                                 $last_refresh_date_obj $transDate;
  2417.                             }
  2418.                         }
  2419.                     }
  2420.                 }
  2421.             }
  2422.             if ($modifyAccTransaction == 1) {
  2423.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2424.                     $docHere $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  2425.                         $docEntityIdField => $docId,
  2426.                     ));;
  2427.                     if ($docHere) {
  2428.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2429.                         if ($curr_v_ids == null)
  2430.                             $curr_v_ids = [];
  2431.                         $skipVids = [];
  2432.                         $toChangeVid 0;
  2433.                         $voucher null;
  2434.                         foreach ($curr_v_ids as $vid) {
  2435.                             if (in_array($vid$skipVids))
  2436.                                 continue;
  2437.                             $skipVids[] = $vid//to prevent duplicate query
  2438.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2439.                                 'transactionId' => $vid,
  2440.                             ));;
  2441.                             if ($voucher) {
  2442.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2443.                                     $toChangeVid $vid;
  2444.                                 } else {
  2445.                                     continue;
  2446.                                 }
  2447.                             }
  2448.                         }
  2449.                         if ($toChangeVid == 0) {
  2450.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2451.                                 $em,
  2452.                                 $docHere->getProductionDate()->format('Y-m-d'),
  2453.                                 0,
  2454.                                 AccountsConstant::VOUCHER_JOURNAL,
  2455.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  2456.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2457.                                 'JV',
  2458.                                 'GN',
  2459.                                 0,
  2460.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2461.                                 0,
  2462.                                 $docHere->getCreatedLoginId(),
  2463.                                 $docHere->getCompanyId(),
  2464.                                 '',
  2465.                                 0,
  2466.                                 1
  2467.                             );
  2468.                             $em->flush();
  2469.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2470.                                 'transactionId' => $toChangeVid,
  2471.                             ));;
  2472.                         }
  2473.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  2474.                         $tot_inv_amount 0;
  2475.                         foreach ($transData as $k => $v) {
  2476.                             $tot_inv_amount += ($v);
  2477.                             Accounts::CreateNewTransactionDetails($em,
  2478.                                 '',
  2479.                                 $toChangeVid,
  2480.                                 Generic::CurrToInt($v),
  2481.                                 $k,
  2482.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2483.                                 AccountsConstant::DEBIT,
  2484.                                 0,
  2485.                                 [],
  2486.                                 [],
  2487.                                 $docHere->getCreatedLoginId()
  2488.                             );
  2489.                         }
  2490. //                        $stockReceivedType = $docHere->getType();
  2491.                         $to_balance_head 0;
  2492. //                        if ($docHere->getTransferActionType() == 4)
  2493.                         if (1) {
  2494.                         } else {
  2495.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  2496.                                     'name' => 'inv_on_transit_head')
  2497.                             );
  2498.                             if ($inv_transit_head)
  2499.                                 $to_balance_head $inv_transit_head->getData();
  2500.                         }
  2501.                         if ($to_balance_head != 0) {
  2502.                             Accounts::CreateNewTransactionDetails($em,
  2503.                                 '',
  2504.                                 $toChangeVid,
  2505.                                 Generic::CurrToInt($tot_inv_amount),
  2506.                                 $to_balance_head,
  2507.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  2508.                                 AccountsConstant::CREDIT,
  2509.                                 0,
  2510.                                 [],
  2511.                                 [],
  2512.                                 $docHere->getCreatedLoginId()
  2513.                             );
  2514.                         }
  2515.                         if ($voucher)
  2516.                             $voucher->setTransactionAmount($tot_inv_amount);
  2517.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2518.                         if ($curr_v_ids != null)
  2519.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2520.                         else
  2521.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2522.                         $em->flush();
  2523. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2524.                     }
  2525.                 }
  2526.             }
  2527.             if ($terminate == 0) {
  2528.                 return new JsonResponse(array(
  2529.                     "success" => true,
  2530.                     "last_refresh_date" => $last_refresh_date,
  2531.                     "inventory_refreshed" => $refreshed_opening
  2532.                 ));
  2533.             } else {
  2534.                 return new JsonResponse(array(
  2535.                     "success" => false,
  2536.                     "last_refresh_date" => $last_refresh_date,
  2537.                     "inventory_refreshed" => $refreshed_opening
  2538.                 ));
  2539.             }
  2540.         }
  2541.         return new JsonResponse(array(
  2542.             "success" => false,
  2543.             "last_refresh_date" => $last_refresh_date,
  2544.             "inventory_refreshed" => $refreshed_opening
  2545.         ));
  2546.         //2 .now make an array with necessary data based on challan and grn for now willl need consumption later
  2547.         //broken into transactions not closing
  2548.         //structure---> $data['productId']=array(
  2549.         //'date'=>'2017-09-02 00:00:00'
  2550.         //'qtyAdd'=>'2'
  2551.         //'qtySub'=>'0'
  2552.         //'valueAdd'=>'2000'
  2553.         //'valueSub'=>'0'
  2554.         //'fromWarehouse'=>'0'
  2555.         //'toWarehouse'=>'0'
  2556.         //'fromWarehouseSub'=>'0'
  2557.         //'toWarehouseSub'=>'0'
  2558.         //)
  2559.         //
  2560.     }
  2561.     public function OpeningItemAction(Request $request)
  2562.     {
  2563.         $em $this->getDoctrine()->getManager();
  2564.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  2565.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  2566.         if ($request->isMethod('POST')) {
  2567.             $pp trim($request->request->get('purchasePrice'));
  2568. //replace comma with space
  2569.             $pp str_replace(","""$pp);
  2570.             if ($request->request->get('productId') != '') {
  2571.                 foreach ($request->request->get('warehouseId') as $key => $value) {
  2572.                     $data = array(
  2573.                         'productId' => $request->request->get('productId'),
  2574.                         'warehouseId' => $request->request->get('warehouseId')[$key],
  2575.                         'warehouseActionId' => $request->request->get('warehouseActionId')[$key],
  2576.                         'purchasePrice' => $pp,
  2577.                         'date' => new \DateTime($request->request->get('date')),
  2578.                         'qty' => $request->request->get('qty')[$key],
  2579.                     );
  2580.                     $transDate = new \DateTime($request->request->get('date'));
  2581.                     $new = new InvItemInOut();
  2582.                     $new->setProductId($request->request->get('productId'));
  2583.                     $new->setWarehouseId($request->request->get('warehouseId')[$key]);
  2584.                     $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  2585.                     $new->setActionTagId($request->request->get('warehouseActionId')[$key]);
  2586.                     $new->setTransactionDate($transDate);
  2587.                     $new->setQty($request->request->get('qty')[$key]);
  2588.                     $new->setPrice($pp);
  2589.                     $new->setAmount($request->request->get('qty')[$key] * $pp);
  2590.                     $new->setEntity(0);// opening =0
  2591.                     $new->setEntityId(0);// opening =0
  2592.                     $new->setDebitCreditHeadId(0);// opening =0
  2593.                     $new->setVoucherIds(null);// opening =0
  2594.                     $em->persist($new);
  2595.                     $em->flush();
  2596. //                    $total_inv_value_in_by_id += $request->request->get('qty')[$key] * $pp;
  2597.                     Inventory::AddOpeningInventoryStock($em$data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2598.                 }
  2599.             }
  2600.         }
  2601.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  2602.             'name' => 'warehouse_action_1'//for now for stock of goods
  2603.         ));
  2604.         return $this->render('@Inventory/pages/input_forms/opening_item_assign.html.twig',
  2605.             array(
  2606.                 'page_title' => "Opening Items",
  2607.                 'inv_head' => $inv_head $inv_head->getData() : '',
  2608.                 'products' => $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\InvProducts')->findBy(array(
  2609.                     'status' => GeneralConstant::ACTIVE//for now for stock of goods
  2610. //                    'opening_locked'=>0
  2611.                 )),
  2612.                 'warehouseList' => Inventory::WarehouseList($em),
  2613.                 'warehouseActionList' => $warehouse_action_list
  2614.             )
  2615.         );
  2616.     }
  2617.     public function CreateProductCategoryAction(Request $request)
  2618.     {
  2619.         if ($request->isMethod('POST')) {
  2620.             $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));
  2621.             if ($cat_data['id'] != '')
  2622.                 return new JsonResponse(array("success" => true'cat_data' => $cat_data));
  2623.         }
  2624.         return new JsonResponse(array("success" => false,));
  2625. //        return $this->redirectToRoute("create_product");
  2626.     }
  2627.     public function CreateProductSubCategoryAction(Request $request)
  2628.     {
  2629.         if ($request->isMethod('POST')) {
  2630.             $spec_data Inventory::CreateSubCategory($this->getDoctrine()->getManager(),
  2631.                 $this->getLoggedUserCompanyId($request), $request->request->get('spec_name'),
  2632.                 $request->request->get('level'0),
  2633.                 $request->request->get('parentId'0),
  2634.                 $request->request->get('itemgroupId'),
  2635.                 $request->request->get('categoryId'),
  2636.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2637.             if ($spec_data['id'] != '')
  2638.                 return new JsonResponse(array("success" => true'spec_data' => $spec_data));
  2639.         }
  2640.         return new JsonResponse(array("success" => false,));
  2641. //        return $this->redirectToRoute("create_product");
  2642.     }
  2643.     public function CreateProductBrandAction(Request $request)
  2644.     {
  2645.         if ($request->isMethod('POST')) {
  2646.             $data Inventory::CreateBrand($this->getDoctrine()->getManager(),
  2647.                 $this->getLoggedUserCompanyId($request), $request->request->get('brand_name'),
  2648.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2649.             if ($data['id'] != '')
  2650.                 return new JsonResponse(array("success" => true'data' => $data));
  2651.         }
  2652.         return new JsonResponse(array("success" => false,));
  2653. //        return $this->redirectToRoute("create_product");
  2654.     }
  2655.     public function CreateIssueNoteAction(Request $request)
  2656.     {
  2657.         return $this->render('@Inventory/pages/input_forms/issue_note.html.twig',
  2658.             array(
  2659.                 'page_title' => 'Issue Note'
  2660.             )
  2661.         );
  2662.     }
  2663.     public function ProcessDraftDeliveryReceiptAction(Request $request$id 0)
  2664.     {
  2665.         $em $this->getDoctrine()->getManager();
  2666.         $companyId $this->getLoggedUserCompanyId($request);
  2667.         $extId $id;
  2668.         $receiptId $id;
  2669.         $allowed 0;
  2670.         if ($request->isMethod('POST')) {
  2671.             $receiptId $request->request->get('deliveryReceiptId');
  2672.             $QD $this->getDoctrine()
  2673.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  2674.                 ->findOneBy(
  2675.                     array(
  2676.                         'deliveryReceiptId' => $receiptId
  2677.                     ),
  2678.                     array()
  2679.                 );
  2680.             $soId $QD->getSalesOrderId();
  2681.             $drData = [];
  2682.             $dr_item_data $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')->findBy(
  2683.                 array(
  2684.                     'deliveryReceiptId' => $receiptId,
  2685.                 )
  2686.             );
  2687.             foreach ($dr_item_data as $dr_item) {
  2688.                 $drData[] = array(
  2689.                     'soItemId' => $dr_item->getSalesorderItemId(),
  2690.                     'qty' => $dr_item->getQty()
  2691.                 );
  2692.             }
  2693. //            $drData=[
  2694. //                ['soItemId'=>9,'qty'=>9],
  2695. //                ['soItemId'=>9,'qty'=>9],
  2696. //                ['soItemId'=>9,'qty'=>9],
  2697. //            ];
  2698.             $toGetSoItemsId = [];
  2699.             $toGetDoItemsId = [];
  2700.             $drDataBySoItemId = [];
  2701.             $drDataByDoItemId = [];
  2702.             $so $em->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findOneBy(array(
  2703.                 'salesOrderId' => $soId   //$id is soId
  2704.             ));
  2705.             if ($so->getDeliveryOrderSkipFlag() == 1) {
  2706.                 foreach ($drData as $pp) {
  2707.                     $toGetSoItemsId[] = $pp['soItemId'];
  2708.                     $drDataBySoItemId[$pp['soItemId']] = $pp;
  2709.                 }
  2710.             } else {
  2711.                 foreach ($drData as $pp) {
  2712.                     $toGetDoItemsId[] = $pp['soItemId'];
  2713.                     $drDataByDoItemId[$pp['soItemId']] = $pp;
  2714.                 }
  2715.                 $do_item_data $em->getRepository('ApplicationBundle\\Entity\\DeliveryOrderItem')->findBy(
  2716.                     array(
  2717.                         'salesorderId' => $id,
  2718.                         'id' => $toGetDoItemsId
  2719.                     )
  2720.                 );
  2721.                 foreach ($do_item_data as $dd) {
  2722.                     $toGetSoItemsId[] = $dd->getSalesorderItemId();
  2723.                     $drDataBySoItemId[$dd->getSalesorderItemId()] = $drDataByDoItemId[$dd->getId()];
  2724.                 }
  2725. //                $do_item_data = $em->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findOneBy(
  2726. //                    array(
  2727. ////                'salesOrderId'=>$post_data->get('soId', null),
  2728. //                        'id' => $post_data->get('do_details_id')[$key]
  2729. //                    )
  2730. //                );
  2731.             }
  2732.             $so_item_data $em->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findBy(
  2733.                 array(
  2734.                     'salesOrderId' => $soId,
  2735.                     'id' => $toGetSoItemsId
  2736.                 )
  2737.             );
  2738.             $prev_so_amount $so->getSoAmount();
  2739.             $total_discounted_amount 0;
  2740.             $total_product_amount 0;
  2741.             $total_discount 0;
  2742.             $total_special_discount $so->getSpecialDiscountAmount();
  2743.             $total_special_discount_rate $so->getSpecialDiscountRate();
  2744.             foreach ($so_item_data as $item) {
  2745.                 $qty $drDataBySoItemId[$item->getId()]['qty'];
  2746.                 $price $item->getPrice();
  2747.                 $amount $qty $price;
  2748.                 $discountAmount $amount * ($item->getDiscountRate() / 100);
  2749.                 $discountedAmount $amount $discountAmount;
  2750.                 $total_discounted_amount += $discountedAmount;
  2751.                 $total_discount += $discountAmount;
  2752.                 $total_product_amount += $amount;
  2753.             }
  2754.             $aitRate $so->getAitRate();
  2755.             $vatRate $so->getVatRate();
  2756.             if ($aitRate == '' || $aitRate == null$aitRate 0;
  2757.             if ($vatRate == '' || $vatRate == null$vatRate 0;
  2758. //        $so->setVatRate($post->get('vat_rate', null));
  2759.             $vatAmount $total_discounted_amount * ($vatRate 100);
  2760.             $aitAmount $total_discounted_amount * ($aitRate 100);
  2761.             $total_sales_amount $total_discounted_amount $vatAmount $aitAmount $total_special_discount;
  2762.             //now get client
  2763.             $client $em->getRepository('ApplicationBundle\\Entity\\AccClients')->findOneBy(array(
  2764.                 'clientId' => $so->getClientId(),
  2765.             ));
  2766.             if ($client->getCreditLimitEnabled() != 1) {
  2767.                 $allowed 1;
  2768.             } else {
  2769.                 $creditLimit $client->getCreditLimit();
  2770.                 $due $client->getClientDue();
  2771.                 if ($creditLimit >= ($due $total_sales_amount))
  2772.                     $allowed 1;
  2773.             }
  2774.             //now package data
  2775.             if ($allowed == 0) {
  2776.                 return new JsonResponse(array(
  2777.                     'success' => false,
  2778. //                        'documentHash' => $order->getDocumentHash(),
  2779.                     'documentId' => $receiptId,
  2780.                     'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  2781.                     'viewUrl' => '',
  2782.                 ));
  2783.             }
  2784.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  2785.             $dochash $request->request->get('docHash'); //change
  2786.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  2787.             $approveRole 1;  //created
  2788.             $approveHash $request->request->get('approvalHash');
  2789.             $receiptId $request->request->get('deliveryReceiptId');
  2790.             $sig DocValidation::isSignatureOk($em$loginId$approveHash);
  2791. //            $this->addFlash(
  2792. //                'success',
  2793. //                'New Transaction Added.'
  2794. //            );
  2795.             $success $sig == false true;
  2796.             if ($success == true) {
  2797.                 $QD $this->getDoctrine()
  2798.                     ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  2799.                     ->findOneBy(
  2800.                         array(
  2801.                             'deliveryReceiptId' => $receiptId
  2802.                         ),
  2803.                         array()
  2804.                     );
  2805.                 $draftFlag $QD->getDraftFlag();
  2806.                 if ($draftFlag == 1) {
  2807.                     //now add Approval info
  2808.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  2809.                     $approveRole 1;  //created
  2810.                     System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  2811.                         $receiptId,
  2812.                         $loginId,
  2813.                         $approveRole,
  2814.                         $request->request->get('approvalHash'));
  2815.                     $options = array(
  2816.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  2817.                         'notification_server' => $this->container->getParameter('notification_server'),
  2818.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  2819.                         'url' => $this->generateUrl(
  2820.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  2821.                             ['entity_view_route_path_name']
  2822.                         )
  2823.                     );
  2824.                     System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  2825.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  2826.                         $receiptId,
  2827.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  2828.                     );
  2829.                     $QD->setDraftFlag(0);
  2830.                     $em->flush();
  2831.                 }
  2832.                 $url $this->generateUrl(
  2833.                     'view_delivery_receipt'
  2834.                 );
  2835.                 if ($request->request->has('returnJson')) {
  2836. //                    $dr = $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findBy(
  2837. //                        array(
  2838. //                            'salesOrderId' => $orderId, ///material
  2839. //
  2840. //                        )
  2841. //                    );
  2842.                     return new JsonResponse(array(
  2843.                         'success' => true,
  2844. //                        'documentHash' => $order->getDocumentHash(),
  2845.                         'documentId' => $receiptId,
  2846.                         'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  2847.                         'viewUrl' => $url "/" $receiptId,
  2848.                     ));
  2849.                 } else {
  2850.                     $this->addFlash(
  2851.                         'success',
  2852.                         'Action Successful'
  2853.                     );
  2854.                     return $this->redirect($url "/" $receiptId);
  2855.                 }
  2856.             }
  2857.         }
  2858.         return new JsonResponse(array(
  2859.             'success' => false,
  2860. //                        'documentHash' => $order->getDocumentHash(),
  2861.             'documentId' => $receiptId,
  2862.             'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  2863.             'viewUrl' => '',
  2864.         ));
  2865.     }
  2866.     public function CreateServiceChallanAction(Request $request)
  2867.     {
  2868.         $em $this->getDoctrine()->getManager();
  2869.         if ($request->isMethod('POST')) {
  2870.             $entity_id array_flip(GeneralConstant::$Entity_list)['ServiceChallan']; //change
  2871.             $dochash $request->request->get('docHash'); //change
  2872.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  2873.             $approveRole $request->request->get('approvalRole');
  2874.             $approveHash $request->request->get('approvalHash');
  2875.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  2876.                 $loginId$approveRole$approveHash)
  2877.             ) {
  2878.                 $this->addFlash(
  2879.                     'error',
  2880.                     'Sorry Could not insert Data.'
  2881.                 );
  2882.             } else {
  2883.                 $receiptId SalesOrderM::CreateNewServiceChallan($this->getDoctrine()->getManager(), $request->request,
  2884.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  2885.                     $this->getLoggedUserCompanyId($request));
  2886.                 //now add Approval info
  2887.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  2888. //                $approveRole = 1;  //created
  2889.                 $options = array(
  2890.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  2891.                     'notification_server' => $this->container->getParameter('notification_server'),
  2892.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  2893.                     'url' => $this->generateUrl(
  2894.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ServiceChallan']]
  2895.                         ['entity_view_route_path_name']
  2896.                     )
  2897.                 );
  2898.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  2899.                     array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  2900.                     $receiptId,
  2901.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  2902.                 );
  2903.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  2904.                     $receiptId,
  2905.                     $loginId,
  2906.                     $approveRole,
  2907.                     $request->request->get('approvalHash'));
  2908.                 $this->addFlash(
  2909.                     'success',
  2910.                     'New Service Challan Created'
  2911.                 );
  2912.                 $url $this->generateUrl(
  2913.                     'view_service_challan'
  2914.                 );
  2915.                 return $this->redirect($url "/" $receiptId);
  2916.             }
  2917.         }
  2918.         return $this->render('@Inventory/pages/input_forms/create_service_challan.html.twig',
  2919.             array(
  2920.                 'page_title' => 'New Service Challan',
  2921.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  2922.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  2923.                 'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  2924.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  2925.                 'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
  2926.                 'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
  2927.                 'deliveryOrders' => SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
  2928.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
  2929.                 'serviceList' => Inventory::ServiceList($em$this->getLoggedUserCompanyId($request))
  2930.             )
  2931.         );
  2932.     }
  2933.     public function GetItemListForDrAction(Request $request)
  2934.     {
  2935.         $em $this->getDoctrine()->getManager();
  2936.         $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  2937.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  2938.         if ($request->isMethod('POST')) {
  2939.             $em $this->getDoctrine();
  2940.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  2941.             );
  2942.             $Content = [];
  2943.             $Transport_data = [];
  2944.             $Lul_data = [];
  2945.             if ($request->request->get('doId') != '')
  2946.                 $find_array['deliveryOrderId'] = $request->request->get('doId');
  2947. //            if($request->request->get('warehouseId')!='')
  2948. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  2949.             $QD $this->getDoctrine()
  2950.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryOrderItem')
  2951.                 ->findBy(
  2952.                     $find_array,
  2953.                     array()
  2954.                 );
  2955. //            if($request->request->get('wareHouseId')!='')
  2956.             $DO $this->getDoctrine()
  2957.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryOrder')
  2958.                 ->findOneBy(
  2959.                     $find_array,
  2960.                     array()
  2961.                 );
  2962.             $sendData = array(
  2963. //                'salesType'=>$SO->getSalesType(),
  2964. //                'packageData'=>[],
  2965.                 'productList' => [],
  2966. //                'productListByPackage'=>[],
  2967.             );
  2968.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  2969.             $pckg_item_cross_match_data = [];
  2970.             $unitList Inventory::UnitTypeList($em);
  2971.             $colorList Inventory::GetColorList($em);
  2972.             foreach ($QD as $product) {
  2973. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  2974.                 if (($product->getBalance()) <= 0)
  2975.                     continue;
  2976.                 $fdm $product->getProductFdm();
  2977.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  2978.                 $find_query = array();
  2979.                 $soItem $this->getDoctrine()
  2980.                     ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  2981.                     ->findOneBy(
  2982.                         array(
  2983.                             'id' => $product->getSalesorderItemId()
  2984.                         )
  2985.                     );
  2986.                 if (!$soItem)
  2987.                     continue;
  2988. //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  2989. //                $soBalance = $soItem->getBalance();
  2990.                 $soBalance $soItem->getQty();
  2991. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  2992. //                $doBalance = $product->getBalance();
  2993.                 $doBalance $product->getQty();
  2994.                 //now check if any so ir do item id there that is at
  2995.                 //least pending
  2996.                 $approvalPendingDrs $this->getDoctrine()
  2997.                     ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  2998.                     ->findBy(
  2999.                         array(
  3000.                             'deliveryOrderId' => $DO->getDeliveryOrderId(),
  3001.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3002.                         )
  3003.                     );
  3004.                 foreach ($approvalPendingDrs as $appPendDr) {
  3005.                     $appPendDrItem $this->getDoctrine()
  3006.                         ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3007.                         ->findOneBy(
  3008.                             array(
  3009.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3010.                                 'salesorderItemId' => $product->getSalesorderItemId()
  3011.                             )
  3012.                         );
  3013.                     if ($appPendDrItem) {
  3014.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3015.                             $soBalance $soBalance $appPendDrItem->getQty();
  3016.                             $doBalance $doBalance $appPendDrItem->getQty();
  3017.                         }
  3018.                     }
  3019.                 }
  3020.                 $colorId $product->getColorId();
  3021.                 $size $product->getSizeId();
  3022. //                $find_query['colorId']=
  3023.                 if ($productData['productId'] != 0) {
  3024.                     $find_query['productId'] = $productData['productId'];
  3025.                     if ($colorId == '' || $colorId == || $colorId == null)
  3026.                         $colorId $productData['defaultColorId'] ?? 0;
  3027.                     if ($size == '' || $size == || $size == null)
  3028.                         $size $productData['defaultSize'] ?? 0;
  3029.                     $find_query['productId'] = $productData['productId'];
  3030.                 } else {
  3031.                     if ($productData['igId'] != 0) {
  3032.                         $find_query['igId'] = $productData['igId'];
  3033.                     }
  3034.                     if ($productData['categoryId'] != 0) {
  3035.                         $find_query['categoryId'] = $productData['categoryId'];
  3036.                     }
  3037.                     if ($productData['subCategoryId'] != 0) {
  3038.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3039.                     }
  3040.                     if ($productData['brandId'] != 0) {
  3041.                         $find_query['brandId'] = $productData['brandId'];
  3042.                     }
  3043.                 }
  3044.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3045.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3046.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3047. //                    $find_query['color'] = $colorId;
  3048.                 } else
  3049.                     $find_query['color'] = $colorId;
  3050.                 if ($size == '' || $size == || $size == null) {
  3051. //                    $find_query['size'] = $size;
  3052.                 } else
  3053.                     $find_query['size'] = 0;
  3054.                 $inventory_by_warehouse_list $this->getDoctrine()
  3055.                     ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  3056.                     ->findBy(
  3057.                         $find_query,
  3058.                         array()
  3059.                     );
  3060.                 $new_pid $productData['productId'];
  3061.                 $p_data = array(
  3062.                     'details_id' => $product->getId(),
  3063. //                        'productId'=>$new_pid,
  3064.                     'productIdList' => [],
  3065.                     'multList' => [],
  3066.                     'drItemIds' => [],
  3067.                     'drItemQty' => [],
  3068.                     'drItemCodeIds' => [],
  3069.                     'drItemCartonIds' => [],
  3070.                     'colorIds' => [],
  3071.                     'colorNames' => [],
  3072.                     'sizeIds' => [],
  3073.                     'productNameList' => [],
  3074.                     'availableInventoryList' => [],
  3075.                     'warehouseActionId' => [],
  3076.                     'warehouseActionName' => [],
  3077.                     'availableBarcodes' => [],
  3078.                     'availableBarcodesStr' => [],
  3079. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3080. //                        'available_inventory'=>0,
  3081. //                        'package_id'=>$product->getPackageId(),
  3082.                     'qty' => $product->getQty(),
  3083.                     'delivered' => $product->getDelivered(),
  3084. //                    'deliverable' => $product->getDeliverable() - $product->getTransitQty(),
  3085.                     'deliverable' => min($soBalance$doBalance),
  3086. //                    'balance' => $product->getBalance(),
  3087.                     'balance' => min($soBalance$doBalance),
  3088.                     'productNameFdm' => $product->getProductNameFdm(),
  3089.                     'productFdm' => $product->getProductFdm(),
  3090. //                        'delivered'=>$product->getDelivered(),
  3091.                 );
  3092.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  3093.                     if ($inventory_by_warehouse->getQty() <= 0)
  3094.                         continue;
  3095.                     $unitType $product->getUnitTypeId();
  3096.                     $mult_unit 1;
  3097.                     if ($drId != 0) {
  3098.                         $drItem $this->getDoctrine()
  3099.                             ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3100.                             ->findOneBy(
  3101.                                 array(
  3102.                                     'deliveryReceiptId' => $drId,
  3103.                                     'productId' => $inventory_by_warehouse->getProductId(),
  3104.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  3105.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  3106.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  3107.                                 )
  3108.                             );
  3109.                         if ($drItem) {
  3110.                             $p_data['drItemIds'][] = $drItem->getId();
  3111.                             $p_data['drItemQty'][] = $drItem->getQty();
  3112.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  3113.                             if ($codes == null)
  3114.                                 $codes = [];
  3115.                             $p_data['drItemCodeIds'][] = $codes;
  3116.                             $codes json_decode($drItem->getCartonIds(), true);
  3117.                             if ($codes == null)
  3118.                                 $codes = [];
  3119.                             $p_data['drItemCartonIds'][] = $codes;
  3120.                         } else {
  3121.                             $p_data['drItemIds'][] = 0;
  3122.                             $p_data['drItemQty'][] = 0;
  3123.                             $p_data['drItemCodeIds'][] = 0;
  3124.                             $p_data['drItemCartonIds'][] = 0;
  3125.                         }
  3126.                     } else {
  3127.                         $p_data['drItemIds'][] = 0;
  3128.                         $p_data['drItemQty'][] = 0;
  3129.                         $p_data['drItemCodeIds'][] = 0;
  3130.                         $p_data['drItemCartonIds'][] = 0;
  3131.                     }
  3132.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  3133.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  3134.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  3135.                         }
  3136.                     };
  3137.                     if ($mult_unit == 0)
  3138.                         $mult_unit 1;
  3139.                     $inv_product_id $inventory_by_warehouse->getProductId();
  3140.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  3141.                     $p_data['multList'][] = $mult_unit;
  3142.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  3143.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  3144.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  3145.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  3146.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  3147. //                        $p_data['availableInventoryList'][]=$inventory_by_warehouse?(($inventory_by_warehouse->getQty())*$mult_unit):0;
  3148.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  3149.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  3150.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  3151.                 }
  3152.                 $sendData['productList'][] = $p_data;
  3153.             }
  3154.             //now package data
  3155.             if ($sendData) {
  3156.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3157.             }
  3158.             return new JsonResponse(array("success" => false));
  3159.         }
  3160.         return new JsonResponse(array("success" => false));
  3161.     }
  3162.     public function GetItemListForDrBySoAction(Request $request)
  3163.     {
  3164.         $em $this->getDoctrine()->getManager();
  3165.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3166.         if ($request->isMethod('POST')) {
  3167.             $em $this->getDoctrine();
  3168.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3169. //                'type'=>1//product only
  3170.             );
  3171.             $find_item_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3172.                 'type' => 1//product only
  3173.             );
  3174.             $Content = [];
  3175.             $Transport_data = [];
  3176.             $Lul_data = [];
  3177.             $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3178.             if ($request->request->get('soId') != '') {
  3179.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3180.                 $find_item_array['salesOrderId'] = $request->request->get('soId');
  3181.             }
  3182. //            if($request->request->get('warehouseId')!='')
  3183. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3184.             $QD $this->getDoctrine()
  3185.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  3186.                 ->findBy(
  3187.                     $find_item_array,
  3188.                     array()
  3189.                 );
  3190. //            if($request->request->get('wareHouseId')!='')
  3191.             $DO $this->getDoctrine()
  3192.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  3193.                 ->findOneBy(
  3194.                     $find_array,
  3195.                     array()
  3196.                 );
  3197.             $sendData = array(
  3198. //                'salesType'=>$SO->getSalesType(),
  3199. //                'packageData'=>[],
  3200.                 'productList' => [],
  3201. //                'productListByPackage'=>[],
  3202.             );
  3203.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3204.             $pckg_item_cross_match_data = [];
  3205.             $unitList Inventory::UnitTypeList($em);
  3206.             $colorList Inventory::GetColorList($em);
  3207.             foreach ($QD as $product) {
  3208.                 if (($product->getBalance() - $product->getTransitQty()) <= 0)
  3209.                     continue;
  3210.                 //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3211. //                $soBalance = $soItem->getBalance();
  3212.                 $soBalance $product->getQty();
  3213. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3214. //                $doBalance = $product->getBalance();
  3215. //                $doBalance = 0;
  3216.                 //now check if any so ir do item id there that is at
  3217.                 //least pending
  3218.                 $approvalPendingDrs $this->getDoctrine()
  3219.                     ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3220.                     ->findBy(
  3221.                         array(
  3222.                             'salesOrderId' => $DO->getSalesOrderId(),
  3223.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3224.                         )
  3225.                     );
  3226.                 foreach ($approvalPendingDrs as $appPendDr) {
  3227.                     $appPendDrItem $this->getDoctrine()
  3228.                         ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3229.                         ->findOneBy(
  3230.                             array(
  3231.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3232. //                                'salesorderItemId' => $product->getId(),
  3233.                                 'salesorderItemId' => $product->getId()
  3234.                             )
  3235.                         );
  3236.                     if ($appPendDrItem) {
  3237.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3238.                             $soBalance $soBalance $appPendDrItem->getQty();
  3239.                         }
  3240. //                        $doBalance=$doBalance-$appPendDrItem->getQty();
  3241.                     }
  3242.                 }
  3243.                 $fdm $product->getProductFdm();
  3244.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3245.                 $find_query = array();
  3246.                 $colorId $product->getColorId();
  3247.                 $size $product->getSizeId();
  3248. //                $find_query['colorId']=
  3249.                 if ($productData['productId'] != 0) {
  3250.                     $find_query['productId'] = $productData['productId'];
  3251.                     if ($colorId == '' || $colorId == || $colorId == null)
  3252.                         $colorId $productData['defaultColorId'] ?? 0;
  3253.                     if ($size == '' || $size == || $size == null)
  3254.                         $size $productData['defaultSize'] ?? 0;
  3255.                 } else {
  3256.                     if ($productData['igId'] != 0) {
  3257.                         $find_query['igId'] = $productData['igId'];
  3258.                     }
  3259.                     if ($productData['categoryId'] != 0) {
  3260.                         $find_query['categoryId'] = $productData['categoryId'];
  3261.                     }
  3262.                     if ($productData['subCategoryId'] != 0) {
  3263.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3264.                     }
  3265.                     if ($productData['brandId'] != 0) {
  3266.                         $find_query['brandId'] = $productData['brandId'];
  3267.                     }
  3268.                 }
  3269.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3270.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3271.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3272. //                    $find_query['color'] = $colorId;
  3273.                 } else
  3274.                     $find_query['color'] = $colorId;
  3275.                 if ($size == '' || $size == || $size == null) {
  3276. //                    $find_query['size'] = $size;
  3277.                 } else
  3278.                     $find_query['size'] = 0;
  3279.                 $inventory_by_warehouse_list $this->getDoctrine()
  3280.                     ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  3281.                     ->findBy(
  3282.                         $find_query,
  3283.                         array()
  3284.                     );
  3285.                 $new_pid $productData['productId'];
  3286.                 $unitType $product->getUnitTypeId();
  3287.                 $p_data = array(
  3288.                     'details_id' => $product->getId(),
  3289.                     'unitType' => $unitType,
  3290.                     'productIdList' => [],
  3291.                     'multList' => [],
  3292.                     'drItemIds' => [],
  3293.                     'drItemQty' => [],
  3294.                     'drItemCodeIds' => [],
  3295.                     'drItemCartonIds' => [],
  3296.                     'colorIds' => [],
  3297.                     'colorNames' => [],
  3298.                     'sizeIds' => [],
  3299.                     'productNameList' => [],
  3300.                     'availableInventoryList' => [],
  3301.                     'warehouseActionId' => [],
  3302.                     'warehouseActionName' => [],
  3303.                     'availableBarcodes' => [],
  3304.                     'availableBarcodesStr' => [],
  3305. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3306. //                        'available_inventory'=>0,
  3307. //                        'package_id'=>$product->getPackageId(),
  3308.                     'qty' => $product->getQty(),
  3309.                     'delivered' => $product->getDelivered(),
  3310. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  3311. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  3312.                     'deliverable' => $soBalance,
  3313. //                    'deliverable' => $product->getBalance(),
  3314.                     'balance' => $soBalance,
  3315. //                    'balance' => $product->getBalance(),
  3316.                     'productNameFdm' => $product->getProductNameFdm(),
  3317.                     'productFdm' => $product->getProductFdm(),
  3318. //                        'delivered'=>$product->getDelivered(),
  3319.                 );
  3320.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  3321.                     if ($inventory_by_warehouse->getQty() <= 0)
  3322.                         continue;
  3323.                     $mult_unit 1;
  3324.                     if ($drId != 0) {
  3325.                         $drItem $this->getDoctrine()
  3326.                             ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3327.                             ->findOneBy(
  3328.                                 array(
  3329.                                     'deliveryReceiptId' => $drId,
  3330.                                     'productId' => $inventory_by_warehouse->getProductId(),
  3331.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  3332.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  3333.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  3334.                                 )
  3335.                             );
  3336.                         if ($drItem) {
  3337.                             $p_data['drItemIds'][] = $drItem->getId();
  3338.                             $p_data['drItemQty'][] = $drItem->getQty();
  3339.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  3340.                             if ($codes == null)
  3341.                                 $codes = [];
  3342.                             $p_data['drItemCodeIds'][] = $codes;
  3343.                             $codes json_decode($drItem->getCartonIds(), true);
  3344.                             if ($codes == null)
  3345.                                 $codes = [];
  3346.                             $p_data['drItemCartonIds'][] = $codes;
  3347.                         } else {
  3348.                             $p_data['drItemIds'][] = 0;
  3349.                             $p_data['drItemQty'][] = 0;
  3350.                             $p_data['drItemCodeIds'][] = 0;
  3351.                             $p_data['drItemCartonIds'][] = 0;
  3352.                         }
  3353.                     } else {
  3354.                         $p_data['drItemIds'][] = 0;
  3355.                         $p_data['drItemQty'][] = 0;
  3356.                         $p_data['drItemCodeIds'][] = 0;
  3357.                         $p_data['drItemCartonIds'][] = 0;
  3358.                     }
  3359.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  3360.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  3361.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  3362.                         }
  3363.                     };
  3364.                     if ($mult_unit == 0)
  3365.                         $mult_unit 1;
  3366.                     $inv_product_id $inventory_by_warehouse->getProductId();
  3367.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  3368.                     $p_data['multList'][] = $mult_unit;
  3369.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  3370.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  3371.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  3372.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  3373.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  3374.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  3375.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  3376.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  3377.                 }
  3378.                 $sendData['productList'][] = $p_data;
  3379.             }
  3380.             //now package data
  3381.             if ($sendData) {
  3382.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3383.             }
  3384.             return new JsonResponse(array("success" => false));
  3385.         }
  3386.         return new JsonResponse(array("success" => false));
  3387.     }
  3388.     public function GetItemListForStockReqBySoAction(Request $request)
  3389.     {
  3390.         $em $this->getDoctrine()->getManager();
  3391.         if ($request->isMethod('POST')) {
  3392.             $em $this->getDoctrine();
  3393.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3394.             );
  3395.             $Content = [];
  3396.             $Transport_data = [];
  3397.             $Lul_data = [];
  3398.             $find_array['serviceId'] = [0null];
  3399.             $sendData = array(
  3400. //                'salesType'=>$SO->getSalesType(),
  3401. //                'packageData'=>[],
  3402.                 'productList' => [],
  3403. //                'productListByPackage'=>[],
  3404.             );
  3405.             if ($request->request->get('soId') != '') {
  3406.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3407. //            if($request->request->get('warehouseId')!='')
  3408. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3409.                 $QD $this->getDoctrine()
  3410.                     ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  3411.                     ->findBy(
  3412.                         $find_array,
  3413.                         array()
  3414.                     );
  3415. //            if($request->request->get('wareHouseId')!='')
  3416. //            $DO = $this->getDoctrine()
  3417. //                ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  3418. //                ->findOneBy(
  3419. //                    $find_array,
  3420. //                    array()
  3421. //                );
  3422.                 $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3423.                 $pckg_item_cross_match_data = [];
  3424.                 $unitList Inventory::UnitTypeList($em);
  3425.                 foreach ($QD as $product) {
  3426. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  3427. //                    continue;
  3428.                     $fdm $product->getProductFdm();
  3429.                     $unitType $product->getUnitTypeId();
  3430.                     $p_data = array(
  3431.                         'details_id' => $product->getId(),
  3432.                         'unitType' => $unitType,
  3433.                         'productIdList' => [],
  3434.                         'multList' => [],
  3435.                         'productNameList' => [],
  3436.                         'availableInventoryList' => [],
  3437.                         'warehouseActionId' => [],
  3438.                         'warehouseActionName' => [],
  3439.                         'availableBarcodes' => [],
  3440.                         'availableBarcodesStr' => [],
  3441. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3442. //                        'available_inventory'=>0,
  3443. //                        'package_id'=>$product->getPackageId(),
  3444.                         'qty' => $product->getQty(),
  3445.                         'delivered' => $product->getDelivered(),
  3446. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  3447. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  3448.                         'deliverable' => $product->getBalance(),
  3449.                         'balance' => $product->getBalance(),
  3450.                         'productNameFdm' => $product->getProductNameFdm(),
  3451.                         'productFdm' => $product->getProductFdm(),
  3452. //                        'delivered'=>$product->getDelivered(),
  3453.                     );
  3454.                     $sendData['productList'][] = $p_data;
  3455.                 }
  3456.             }
  3457.             //now package data
  3458.             if ($sendData) {
  3459.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3460.             }
  3461.             return new JsonResponse(array("success" => false));
  3462.         }
  3463.         return new JsonResponse(array("success" => false));
  3464.     }
  3465.     public function GetBarcodesListForStAction(Request $request)
  3466.     {
  3467.         $em $this->getDoctrine()->getManager();
  3468.         $sendData = [];
  3469.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3470.         if ($request->isMethod('POST')) {
  3471.             $em $this->getDoctrine();
  3472.             $find_query = array();
  3473.             $find_query['warehouseId'] = $request->request->get('warehouseId');
  3474.             $find_query['actionTagId'] = $request->request->get('warehouseActionId');
  3475.             $find_query['productId'] = $request->request->get('productId');
  3476.             $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3477.             $inventory_by_warehouse_list $this->getDoctrine()
  3478.                 ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  3479.                 ->findBy(
  3480.                     $find_query,
  3481.                     array()
  3482.                 );
  3483.             $new_pid $request->request->get('productId');
  3484.             $p_data = array();
  3485.             //now get bacodes if available
  3486. //                    $query = "SELECT product_by_code_id, GROUP_CONCAT(DISTINCT sales_code SEPARATOR ',') sales_code_list_str
  3487. //FROM product_by_code
  3488. //where company_id=" . $this->getLoggedUserCompanyId($request).
  3489. //                        " and product_id=".$inv_product_id.
  3490. //                        " and warehouse_id=".$inventory_by_warehouse->getWarehouseId().
  3491. //                        " and warehouse_action_id=".$inventory_by_warehouse->getActionTagId();
  3492. //                        " GROUP BY product_by_code_id" ;
  3493.             $query "SELECT product_by_code_id, sales_code
  3494. FROM product_by_code
  3495. where company_id=" $this->getLoggedUserCompanyId($request) .
  3496.                 " and product_id=" $request->request->get('productId') .
  3497.                 " and warehouse_id=" $request->request->get('warehouseId') .
  3498.                 " and warehouse_action_id=" $request->request->get('warehouseActionId');
  3499.             $stmt $em->getConnection()->fetchAllAssociative($query);
  3500.             
  3501.             $results $stmt;
  3502.             $sales_code_list_str '';
  3503.             foreach ($results as $pika => $result) {
  3504.                 if ($pika != 0)
  3505.                     $sales_code_list_str .= ',';
  3506.                 $sales_code_list_str .= str_pad($result['sales_code'], 13'0'STR_PAD_LEFT);
  3507.             }
  3508.             if ($results) {
  3509.                 $p_data['availableBarcodes'] = $sales_code_list_str != '' || $sales_code_list_str != null
  3510.                     explode(','$sales_code_list_str) : [];
  3511.                 $p_data['availableBarcodesStr'] = $sales_code_list_str != '' || $sales_code_list_str != null
  3512.                     $sales_code_list_str "";
  3513. //
  3514.             } else {
  3515.                 $p_data['availableBarcodes'] = [];
  3516.                 $p_data['availableBarcodesStr'] = "";
  3517. //
  3518.             }
  3519.             $sendData $p_data;
  3520.         }
  3521.         //now package data
  3522.         if (!empty($sendData['availableBarcodes'])) {
  3523.             return new JsonResponse(array("success" => true"content" => $sendData));
  3524.         }
  3525.         return new JsonResponse(array("success" => false));
  3526.     }
  3527.     public function GetItemListForSalesReturnAction(Request $request)
  3528.     {
  3529.         if ($request->isMethod('POST')) {
  3530.             $em $this->getDoctrine();
  3531.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3532.             );
  3533.             $Content = [];
  3534.             $Transport_data = [];
  3535.             $Lul_data = [];
  3536.             if ($request->request->get('drId') != '')
  3537.                 $find_array['deliveryReceiptId'] = $request->request->get('drId');
  3538. //            if($request->request->get('warehouseId')!='')
  3539. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3540.             $QD $this->getDoctrine()
  3541.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3542.                 ->findBy(
  3543.                     $find_array,
  3544.                     array()
  3545.                 );
  3546. //            if($request->request->get('wareHouseId')!='')
  3547.             $DR $this->getDoctrine()
  3548.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3549.                 ->findOneBy(
  3550.                     $find_array,
  3551.                     array()
  3552.                 );
  3553.             $sendData = array(
  3554.                 'productList' => [],
  3555.             );
  3556.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3557.             $pckg_item_cross_match_data = [];
  3558.             $unitList Inventory::UnitTypeList($em);
  3559.             foreach ($QD as $product) {
  3560.                 if (($product->getQty()) <= 0)
  3561.                     continue;
  3562.                 $new_pid $product->getProductId();
  3563.                 $sales_code_range = [];
  3564.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  3565.                     $sales_code_range json_decode($product->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  3566.                 } else {
  3567.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  3568.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getSalesCodeRange());
  3569.                     $sales_code_range json_decode($json_without_bigintstrue);
  3570.                 }
  3571.                 $p_data = array(
  3572.                     'details_id' => $product->getId(),
  3573.                     'dr_id' => $product->getDeliveryReceiptId(),
  3574.                     'productId' => $new_pid,
  3575.                     'product_name' => isset($productList[$new_pid]) ? $productList[$new_pid]['name'] : '',
  3576.                     'qty' => $product->getQty(),
  3577.                     'delivered' => $product->getDelivered(),
  3578.                     'unitTypeId' => $product->getUnitTypeId(),
  3579.                     'deliverable' => $product->getDeliverable(),
  3580.                     'balance' => $product->getBalance(),
  3581.                     'salesCodeRangeStr' => $product->getSalesCodeRange(),
  3582.                     'salesCodeRange' => $sales_code_range,
  3583.                     'sales_codes' => $sales_code_range,
  3584.                     'sales_price' => $product->getPrice(),
  3585.                     'purchase_price' => $product->getCurrentPurchasePrice()
  3586. //                        'delivered'=>$product->getDelivered(),
  3587.                 );
  3588.                 $sendData['productList'][] = $p_data;
  3589.             }
  3590.             //now package data
  3591.             if ($sendData) {
  3592.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3593.             }
  3594.             return new JsonResponse(array("success" => false));
  3595.         }
  3596.         return new JsonResponse(array("success" => false));
  3597.     }
  3598.     public function GetItemListForIrrAction(Request $request)
  3599.     {
  3600.         if ($request->isMethod('POST')) {
  3601.             $em $this->getDoctrine();
  3602.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3603.             );
  3604.             $Content = [];
  3605.             $Transport_data = [];
  3606.             $Lul_data = [];
  3607.             if ($request->request->get('srId') != '')
  3608.                 $find_array['salesReturnId'] = $request->request->get('srId');
  3609. //            if($request->request->get('warehouseId')!='')
  3610. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3611.             $QD $this->getDoctrine()
  3612.                 ->getRepository('ApplicationBundle\\Entity\\SalesReturnItem')
  3613.                 ->findBy(
  3614.                     $find_array,
  3615.                     array()
  3616.                 );
  3617. //            if($request->request->get('wareHouseId')!='')
  3618.             $sendData = array(
  3619.                 'productList' => [],
  3620.             );
  3621.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3622.             $pckg_item_cross_match_data = [];
  3623.             $unitList Inventory::UnitTypeList($em);
  3624.             foreach ($QD as $product) {
  3625.                 if (($product->getReceivedBalance()) <= && ($product->getReplacedBalance()) <= 0)
  3626.                     continue;
  3627.                 $DR_ITEM null;
  3628.                 $DR_TAGGED_CODES = [];
  3629.                 $DR_TAGGED_CODES_FOR_SELECTIZE = [];
  3630.                 $RESTRICT_RECEIVED_CODES_FLAG 0;
  3631.                 $sales_code_range = [];
  3632.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  3633.                     $sales_code_range json_decode($product->getReceivedCodeRange(), true512JSON_BIGINT_AS_STRING);
  3634.                 } else {
  3635.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  3636.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getReceivedCodeRange());
  3637.                     $sales_code_range json_decode($json_without_bigintstrue);
  3638.                 }
  3639.                 $DR_TAGGED_CODES $sales_code_range;
  3640.                 if (!empty($DR_TAGGED_CODES)) {
  3641.                     $RESTRICT_RECEIVED_CODES_FLAG 1;
  3642.                     foreach ($DR_TAGGED_CODES as $DTC) {
  3643.                         $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  3644.                             'value' => $DTC
  3645.                         );
  3646.                     }
  3647.                 }
  3648. //                if ($product->getTaggedDetailsId() != 0 && $product->getTaggedDetailsId() != null) {
  3649. //
  3650. //                    $DR_ITEM = $this->getDoctrine()
  3651. //                        ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3652. //                        ->findOneBy(
  3653. //                            array(
  3654. //                                'id' => $product->getTaggedDetailsId()
  3655. //                            ),
  3656. //                            array()
  3657. //                        );
  3658. //                    if ($DR_ITEM) {
  3659. //                        if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  3660. //
  3661. //                            $DR_TAGGED_CODES = json_decode($DR_ITEM->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  3662. //                        } else {
  3663. //
  3664. //                            $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  3665. //                            $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $DR_ITEM->getSalesCodeRange());
  3666. //                            $DR_TAGGED_CODES = json_decode($json_without_bigints, true);
  3667. //                        }
  3668. //
  3669. //                        if ($DR_TAGGED_CODES == null)
  3670. //                            $DR_TAGGED_CODES = [];
  3671. //                        if (!empty($DR_TAGGED_CODES)) {
  3672. //                            $RESTRICT_RECEIVED_CODES_FLAG = 1;
  3673. //                            foreach ($DR_TAGGED_CODES as $DTC) {
  3674. //                                $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  3675. //                                    'value' => $DTC
  3676. //                                );
  3677. //                            }
  3678. //                        }
  3679. //                    }
  3680. //                }
  3681.                 $p_data = array(
  3682.                     'details_id' => $product->getId(),
  3683.                     'receivedDrTaggedCodes' => $DR_TAGGED_CODES,
  3684.                     'receivedDrTaggedCodesStr' => implode(','$DR_TAGGED_CODES),
  3685.                     'receivedDrTaggedCodesForSel' => $DR_TAGGED_CODES_FOR_SELECTIZE,
  3686.                     'receivedRestrictCodesFlag' => $RESTRICT_RECEIVED_CODES_FLAG,
  3687.                     'receivedProductId' => $product->getReceivedProductId(),
  3688.                     'receivedBalance' => $product->getReceivedBalance(),
  3689.                     'receivedUnitSalesPrice' => $product->getReceivedUnitSalesPrice(),
  3690.                     'receivedUnitPurchasePrice' => $product->getReceivedUnitPurchasePrice(),
  3691.                     'receivedProductName' => isset($productList[$product->getReceivedProductId()]) ? $productList[$product->getReceivedProductId()]['name'] : '',
  3692.                     'replacedProductId' => $product->getReplacedProductId(),
  3693.                     'replacedBalance' => $product->getReplacedBalance(),
  3694.                     'replacedUnitSalesPrice' => $product->getReplacedUnitSalesPrice(),
  3695.                     'replacedUnitPurchasePrice' => $product->getReplacedUnitPurchasePrice(),
  3696.                     'replacedProductName' => isset($productList[$product->getReplacedProductId()]) ? $productList[$product->getReplacedProductId()]['name'] : '',
  3697.                     'disposeBalance' => $product->getDisposeBalance(),
  3698.                     'unusedBalance' => $product->getUnusedBalance(),
  3699.                     'disposeTag' => $product->getDisposeTag(),
  3700.                     'unitTypeId' => $product->getUnitTypeId(),
  3701. //                        'delivered'=>$product->getDelivered(),
  3702.                 );
  3703.                 $sendData['productList'][] = $p_data;
  3704.             }
  3705.             //now package data
  3706.             if ($sendData) {
  3707.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3708.             }
  3709.             return new JsonResponse(array("success" => false));
  3710.         }
  3711.         return new JsonResponse(array("success" => false));
  3712.     }
  3713.     public function LabelFormatAction(Request $request$id 0)
  3714.     {
  3715.         $data = array(
  3716.             'formatId' => '',
  3717.             'formatCode' => '',
  3718.             'name' => '',
  3719.             'labelType' => 0,
  3720.             'width' => 60,
  3721.             'pageWidth' => 6,
  3722.             'height' => 39,
  3723.             'pageHeight' => 2,
  3724.             'formatData' => '',
  3725.         );
  3726.         if ($request->isMethod('POST')) {
  3727.             $post $request->request;
  3728.             $exists_already 0;
  3729.             if ($request->request->get('formatId') != '') {
  3730.                 $query_here $this->getDoctrine()
  3731.                     ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  3732.                     ->findOneBy(
  3733.                         array(
  3734.                             'formatId' => $request->request->get('formatId')
  3735.                         )
  3736.                     );
  3737.                 if (!empty($query_here)) {
  3738.                     $exists_already 1;
  3739.                     $new $query_here;
  3740.                 } else
  3741.                     $new = new LabelFormat();
  3742.             } else
  3743.                 $new = new LabelFormat();
  3744.             $new->setName($request->request->get('name'));
  3745.             $new->setLabelType($request->request->get('labelType'));
  3746.             $new->setWidth($request->request->get('width'));
  3747.             $new->setHeight($request->request->get('height'));
  3748.             $new->setFormatCode($request->request->get('formatCode'));
  3749.             $new->setActive(GeneralConstant::ACTIVE);
  3750.             $new->setPageHeight($request->request->get('pageHeight'));
  3751.             $new->setPageWidth($request->request->get('pageWidth'));
  3752.             $new->setFormatData($request->request->get('formatData'));
  3753.             if ($exists_already == 0)
  3754.                 $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3755.             $new->setEditLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3756.             $new->setCompanyId($request->getSession()->get(UserConstants::USER_COMPANY_ID));
  3757.             $em $this->getDoctrine()->getManager();
  3758.             $em->persist($new);
  3759.             $em->flush();
  3760.         }
  3761.         if ($id != 0) {
  3762.             $query_here $this->getDoctrine()
  3763.                 ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  3764.                 ->findOneBy(
  3765.                     array(
  3766.                         'formatId' => $id
  3767.                     )
  3768.                 );
  3769.             if ($query_here)
  3770.                 $data $query_here;
  3771.         } else if ($request->query->has('formatId')) {
  3772.             $query_here $this->getDoctrine()
  3773.                 ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  3774.                 ->findOneBy(
  3775.                     array(
  3776.                         'formatId' => $request->query->get('formatId')
  3777.                     )
  3778.                 );
  3779.             if ($query_here)
  3780.                 $data $query_here;
  3781.         }
  3782.         return $this->render(
  3783.             '@Inventory/pages/input_forms/label_format.html.twig',
  3784.             array(
  3785.                 'page_title' => 'Label Format',
  3786.                 'data' => $data,
  3787.                 'labelTypeList' => LabelConstant::$label_type_list,
  3788.                 'labelFieldsList' => LabelConstant::$label_fields_list,
  3789.                 'formatList' => $this->getDoctrine()
  3790.                     ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  3791.                     ->findBy(
  3792.                         array( //                            'formatId' => $request->query->get('formatId')
  3793.                         )
  3794.                     )
  3795.                 //                'incomeLedgerHeads'=>Accounts::getChildLedgerHeads($this->getDoctrine()->getManager(),AccountsConstant::INCOME)
  3796.             )
  3797.         );
  3798.     }
  3799.     public function GetServiceListForScAction(Request $request)
  3800.     {
  3801.         if ($request->isMethod('POST')) {
  3802.             $em $this->getDoctrine();
  3803.             $find_array = array(
  3804.                 'type' => 2//service
  3805.             );
  3806.             $Content = [];
  3807.             $Transport_data = [];
  3808.             $Lul_data = [];
  3809.             if ($request->request->get('soId') != '')
  3810.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3811. //            if($request->request->get('warehouseId')!='')
  3812. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3813.             $QD $this->getDoctrine()
  3814.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  3815.                 ->findBy(
  3816.                     $find_array,
  3817.                     array()
  3818.                 );
  3819. //            if($request->request->get('wareHouseId')!='')
  3820.             $SO $this->getDoctrine()
  3821.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  3822.                 ->findOneBy(
  3823.                     array(
  3824.                         'salesOrderId' => $request->request->get('soId')
  3825.                     ),
  3826.                     array()
  3827.                 );
  3828.             $sendData = array(
  3829. //                'salesType'=>$SO->getSalesType(),
  3830. //                'packageData'=>[],
  3831.                 'productList' => [],
  3832. //                'productListByPackage'=>[],
  3833.             );
  3834.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager(), $SO->getCompanyId());
  3835.             $pckg_item_cross_match_data = [];
  3836.             foreach ($QD as $product) {
  3837.                 $p_data = array(
  3838.                     'details_id' => $product->getId(),
  3839.                     'service_id' => $product->getServiceId(),
  3840.                     'service_name' => $serviceList[$product->getServiceId()]['name'],
  3841.                     'available_inventory' => $product->getBalance(),
  3842. //                        'package_id'=>$product->getPackageId(),
  3843.                     'qty' => $product->getQty(),
  3844.                     'delivered' => $product->getDelivered(),
  3845. //                    'deliverable'=>$product->getDeliverable(),
  3846.                     'balance' => $product->getBalance(),
  3847. //                        'delivered'=>$product->getDelivered(),
  3848.                 );
  3849.                 $sendData['serviceList'][] = $p_data;
  3850.             }
  3851.             //now package data
  3852.             if ($sendData) {
  3853.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3854.             }
  3855.             return new JsonResponse(array("success" => false));
  3856.         }
  3857.         return new JsonResponse(array("success" => false));
  3858.     }
  3859.     public function CreateReceivedNoteAction(Request $request)
  3860.     {
  3861.         if ($request->isMethod('POST')) {
  3862.             $em $this->getDoctrine()->getManager();
  3863.             $entity_id array_flip(GeneralConstant::$Entity_list)['Grn']; //change
  3864.             $dochash $request->request->get('docHash'); //change
  3865.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3866.             $approveRole 1;  //created
  3867.             $approveHash $request->request->get('approvalHash');
  3868.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  3869.                 $loginId$approveRole$approveHash)
  3870.             ) {
  3871.                 $this->addFlash(
  3872.                     'error',
  3873.                     'Sorry Couldnot insert Data.'
  3874.                 );
  3875.             } else {
  3876.                 $data $request->request;
  3877.                 $grnId Inventory::CreateGrn($this->getDoctrine()->getManager(), $data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3878.                 //now add Approval info
  3879.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3880.                 $approveRole 1;  //created
  3881.                 $options = array(
  3882.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3883.                     'notification_server' => $this->container->getParameter('notification_server'),
  3884.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3885.                     'url' => $this->generateUrl(
  3886.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['Grn']]
  3887.                         ['entity_view_route_path_name']
  3888.                     )
  3889.                 );
  3890.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3891.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  3892.                     $grnId,
  3893.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3894.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['Grn'], $grnId,
  3895.                     $loginId,
  3896.                     $approveRole,
  3897.                     $request->request->get('approvalHash'));
  3898.                 $this->addFlash(
  3899.                     'success',
  3900.                     'New GRN Added.'
  3901.                 );
  3902.                 $url $this->generateUrl(
  3903.                     'view_grn'
  3904.                 );
  3905.                 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),
  3906.                     "Good Received Note : " $dochash " Has Been Created And is Under Processing",
  3907.                     'pos',
  3908.                     System::getPositionIdsByDepartment($em, [GeneralConstant::SALES_DEPARTMENTGeneralConstant::PURCHASE_DEPARTMENTGeneralConstant::ACCOUNTS_DEPARTMENTGeneralConstant::INVENTORY_DEPARTMENT]),
  3909.                     'success',
  3910.                     $url "/" $grnId,
  3911.                     "GRN"
  3912.                 );
  3913.                 return $this->redirect($url "/" $grnId);
  3914.             }
  3915.         }
  3916.         return $this->render('@Inventory/pages/input_forms/received_note.html.twig',
  3917.             array(
  3918.                 'page_title' => 'GRN',
  3919.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  3920.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  3921.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  3922.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  3923.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  3924.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  3925.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  3926.                 'material_inward' => $this->getDoctrine()
  3927.                     ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  3928.                     ->findBy(
  3929.                         array(
  3930.                             'stage' => GeneralConstant::STAGE_PENDING_TAG
  3931.                         )
  3932.                     )
  3933. //                'po'=>Inventory::getPurchaseOrderList
  3934.             )
  3935.         );
  3936.     }
  3937.     public function GetQcListForGrnAction(Request $request)
  3938.     {
  3939.         if ($request->isMethod('POST')) {
  3940.             $find_array = array(
  3941.                 'stage' => GeneralConstant::STAGE_PENDING_TAG
  3942.             );
  3943.             $Content = [];
  3944.             $ContentByProductId = [];
  3945.             $Transport_data = [];
  3946.             $Lul_data = [];
  3947.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  3948.             if ($request->request->get('poId') != '')
  3949.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  3950.             if ($request->request->get('warehouseId') != '')
  3951.                 $find_array['warehouseId'] = $request->request->get('warehouseId');
  3952.             $QD $this->getDoctrine()
  3953.                 ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  3954.                 ->findBy(
  3955.                     $find_array,
  3956.                     array(
  3957.                         'inwardDate' => 'ASC',
  3958.                         'qcDate' => 'ASC'
  3959.                     )
  3960.                 );
  3961.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  3962.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  3963.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3964.             $lotNumArray = [];
  3965.             foreach ($QD as $entry) {
  3966. //                $inwardDate=strtotime($entry->getInwardDate());
  3967. //                $qcDate=strtotime($entry->getQcDate());
  3968.                 $inwardDate = ($entry->getInwardDate() instanceof \DateTime) ? $entry->getInwardDate()->format('m/d/Y') : '';
  3969.                 $qcDate = ($entry->getQcDate() instanceof \DateTime) ? $entry->getQcDate()->format('m/d/Y') : '';
  3970.                 if (!in_array($entry->getLotNumber(), $lotNumArray))
  3971.                     $lotNumArray[] = $entry->getLotNumber();
  3972.                 if (isset($ContentByProductId[$entry->getPurchaseOrderItemId()])) {
  3973.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['inwardDateList'][] = $inwardDate;
  3974.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcDateList'][] = $inwardDate;
  3975.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcIdList'][] = $entry->getQcId();
  3976.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['appQtyList'][] = $entry->getApprovedQty();
  3977.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['totQty'] += ($entry->getApprovedQty());
  3978.                 } else {
  3979.                     $ContentByProductId[$entry->getPurchaseOrderItemId()] = array(
  3980.                         'productName' => $productList[$entry->getProductId()]['name'],
  3981.                         'productUnitName' => $unitList[$productList[$entry->getProductId()]['unit_type']]['name'],
  3982.                         'qcHash' => $entry->getDocumentHash(),
  3983.                         'warehouseName' => $warehouse[$entry->getWarehouseId()]['name'],
  3984.                         'inwardDate' => $inwardDate,
  3985.                         'inwardDateList' => [$inwardDate],
  3986.                         'qcDateList' => [$qcDate],
  3987.                         'qcIdList' => [$entry->getQcId()],
  3988.                         'qcDate' => $qcDate,
  3989.                         'poQty' => $entry->getPoQty(),
  3990.                         'poPrevbalance' => $entry->getPoBalance(),
  3991.                         'appQty' => $entry->getApprovedQty(),
  3992.                         'appQtyList' => [$entry->getApprovedQty()],
  3993.                         'totQty' => $entry->getApprovedQty(),
  3994.                         'poBalance' => $entry->getPoBalance() - $entry->getApprovedQty(),
  3995.                         'qcId' => $entry->getQcId(),
  3996.                         'productId' => $entry->getProductId()
  3997.                     );
  3998.                 }
  3999.                 $Expense_Cost[$entry->getQcId()] = json_decode($entry->getExpenseCost());
  4000.                 $Expense_Id[$entry->getQcId()] = json_decode($entry->getExpenseId());
  4001.             }
  4002.             foreach ($ContentByProductId as $c) {
  4003.                 $Content[] = $c;
  4004.             }
  4005.             if ($QD) {
  4006.                 return new JsonResponse(array("success" => true"content" => $Content"lotNumber" => implode(', '$lotNumArray), 'Expense_Cost' => $Expense_Cost'Expense_Id' => $Expense_Id));
  4007.             }
  4008.             return new JsonResponse(array("success" => false));
  4009.         }
  4010.         return new JsonResponse(array("success" => false));
  4011.     }
  4012.     public function GetSrListForIrAction(Request $request)
  4013.     {
  4014.         if ($request->isMethod('POST')) {
  4015.             $find_array = array();
  4016.             $Content = [];
  4017.             if ($request->request->get('srId') != '')
  4018.                 $find_array['stockRequisitionId'] = $request->request->get('srId');
  4019.             $find_array['forceSkipTag'] = [0null];
  4020.             $QD $this->getDoctrine()
  4021.                 ->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')
  4022.                 ->findBy(
  4023.                     $find_array
  4024.                 );
  4025.             $itemList Inventory::ItemGroupList($this->getDoctrine()->getManager());
  4026.             $catgoryList Inventory::ProductCategoryList($this->getDoctrine()->getManager());
  4027.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4028.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4029.             $fdmData = array();
  4030.             $em $this->getDoctrine()->getManager();
  4031.             $matchType 'MAXIMUM';
  4032.             if ($request->request->has('matchType') != '') {
  4033.                 $matchType $request->request->get('matchType');
  4034.             }
  4035.             if ($matchType == 'MINIMUM') {
  4036.                 foreach ($QD as $entry) {
  4037.                     if ($entry->getTagPendingAmount() <= 0)
  4038.                         continue;
  4039.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4040.                     $combined_id $entry->getProductFdm();
  4041.                     if (isset($fdmData[$combined_id])) {
  4042.                         $fdmData[$combined_id]['unit'] += $entry->getTagPendingAmount();
  4043.                         $fdmData[$combined_id]['specific_unit'][] = $entry->getTagPendingAmount();
  4044.                         $fdmData[$combined_id]['detailsIds'][] = $entry->getId();
  4045.                         $fdmData[$combined_id]['docIds'][] = $entry->getStockRequisitionId();
  4046.                     } else {
  4047.                         $fdmData[$combined_id] = array(
  4048.                             'id' => 0,
  4049.                             'alias' => $entry->getNote(),
  4050.                             'unit' => $entry->getTagPendingAmount(),
  4051.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4052.                             'warranty' => 0,
  4053.                             'unitTypeId' => 0,
  4054.                             'unit_price' => 0,
  4055.                             'fdm' => $combined_id,
  4056.                             'extDetailsId' => 0,
  4057.                             'product_name' => $productData['productName'],
  4058.                             'total_price' => 0,
  4059.                             'detailsIds' => [$entry->getId()],
  4060.                             'docIds' => [$entry->getStockRequisitionId()],
  4061.                         );
  4062.                     }
  4063.                 }
  4064.             }
  4065.             if ($matchType == 'MAXIMUM') {
  4066.                 foreach ($QD as $entry) {
  4067.                     if ($entry->getTagPendingAmount() <= 0)
  4068.                         continue;
  4069.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4070.                     $combined_id $entry->getProductFdm();
  4071.                     $assigned 0;
  4072.                     foreach ($fdmData as $key_ind => $rel_val) {
  4073.                         $matchFdm Inventory::MatchFdm($key_ind$combined_id);
  4074.                         if ($matchFdm['hasMatched'] == 1) {
  4075.                             if ($matchFdm['isIdentical'] == 1) {
  4076.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4077.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4078.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4079.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4080.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4081.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4082.                                 $assigned 1;
  4083.                             } elseif ($matchFdm['SecondBelongsToFirst'] == 1) {
  4084.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4085.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4086.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4087.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4088.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4089.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4090.                                 $assigned 1;
  4091.                             } elseif ($matchFdm['FirstBelongsToSecond'] == 1) {
  4092.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4093.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4094.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4095.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4096.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4097.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4098.                                 $fdmData[$combined_id] = $fdmData[$key_ind];
  4099.                                 unset($fdmData[$key_ind]);
  4100.                                 $assigned 1;
  4101.                             }
  4102.                         } else {
  4103.                         }
  4104.                         if ($assigned == 1)
  4105.                             break;
  4106.                     }
  4107.                     if ($assigned == 0) {
  4108.                         $fdmData[$combined_id] = array(
  4109.                             'id' => 0,
  4110.                             'alias' => $entry->getNote(),
  4111.                             'unit' => $entry->getTagPendingAmount(),
  4112.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4113.                             'specific_unit_type_id' => [$entry->getUnitTypeId()],
  4114.                             'warranty' => 0,
  4115.                             'unitTypeId' => $productData['unitTypeId'],
  4116. //                            'unitTypeId' => $productData['unitTypeId'],
  4117.                             'unit_price' => 0,
  4118.                             'fdm' => $combined_id,
  4119.                             'extDetailsId' => 0,
  4120.                             'product_name' => htmlspecialchars($productData['productName']),
  4121.                             'total_price' => 0,
  4122.                             'detailsIds' => [$entry->getId()],
  4123.                             'docIds' => [$entry->getStockRequisitionId()],
  4124.                         );
  4125.                     }
  4126.                     if (isset($fdmData[$combined_id])) {
  4127.                     } else {
  4128.                     }
  4129.                 }
  4130.             }
  4131.             $QD $this->getDoctrine()
  4132.                 ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  4133.                 ->findBy(
  4134.                     array('stockRequisitionId' => $request->request->get('srId'))
  4135.                 );
  4136.             $contentNote "";
  4137.             foreach ($QD as $r) {
  4138.                 $contentNote .= $r->getNote();
  4139.                 $contentNote .= " , ";
  4140.             }
  4141.             foreach ($fdmData as $dt) {
  4142.                 $Content[] = $dt;
  4143.             }
  4144.             if ($Content) {
  4145.                 return new JsonResponse(array("success" => true"content" => $Content"contentNote" => $contentNote));
  4146.             }
  4147.             return new JsonResponse(array("success" => false));
  4148.         }
  4149.         return new JsonResponse(array("success" => false));
  4150.     }
  4151.     public function GetGrnListForEiAction(Request $request)
  4152.     {
  4153.         if ($request->isMethod('POST')) {
  4154.             $find_array = array(
  4155.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  4156.                 'approved' => GeneralConstant::APPROVED,
  4157.                 'invoiceTagged' => 1
  4158.             );
  4159.             $Content = [];
  4160.             $Content_obj = [];
  4161.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4162.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4163.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4164.             if ($request->request->get('poId') != '')
  4165.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4166.             if ($request->request->get('grnId') != '')
  4167.                 $find_array['grnId'] = $request->request->get('grnId');
  4168.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4169.             $QD_GRN $this->getDoctrine()
  4170.                 ->getRepository('ApplicationBundle\\Entity\\Grn')
  4171.                 ->findBy(
  4172.                     $find_array,
  4173.                     array(
  4174.                         'grnDate' => 'ASC'
  4175.                     )
  4176.                 );
  4177.             $poId 0;
  4178. //
  4179. //            $expense_id=$QD_GRN->getExpenseId()!=''?json_decode($QD_GRN->getExpenseId()):[];
  4180. //                $expense_list=$QD_GRN->getExpenseCost()!=''?json_decode($QD_GRN->getExpenseCost()):[];
  4181. //                $expense_tagged=$QD_GRN->getExpenseTagged()!=''?json_decode($QD_GRN->getExpenseTagged()):[];
  4182.             $partyId $request->request->get('partyId');
  4183.             $bill_details = [];
  4184.             $bill_details_data = [];
  4185.             $bill_details_for_grn = [];
  4186.             $exp_list InventoryConstant::$Expense_list_details;
  4187.             $supp_list Inventory::ProductSupplierList($this->getDoctrine()->getManager());
  4188.             $head_qry $this->getDoctrine()
  4189.                 ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  4190.                 ->findAll();
  4191.             $head_list = [];
  4192.             $head_list_by_advance = [];
  4193.             foreach ($head_qry as $data) {
  4194.                 $head_list[$data->getAccountsHeadId()] = array(
  4195.                     'id' => $data->getAccountsHeadId(),
  4196.                     'name' => $data->getName(),
  4197.                     'advanceTagged' => $data->getAdvanceTagged(),
  4198.                     'advanceOf' => $data->getAdvanceOf(),
  4199.                     'balance' => $data->getCurrentBalance()
  4200.                 );
  4201.                 if ($data->getAdvanceOf() != null && $data->getAdvanceOf() != && $data->getAdvanceOf() != '')
  4202.                     $head_list_by_advance[$data->getAdvanceOf()] = array(
  4203.                         'id' => $data->getAccountsHeadId(),
  4204.                         'name' => $data->getName(),
  4205.                         'advanceTagged' => $data->getAdvanceTagged(),
  4206.                         'advanceOf' => $data->getAdvanceOf(),
  4207.                         'balance' => $data->getCurrentBalance()
  4208.                     );
  4209.             }
  4210.             $exp_def_head = [];
  4211.             foreach ($exp_list as $key => $item) {
  4212.                 $def_settings $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  4213.                     'name' => $item['name'] . '_onsite_head'
  4214.                 ));
  4215.                 if ($def_settings)
  4216.                     $exp_def_head[$item['id']] = $def_settings->getData();
  4217.                 else
  4218.                     $exp_def_head[$item['id']] = '';
  4219.             }
  4220.             $bill_details_by_party = [];
  4221. //            System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($QD_GRN),'debug_data');
  4222. //            System::log_it($this->container->getParameter('kernel.root_dir'),$partyId,'debug_data');
  4223. //            System::log_it($this->container->getParameter('kernel.root_dir'),"\nexp list here".json_encode($exp_list),'debug_data');
  4224. //
  4225.             foreach ($QD_GRN as $key => $value) {
  4226.                 $expense_id $value->getExpenseId() != '' json_decode($value->getExpenseId(), true) : [];
  4227.                 $expense_list $value->getExpenseCost() != '' json_decode($value->getExpenseCost(), true) : [];
  4228.                 $expense_tagged $value->getExpenseTagged() != '' json_decode($value->getExpenseTagged(), true) : [];
  4229. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_id),'debug_data');
  4230. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_list),'debug_data');
  4231.                 foreach ($exp_list as $chabi => $entry) {
  4232. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nChabi ".$chabi,'debug_data');
  4233. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nkeys are ".array_keys($expense_id),'debug_data');
  4234.                     if (array_key_exists($chabi$expense_id)) {
  4235. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nFOUND KEY!! ",'debug_data');
  4236.                         if ($partyId == ''//all
  4237.                         {
  4238.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  4239.                                 $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  4240.                                 $advance_balance 0;
  4241.                                 if ($partyHeadId != 0) {
  4242.                                     $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  4243.                                     $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  4244.                                     $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  4245.                                 }
  4246.                                 $bill_details_by_party[$my_val][] = array(
  4247.                                     'partyId' => $my_val,
  4248.                                     'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  4249.                                     'partyHeadId' => $partyHeadId,
  4250.                                     'expTypeId' => $chabi,
  4251.                                     'expTypeName' => $exp_list[$chabi]['name'],
  4252.                                     'expTypeAlias' => $exp_list[$chabi]['alias'],
  4253.                                     'expAmount' => $expense_list[$chabi][$index],
  4254.                                     'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  4255.                                     'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  4256.                                     'AdvanceBalance' => $advance_balance,
  4257.                                     'grnId' => $value->getGrnId(),
  4258.                                     'grnName' => $value->getDocumentHash(),
  4259.                                 );
  4260.                             }
  4261.                         } else {
  4262.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  4263.                                 if (in_array($my_val$partyId)) {
  4264.                                     $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  4265.                                     $advance_balance 0;
  4266.                                     if ($partyHeadId != 0) {
  4267.                                         $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  4268.                                         $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  4269.                                         $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  4270.                                     }
  4271.                                     $bill_details_by_party[$my_val][] = array(
  4272.                                         'partyId' => $my_val,
  4273.                                         'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  4274.                                         'partyHeadId' => $partyHeadId,
  4275.                                         'expTypeId' => $chabi,
  4276.                                         'expTypeName' => $exp_list[$chabi]['name'],
  4277.                                         'expTypeAlias' => $exp_list[$chabi]['alias'],
  4278.                                         'expAmount' => $expense_list[$chabi][$index],
  4279.                                         'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  4280.                                         'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  4281.                                         'AdvanceBalance' => $advance_balance,
  4282.                                         'grnId' => $value->getGrnId(),
  4283.                                         'grnName' => $value->getDocumentHash(),
  4284.                                     );
  4285.                                 }
  4286.                             }
  4287.                         }
  4288.                     }
  4289.                 }
  4290.             }
  4291. //            $Content_obj=
  4292. //
  4293. //            foreach($Content_obj as $item)
  4294. //            {
  4295. //                $Content[]=$item;
  4296. //
  4297. //            }
  4298.             $list_of_keys array_keys($bill_details_by_party);
  4299.             if ($bill_details_by_party) {
  4300.                 return new JsonResponse(array("success" => true"content" => $bill_details_by_party'index' => $list_of_keys'h_l_b_a' => $head_list_by_advance));
  4301.             }
  4302.             return new JsonResponse(array("success" => false));
  4303.         }
  4304.         return new JsonResponse(array("success" => false));
  4305.     }
  4306.     public function GetServiceListForPiAction(Request $request)
  4307.     {
  4308.         if ($request->isMethod('POST')) {
  4309. //            $find_array=array(
  4310. //                'stage' =>  GeneralConstant::STAGE_PENDING_TAG,
  4311. //                'approved'=>GeneralConstant::APPROVED
  4312. //            );
  4313.             $Content = [];
  4314.             $Content_obj = [];
  4315.             $ContentService = [];
  4316.             $Content_service_obj = [];
  4317. //            $warehouse=Inventory::WarehouseList($this->getDoctrine()->getManager());
  4318. //            $poList=Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4319. //            $productList=Inventory::ProductList($this->getDoctrine()->getManager());
  4320.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  4321.             if ($request->request->get('poId') != '')
  4322.                 $poId $request->request->get('poId');
  4323.             if ($request->request->get('grnId') != '')
  4324.                 $find_array['grnId'] = $request->request->get('grnId');
  4325.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4326.             //adding service data temporarily
  4327.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(
  4328.                 array('purchaseOrderId' => $poId));
  4329.             $multiply_type $po->getCurrencyMultiply();
  4330.             $multiply_rate $po->getCurrencyMultiplyRate();
  4331.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  4332.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  4333.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  4334.                 array('purchaseOrderId' => $poId));
  4335.             foreach ($po_items as $item) {
  4336. //                $po_item_list[$item->getProductId()]=$item;
  4337.                 //temporary service add
  4338.                 if ($item->getType() == 2)
  4339.                     $Content_service_obj[$item->getId()] = array(
  4340.                         'serviceId' => $item->getServiceId(),
  4341.                         'poItemId' => $item->getId(),
  4342.                         'colorId' => 0,
  4343.                         'sizeId' => 0,
  4344.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  4345.                         'qty' => $item->getQty(),
  4346.                         'balance' => $item->getBalance(),
  4347.                         'unit_name' => '',
  4348.                         'unit_price' => $item->getPrice() * $multiplier,
  4349.                         'grn_id' => 0,
  4350.                     );
  4351.                 //temprary service add end
  4352.             }
  4353.             //temporary service data adding done
  4354.             $po_data = [];
  4355.             $po_data = array(
  4356.                 'docHash' => $po->getDocumentHash(),
  4357.                 'docDate' => $po->getPurchaseOrderDate(),
  4358.                 'supplierId' => $po->getSupplierId(),
  4359.                 'supplierName' => $po->getSupplierId(),
  4360.                 'vatRate' => $po->getVatRate(),
  4361.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  4362.                 'aitRate' => $po->getAitRate(),
  4363.                 'aitAmount' => $po->getAitAmount(),
  4364.                 'tdsRate' => $po->getTdsRate(),
  4365.                 'tdsAmount' => $po->getTdsAmount(),
  4366.                 'vdsRate' => $po->getVdsRate(),
  4367.                 'vdsAmount' => $po->getVdsAmount(),
  4368.                 'discountRate' => $po->getDiscountRate(),
  4369.                 'discountAmount' => $po->getVatAmount(),
  4370.             );
  4371.             foreach ($Content_obj as $item) {
  4372.                 $Content[] = $item;
  4373.             }
  4374.             foreach ($Content_service_obj as $item) {
  4375.                 $ContentService[] = $item;
  4376.             }
  4377.             if ($Content || $ContentService) {
  4378.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  4379.             }
  4380.             return new JsonResponse(array("success" => false));
  4381.         }
  4382.         return new JsonResponse(array("success" => false));
  4383.     }
  4384.     public function GetGrnListForPiAction(Request $request)
  4385.     {
  4386.         if ($request->isMethod('POST')) {
  4387.             $find_array = array(
  4388.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  4389.                 'approved' => GeneralConstant::APPROVED
  4390.             );
  4391.             $Content = [];
  4392.             $Content_obj = [];
  4393.             $ContentService = [];
  4394.             $Content_service_obj = [];
  4395.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4396.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4397.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4398.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  4399.             if ($request->request->get('poId') != '')
  4400.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4401.             if ($request->request->get('grnId') != '')
  4402.                 $find_array['grnId'] = $request->request->get('grnId');
  4403.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4404.             $QD_GRN $this->getDoctrine()
  4405.                 ->getRepository('ApplicationBundle\\Entity\\Grn')
  4406.                 ->findBy(
  4407.                     $find_array,
  4408.                     array(
  4409.                         'grnDate' => 'ASC'
  4410.                     )
  4411.                 );
  4412.             $poId 0;
  4413.             foreach ($QD_GRN as $value) {
  4414.                 $grn_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\GrnItem')->findBy(
  4415.                     array('grnId' => $value->getGrnId()));
  4416.                 $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  4417.                     array('purchaseOrderId' => $value->getPurchaseOrderId()));
  4418.                 $poId $value->getPurchaseOrderId();
  4419.                 $po_item_list = [];
  4420.                 foreach ($po_items as $item) {
  4421.                     $po_item_list[$item->getProductId()] = $item;
  4422.                 }
  4423.                 foreach ($grn_items as $entry) {
  4424.                     //adding transaction
  4425. //                    System::log_it($this->container->getParameter('kernel.root_dir'),$entry->getProductId(),'debug_data');
  4426.                     $Content_obj[$entry->getId()] = array(
  4427.                         'productId' => $entry->getProductId(),
  4428.                         'poItemId' => $entry->getPurchaseOrderItemId(),
  4429.                         'productName' => $productList[$entry->getProductId()]['name'],
  4430.                         'colorId' => $entry->getColorId(),
  4431.                         'sizeId' => $entry->getSizeId(),
  4432.                         'qty' => isset($Content_obj[$entry->getId()]) ? $Content_obj[$entry->getId()]['qty'] + $entry->getQty() : $entry->getQty(),
  4433.                         'unit_name' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  4434. //                            'unit_price'=>$po_item_list[$entry->getProductId()]->getPrice(),
  4435.                         'unit_price' => $entry->getPrice(),
  4436.                         'grn_id' => $entry->getId(),
  4437.                     );
  4438.                 }
  4439. //            for
  4440.             }
  4441.             //adding service data temporarily
  4442.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(
  4443.                 array('purchaseOrderId' => $poId));
  4444.             $multiply_type $po->getCurrencyMultiply();
  4445.             $multiply_rate $po->getCurrencyMultiplyRate();
  4446.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  4447.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  4448.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  4449.                 array('purchaseOrderId' => $poId));
  4450.             foreach ($po_items as $item) {
  4451. //                $po_item_list[$item->getProductId()]=$item;
  4452.                 //temporary service add
  4453.                 if ($item->getType() == 2)
  4454.                     $Content_service_obj[$item->getId()] = array(
  4455.                         'serviceId' => $item->getServiceId(),
  4456.                         'poItemId' => $item->getId(),
  4457.                         'colorId' => 0,
  4458.                         'sizeId' => 0,
  4459.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  4460.                         'qty' => $item->getQty(),
  4461.                         'balance' => $item->getBalance(),
  4462.                         'unit_name' => '',
  4463.                         'unit_price' => $item->getPrice() * $multiplier,
  4464.                         'grn_id' => 0,
  4465.                     );
  4466.                 //temprary service add end
  4467.             }
  4468.             //temporary service data adding done
  4469.             $po_data = [];
  4470.             $vatAmount 1*$po->getVatAmount();
  4471.             $priceAfterDiscount $po->getSupplierPayableAmount() - $po->getVatAmount();
  4472.             $vatRate = ($vatAmount/$priceAfterDiscount)*100;
  4473.             $po_data = array(
  4474.                 'docHash' => $po->getDocumentHash(),
  4475.                 'docDate' => $po->getPurchaseOrderDate(),
  4476.                 'supplierId' => $po->getSupplierId(),
  4477.                 'supplierName' => $po->getSupplierId(),
  4478.                 'vatRate' => $vatRate,
  4479.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  4480.                 'aitRate' => $po->getAitRate(),
  4481.                 'aitAmount' => $po->getAitAmount(),
  4482.                 'tdsRate' => $po->getTdsRate(),
  4483.                 'tdsAmount' => $po->getTdsAmount(),
  4484.                 'vdsRate' => $po->getVdsRate(),
  4485.                 'vdsAmount' => $po->getVdsAmount(),
  4486.                 'discountRate' => $po->getDiscountRate(),
  4487. //                'discountAmount' => $po->getVatAmount(),
  4488.                 'vatAmount' => $vatAmount,
  4489.                 'discountAmount' => $po->getDiscountAmount(),
  4490.                 'supplierPayableAmount'=> $po->getSupplierPayableAmount(),
  4491.                 'priceAfterDiscount' =>  $priceAfterDiscount
  4492.             );
  4493.             foreach ($Content_obj as $item) {
  4494.                 $Content[] = $item;
  4495.             }
  4496.             foreach ($Content_service_obj as $item) {
  4497.                 $ContentService[] = $item;
  4498.             }
  4499.             if ($Content) {
  4500.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  4501.             }
  4502.             return new JsonResponse(array("success" => false));
  4503.         }
  4504.         return new JsonResponse(array("success" => false));
  4505.     }
  4506.     public function GetPoDetailsForPiAction(Request $request$poId)
  4507.     {
  4508.     }
  4509.     public function GetPoDetailsAction(Request $request$poId)
  4510.     {
  4511.         if ($request->isMethod('POST')) {
  4512.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findBy(
  4513.                 array('purchaseOrderId' => $poId));
  4514.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  4515.                 array('purchaseOrderId' => $poId));
  4516.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4517.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4518.             $Content = [];
  4519.             $po_items_list = [];
  4520.             foreach ($po_items as $entry) {
  4521.                 $po_items_list[] = array(
  4522.                     'productId' => $entry->getProductId(),
  4523.                     'productName' => $productList[$entry->getProductId()]['name'],
  4524.                     'price' => $entry->getPrice(),
  4525.                     'unit' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  4526.                     'received' => $entry->getReceived(),
  4527.                     'qty' => $entry->getQty(),
  4528.                     'balance' => $entry->getBalance()
  4529.                 );
  4530.             }
  4531.             $po_data = [];
  4532.             $po_data = array(
  4533.                 'docHash' => $po->getDocumentHash(),
  4534.                 'docDate' => $po->getPurchaseOrderDate(),
  4535.                 'supplierId' => $po->getSupplierId(),
  4536.                 'supplierName' => $po->getSupplierId(),
  4537.             );
  4538.             if ($po_data) {
  4539.                 return new JsonResponse(array("success" => true"content" => $po_data));
  4540.             }
  4541.             return new JsonResponse(array("success" => false));
  4542.         }
  4543.         return new JsonResponse(array("success" => false));
  4544.     }
  4545.     public function CreateSalesReplacementAction(Request $request)
  4546.     {
  4547.         $em $this->getDoctrine()->getManager();
  4548.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4549.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4550.         if ($request->isMethod('POST')) {
  4551.             $em $this->getDoctrine()->getManager();
  4552.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesReplacement']; //change
  4553.             $dochash $request->request->get('voucherNumber'); //change
  4554.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4555.             $approveRole $request->request->get('approvalRole');
  4556.             $approveHash $request->request->get('approvalHash');
  4557.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4558.                 $loginId$approveRole$approveHash)
  4559.             ) {
  4560.                 $this->addFlash(
  4561.                     'error',
  4562.                     'Sorry Couldnot insert Data.'
  4563.                 );
  4564.             } else {
  4565.                 if ($request->request->has('check_allowed'))
  4566.                     $check_allowed 1;
  4567.                 $StID Inventory::CreateNewSalesReplacement(
  4568.                     $this->getDoctrine()->getManager(),
  4569.                     $request->request,
  4570.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  4571.                     $this->getLoggedUserCompanyId($request)
  4572.                 );
  4573.                 //now add Approval info
  4574.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4575.                 $approveRole 1;  //created
  4576.                 $options = array(
  4577.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4578.                     'notification_server' => $this->container->getParameter('notification_server'),
  4579.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4580.                     'url' => $this->generateUrl(
  4581.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesReplacement']]
  4582.                         ['entity_view_route_path_name']
  4583.                     )
  4584.                 );
  4585.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4586.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4587.                     $StID,
  4588.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  4589.                 );
  4590.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesReplacement'], $StID,
  4591.                     $loginId,
  4592.                     $approveRole,
  4593.                     $request->request->get('approvalHash'));
  4594.                 $this->addFlash(
  4595.                     'success',
  4596.                     'Stock Transfer Added.'
  4597.                 );
  4598.                 $url $this->generateUrl(
  4599.                     'view_st'
  4600.                 );
  4601.                 return $this->redirect($url "/" $StID);
  4602.             }
  4603.         }
  4604.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  4605.             array(
  4606.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  4607.             )
  4608.         );
  4609.         $INVLIST = [];
  4610.         foreach ($slotList as $slot) {
  4611.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  4612.         }
  4613.         return $this->render('@Inventory/pages/input_forms/sales_replacement.html.twig',
  4614.             array(
  4615.                 'page_title' => 'Sales Replacement Note',
  4616.                 'warehouseList' => Inventory::WarehouseList($em),
  4617.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  4618.                 'warehouseActionList' => $warehouse_action_list,
  4619.                 'warehouseActionListArray' => $warehouse_action_list_array,
  4620.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  4621.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  4622.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  4623.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  4624.                 'prefix_list' => array(
  4625.                     [
  4626.                         'id' => 1,
  4627.                         'value' => 'GN',
  4628.                         'text' => 'GN'
  4629.                     ]
  4630.                 ),
  4631.                 'assoc_list' => array(
  4632.                     [
  4633.                         'id' => 1,
  4634.                         'value' => 1,
  4635.                         'text' => 'GN'
  4636.                     ]
  4637.                 ),
  4638.                 'INVLIST' => $INVLIST
  4639.             )
  4640.         );
  4641.     }
  4642.     public function SalesReplacementListAction(Request $request)
  4643.     {
  4644.         $q $this->getDoctrine()
  4645.             ->getRepository('ApplicationBundle\\Entity\\SalesReplacement')
  4646.             ->findBy(
  4647.                 array(
  4648.                     'status' => GeneralConstant::ACTIVE,
  4649.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  4650. //                    'approved' =>  GeneralConstant::APPROVED,
  4651.                 )
  4652.             );
  4653.         $stage_list = array(
  4654.             => 'Pending',
  4655.             => 'Pending',
  4656.             => 'Complete',
  4657.             => 'Partial',
  4658.         );
  4659.         $data = [];
  4660.         foreach ($q as $entry) {
  4661.             $data[] = array(
  4662.                 'doc_date' => $entry->getSalesReplacementDate(),
  4663.                 'id' => $entry->getSalesReplacementId(),
  4664.                 'doc_hash' => $entry->getDocumentHash(),
  4665.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  4666.                 'stage' => $stage_list[$entry->getStage()]
  4667.             );
  4668.         }
  4669.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  4670.             array(
  4671.                 'page_title' => 'Stock Transfer List',
  4672.                 'data' => $data
  4673.             )
  4674.         );
  4675.     }
  4676.     public function ViewSalesReplacementAction(Request $request$id)
  4677.     {
  4678.         $em $this->getDoctrine()->getManager();
  4679.         $dt Inventory::GetSalesReplacementDetails($em$id);
  4680.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  4681.             array(
  4682.                 'page_title' => 'Stock Transfer',
  4683.                 'data' => $dt,
  4684.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4685.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  4686.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  4687.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4688.                     $id,
  4689.                     $dt['created_by'],
  4690.                     $dt['edited_by'])
  4691.             )
  4692.         );
  4693.     }
  4694.     public function PrintSalesReplacementAction(Request $request$id)
  4695.     {
  4696.         $em $this->getDoctrine()->getManager();
  4697.         $dt Inventory::GetSalesReplacementDetails($em$id);
  4698.         $company_data Company::getCompanyData($em1);
  4699.         $document_mark = array(
  4700.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4701.             'copy' => ''
  4702.         );
  4703.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  4704.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  4705.                 array(
  4706.                     //full array here
  4707.                     'pdf' => true,
  4708.                     'page_title' => 'Stock Transfer',
  4709.                     'export' => 'pdf,print',
  4710.                     'data' => $dt,
  4711.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4712.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  4713.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  4714.                         array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4715.                         $id,
  4716.                         $dt['created_by'],
  4717.                         $dt['edited_by']),
  4718.                     'document_mark_image' => $document_mark['original'],
  4719.                     'company_name' => $company_data->getName(),
  4720.                     'company_data' => $company_data,
  4721.                     'company_address' => $company_data->getAddress(),
  4722.                     'company_image' => $company_data->getImage(),
  4723.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  4724.                     'red' => 0
  4725.                 )
  4726.             );
  4727.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  4728. //                'orientation' => 'landscape',
  4729. //                'enable-javascript' => true,
  4730. //                'javascript-delay' => 1000,
  4731.                 'no-stop-slow-scripts' => false,
  4732.                 'no-background' => false,
  4733.                 'lowquality' => false,
  4734.                 'encoding' => 'utf-8',
  4735. //            'images' => true,
  4736. //            'cookie' => array(),
  4737.                 'dpi' => 300,
  4738.                 'image-dpi' => 300,
  4739. //                'enable-external-links' => true,
  4740. //                'enable-internal-links' => true
  4741.             ));
  4742.             return new Response(
  4743.                 $pdf_response,
  4744.                 200,
  4745.                 array(
  4746.                     'Content-Type' => 'application/pdf',
  4747.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  4748.                 )
  4749.             );
  4750.         }
  4751.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  4752.             array(
  4753.                 'page_title' => 'Stock Transfer',
  4754.                 'export' => 'pdf,print',
  4755.                 'data' => $dt,
  4756.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4757.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  4758.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  4759.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4760.                     $id,
  4761.                     $dt['created_by'],
  4762.                     $dt['edited_by']),
  4763.                 'document_mark_image' => $document_mark['original'],
  4764.                 'company_name' => $company_data->getName(),
  4765.                 'company_data' => $company_data,
  4766.                 'company_address' => $company_data->getAddress(),
  4767.                 'company_image' => $company_data->getImage(),
  4768.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  4769.                 'red' => 0
  4770.             )
  4771.         );
  4772.     }
  4773.     public function CreateStockTransferAction(Request $request)
  4774.     {
  4775.         $em $this->getDoctrine()->getManager();
  4776.         $companyId $this->getLoggedUserCompanyId($request);
  4777.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4778.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4779.         if ($request->isMethod('POST')) {
  4780.             $em $this->getDoctrine()->getManager();
  4781.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  4782.             $dochash $request->request->get('docHash'); //change
  4783.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4784.             $approveRole $request->request->get('approvalRole');
  4785.             $approveHash $request->request->get('approvalHash');
  4786.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4787.                 $loginId$approveRole$approveHash)
  4788.             ) {
  4789.                 $this->addFlash(
  4790.                     'error',
  4791.                     'Sorry Could Not insert Data.'
  4792.                 );
  4793.             } else {
  4794.                 if ($request->request->has('check_allowed'))
  4795.                     $check_allowed 1;
  4796.                 $StID Inventory::CreateNewStockTransfer(
  4797.                     $this->getDoctrine()->getManager(),
  4798.                     $request->request,
  4799.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  4800.                     $this->getLoggedUserCompanyId($request)
  4801.                 );
  4802.                 //now add Approval info
  4803.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4804.                 $approveRole 1;  //created
  4805.                 $options = array(
  4806.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4807.                     'notification_server' => $this->container->getParameter('notification_server'),
  4808.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4809.                     'url' => $this->generateUrl(
  4810.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  4811.                         ['entity_view_route_path_name']
  4812.                     )
  4813.                 );
  4814.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4815.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  4816.                     $StID,
  4817.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  4818.                 );
  4819.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  4820.                     $loginId,
  4821.                     $approveRole,
  4822.                     $request->request->get('approvalHash'));
  4823.                 $this->addFlash(
  4824.                     'success',
  4825.                     'Stock Transfer Added.'
  4826.                 );
  4827.                 $url $this->generateUrl(
  4828.                     'view_st'
  4829.                 );
  4830.                 return $this->redirect($url "/" $StID);
  4831.             }
  4832.         }
  4833.         $INVLIST = [];
  4834.         return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  4835.             array(
  4836.                 'page_title' => 'Stock Transfer Note',
  4837.                 'warehouseList' => Inventory::WarehouseList($em),
  4838.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  4839.                 'colorList' => Inventory::GetColorList($em),
  4840.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  4841.                 'srList' => [],
  4842.                 'warehouseActionList' => $warehouse_action_list,
  4843.                 'warehouseActionListArray' => $warehouse_action_list_array,
  4844.                 'item_list' => Inventory::ItemGroupList($em),
  4845.                 'item_list_array' => Inventory::ItemGroupListArray($em),
  4846.                 'category_list_array' => Inventory::ProductCategoryListArray($em),
  4847.                 'product_list_array' => Inventory::ProductListDetailedArray($em),
  4848. //                'product_list_array' => [],
  4849.                 'product_list' => Inventory::ProductList($em$companyId),
  4850. //                'product_list' => [],
  4851.                 'prefix_list' => array(
  4852.                     [
  4853.                         'id' => 1,
  4854.                         'value' => 'GN',
  4855.                         'text' => 'GN'
  4856.                     ]
  4857.                 ),
  4858.                 'assoc_list' => array(
  4859.                     [
  4860.                         'id' => 1,
  4861.                         'value' => 1,
  4862.                         'text' => 'GN'
  4863.                     ]
  4864.                 ),
  4865.                 'INVLIST' => $INVLIST
  4866.             )
  4867.         );
  4868.     }
  4869.     public function GetSrItemForTransferAction(Request $request)
  4870.     {
  4871.         $em $this->getDoctrine()->getManager();
  4872.         $search_query = [];
  4873.         $res_data_by_so_item_id = [];
  4874.         $Content = [];
  4875.         $productionProcessSettings = array(
  4876.             'id' => 0
  4877.         );
  4878.         if ($request->query->has('srId'))
  4879.             $search_query['stockRequisitionId'] = $request->query->get('srId');
  4880.         $DT $this->getDoctrine()
  4881.             ->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')
  4882.             ->findBy(
  4883.                 $search_query
  4884.             );
  4885.         $Content = array(
  4886.             'requisitioned_product_item_id' => [],
  4887.             'requisitioned_products' => [],
  4888.             'requisitioned_product_fdm' => [],
  4889.             'requisitioned_product_name' => [],
  4890.             'requisitioned_product_units' => [],
  4891.             'requisitioned_product_unit_type' => [],
  4892.             'requisitioned_product_balance' => [],
  4893.         );
  4894.         foreach ($DT as $dt) {
  4895. //            $data=json_decode($DT->getData(),true);
  4896.             $Content['requisitioned_products'][] = $dt->getProductId();
  4897.             $Content['requisitioned_product_item_id'][] = $dt->getId();
  4898.             $Content['requisitioned_product_fdm'][] = $dt->getProductFdm();
  4899.             $Content['requisitioned_product_name'][] = $dt->getProductNameFdm();
  4900.             $Content['requisitioned_product_units'][] = $dt->getQty();
  4901.             $Content['requisitioned_product_balance'][] = $dt->getAlottmentPendingAmount();
  4902.         }
  4903.         $INVLIST = [];
  4904.         if (!empty($Content)) {
  4905.             return new JsonResponse(array("success" => true"content" => $Content"INVLIST" => $INVLIST));
  4906.         } else {
  4907.             return new JsonResponse(array("success" => false"content" => $Content"INVLIST" => $INVLIST));
  4908.         }
  4909.     }
  4910.     public function StockTransferListAction(Request $request)
  4911.     {
  4912.         $q $this->getDoctrine()
  4913.             ->getRepository('ApplicationBundle\\Entity\\StockTransfer')
  4914.             ->findBy(
  4915.                 array(
  4916.                     'status' => GeneralConstant::ACTIVE,
  4917.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  4918. //                    'approved' =>  GeneralConstant::APPROVED,
  4919.                 )
  4920.             );
  4921.         $stage_list = array(
  4922.             => 'Pending',
  4923.             => 'Pending',
  4924.             => 'Complete',
  4925.             => 'Partial',
  4926.         );
  4927.         $data = [];
  4928.         foreach ($q as $entry) {
  4929.             $data[] = array(
  4930.                 'doc_date' => $entry->getStockTransferDate(),
  4931.                 'id' => $entry->getStockTransferId(),
  4932.                 'doc_hash' => $entry->getDocumentHash(),
  4933.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  4934.                 'stage' => $stage_list[$entry->getStage()]
  4935.             );
  4936.         }
  4937.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  4938.             array(
  4939.                 'page_title' => 'Stock Transfer List',
  4940.                 'data' => $data
  4941.             )
  4942.         );
  4943.     }
  4944.     public function ViewStockTransferAction(Request $request$id)
  4945.     {
  4946.         $em $this->getDoctrine()->getManager();
  4947.         $dt Inventory::GetStockTransferDetails($em$id);
  4948.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  4949.             array(
  4950.                 'page_title' => 'Stock Transfer',
  4951.                 'data' => $dt,
  4952.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  4953.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  4954.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  4955.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  4956.                     $id,
  4957.                     $dt['created_by'],
  4958.                     $dt['edited_by'])
  4959.             )
  4960.         );
  4961.     }
  4962.     public function PrintStockTransferAction(Request $request$id)
  4963.     {
  4964.         $em $this->getDoctrine()->getManager();
  4965.         $dt Inventory::GetStockTransferDetails($em$id);
  4966.         $company_data Company::getCompanyData($em1);
  4967.         $document_mark = array(
  4968.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4969.             'copy' => ''
  4970.         );
  4971.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  4972.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  4973.                 array(
  4974.                     //full array here
  4975.                     'pdf' => true,
  4976.                     'page_title' => 'Stock Transfer',
  4977.                     'export' => 'pdf,print',
  4978.                     'data' => $dt,
  4979.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  4980.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  4981.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  4982.                         array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  4983.                         $id,
  4984.                         $dt['created_by'],
  4985.                         $dt['edited_by']),
  4986.                     'document_mark_image' => $document_mark['original'],
  4987.                     'company_name' => $company_data->getName(),
  4988.                     'company_data' => $company_data,
  4989.                     'company_address' => $company_data->getAddress(),
  4990.                     'company_image' => $company_data->getImage(),
  4991.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  4992.                     'red' => 0
  4993.                 )
  4994.             );
  4995.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  4996. //                'orientation' => 'landscape',
  4997. //                'enable-javascript' => true,
  4998. //                'javascript-delay' => 1000,
  4999.                 'no-stop-slow-scripts' => false,
  5000.                 'no-background' => false,
  5001.                 'lowquality' => false,
  5002.                 'encoding' => 'utf-8',
  5003. //            'images' => true,
  5004. //            'cookie' => array(),
  5005.                 'dpi' => 300,
  5006.                 'image-dpi' => 300,
  5007. //                'enable-external-links' => true,
  5008. //                'enable-internal-links' => true
  5009.             ));
  5010.             return new Response(
  5011.                 $pdf_response,
  5012.                 200,
  5013.                 array(
  5014.                     'Content-Type' => 'application/pdf',
  5015.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5016.                 )
  5017.             );
  5018.         }
  5019.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5020.             array(
  5021.                 'page_title' => 'Stock Transfer',
  5022.                 'export' => 'pdf,print',
  5023.                 'data' => $dt,
  5024.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5025.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5026.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5027.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5028.                     $id,
  5029.                     $dt['created_by'],
  5030.                     $dt['edited_by']),
  5031.                 'document_mark_image' => $document_mark['original'],
  5032.                 'company_name' => $company_data->getName(),
  5033.                 'company_data' => $company_data,
  5034.                 'company_address' => $company_data->getAddress(),
  5035.                 'company_image' => $company_data->getImage(),
  5036.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5037.                 'red' => 0
  5038.             )
  5039.         );
  5040.     }
  5041.     public function CreateStockConsumptionNoteAction(Request $request)
  5042.     {
  5043.         $em $this->getDoctrine()->getManager();
  5044.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5045.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5046.         if ($request->isMethod('POST')) {
  5047.             $em $this->getDoctrine()->getManager();
  5048.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']; //change
  5049.             $dochash $request->request->get('voucherNumber'); //change
  5050.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5051.             $approveRole $request->request->get('approvalRole');
  5052.             $approveHash $request->request->get('approvalHash');
  5053.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5054.                 $loginId$approveRole$approveHash)
  5055.             ) {
  5056.                 $this->addFlash(
  5057.                     'error',
  5058.                     'Sorry Could not insert Data.'
  5059.                 );
  5060.             } else {
  5061.                 if ($request->request->has('check_allowed'))
  5062.                     $check_allowed 1;
  5063.                 $StID Inventory::CreateNewStockConsumptionNote(
  5064.                     $this->getDoctrine()->getManager(),
  5065.                     $request->request,
  5066.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5067.                     $this->getLoggedUserCompanyId($request)
  5068.                 );
  5069.                 //now add Approval info
  5070.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5071.                 $approveRole 1;  //created
  5072.                 $options = array(
  5073.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5074.                     'notification_server' => $this->container->getParameter('notification_server'),
  5075.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5076.                     'url' => $this->generateUrl(
  5077.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']]
  5078.                         ['entity_view_route_path_name']
  5079.                     )
  5080.                 );
  5081.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5082.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5083.                     $StID,
  5084.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5085.                 );
  5086.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'], $StID,
  5087.                     $loginId,
  5088.                     $approveRole,
  5089.                     $request->request->get('approvalHash'));
  5090.                 $this->addFlash(
  5091.                     'success',
  5092.                     'Stock Consumption Added.'
  5093.                 );
  5094.                 $url $this->generateUrl(
  5095.                     'view_stock_consumption_note'
  5096.                 );
  5097.                 return $this->redirect($url "/" $StID);
  5098.             }
  5099.         }
  5100.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  5101.             array(
  5102.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5103.             )
  5104.         );
  5105.         $INVLIST = [];
  5106.         foreach ($slotList as $slot) {
  5107.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5108.         }
  5109.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  5110.             array(
  5111.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5112.             )
  5113.         );
  5114.         $consumptionTypeList = [];
  5115.         $consumptionTypeListArray = [];
  5116.         foreach ($consumptionTypeQry as $entry) {
  5117.             $p = array(
  5118.                 'name' => $entry->getName(),
  5119.                 'id' => $entry->getConsumptionTypeId(),
  5120.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5121.                 'cost_center_id' => $entry->getCostCenterId(),
  5122.             );
  5123.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5124.             $consumptionTypeListArray[] = $p;
  5125.         }
  5126.         //add bill list
  5127.         $service_purchase_bill_query $this->getDoctrine()
  5128.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  5129.             ->findBy(
  5130.                 array(
  5131.                     'typeHash' => 'SPB',
  5132.                     'approved' => GeneralConstant::APPROVED
  5133.                 )
  5134.             );
  5135.         $service_purchase_bill_list = [];
  5136.         $service_purchase_bill_list_array = [];
  5137.         $bill = array(
  5138.             'id' => 0,
  5139.             'type' => 'SPB',
  5140.             'name' => 'New Expense',
  5141.             'text' => 'New Expense',
  5142.             'amount' => 0,
  5143.         );
  5144.         $service_purchase_bill_list[0] = $bill;
  5145.         $service_purchase_bill_list_array[] = $bill;
  5146.         foreach ($service_purchase_bill_query as $d) {
  5147.             $bill = array(
  5148.                 'id' => $d->getPurchaseInvoiceId(),
  5149.                 'type' => 'SPB',
  5150.                 'name' => $d->getDocumentHash(),
  5151.                 'text' => $d->getDocumentHash(),
  5152.                 'amount' => $d->getInvoiceAmount(),
  5153.             );
  5154.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5155.             $service_purchase_bill_list_array[] = $bill;
  5156.         }
  5157.         return $this->render('@Inventory/pages/input_forms/stock_consumption_note.html.twig',
  5158.             array(
  5159.                 'page_title' => 'Stock Consumption Note',
  5160.                 'warehouseList' => Inventory::WarehouseList($em),
  5161.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5162.                 'consumptionTypeList' => $consumptionTypeList,
  5163.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5164.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5165.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5166.                 'warehouseActionList' => $warehouse_action_list,
  5167.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5168.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5169.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5170.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5171.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5172.                 'product_list' => Inventory::ProductListDetailed($this->getDoctrine()->getManager()),
  5173.                 'prefix_list' => array(
  5174.                     [
  5175.                         'id' => 1,
  5176.                         'value' => 'GN',
  5177.                         'text' => 'GN'
  5178.                     ]
  5179.                 ),
  5180.                 'assoc_list' => array(
  5181.                     [
  5182.                         'id' => 1,
  5183.                         'value' => 1,
  5184.                         'text' => 'GN'
  5185.                     ]
  5186.                 ),
  5187.                 'INVLIST' => $INVLIST
  5188.             )
  5189.         );
  5190.     }
  5191.     public function StockConsumptionNoteListAction(Request $request)
  5192.     {
  5193.         $q $this->getDoctrine()
  5194.             ->getRepository('ApplicationBundle\\Entity\\StockConsumptionNote')
  5195.             ->findBy(
  5196.                 array(
  5197.                     'status' => GeneralConstant::ACTIVE,
  5198.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5199. //                    'approved' =>  GeneralConstant::APPROVED,
  5200.                 )
  5201.             );
  5202.         $stage_list = array(
  5203.             => 'Pending',
  5204.             => 'Pending',
  5205.             => 'Complete',
  5206.             => 'Partial',
  5207.         );
  5208.         $data = [];
  5209.         foreach ($q as $entry) {
  5210.             $data[] = array(
  5211.                 'doc_date' => $entry->getStockConsumptionNoteDate(),
  5212.                 'id' => $entry->getStockConsumptionNoteId(),
  5213.                 'doc_hash' => $entry->getDocumentHash(),
  5214.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5215.                 'stage' => $stage_list[$entry->getStage()]
  5216.             );
  5217.         }
  5218.         return $this->render('@Inventory/pages/views/stock_consumption_note_list.html.twig',
  5219.             array(
  5220.                 'page_title' => 'Stock Consumption Note List',
  5221.                 'data' => $data
  5222.             )
  5223.         );
  5224.     }
  5225.     public function ViewStockConsumptionNoteAction(Request $request$id)
  5226.     {
  5227.         $em $this->getDoctrine()->getManager();
  5228.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5229.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  5230.             array(
  5231.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5232.             )
  5233.         );
  5234.         $consumptionTypeList = [];
  5235.         $consumptionTypeListArray = [];
  5236.         foreach ($consumptionTypeQry as $entry) {
  5237.             $p = array(
  5238.                 'name' => $entry->getName(),
  5239.                 'id' => $entry->getConsumptionTypeId(),
  5240.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5241.                 'cost_center_id' => $entry->getCostCenterId(),
  5242.             );
  5243.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5244.             $consumptionTypeListArray[] = $p;
  5245.         }
  5246.         //add bill list
  5247.         $service_purchase_bill_query $this->getDoctrine()
  5248.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  5249.             ->findBy(
  5250.                 array(
  5251.                     'typeHash' => 'SPB',
  5252.                     'approved' => GeneralConstant::APPROVED
  5253.                 )
  5254.             );
  5255.         $service_purchase_bill_list = [];
  5256.         $service_purchase_bill_list_array = [];
  5257.         $bill = array(
  5258.             'id' => 0,
  5259.             'type' => 'SPB',
  5260.             'name' => 'New Expense',
  5261.             'text' => 'New Expense',
  5262.             'amount' => 0,
  5263.         );
  5264.         $service_purchase_bill_list[0] = $bill;
  5265.         $service_purchase_bill_list_array[] = $bill;
  5266.         foreach ($service_purchase_bill_query as $d) {
  5267.             $bill = array(
  5268.                 'id' => $d->getPurchaseInvoiceId(),
  5269.                 'type' => 'SPB',
  5270.                 'name' => $d->getDocumentHash(),
  5271.                 'text' => $d->getDocumentHash(),
  5272.                 'amount' => $d->getInvoiceAmount(),
  5273.             );
  5274.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5275.             $service_purchase_bill_list_array[] = $bill;
  5276.         }
  5277.         return $this->render('@Inventory/pages/views/view_stock_consumption_note.html.twig',
  5278.             array(
  5279.                 'page_title' => 'Stock Transfer',
  5280.                 'data' => $dt,
  5281.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5282.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5283.                 'consumptionTypeList' => $consumptionTypeList,
  5284.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5285.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5286.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5287.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5288.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5289.                     $id,
  5290.                     $dt['created_by'],
  5291.                     $dt['edited_by'])
  5292.             )
  5293.         );
  5294.     }
  5295.     public function PrintStockConsumptionNoteAction(Request $request$id)
  5296.     {
  5297.         $em $this->getDoctrine()->getManager();
  5298.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5299.         $company_data Company::getCompanyData($em1);
  5300.         $document_mark = array(
  5301.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5302.             'copy' => ''
  5303.         );
  5304.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  5305.             array(
  5306.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5307.             )
  5308.         );
  5309.         $consumptionTypeList = [];
  5310.         $consumptionTypeListArray = [];
  5311.         foreach ($consumptionTypeQry as $entry) {
  5312.             $p = array(
  5313.                 'name' => $entry->getName(),
  5314.                 'id' => $entry->getConsumptionTypeId(),
  5315.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5316.                 'cost_center_id' => $entry->getCostCenterId(),
  5317.             );
  5318.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5319.             $consumptionTypeListArray[] = $p;
  5320.         }
  5321.         //add bill list
  5322.         $service_purchase_bill_query $this->getDoctrine()
  5323.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  5324.             ->findBy(
  5325.                 array(
  5326.                     'typeHash' => 'SPB',
  5327.                     'approved' => GeneralConstant::APPROVED
  5328.                 )
  5329.             );
  5330.         $service_purchase_bill_list = [];
  5331.         $service_purchase_bill_list_array = [];
  5332.         $bill = array(
  5333.             'id' => 0,
  5334.             'type' => 'SPB',
  5335.             'name' => 'New Expense',
  5336.             'text' => 'New Expense',
  5337.             'amount' => 0,
  5338.         );
  5339.         $service_purchase_bill_list[0] = $bill;
  5340.         $service_purchase_bill_list_array[] = $bill;
  5341.         foreach ($service_purchase_bill_query as $d) {
  5342.             $bill = array(
  5343.                 'id' => $d->getPurchaseInvoiceId(),
  5344.                 'type' => 'SPB',
  5345.                 'name' => $d->getDocumentHash(),
  5346.                 'text' => $d->getDocumentHash(),
  5347.                 'amount' => $d->getInvoiceAmount(),
  5348.             );
  5349.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5350.             $service_purchase_bill_list_array[] = $bill;
  5351.         }
  5352.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5353.             $html $this->renderView('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  5354.                 array(
  5355.                     //full array here
  5356.                     'pdf' => true,
  5357.                     'page_title' => 'Stock Consumption',
  5358.                     'export' => 'pdf,print',
  5359.                     'data' => $dt,
  5360.                     'service_purchase_bill_list' => $service_purchase_bill_list,
  5361.                     'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5362.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5363.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5364.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5365.                         array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5366.                         $id,
  5367.                         $dt['created_by'],
  5368.                         $dt['edited_by']),
  5369.                     'document_mark_image' => $document_mark['original'],
  5370.                     'consumptionTypeList' => $consumptionTypeList,
  5371.                     'consumptionTypeListArray' => $consumptionTypeListArray,
  5372.                     'company_name' => $company_data->getName(),
  5373.                     'company_data' => $company_data,
  5374.                     'company_address' => $company_data->getAddress(),
  5375.                     'company_image' => $company_data->getImage(),
  5376.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5377.                     'red' => 0
  5378.                 )
  5379.             );
  5380.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5381. //                'orientation' => 'landscape',
  5382. //                'enable-javascript' => true,
  5383. //                'javascript-delay' => 1000,
  5384.                 'no-stop-slow-scripts' => false,
  5385.                 'no-background' => false,
  5386.                 'lowquality' => false,
  5387.                 'encoding' => 'utf-8',
  5388. //            'images' => true,
  5389. //            'cookie' => array(),
  5390.                 'dpi' => 300,
  5391.                 'image-dpi' => 300,
  5392. //                'enable-external-links' => true,
  5393. //                'enable-internal-links' => true
  5394.             ));
  5395.             return new Response(
  5396.                 $pdf_response,
  5397.                 200,
  5398.                 array(
  5399.                     'Content-Type' => 'application/pdf',
  5400.                     'Content-Disposition' => 'attachment; filename="stock_consumption_note_' $id '.pdf"'
  5401.                 )
  5402.             );
  5403.         }
  5404.         return $this->render('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  5405.             array(
  5406.                 'page_title' => 'Stock Consumption',
  5407.                 'export' => 'pdf,print',
  5408.                 'data' => $dt,
  5409.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5410.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5411.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5412.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5413.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5414.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5415.                     $id,
  5416.                     $dt['created_by'],
  5417.                     $dt['edited_by']),
  5418.                 'document_mark_image' => $document_mark['original'],
  5419.                 'consumptionTypeList' => $consumptionTypeList,
  5420.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5421.                 'company_name' => $company_data->getName(),
  5422.                 'company_data' => $company_data,
  5423.                 'company_address' => $company_data->getAddress(),
  5424.                 'company_image' => $company_data->getImage(),
  5425.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5426.                 'red' => 0
  5427.             )
  5428.         );
  5429.     }
  5430.     public function CreateStockReceivedNoteAction(Request $request$id 0)
  5431.     {
  5432.         $em $this->getDoctrine()->getManager();
  5433.         $companyId $this->getLoggedUserCompanyId($request);
  5434.         $extDocData = [];
  5435.         $userId $request->getSession()->get(UserConstants::USER_ID);
  5436.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  5437.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  5438.         $userBranchIdList $request->getSession()->get('branchIdList');
  5439.         if ($userBranchIdList == null$userBranchIdList = [];
  5440.         $userBranchId $request->getSession()->get('branchId');
  5441.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  5442.             $em $this->getDoctrine()->getManager();
  5443.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'];
  5444.             $dochash $request->request->get('docHash');
  5445.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5446.             $approveRole $request->request->get('approvalRole');
  5447.             $approveHash $request->request->get('approvalHash');
  5448.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5449.                 $loginId$approveRole$approveHash$id)
  5450.             ) {
  5451.                 if ($request->request->has('returnJson')) {
  5452.                     return new JsonResponse(array(
  5453.                         'success' => false,
  5454.                         'documentHash' => 0,
  5455.                         'documentId' => 0,
  5456.                         'billIds' => [],
  5457.                         'drIds' => [],
  5458.                         'pmntTransIds' => [],
  5459.                         'viewUrl' => '',
  5460.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  5461.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  5462.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  5463.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  5464.                     ));
  5465.                 } else
  5466.                     $this->addFlash(
  5467.                         'error',
  5468.                         'Sorry Could not insert Data.'
  5469.                     );
  5470.             } else {
  5471.                 if ($request->request->has('check_allowed'))
  5472.                     $check_allowed 1;
  5473.                 try {
  5474.                     $StID Inventory::CreateNewStockReceivedNote(
  5475.                         $this->getDoctrine()->getManager(),
  5476.                         $request->request,
  5477.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5478.                         $this->getLoggedUserCompanyId($request)
  5479.                     );
  5480.                 } catch (\InvalidArgumentException $e) {
  5481.                     if ($request->request->has('returnJson')) {
  5482.                         return new JsonResponse(array(
  5483.                             'success' => false,
  5484.                             'message' => $e->getMessage(),
  5485.                         ));
  5486.                     }
  5487.                     $this->addFlash('error'$e->getMessage());
  5488.                     return $this->redirect($request->getUri());
  5489.                 } catch (\Exception $e) {
  5490.                     if ($request->request->has('returnJson')) {
  5491.                         return new JsonResponse(array(
  5492.                             'success' => false,
  5493.                             'message' => 'Sorry Could not insert Data.',
  5494.                         ));
  5495.                     }
  5496.                     $this->addFlash('error''Sorry Could not insert Data.');
  5497.                     return $this->redirect($request->getUri());
  5498.                 }
  5499.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5500.                 $approveRole 1;
  5501.                 $options = array(
  5502.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5503.                     'notification_server' => $this->container->getParameter('notification_server'),
  5504.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5505.                     'url' => $this->generateUrl(
  5506.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  5507.                         ['entity_view_route_path_name']
  5508.                     )
  5509.                 );
  5510.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5511.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5512.                     $StID,
  5513.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5514.                 );
  5515.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  5516.                     $loginId,
  5517.                     $approveRole,
  5518.                     $request->request->get('approvalHash'));
  5519.                 $url $this->generateUrl(
  5520.                     'view_srcv'
  5521.                 );
  5522.                 if ($request->request->has('returnJson')) {
  5523.                     return new JsonResponse(array(
  5524.                         'success' => true,
  5525.                         'documentHash' => $dochash,
  5526.                         'documentId' => $StID,
  5527.                         'viewUrl' => $url "/" $StID,
  5528.                     ));
  5529.                 } else {
  5530.                     $this->addFlash(
  5531.                         'success',
  5532.                         'Stock Received Note Added.'
  5533.                     );
  5534.                     return $this->redirect($url "/" $StID);
  5535.                 }
  5536.             }
  5537.         }
  5538.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  5539.             array(
  5540.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5541.             )
  5542.         );
  5543.         if ($id == 0) {
  5544.         } else {
  5545.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')->findOneBy(
  5546.                 array(
  5547.                     'salesOrderId' => $id,
  5548.                 )
  5549.             );
  5550.             if ($extDoc) {
  5551.                 if ($extDoc->getEditFlag() != 1) {
  5552.                     $url $this->generateUrl(
  5553.                         'view_srcv'
  5554.                     );
  5555.                     return $this->redirect($url "/" $id);
  5556.                 } else {
  5557.                     $extDocData $extDoc;
  5558.                     $extDocDataDetails $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findOneBy(
  5559.                         array(
  5560.                             'stockReceivedNoteId' => $id,
  5561.                         )
  5562.                     );
  5563.                 }
  5564.             } else {
  5565.             }
  5566.         }
  5567.         $INVLIST = [];
  5568.         foreach ($slotList as $slot) {
  5569.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5570.         }
  5571.         $dataArray = array(
  5572.             'page_title' => 'Stock Received Note',
  5573. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  5574.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  5575.             'users' => Users::getUserListById($em),
  5576.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  5577.             'warehouseList' => Inventory::WarehouseList($em),
  5578.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  5579.             'warehouseActionList' => $warehouse_action_list,
  5580.             'warehouseActionListArray' => $warehouse_action_list_array,
  5581.             'extDocData' => $extDocData,
  5582.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  5583.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5584.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5585.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5586. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5587. //            'product_list' => Inventory::ProductList($em, $companyId),
  5588.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  5589.             'prefix_list' => array(
  5590.                 [
  5591.                     'id' => 1,
  5592.                     'value' => 'GN',
  5593.                     'text' => 'GN'
  5594.                 ]
  5595.             ),
  5596.             'assoc_list' => array(
  5597.                 [
  5598.                     'id' => 1,
  5599.                     'value' => 1,
  5600.                     'text' => 'GN'
  5601.                 ]
  5602.             ),
  5603.             'INVLIST' => $INVLIST,
  5604.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  5605.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  5606.             'userBranchIdList' => $userBranchIdList,
  5607.             'userBranchId' => $userBranchId,
  5608. //            'headList' => Accounts::HeadList($em),
  5609.         );
  5610.         //json
  5611.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  5612.         {
  5613.             $dataArray['success'] = true;
  5614.             return new JsonResponse(
  5615.                 $dataArray
  5616.             );
  5617.         }
  5618.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  5619.             $dataArray
  5620.         );
  5621.     }
  5622.     public function GetItemListForStockReceivedAction(Request $request)
  5623.     {
  5624.         if ($request->isMethod('POST')) {
  5625.             $em $this->getDoctrine();
  5626.             $receiveType 1;//transfer
  5627.             if ($request->request->has('receiveType'))
  5628.                 $receiveType $request->request->get('receiveType');
  5629.             $QD = [];
  5630.             if ($receiveType == 1)
  5631.                 $QD $this->getDoctrine()
  5632.                     ->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  5633.                     ->findBy(
  5634.                         array(
  5635. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  5636.                             'stockTransferId' => $request->request->get('stId')
  5637.                         ),
  5638.                         array()
  5639.                     );
  5640.             if ($receiveType == 2)
  5641.                 $QD $this->getDoctrine()
  5642.                     ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  5643.                     ->findBy(
  5644.                         array(
  5645. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  5646.                             'salesOrderId' => $request->request->get('soId')
  5647.                         ),
  5648.                         array()
  5649.                     );
  5650. //            if($request->request->get('wareHouseId')!='')
  5651. //
  5652. //            $DO=$this->getDoctrine()
  5653. //                ->getRepository('ApplicationBundle\\Entity\\DeliveryOrder')
  5654. //                ->findOneBy(
  5655. //                    $find_array,
  5656. //                    array(
  5657. //
  5658. //                    )
  5659. //                );
  5660.             $sendData = array(
  5661. //                'salesType'=>$SO->getSalesType(),
  5662. //                'packageData'=>[],
  5663.                 'productList' => [],
  5664. //                'productListByPackage'=>[],
  5665.             );
  5666.             $productList Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request));
  5667.             $pckg_item_cross_match_data = [];
  5668.             foreach ($QD as $product) {
  5669. //                $b_code=json_decode($product->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  5670.                 $b_code = [];
  5671.                 $newProductId $product->getProductId();
  5672.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  5673.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  5674.                     if ($to_analyze_codes_str != null)
  5675.                         $b_code json_decode($to_analyze_codes_strtrue512JSON_BIGINT_AS_STRING);
  5676.                     else
  5677.                         $b_code = [];
  5678.                 } else {
  5679.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  5680.                     if ($to_analyze_codes_str != null) {
  5681.                         $max_int_length strlen((string)PHP_INT_MAX) - 1;
  5682.                         $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$to_analyze_codes_str);
  5683.                         $b_code json_decode($json_without_bigintstrue);
  5684.                     } else {
  5685.                         $b_code = [];
  5686.                     }
  5687.                 }
  5688.                 $b_code_data = [];
  5689.                 foreach ($b_code as $d) {
  5690.                     $b_code_data[] = array(
  5691.                         'id' => $d,
  5692.                         'name' => str_pad($d13'0'STR_PAD_LEFT),
  5693.                     );
  5694.                 }
  5695.                 $p_data = array(
  5696.                     'details_id' => $product->getId(),
  5697.                     'productId' => $product->getProductId(),
  5698.                     'product_name' => isset($productList[$product->getProductId()]) ? $productList[$product->getProductId()]['name'] : 'Unknown Product',
  5699.                     'product_barcodes' => $b_code_data,
  5700. //                    'available_inventory'=>$inventory_by_warehouse?$inventory_by_warehouse->getQty():0,
  5701. //                        'package_id'=>$product->getPackageId(),
  5702.                     'qty' => $receiveType == $product->getQty() : $product->getToBeReceived(),
  5703.                     'unit_price' => $receiveType == $product->getPrice() : $productList[$product->getProductId()]['purchase_price'],
  5704.                     'balance' => $receiveType == $product->getBalance() : ($product->getToBeReceived() - $product->getReceived()),
  5705. //                        'delivered'=>$product->getDelivered(),
  5706.                 );
  5707.                 $sendData['productList'][] = $p_data;
  5708.             }
  5709.             //now package data
  5710.             if ($sendData) {
  5711.                 return new JsonResponse(array("success" => true"content" => $sendData));
  5712.             }
  5713.             return new JsonResponse(array("success" => false));
  5714.         }
  5715.         return new JsonResponse(array("success" => false));
  5716.     }
  5717.     public function StockReceivedNoteListAction(Request $request)
  5718.     {
  5719.         $q $this->getDoctrine()
  5720.             ->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')
  5721.             ->findBy(
  5722.                 array(
  5723.                     'status' => GeneralConstant::ACTIVE,
  5724.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5725. //                    'approved' =>  GeneralConstant::APPROVED,
  5726.                 )
  5727.             );
  5728.         $stage_list = array(
  5729.             => 'Pending',
  5730.             => 'Pending',
  5731.             => 'Complete',
  5732.             => 'Partial',
  5733.         );
  5734.         $data = [];
  5735.         foreach ($q as $entry) {
  5736.             $data[] = array(
  5737.                 'doc_date' => $entry->getStockReceivedNoteDate(),
  5738.                 'id' => $entry->getStockReceivedNoteId(),
  5739.                 'doc_hash' => $entry->getDocumentHash(),
  5740.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5741.                 'stage' => $stage_list[$entry->getStage()]
  5742.             );
  5743.         }
  5744.         return $this->render('@Inventory/pages/views/stock_received_note_list.html.twig',
  5745.             array(
  5746.                 'page_title' => 'Stock Received List',
  5747.                 'data' => $data
  5748.             )
  5749.         );
  5750.     }
  5751.     public function ViewStockReceivedNoteAction(Request $request$id)
  5752.     {
  5753.         $em $this->getDoctrine()->getManager();
  5754.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  5755.         return $this->render('@Inventory/pages/views/view_stock_received_note.html.twig',
  5756.             array(
  5757.                 'page_title' => 'Stock Received Note',
  5758.                 'data' => $dt,
  5759.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  5760.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5761.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5762.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5763.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5764.                     $id,
  5765.                     $dt['created_by'],
  5766.                     $dt['edited_by'])
  5767.             )
  5768.         );
  5769.     }
  5770.     public function PrintStockReceivedNoteAction(Request $request$id)
  5771.     {
  5772.         $em $this->getDoctrine()->getManager();
  5773.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  5774.         $company_data Company::getCompanyData($em1);
  5775.         $document_mark = array(
  5776.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5777.             'copy' => ''
  5778.         );
  5779.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5780.             $html $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
  5781.                 array(
  5782.                     //full array here
  5783.                     'pdf' => true,
  5784.                     'page_title' => 'Stock Received Note',
  5785.                     'export' => 'pdf,print',
  5786.                     'data' => $dt,
  5787.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5788.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5789.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5790.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5791.                         $id,
  5792.                         $dt['created_by'],
  5793.                         $dt['edited_by']),
  5794.                     'document_mark_image' => $document_mark['original'],
  5795.                     'company_name' => $company_data->getName(),
  5796.                     'company_data' => $company_data,
  5797.                     'company_address' => $company_data->getAddress(),
  5798.                     'company_image' => $company_data->getImage(),
  5799.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5800.                     'red' => 0
  5801.                 )
  5802.             );
  5803.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5804. //                'orientation' => 'landscape',
  5805. //                'enable-javascript' => true,
  5806. //                'javascript-delay' => 1000,
  5807.                 'no-stop-slow-scripts' => false,
  5808.                 'no-background' => false,
  5809.                 'lowquality' => false,
  5810.                 'encoding' => 'utf-8',
  5811. //            'images' => true,
  5812. //            'cookie' => array(),
  5813.                 'dpi' => 300,
  5814.                 'image-dpi' => 300,
  5815. //                'enable-external-links' => true,
  5816. //                'enable-internal-links' => true
  5817.             ));
  5818.             return new Response(
  5819.                 $pdf_response,
  5820.                 200,
  5821.                 array(
  5822.                     'Content-Type' => 'application/pdf',
  5823.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  5824.                 )
  5825.             );
  5826.         }
  5827.         return $this->render('@Inventory/pages/print/print_stock_received_note.html.twig',
  5828.             array(
  5829.                 'page_title' => 'Stock Received Note',
  5830.                 'export' => 'pdf,print',
  5831.                 'data' => $dt,
  5832.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5833.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5834.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5835.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5836.                     $id,
  5837.                     $dt['created_by'],
  5838.                     $dt['edited_by']),
  5839.                 'document_mark_image' => $document_mark['original'],
  5840.                 'company_name' => $company_data->getName(),
  5841.                 'company_data' => $company_data,
  5842.                 'company_address' => $company_data->getAddress(),
  5843.                 'company_image' => $company_data->getImage(),
  5844.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5845.                 'red' => 0
  5846.             )
  5847.         );
  5848.     }
  5849.     public function CreateStoreRequisitionSlipAction(Request $request$id 0)
  5850.     {
  5851.         $em $this->getDoctrine()->getManager();
  5852. //        $id;
  5853.         if ($request->isMethod('POST')) {
  5854.             $em $this->getDoctrine()->getManager();
  5855.             $entity_id array_flip(GeneralConstant::$Entity_list)['StoreRequisition']; //change
  5856.             $dochash $request->request->get('voucherNumber'); //change
  5857.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5858.             $approveRole $request->request->get('approvalRole');
  5859.             $approveHash $request->request->get('approvalHash');
  5860.             $validation Inventory::ValidateStoreRequisitionSlip($request->request);
  5861.             if (!$validation['success']) {
  5862.                 $this->addFlash(
  5863.                     'error',
  5864.                     $validation['error']
  5865.                 );
  5866.             } else if (!DocValidation::isInsertable($em$entity_id$dochash,
  5867.                 $loginId$approveRole$approveHash$id)
  5868.             ) {
  5869.                 $this->addFlash(
  5870.                     'error',
  5871.                     'Sorry, could not insert Data.'
  5872.                 );
  5873.             } else {
  5874.                 if ($request->request->has('check_allowed'))
  5875.                     $check_allowed 1;
  5876.                 $IrID Inventory::CreateNewStoreRequisition($id,
  5877.                     $this->getDoctrine()->getManager(),
  5878.                     $request->request,
  5879.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5880.                     $this->getLoggedUserCompanyId($request)
  5881.                 );
  5882.                 //now add Approval info
  5883.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5884.                 $approveRole $request->request->get('approvalRole');
  5885.                 $options = array(
  5886.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5887.                     'notification_server' => $this->container->getParameter('notification_server'),
  5888.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5889.                     'url' => $this->generateUrl(
  5890.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StoreRequisition']]
  5891.                         ['entity_view_route_path_name']
  5892.                     )
  5893.                 );
  5894.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5895.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  5896.                     $IrID,
  5897.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5898.                 );
  5899.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StoreRequisition'], $IrID,
  5900.                     $loginId,
  5901.                     $approveRole,
  5902.                     $request->request->get('approvalHash'));
  5903.                 $this->addFlash(
  5904.                     'success',
  5905.                     'New Indent Added.'
  5906.                 );
  5907.                 $url $this->generateUrl(
  5908.                     'view_ir'
  5909.                 );
  5910.                 return $this->redirect($url "/" $IrID);
  5911.             }
  5912.         }
  5913.         $extDocData = [];
  5914.         $extDocDetailsData = [];
  5915.         if ($id == 0) {
  5916.         } else {
  5917.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StoreRequisition')->findOneBy(
  5918.                 array(
  5919.                     'storeRequisitionId' => $id///material
  5920.                 )
  5921.             );
  5922.             //now if its not editable, redirect to view
  5923.             if ($extDoc) {
  5924.                 if ($extDoc->getEditFlag() != 1) {
  5925.                     $url $this->generateUrl(
  5926.                         'view_ir'
  5927.                     );
  5928.                     return $this->redirect($url "/" $id);
  5929.                 } else {
  5930.                     $extDocData $extDoc;
  5931.                     $extDocDetailsData $em->getRepository('ApplicationBundle\\Entity\\StoreRequisitionItem')->findBy(
  5932.                         array(
  5933.                             'storeRequisitionId' => $id///material
  5934.                         )
  5935.                     );;
  5936.                 }
  5937.             } else {
  5938.             }
  5939.         }
  5940.         $companyId $this->getLoggedUserCompanyId($request);
  5941.         $productListArray = [];
  5942.         $subCategoryListArray = [];
  5943.         $categoryListArray = [];
  5944.         $igListArray = [];
  5945.         $unitListArray = [];
  5946.         $brandListArray = [];
  5947.         $productList Inventory::ProductList($em$companyId);
  5948.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  5949.         $categoryList Inventory::ProductCategoryList($em$companyId);
  5950.         $igList Inventory::ItemGroupList($em$companyId);
  5951.         $unitList Inventory::UnitTypeList($em);
  5952.         $brandList Inventory::GetBrandList($em$companyId);
  5953.         foreach ($productList as $product$productListArray[] = $product;
  5954.         foreach ($categoryList as $product$categoryListArray[] = $product;
  5955.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  5956.         foreach ($igList as $product$igListArray[] = $product;
  5957.         foreach ($unitList as $product$unitListArray[] = $product;
  5958.         foreach ($brandList as $product$brandListArray[] = $product;
  5959.         $sr_list = [];
  5960.         $QD $this->getDoctrine()
  5961.             ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  5962.             ->findBy(
  5963.                 array(
  5964.                     'indentTagged' => 0,
  5965.                     'approved' => 1
  5966.                 )
  5967.             );
  5968.         foreach ($QD as $dt) {
  5969.             $sr_list[$dt->getStockRequisitionId()] = array(
  5970.                 'id' => $dt->getStockRequisitionId(),
  5971.                 'name' => $dt->getDocumentHash(),
  5972.                 'text' => $dt->getDocumentHash(),
  5973.             );
  5974.         }
  5975.         return $this->render('@Inventory/pages/input_forms/store_requisition.html.twig',
  5976.             array(
  5977.                 'page_title' => 'Indent Requisition Slip',
  5978.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5979.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5980.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5981.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5982.                 'sr_list' => $sr_list,
  5983.                 'productList' => $productList,
  5984.                 'subCategoryList' => $subCategoryList,
  5985.                 'categoryList' => $categoryList,
  5986.                 'igList' => $igList,
  5987.                 'extId' => $id,
  5988.                 'extDocDetailsData' => $extDocDetailsData,
  5989.                 'extDocData' => $extDocData,
  5990.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  5991.                 'unitList' => $unitList,
  5992.                 'brandList' => $brandList,
  5993.                 'brandListArray' => $brandListArray,
  5994.                 'productListArray' => $productListArray,
  5995.                 'subCategoryListArray' => $subCategoryListArray,
  5996.                 'categoryListArray' => $categoryListArray,
  5997.                 'igListArray' => $igListArray,
  5998.                 'unitListArray' => $unitListArray,
  5999.                 'prefix_list' => array(
  6000.                     [
  6001.                         'id' => 1,
  6002.                         'value' => 'GN',
  6003.                         'text' => 'General'
  6004.                     ],
  6005.                     [
  6006.                         'id' => 1,
  6007.                         'value' => 'SD',
  6008.                         'text' => 'For Sales Demand'
  6009.                     ]
  6010.                 ),
  6011.                 'assoc_list' => array(
  6012.                     [
  6013.                         'id' => 1,
  6014.                         'value' => 1,
  6015.                         'text' => 'GN'
  6016.                     ]
  6017.                 )
  6018.             )
  6019.         );
  6020.     }
  6021.     public function CreateStockRequisitionSlipAction(Request $request$id 0)
  6022.     {
  6023.         $em $this->getDoctrine()->getManager();
  6024.         if ($request->isMethod('POST')) {
  6025.             $em $this->getDoctrine()->getManager();
  6026.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockRequisition']; //change
  6027.             $dochash $request->request->get('voucherNumber'); //change
  6028.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6029.             $approveRole $request->request->get('approvalRole');
  6030.             $approveHash $request->request->get('approvalHash');
  6031.             $validation Inventory::ValidateStockRequisitionSlip($request->request);
  6032.             if (!$validation['success']) {
  6033.                 $this->addFlash(
  6034.                     'error',
  6035.                     $validation['error']
  6036.                 );
  6037.             } else if (!DocValidation::isInsertable($em$entity_id$dochash,
  6038.                 $loginId$approveRole$approveHash$id)
  6039.             ) {
  6040.                 $this->addFlash(
  6041.                     'error',
  6042.                     'Sorry, could not insert Data.'
  6043.                 );
  6044.             } else {
  6045.                 if ($request->request->has('check_allowed'))
  6046.                     $check_allowed 1;
  6047.                 $SrID Inventory::CreateNewStockRequisition($id,
  6048.                     $this->getDoctrine()->getManager(),
  6049.                     $request->request,
  6050.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6051.                     $this->getLoggedUserCompanyId($request)
  6052.                 );
  6053.                 //now add Approval info
  6054.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6055.                 $approveRole $request->request->get('approvalRole');
  6056.                 $options = array(
  6057.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6058.                     'notification_server' => $this->container->getParameter('notification_server'),
  6059.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6060.                     'url' => $this->generateUrl(
  6061.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockRequisition']]
  6062.                         ['entity_view_route_path_name']
  6063.                     )
  6064.                 );
  6065.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6066.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  6067.                     $SrID,
  6068.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6069.                 );
  6070.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockRequisition'], $SrID,
  6071.                     $loginId,
  6072.                     $approveRole,
  6073.                     $request->request->get('approvalHash'));
  6074.                 $this->addFlash(
  6075.                     'success',
  6076.                     'New Requisition Added.'
  6077.                 );
  6078.                 $url $this->generateUrl(
  6079.                     'view_sr'
  6080.                 );
  6081. //                return $this->redirect($url . "/" . $SrID);
  6082.             }
  6083.         }
  6084.         $extDocData = [];
  6085.         $extDocDetailsData = [];
  6086.         if ($id == 0) {
  6087.         } else {
  6088.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StockRequisition')->findOneBy(
  6089.                 array(
  6090.                     'stockRequisitionId' => $id///material
  6091.                 )
  6092.             );
  6093.             //now if its not editable, redirect to view
  6094.             if ($extDoc) {
  6095.                 if ($extDoc->getEditFlag() != 1) {
  6096.                     $url $this->generateUrl(
  6097.                         'view_sr'
  6098.                     );
  6099.                     return $this->redirect($url "/" $id);
  6100.                 } else {
  6101.                     $extDocData $extDoc;
  6102.                     $extDocDetailsData $em->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')->findBy(
  6103.                         array(
  6104.                             'stockRequisitionId' => $id///material
  6105.                         )
  6106.                     );;
  6107.                 }
  6108.             } else {
  6109.             }
  6110.         }
  6111.         $companyId $this->getLoggedUserCompanyId($request);
  6112.         $productListArray = [];
  6113.         $subCategoryListArray = [];
  6114.         $categoryListArray = [];
  6115.         $igListArray = [];
  6116.         $unitListArray = [];
  6117.         $brandListArray = [];
  6118.         $productList Inventory::ProductList($em$companyId);
  6119.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6120.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6121.         $igList Inventory::ItemGroupList($em$companyId);
  6122.         $unitList Inventory::UnitTypeList($em);
  6123.         $brandList Inventory::GetBrandList($em$companyId);
  6124.         foreach ($productList as $product$productListArray[] = $product;
  6125.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6126.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6127.         foreach ($igList as $product$igListArray[] = $product;
  6128.         foreach ($unitList as $product$unitListArray[] = $product;
  6129.         foreach ($brandList as $product$brandListArray[] = $product;
  6130.         return $this->render('@Inventory/pages/input_forms/stock_requisition_slip.html.twig',
  6131.             array(
  6132.                 'page_title' => 'Stock Requisition Slip',
  6133.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6134.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6135.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6136.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6137.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  6138.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6139.                 'productList' => $productList,
  6140.                 'extId' => $id,
  6141.                 'extDocDetailsData' => $extDocDetailsData,
  6142.                 'extDocData' => $extDocData,
  6143.                 'subCategoryList' => $subCategoryList,
  6144.                 'categoryList' => $categoryList,
  6145.                 'igList' => $igList,
  6146.                 'unitList' => $unitList,
  6147.                 'brandList' => $brandList,
  6148.                 'brandListArray' => $brandListArray,
  6149.                 'productListArray' => $productListArray,
  6150.                 'subCategoryListArray' => $subCategoryListArray,
  6151.                 'categoryListArray' => $categoryListArray,
  6152.                 'igListArray' => $igListArray,
  6153.                 'unitListArray' => $unitListArray,
  6154.                 'productionBomList' => ProductionM::ProductionBomList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6155.                 'productionScheduleList' => ProductionM::ProductionScheduleList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6156.                 'prefix_list' => array(
  6157.                     [
  6158.                         'id' => 1,
  6159.                         'value' => 'GN',
  6160.                         'text' => 'General'
  6161.                     ],
  6162.                     [
  6163.                         'id' => 1,
  6164.                         'value' => 'SD',
  6165.                         'text' => 'For Sales Demand'
  6166.                     ]
  6167.                 ),
  6168.                 'projectList' => $em->getRepository('ApplicationBundle\\Entity\\Project')->findBy(
  6169.                     array(
  6170.                         'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  6171.                     ), array('projectDate' => 'desc')
  6172.                 ),
  6173.                 'salesOrderList' => SalesOrderM::SalesOrderListPendingDelivery($em),
  6174.                 'assoc_list' => array(
  6175.                     [
  6176.                         'id' => 1,
  6177.                         'value' => 'GN',
  6178.                         'text' => 'General'
  6179.                     ]
  6180.                 )
  6181.             )
  6182.         );
  6183.     }
  6184.     public function CreateStockReturnAction(Request $request)
  6185.     {
  6186.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  6187.             array(
  6188.                 'page_title' => 'Stock Return',
  6189. //                'dataList'=>$dta_list
  6190.             )
  6191.         );
  6192.     }
  6193.     public function MaterialInwardAction(Request $request)
  6194.     {
  6195.         $data = [];
  6196.         if ($request->isMethod('POST')) {
  6197.             //first of all resolve the transport costs
  6198.             $total_price_value 0;
  6199.             $data_list $dt $this->getDoctrine()
  6200.                 ->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')
  6201.                 ->findBy(
  6202.                     array(
  6203.                         'purchaseOrderId' => $request->request->get('poId'),
  6204.                         'productId' => $request->request->get('products')
  6205.                     )
  6206.                 );
  6207.             $purchase_items = [];
  6208.             foreach ($data_list as $key => $value) {
  6209.                 $purchase_items[$value->getProductId()] = $value;
  6210.             }
  6211.             foreach ($request->request->get('products') as $key => $entry) {
  6212.                 $total_price_value $total_price_value + ($request->request->get('receivedQty')[$key]) * ($purchase_items[$entry]->getPrice());
  6213.             }
  6214.             $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$request->request->get('poId')];
  6215.             $supplier_id $po_data['supplier_id'];
  6216.             $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6217.             foreach ($request->request->get('products') as $key => $entry) {
  6218.                 if ($request->request->get('receivedQty')[$key] > 0)
  6219.                     Inventory::NewMaterialInward($this->getDoctrine()->getManager(),
  6220.                         $request->request,
  6221.                         $key,
  6222.                         $request->request->get('poId'),
  6223.                         $request->request->get('purchaseOrderItemId'),
  6224.                         $supplier_id,
  6225.                         $request->request->get('warehouseId'),
  6226.                         $request->request->get('lotNumber'),
  6227.                         $request->request->get('type_hash'),
  6228.                         $request->request->get('prefix_hash'),
  6229.                         $request->request->get('assoc_hash'),
  6230.                         $request->request->get('number_hash'),
  6231.                         $request->request->get('docHash'),
  6232.                         $request->request->get('docDate'),
  6233.                         $purchase_items[$entry],
  6234.                         $total_price_value,
  6235.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6236.             }
  6237.             $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$request->request->get('warehouseId')]['name'];
  6238. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6239.             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),
  6240.                 "A stack of material Has Arrived at The " $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6241.                 'all',
  6242.                 "",
  6243.                 'information',
  6244.                 "",
  6245.                 "Inbound Material"
  6246.             );
  6247. //                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);
  6248.         }
  6249.         return $this->render('@Inventory/pages/input_forms/material_inward.html.twig',
  6250.             array(
  6251.                 'page_title' => 'Material Inward',
  6252.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6253.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  6254.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  6255.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  6256.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  6257.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  6258.                 "unitList" => Inventory::UnitTypeList($this->getDoctrine()->getManager())
  6259. //                'po'=>Inventory::getPurchaseOrderList
  6260.             )
  6261.         );
  6262.     }
  6263.     public function QualityControlAction(Request $request)
  6264.     {
  6265.         $checked_qc_list_flag 0;
  6266.         if ($request->query->has('checked_qc_list_flag'))
  6267.             $checked_qc_list_flag $request->query->has('checked_qc_list_flag');
  6268.         if ($request->isMethod('POST')) {
  6269.             foreach ($request->request->get('qc_checked', []) as $key => $entry) {
  6270.                 $em $this->getDoctrine()->getManager();
  6271.                 $data $this->getDoctrine()
  6272.                     ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  6273.                     ->findOneBy(
  6274.                         array(
  6275.                             'qcId' => $entry
  6276.                         )
  6277.                     );
  6278.                 if ($request->request->get('approvedQty')[$entry] <= 0) {
  6279.                     $em->remove($data);
  6280.                     $em->flush();
  6281.                 } else {
  6282.                     $data->setApprovedQty($request->request->get('approvedQty')[$entry]);
  6283.                     $data->setRejectedQty($data->getInwardQty() - $request->request->get('approvedQty')[$entry]);
  6284.                     $data->setQcDate(new \DateTime($request->request->get('qcDate')));
  6285.                     $data->setStage(GeneralConstant::STAGE_PENDING_TAG);
  6286.                     $em->flush();
  6287.                 }
  6288.                 //notification
  6289.                 $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$data->getPurchaseOrderId()];
  6290.                 $supplier_id $po_data['supplier_id'];
  6291.                 $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6292.                 $product_name Inventory::ProductList($this->getDoctrine()->getManager())[$data->getProductId()]['name'];
  6293.                 $qty $request->request->get('approvedQty')[$entry];
  6294.                 $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$data->getWarehouseId()]['name'];
  6295. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6296.                 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),
  6297.                     $qty " among " $data->getInwardQty() . " units of " $product_name " has passed the Quality Control in " .
  6298.                     $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6299.                     'all',
  6300.                     "",
  6301.                     'success',
  6302.                     "",
  6303.                     "Quality Control"
  6304.                 );
  6305.             }
  6306.         }
  6307.         return $this->render('@Inventory/pages/input_forms/qc.html.twig',
  6308.             array(
  6309.                 'page_title' => 'Quality Control',
  6310.                 'checked_qc_list_flag' => $checked_qc_list_flag,
  6311.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6312.                 'warehouse_indexed' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6313.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  6314.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  6315.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  6316.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  6317.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6318.                 'material_inward' => $this->getDoctrine()
  6319.                     ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  6320.                     ->findBy(
  6321.                         array(
  6322.                             'stage' => $checked_qc_list_flag == GeneralConstant::STAGE_PENDING GeneralConstant::STAGE_PENDING_TAG
  6323.                         )
  6324.                     )
  6325. //                'po'=>Inventory::getPurchaseOrderList
  6326.             )
  6327.         );
  6328.     }
  6329.     public function InventoryTransactionViewAction(Request $request)
  6330.     {
  6331.         $em $this->getDoctrine()->getManager();
  6332.         $qry_data = array(
  6333.             'warehouseId' => [0],
  6334.             'igId' => [0],
  6335.             'brandId' => [0],
  6336.             'categoryId' => [0],
  6337.             'actionTagId' => [0],
  6338.         );
  6339.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6340.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6341.         $data_searched = [];
  6342.         $em $this->getDoctrine()->getManager();
  6343.         $companyId $this->getLoggedUserCompanyId($request);
  6344.         $company_data Company::getCompanyData($em$companyId);
  6345.         $data = [];
  6346.         $print_title "Inventory Report";
  6347.         $document_mark = array(
  6348.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6349.             'copy' => ''
  6350.         );
  6351.         if ($request->isMethod('POST'))
  6352.             $method 'POST';
  6353.         else
  6354.             $method 'GET';
  6355.         {
  6356.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  6357.                 $request->request$method,
  6358.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6359.                 $companyId);
  6360.             if ($request->query->has('returnJson') || $request->request->has('returnJson')) {
  6361.                 return new JsonResponse(
  6362.                     array(
  6363.                         'success' => true,
  6364. //                    'page_title' => 'Product Details',
  6365. //                    'company_data' => $company_data,
  6366.                         'page_title' => 'Inventory Transactions',
  6367.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6368.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6369.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6370.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6371.                         'data_products' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6372.                         'action_tag' => $warehouse_action_list,
  6373.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6374.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6375.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6376.                         'data_searched' => $data_searched
  6377.                     )
  6378.                 );
  6379.             } else if ($request->request->get('print_data_enabled') == 1) {
  6380.                 $print_sub_title "";
  6381.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  6382.                     array(
  6383.                         'page_title' => 'Inventory Report',
  6384.                         'page_header' => 'Report',
  6385.                         'print_title' => $print_title,
  6386.                         'document_type' => 'Journal voucher',
  6387.                         'document_mark_image' => $document_mark['original'],
  6388.                         'page_header_sub' => 'Add',
  6389.                         'item_data' => [],
  6390.                         'received' => 2,
  6391.                         'return' => 1,
  6392.                         'total_w_vat' => 1,
  6393.                         'total_vat' => 1,
  6394.                         'total_wo_vat' => 1,
  6395.                         'invoice_id' => 'abcd1234',
  6396.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6397.                         'created_by' => 'created by',
  6398.                         'created_at' => '',
  6399.                         'red' => 0,
  6400.                         'company_name' => $company_data->getName(),
  6401.                         'company_data' => $company_data,
  6402.                         'company_address' => $company_data->getAddress(),
  6403.                         'company_image' => $company_data->getImage(),
  6404.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6405.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6406.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6407.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6408.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6409.                         'action_tag' => $warehouse_action_list,
  6410.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6411.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6412.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6413.                         'data_searched' => $data_searched
  6414.                     )
  6415.                 );
  6416.             }
  6417.         }
  6418.         return $this->render('@Inventory/pages/report/inventory_transaction_view.html.twig',
  6419.             array(
  6420.                 'page_title' => 'Inventory Transactions',
  6421.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6422.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6423.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6424.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6425.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6426.                 'action_tag' => $warehouse_action_list,
  6427.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6428.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6429.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6430.                 'data_searched' => $data_searched
  6431.             )
  6432.         );
  6433.     }
  6434.     public function StockConsumptionViewAction(Request $request)
  6435.     {
  6436.         $em $this->getDoctrine()->getManager();
  6437.         $start_date $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
  6438.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : new \DateTime();
  6439.         $qry_data = array(
  6440.             'warehouseId' => [0],
  6441.             'igId' => [0],
  6442.             'brandId' => [0],
  6443.             'categoryId' => [0],
  6444.             'actionTagId' => [0],
  6445.         );
  6446.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6447.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6448.         $data_searched = [];
  6449.         $em $this->getDoctrine()->getManager();
  6450.         $company_data Company::getCompanyData($em1);
  6451.         $data = [];
  6452.         $print_title "Inventory Report";
  6453.         $document_mark = array(
  6454.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6455.             'copy' => ''
  6456.         );
  6457.         if ($request->isMethod('POST'))
  6458.             $method 'POST';
  6459.         else
  6460.             $method 'GET';
  6461.         $post_data $method == 'POST' $request->request $request->query;
  6462.         $data_searched Inventory::GetStockConsumptionData($this->getDoctrine()->getManager(),
  6463.             $post_data,
  6464.             $method,
  6465.             $start_date,
  6466.             $end_date,
  6467.             $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6468.         if ($post_data->get('print_data_enabled') == 1) {
  6469.             $print_sub_title "";
  6470.             if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6471.                 $html $this->renderView('@Inventory/pages/print/print_stock_consumption.html.twig',
  6472.                     array(
  6473.                         'pdf' => 'true',
  6474.                         'page_title' => 'Inventory Report',
  6475.                         'page_header' => 'Report',
  6476.                         'print_title' => $print_title,
  6477.                         'document_type' => 'Journal voucher',
  6478.                         'document_mark_image' => $document_mark['original'],
  6479.                         'page_header_sub' => 'Add',
  6480.                         'item_data' => [],
  6481.                         'received' => 2,
  6482.                         'return' => 1,
  6483.                         'total_w_vat' => 1,
  6484.                         'total_vat' => 1,
  6485.                         'total_wo_vat' => 1,
  6486.                         'invoice_id' => 'abcd1234',
  6487.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6488.                         'created_by' => 'created by',
  6489.                         'created_at' => '',
  6490.                         'red' => 0,
  6491.                         'start_date' => $start_date,
  6492.                         'end_date' => $end_date,
  6493.                         'openFilter' => empty($post_data->keys()) ? 0,
  6494.                         'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6495.                         'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6496.                         'company_name' => $company_data->getName(),
  6497.                         'company_data' => $company_data,
  6498.                         'company_address' => $company_data->getAddress(),
  6499.                         'company_image' => $company_data->getImage(),
  6500.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6501.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6502.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6503.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6504.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6505.                         'action_tag' => $warehouse_action_list,
  6506.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6507.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6508.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6509.                         'data_searched' => $data_searched,
  6510.                         'export' => 'all'
  6511.                     )
  6512.                 );
  6513.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6514.                     'orientation' => count($data_searched['query_columns_filter']) > 'landscape' 'portrait',
  6515.                     'no-stop-slow-scripts' => true,
  6516.                     'no-background' => false,
  6517.                     'lowquality' => false,
  6518.                     'encoding' => 'utf-8',
  6519.                     'dpi' => 300,
  6520.                     'image-dpi' => 300,
  6521.                 ));
  6522.                 return new Response(
  6523.                     $pdf_response,
  6524.                     200,
  6525.                     array(
  6526.                         'Content-Type' => 'application/pdf',
  6527.                         'Content-Disposition' => 'attachment; filename="Stock_Consumption.pdf"'
  6528.                     )
  6529.                 );
  6530.             }
  6531.             return $this->render('@Inventory/pages/print/print_stock_consumption.html.twig',
  6532.                 array(
  6533.                     'page_title' => 'Inventory Report',
  6534.                     'page_header' => 'Report',
  6535.                     'print_title' => $print_title,
  6536.                     'document_type' => 'Journal voucher',
  6537.                     'document_mark_image' => $document_mark['original'],
  6538.                     'page_header_sub' => 'Add',
  6539.                     'item_data' => [],
  6540.                     'received' => 2,
  6541.                     'return' => 1,
  6542.                     'total_w_vat' => 1,
  6543.                     'total_vat' => 1,
  6544.                     'total_wo_vat' => 1,
  6545.                     'invoice_id' => 'abcd1234',
  6546.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6547.                     'created_by' => 'created by',
  6548.                     'created_at' => '',
  6549.                     'red' => 0,
  6550.                     'start_date' => $start_date,
  6551.                     'end_date' => $end_date,
  6552.                     'openFilter' => empty($post_data->keys()) ? 0,
  6553.                     'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6554.                     'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6555.                     'company_name' => $company_data->getName(),
  6556.                     'company_data' => $company_data,
  6557.                     'company_address' => $company_data->getAddress(),
  6558.                     'company_image' => $company_data->getImage(),
  6559.                     'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6560.                     'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6561.                     'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6562.                     'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6563.                     'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6564.                     'action_tag' => $warehouse_action_list,
  6565.                     'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6566.                     'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6567.                     'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6568.                     'data_searched' => $data_searched,
  6569.                     'export' => 'all'
  6570.                 )
  6571.             );
  6572.         }
  6573.         return $this->render('@Inventory/pages/report/stock_consumption.html.twig',
  6574.             array(
  6575.                 'page_title' => 'Stock Consumption',
  6576.                 'start_date' => $start_date,
  6577.                 'end_date' => $end_date,
  6578.                 'openFilter' => empty($post_data->keys()) ? 0,
  6579.                 'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6580.                 'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6581.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6582.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6583.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6584.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6585.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6586.                 'action_tag' => $warehouse_action_list,
  6587.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6588.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6589.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6590.                 'data_searched' => $data_searched
  6591.             )
  6592.         );
  6593.     }
  6594.     public function ItemViewAction(Request $request)
  6595.     {
  6596.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  6597.             array(
  6598.                 'page_title' => 'Stock Return'
  6599.             )
  6600.         );
  6601.     }
  6602.     public function ProductViewAction(Request $request$id 0)
  6603.     {
  6604.         $em $this->getDoctrine()->getManager();
  6605.         $companyId $this->getLoggedUserCompanyId($request);
  6606.         $company_data Company::getCompanyData($em$companyId);
  6607.         $data = [];
  6608.         $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  6609.             ->findOneBy(
  6610.                 array(
  6611.                     'id' => $id
  6612.                 )
  6613.             );
  6614.         $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  6615.             ->findBy(
  6616.                 array(
  6617.                     'productId' => $id
  6618.                 )
  6619.             );
  6620.         $trans_history $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')
  6621.             ->findBy(
  6622.                 array(
  6623.                     'productId' => $id
  6624.                 ), array(
  6625.                     'transactionDate' => 'ASC',
  6626.                     'id' => 'ASC'
  6627.                 )
  6628.             );
  6629.         $productDataObj = array();
  6630.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  6631.             $getters array_filter(get_class_methods($productData), function ($method) {
  6632.                 return 'get' === substr($method03);
  6633.             });
  6634.             foreach ($getters as $getter) {
  6635.                 if ($getter == 'getGlobalId')
  6636.                     continue;
  6637.         //                    if ($getter == 'getId')
  6638.         //                        continue;
  6639.                 $Fieldname str_replace('get'''$getter);
  6640.                 $productDataObj[$Fieldname] = $productData->{$getter}(); // `foo!`
  6641.             }
  6642.             if ($request->request->has('genInfoOnly') && $request->request->get('genInfoOnly') == 1) {
  6643.                 $dataArray = array(
  6644.                     'success' => true,
  6645.                     'page_title' => 'Product Details',
  6646.                     'company_data' => $company_data,
  6647.                     'productData' => $productData,
  6648.                     'productDataObj' => $productDataObj,
  6649.                     'defaultImageAppendUrl' => '/uploads/Products/',
  6650.                 );
  6651.             } else {
  6652.                 $dataArray = array(
  6653.                     'success' => true,
  6654.                     'page_title' => 'Product Details',
  6655.                     'company_data' => $company_data,
  6656.                     'productData' => $productData,
  6657.                     'productDataObj' => $productDataObj,
  6658.                     'currInvList' => $currInvList,
  6659.                     'trans_history' => $trans_history,
  6660.                     'entityList' => GeneralConstant::$Entity_list_details,
  6661.         //                    'productList' => Inventory::ProductList($em, $companyId),
  6662.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  6663.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  6664.                     'igList' => Inventory::ItemGroupList($em$companyId),
  6665.                     'unitList' => Inventory::UnitTypeList($em),
  6666.                     'brandList' => Inventory::GetBrandList($em$companyId),
  6667.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  6668.                     'warehouseList' => Inventory::WarehouseList($em),
  6669.                     'defaultImageAppendUrl' => '/uploads/Products/',
  6670.                 );
  6671.             }
  6672.             return new JsonResponse(
  6673.                 $dataArray
  6674.             );
  6675.         }
  6676.         $dataArray = array(
  6677.             'page_title' => 'Product Details',
  6678.             'company_data' => $company_data,
  6679.             'productData' => $productData,
  6680.             'currInvList' => $currInvList,
  6681.             'trans_history' => $trans_history,
  6682.             'entityList' => GeneralConstant::$Entity_list_details,
  6683.         //            'productList' => Inventory::ProductList($em, $companyId),
  6684.             'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  6685.             'categoryList' => Inventory::ProductCategoryList($em$companyId),
  6686.             'igList' => Inventory::ItemGroupList($em$companyId),
  6687.             'unitList' => Inventory::UnitTypeList($em),
  6688.             'brandList' => Inventory::GetBrandList($em$companyId),
  6689.             'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  6690.             'warehouseList' => Inventory::WarehouseList($em),
  6691.         );
  6692.         return $this->render('@Inventory/pages/views/product_view.html.twig'$dataArray
  6693.         );
  6694.     }
  6695.     public function CheckForProductInWarehouseAction(Request $request$queryStr '')
  6696.     {
  6697.         $em $this->getDoctrine()->getManager();
  6698.         $companyId $this->getLoggedUserCompanyId($request);
  6699.         $data = [
  6700.             'availableQty' => 0,
  6701.             'productByCodesArray' => [],
  6702.             'indRowId' => 0
  6703.         ];
  6704.         $html '';
  6705.         $productByCodeData = [];
  6706.         if ($request->isMethod('POST')) {
  6707.             $warehouseId $request->request->get('warehouseId'0);
  6708.             $warehouseActionId $request->request->get('warehouseActionId'0);
  6709.             $productId $request->request->get('productId'0);
  6710.             $indRowId $request->request->get('indRowId'0);
  6711.             $data['indRowId'] = $indRowId;
  6712.             $inStorage $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  6713.                 ->findBy(
  6714.                     array(
  6715.                         'productId' => $productId,
  6716.                         'warehouseId' => $warehouseId,
  6717.                         'actionTagId' => $warehouseActionId,
  6718.                         'CompanyId' => $companyId,
  6719.                     )
  6720.                 );
  6721.             foreach ($inStorage as $strg) {
  6722.                 $data['availableQty'] += $strg->getQty();
  6723.             }
  6724.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  6725.                 ->findBy(
  6726.                     array(
  6727.                         'productId' => $productId,
  6728.                         'warehouseId' => $warehouseId,
  6729.                         'warehouseActionId' => $warehouseActionId,
  6730.                         'CompanyId' => $companyId,
  6731.                     )
  6732.                 );
  6733.             foreach ($productByCodeData as $pbc) {
  6734.                 $data['productByCodesArray'][] = array(
  6735.                     'id' => $pbc->getProductByCodeId(),
  6736.                     'productId' => $pbc->getProductId(),
  6737.                     'warehouseId' => $pbc->getWarehouseId(),
  6738.                     'warehouseActionId' => $pbc->getWarehouseActionId(),
  6739. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  6740.                     'sales_code' => str_pad($pbc->getSalesCode(), 13'0'STR_PAD_LEFT),
  6741. //                'sales_code'=>$d['sales_code'],
  6742.                 );
  6743.             }
  6744.             return new JsonResponse(array(
  6745.                     'success' => true,
  6746.                     'data' => $data,
  6747.                 )
  6748.             );
  6749.         }
  6750.         return new JsonResponse(
  6751.             array(
  6752.                 'success' => false,
  6753.                 'data' => $data,
  6754.             )
  6755.         );
  6756.     }
  6757.     public function ProductByCodeListAjaxAction(Request $request$queryStr '')
  6758.     {
  6759.         $em $this->getDoctrine()->getManager();
  6760.         $companyId $this->getLoggedUserCompanyId($request);
  6761.         $company_data Company::getCompanyData($em$companyId);
  6762.         $data = [];
  6763.         $html '';
  6764.         $productByCodeData = [];
  6765.         if ($request->request->has('query') && $queryStr == '')
  6766.             $queryStr $request->request->get('queryStr');
  6767.         $get_kids_sql "select product_by_code_id id, product_id, warehouse_id, warehouse_action_id,
  6768.                             sales_code ,
  6769.                             serial_no,
  6770.                             imei1,
  6771.                             imei2,
  6772.                             imei3,
  6773.                             imei4
  6774.                             from product_by_code
  6775.                             where ( CONVERT(sales_code,char)  like '%" $queryStr "%'
  6776.                                     or  CONVERT(serial_no,char)  like '%" $queryStr "%'
  6777.                                     or  CONVERT(imei1,char)  like '%" $queryStr "%'
  6778.                                     or  CONVERT(imei2,char)  like '%" $queryStr "%'
  6779.                                     or  CONVERT(imei3,char)  like '%" $queryStr "%'
  6780.                                     or  CONVERT(imei4,char)  like '%" $queryStr "%'
  6781.                                     ) ";
  6782.         if ($request->query->has('warehouseId'))
  6783.             $get_kids_sql .= " and warehouse_id=" $request->query->get('warehouseId') . " ";
  6784.         if ($request->query->has('position'))
  6785.             $get_kids_sql .= " and position=" $request->query->get('position') . " ";
  6786.         if ($request->query->has('deliveryReceiptId'))
  6787.             $get_kids_sql .= " and deliveryReceiptId=" $request->query->get('deliveryReceiptId') . " ";
  6788.         if ($request->query->has('warehouseActionId'))
  6789.             $get_kids_sql .= " and warehouse_action_id=" $request->query->get('warehouseActionId') . " ";
  6790.         if ($request->query->has('productId'))
  6791.             $get_kids_sql .= " and product_id=" $request->query->get('productId') . " ";
  6792.         $get_kids_sql .= " and company_id=" $companyId " limit 25";
  6793.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  6794.         
  6795.         $get_kids $stmt;
  6796.         if (!empty($get_kids)) {
  6797.             foreach ($get_kids as $d) {
  6798.                 $dt = array(
  6799.                     'id' => $d['id'],
  6800.                     'productId' => $d['product_id'],
  6801.                     'warehouseId' => $d['warehouse_id'],
  6802.                     'warehouseActionId' => $d['warehouse_action_id'],
  6803. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  6804.                     'sales_code' => str_pad($d['sales_code'], 13'0'STR_PAD_LEFT),
  6805.                     'serial_no' => str_pad($d['serial_no'], 13'0'STR_PAD_LEFT),
  6806.                     'imei1' => str_pad($d['imei1'], 13'0'STR_PAD_LEFT),
  6807.                     'imei2' => str_pad($d['imei2'], 13'0'STR_PAD_LEFT),
  6808.                     'imei3' => str_pad($d['imei3'], 13'0'STR_PAD_LEFT),
  6809.                     'imei4' => str_pad($d['imei4'], 13'0'STR_PAD_LEFT),
  6810. //                'sales_code'=>$d['sales_code'],
  6811.                 );
  6812.                 $data[] = $dt;
  6813.             }
  6814.         }
  6815. //        if($request->query->has('returnJson'))
  6816.         {
  6817.             return new JsonResponse(
  6818.                 array(
  6819.                     'success' => true,
  6820. //                    'page_title' => 'Product Details',
  6821. //                    'company_data' => $company_data,
  6822.                     'data' => $data,
  6823. //                    'exId'=>$id,
  6824. //                'productByCodeData' => $productByCodeData,
  6825. //                'productData' => $productData,
  6826. //                'currInvList' => $currInvList,
  6827. //                'productList' => Inventory::ProductList($em, $companyId),
  6828. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  6829. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  6830. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  6831. //                'unitList' => Inventory::UnitTypeList($em),
  6832. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  6833. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  6834. //                'warehouseList' => Inventory::WarehouseList($em),
  6835.                 )
  6836.             );
  6837.         }
  6838.     }
  6839.     public function selectDataAjaxAction(Request $request$queryStr '',
  6840.                                                  $version 'latest',
  6841.                                                  $identifier '_default_',
  6842.                                                  $apiKey '_ignore_'
  6843.     )
  6844.     {
  6845.         $em $this->getDoctrine()->getManager();
  6846.         $em_goc $this->getDoctrine()->getManager('company_group');
  6847.         $companyId 0;
  6848.         $skipCurrentUserIdRestriction $request->get('skipCurrentUserIdRestriction'0);
  6849.         $dataOnly $request->get('dataOnly'0);
  6850.         $skipCurrentEmployeeIdRestriction $request->get('skipCurrentEmployeeIdRestriction'0);
  6851.         $skipCurrentUserLoginIdRestriction $request->get('skipCurrentUserLoginIdRestriction'0);
  6852.         $currentUserId $request->getSession()->get(UserConstants::USER_ID0);
  6853.         $currentEmployeeId $request->getSession()->get(UserConstants::USER_EMPLOYEE_ID0);
  6854.         $currentUserLoginIds = [];
  6855.         if ($request->request->get('entity_group'0)) {
  6856.             $companyId 0;
  6857.             $em $this->getDoctrine()->getManager('company_group');
  6858.         } else {
  6859.             if ($request->request->get('appId'0) != 0) {
  6860.                 $gocEnabled 0;
  6861.                 if ($this->container->hasParameter('entity_group_enabled'))
  6862.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  6863.                 else
  6864.                     $gocEnabled 1;
  6865.                 if ($gocEnabled == 1) {
  6866.                     $dataToConnect System::changeDoctrineManagerByAppId(
  6867.                         $this->getDoctrine()->getManager('company_group'),
  6868.                         $gocEnabled,
  6869.                         $request->request->get('appId'0)
  6870.                     );
  6871.                     if (!empty($dataToConnect)) {
  6872.                         $connector $this->container->get('application_connector');
  6873.                         $connector->resetConnection(
  6874.                             'default',
  6875.                             $dataToConnect['dbName'],
  6876.                             $dataToConnect['dbUser'],
  6877.                             $dataToConnect['dbPass'],
  6878.                             $dataToConnect['dbHost'],
  6879.                             $reset true
  6880.                         );
  6881.                         $em $this->getDoctrine()->getManager();
  6882.                     }
  6883.                 }
  6884.             } else if ($request->getSession()->get(UserConstants::USER_APP_ID) != && $request->getSession()->get(UserConstants::USER_APP_ID) != null) {
  6885.                 $gocEnabled 0;
  6886.                 if ($this->container->hasParameter('entity_group_enabled'))
  6887.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  6888.                 else
  6889.                     $gocEnabled 1;
  6890.                 if ($gocEnabled == 1) {
  6891.                     $dataToConnect System::changeDoctrineManagerByAppId(
  6892.                         $this->getDoctrine()->getManager('company_group'),
  6893.                         $gocEnabled,
  6894.                         $request->getSession()->get(UserConstants::USER_APP_ID)
  6895.                     );
  6896.                     if (!empty($dataToConnect)) {
  6897.                         $connector $this->container->get('application_connector');
  6898.                         $connector->resetConnection(
  6899.                             'default',
  6900.                             $dataToConnect['dbName'],
  6901.                             $dataToConnect['dbUser'],
  6902.                             $dataToConnect['dbPass'],
  6903.                             $dataToConnect['dbHost'],
  6904.                             $reset true
  6905.                         );
  6906.                         $em $this->getDoctrine()->getManager();
  6907.                     }
  6908.                 }
  6909.             }
  6910.             $companyId $this->getLoggedUserCompanyId($request);
  6911.         }
  6912.         $configData = [];
  6913.         $isSingleDataset 1;
  6914.         $dataSet $request->request->has('dataset') ? $request->request->get('dataset') : [];
  6915.         if (is_string($dataSet)) $dataSet json_decode($dataSettrue);
  6916.         $valuePairs $request->get('valuePairs', []);
  6917.         if (is_string($valuePairs)) $valuePairs json_decode($valuePairstrue);
  6918.         $allResult = [];
  6919.         $datasetFromConfig = [];
  6920.         if ($identifier != '_default_') {
  6921.             $config_file $this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' $identifier 'Config.json';
  6922.             if (!file_exists($config_file)) {
  6923.             } else {
  6924.                 $fileText file_get_contents($config_file);
  6925.                 //now replace any value pairs
  6926.                 foreach ($valuePairs as $kkeeyy => $vvaalluuee) {
  6927.                     if (is_array($vvaalluuee)) {
  6928.                         if (isset($vvaalluuee['value']) && isset($vvaalluuee['type'])) {
  6929.                             if ($vvaalluuee['type'] == 'array'$fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee['value']), $fileText);
  6930.                             if ($vvaalluuee['type'] == 'value'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  6931.                             if ($vvaalluuee['type'] == 'text'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  6932.                         } else {
  6933.                             $fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee), $fileText);
  6934.                         }
  6935.                     }
  6936.                     $fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee$fileText);
  6937.                 }
  6938.                 $fileText str_ireplace('_query_'$request->get('query'$queryStr), $fileText);
  6939.                 $fileText str_ireplace('_itemLimit_'$request->get('itemLimit''_all_'), $fileText);
  6940.                 $fileText str_ireplace('_offset_'$request->get('offset', ($request->get('itemLimit'10))*($request->get('page'1)-1)), $fileText);
  6941.                 if (!(strpos($fileText'_CURRENT_USER_LOGIN_IDS_') === false) && $skipCurrentUserLoginIdRestriction == 0) {
  6942.                     $userInfo = [];
  6943.                     if ($request->getSession()->get(UserConstants::USER_TYPE0) == UserConstants::USER_TYPE_APPLICANT) {
  6944.                         $userInfo $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityLoginLog')->findBy(
  6945.                             array('userId' => $currentUserId)
  6946.                         );
  6947.                     } else {
  6948.                         $userInfo $em->getRepository('ApplicationBundle\\Entity\\SysLoginLog')->findBy(
  6949.                             array('userId' => $currentUserId)
  6950.                         );
  6951.                     }
  6952.                     foreach ($userInfo as $uLogininfo) {
  6953.                         $currentUserLoginIds[] = $uLogininfo->getLoginId();
  6954.                     }
  6955.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_'json_encode($currentUserLoginIds), $fileText);
  6956.                 } else {
  6957.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_''_EMPTY_'$fileText);
  6958.                 }
  6959.                 if (!(strpos($fileText'_CURRENT_USER_ID_') === false) && $skipCurrentUserIdRestriction == 0) {
  6960.                     $fileText str_ireplace('_CURRENT_USER_ID_'$currentUserId$fileText);
  6961.                 } else {
  6962.                     $fileText str_ireplace('_CURRENT_USER_ID_''_EMPTY_'$fileText);
  6963.                 }
  6964.                 if (!(strpos($fileText'_CURRENT_USER_EMPLOYEE_ID_') === false) && $skipCurrentEmployeeIdRestriction == 0) {
  6965.                     if ((strpos($fileText'skipCurrentEmployeeIdRestriction') === false)) {
  6966.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_'$currentEmployeeId$fileText);
  6967.                     } else {
  6968.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  6969.                     }
  6970.                 } else {
  6971.                     $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  6972.                 }
  6973.                 if ($fileText)
  6974.                     $datasetFromConfig json_decode($fileTexttrue);
  6975.                 $skipCurrentUserIdRestriction = isset($datasetFromConfig['skipCurrentUserIdRestriction']) ? $datasetFromConfig['skipCurrentUserIdRestriction'] : $skipCurrentUserIdRestriction;
  6976.                 $skipCurrentEmployeeIdRestriction = isset($datasetFromConfig['skipCurrentEmployeeIdRestriction']) ? $datasetFromConfig['skipCurrentEmployeeIdRestriction'] : $skipCurrentEmployeeIdRestriction;
  6977.                 $skipCurrentUserLoginIdRestriction = isset($datasetFromConfig['skipCurrentUserLoginIdRestriction']) ? $datasetFromConfig['skipCurrentUserLoginIdRestriction'] : $skipCurrentUserLoginIdRestriction;
  6978.             }
  6979.         }
  6980.         if ($dataSet == null$dataSet = [];
  6981. //        return new JsonResponse(array(
  6982. //            'queryStr'=>$queryStr
  6983. //        ));
  6984.         if (!empty($datasetFromConfig)) {
  6985.             if (isset($datasetFromConfig['tableName'])) {
  6986.                 $isSingleDataset 1;
  6987.                 $dataSet[] = $datasetFromConfig;
  6988.             } else {
  6989.                 if (count($datasetFromConfig) == 1)
  6990.                     $isSingleDataset 1;
  6991.                 $dataSet $datasetFromConfig;
  6992.             }
  6993.         }
  6994.         if (empty($dataSet)) {
  6995.             $isSingleDataset 1;
  6996.             $singleDataSet = array(
  6997.                 "valueField" => $request->request->has('valueField') ? $request->request->get('valueField') : 'id',
  6998.                 "query" => $request->get('query'$queryStr),
  6999.                 "headMarkers" => $request->get('headMarkers'''),
  7000.                 "headMarkersStrictMatch" => $request->get('headMarkersStrictMatch'0),
  7001.                 "itemLimit" => $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25,
  7002.                 "selectorId" => $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_',
  7003.                 "textField" => $request->request->has('textField') ? $request->request->get('textField') : 'name',
  7004.                 "tableName" => $request->request->has('tableName') ? $request->request->get('tableName') : '',
  7005.                 "isMultiple" => $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0,
  7006.                 "orConditions" => $request->request->has('orConditions') ? $request->request->get('orConditions') : [],
  7007.                 "andConditions" => $request->request->has('andConditions') ? $request->request->get('andConditions') : [],
  7008.                 "andOrConditions" => $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [],
  7009.                 "mustConditions" => $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [],
  7010.                 "joinTableData" => $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [],
  7011.                 "renderTextFormat" => $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '',
  7012.                 "setDataForSingle" => $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0,
  7013.                 "dataId" => $request->request->has('dataId') ? $request->request->get('dataId') : 0,
  7014.                 "lastChildrenOnly" => $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0,
  7015.                 "parentOnly" => $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0,
  7016.                 "parentIdField" => $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id',
  7017.                 "skipDefaultCompanyId" => $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1,
  7018.                 "offset" => $request->request->has('offset') ? $request->request->get('offset') : 0,
  7019.                 "returnTotalMatchedEntriesFlag" => $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0,
  7020.                 "nextOffset" => 0,
  7021.                 "totalMatchedEntries" => 0,
  7022.                 "convertToObject" => $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [],
  7023.                 "convertDateToStringFieldList" => $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [],
  7024.                 "orderByConditions" => $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [],
  7025.                 "convertToUrl" => $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [],
  7026.                 "fullPathList" => $request->request->has('fullPathList') ? $request->request->get('fullPathList') : [],
  7027.                 "ret_data" => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  7028.             );
  7029.             $dataSet[] = $singleDataSet;
  7030.         }
  7031. //        $lastResult = [
  7032. //            'identifier' => $identifier,
  7033. //            'dataSet' => $dataSet,
  7034. //        ];
  7035. //        return new JsonResponse($lastResult);
  7036.         $userId $request->getSession()->get(UserConstants::USER_ID);
  7037. //        public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [],$userId=0)
  7038.         foreach ($dataSet as $dsIndex => $dataConfig) {
  7039.             $companyId 0;
  7040.             $queryStringIndividual $queryStr;
  7041.             $data = [];
  7042.             $data_by_id = [];
  7043.             $setValueArray = [];
  7044.             $silentChangeSelectize 0;
  7045.             $setValue 0;
  7046.             $setValueType 0;// 0 for id , 1 for query
  7047.             $selectAll 0;
  7048.             if ($queryStringIndividual == '_EMPTY_')
  7049.                 $queryStringIndividual '';
  7050.             if (isset($dataConfig['query']))
  7051.                 $queryStringIndividual $dataConfig['query'];
  7052.             if ($queryStringIndividual == '_EMPTY_')
  7053.                 $queryStringIndividual '';
  7054.             $queryStringIndividual str_replace('_FSLASH_''/'$queryStringIndividual);
  7055.             if ($queryStringIndividual === '#setValue:') {
  7056.                 $queryStringIndividual '';
  7057.             }
  7058.             if (!(strpos($queryStringIndividual'_silent_change_') === false)) {
  7059.                 $silentChangeSelectize 1;
  7060.                 $queryStringIndividual str_ireplace('_silent_change_'''$queryStringIndividual);
  7061.             }
  7062.             if (!(strpos($queryStringIndividual'#setValue:') === false)) {
  7063.                 $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStringIndividual));
  7064.                 foreach ($setValueArrayBeforeFilter as $svf) {
  7065.                     if ($svf == '_ALL_') {
  7066.                         $selectAll 1;
  7067.                         $setValueArray = [];
  7068.                         continue;
  7069.                     }
  7070.                     if (is_numeric($svf)) {
  7071.                         $setValueArray[] = ($svf 1);
  7072.                         $setValue $svf 1;
  7073.                     }
  7074.                 }
  7075.                 $queryStringIndividual '';
  7076.             }
  7077.             $valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
  7078.             $headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''//Special Field
  7079.             $headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0//Special Field
  7080.             $itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
  7081.             $selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
  7082.             $textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
  7083.             $table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
  7084.             $isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
  7085.             $orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
  7086.             $andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
  7087.             $andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
  7088.             $mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
  7089.             $joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
  7090.             $renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
  7091.             $setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
  7092.             $dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
  7093.             $lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
  7094.             $parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
  7095.             $parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
  7096.             $skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
  7097.             $offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
  7098.             $returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
  7099.             $nextOffset 0;
  7100.             $totalMatchedEntries 0;
  7101.             $convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
  7102.             $convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
  7103.             $orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
  7104.             $convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
  7105.             $fullPathList = isset($dataConfig['fullPathList']) ? $dataConfig['fullPathList'] : [];
  7106.             if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  7107.             if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  7108.             if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  7109.             if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  7110.             if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  7111.             if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  7112.             if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  7113.             if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  7114.             if (is_string($fullPathList)) $fullPathList json_decode($fullPathListtrue);
  7115. //            return new JsonResponse(array(
  7116. //                'dataSet'=>$dataSet,
  7117. //                'dataConfig'=>$dataConfig,
  7118. //                'hi'=>$this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json',
  7119. //                'hiD'=>file_get_contents($this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json')
  7120. //            ));
  7121.             if ($table == '') {
  7122.                 $lastResult = array(
  7123.                     'success' => false,
  7124.                     'currentTs' => (new \Datetime())->format('U'),
  7125.                     'isMultiple' => $isMultiple,
  7126.                     'setValueArray' => $setValueArray,
  7127.                     'setValue' => $setValue,
  7128.                     'data' => $data,
  7129.                     'dataId' => $dataId,
  7130.                     'selectorId' => $selectorId,
  7131.                     'dataById' => $data_by_id,
  7132.                     'selectedId' => 0,
  7133.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  7134.                 );
  7135.             } else {
  7136.                 $restrictionData = array(
  7137. //            'table'=>'relevantField in restriction'
  7138.                     'warehouse_action' => 'warehouseActionIds',
  7139.                     'branch' => 'branchIds',
  7140.                     'warehouse' => 'warehouseIds',
  7141.                     'production_process_settings' => 'productionProcessIds',
  7142.                 );
  7143.                 $restrictionIdList = [];
  7144.                 $filterQryForCriteria "select ";
  7145.                 $selectQry "";
  7146. //        $selectQry=" `$table`.* ";
  7147.                 $selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
  7148.                 $selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
  7149.                 if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  7150.                 foreach ($selectFieldList as $selField) {
  7151.                     if ($selectQry != '')
  7152.                         $selectQry .= ", ";
  7153.                     if ($selField == '*')
  7154.                         $selectQry .= " `$table`.$selField ";
  7155.                     else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7156.                         if ($selectPrefix == '')
  7157.                             $selectQry .= " count(*)  ";
  7158.                         else
  7159.                             $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  7160.                     } else {
  7161.                         if ($selectPrefix == '')
  7162.                             $selectQry .= " `$table`.`$selField` ";
  7163.                         else
  7164.                             $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  7165.                     }
  7166.                 }
  7167.                 $joinQry " from $table ";
  7168. //        $filterQryForCriteria = "select * from $table ";
  7169.                 foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  7170. //            $conditionStr.=' 1=1 ';
  7171.                     $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  7172.                     $joinTableAlias $joinTableName '_' $joinIndex;
  7173.                     $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  7174.                     $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  7175.                     $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  7176.                     $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  7177.                     $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  7178.                     $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  7179.                     $joinMustConditions = isset($joinTableDatum['joinMustConditions']) ? $joinTableDatum['joinMustConditions'] : [];
  7180.                     $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  7181.                     $joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
  7182.                     $joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
  7183.                     if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  7184.                     if (is_string($joinMustConditions)) $joinMustConditions json_decode($joinMustConditionstrue);
  7185.                     if (is_string($joinAndOrConditions)) $joinAndOrConditions json_decode($joinAndOrConditionstrue);
  7186.                     if (is_string($joinOrConditions)) $joinOrConditions json_decode($joinOrConditionstrue);
  7187.                     foreach ($selectFieldList as $selField) {
  7188.                         if ($selField == '*')
  7189.                             $selectQry .= ", `$joinTableAlias`.$selField ";
  7190.                         else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7191.                             if ($selectPrefix == '')
  7192.                                 $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  7193.                             else
  7194.                                 $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  7195.                         } else {
  7196.                             if ($selectPrefix == '')
  7197.                                 $selectQry .= ", `$joinTableAlias`.`$selField`  ";
  7198.                             else
  7199.                                 $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  7200.                         }
  7201.                     }
  7202.                     $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  7203. //            if($joinTablePrimaryField!='')
  7204. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7205. //            $joinAndString = '';
  7206.                     $joinMustString '';
  7207.                     if ($joinTablePrimaryField != '') {
  7208.                         if (!(strpos($joinTablePrimaryField'.') === false)) {
  7209.                             $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` pika $fieldJoinType `$joinTablePrimaryField` ";
  7210.                         }
  7211.                         else
  7212.                             $joinQry .= "  `$joinTableAlias`.`$joinTableOnField$fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7213.                     }
  7214.                     foreach ($joinMustConditions as $mustCondition) {
  7215. //            $conditionStr.=' 1=1 ';
  7216.                         $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  7217.                         $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  7218.                         $aliasInCondition $table;
  7219.                         if (!(strpos($cfield'.') === false)) {
  7220.                             $fullCfieldArray explode('.'$cfield);
  7221.                             $aliasInCondition $fullCfieldArray[0];
  7222.                             $cfield $fullCfieldArray[1];
  7223.                         }
  7224.                         $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  7225.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7226.                             if ($joinMustString != '')
  7227.                                 $joinMustString .= " and ";
  7228.                             if ($ctype == 'like') {
  7229.                                 $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7230.                                 $wordsBySpaces explode(' '$cvalue);
  7231.                                 foreach ($wordsBySpaces as $word) {
  7232.                                     if ($joinMustString != '')
  7233.                                         $joinMustString .= " and ";
  7234.                                     $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7235.                                 }
  7236.                             } else if ($ctype == 'not like') {
  7237.                                 $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7238.                                 $wordsBySpaces explode(' '$cvalue);
  7239.                                 foreach ($wordsBySpaces as $word) {
  7240.                                     if ($joinMustString != '')
  7241.                                         $joinMustString .= " and ";
  7242.                                     $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7243.                                 }
  7244.                             } else if ($ctype == 'not_in') {
  7245.                                 $joinMustString .= " ( ";
  7246.                                 if (in_array('null'$cvalue)) {
  7247.                                     $joinMustString .= " `$joinTableAlias`.$cfield is not null";
  7248.                                     $cvalue array_diff($cvalue, ['null']);
  7249.                                     if (!empty($cvalue))
  7250.                                         $joinMustString .= " and ";
  7251.                                 }
  7252.                                 if (in_array(''$cvalue)) {
  7253.                                     $joinMustString .= "`$joinTableAlias`.$cfield != '' ";
  7254.                                     $cvalue array_diff($cvalue, ['']);
  7255.                                     if (!empty($cvalue))
  7256.                                         $joinMustString .= " and ";
  7257.                                 }
  7258.                                 $joinMustString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7259.                             } else if ($ctype == 'in') {
  7260.                                 if (in_array('null'$cvalue)) {
  7261.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null";
  7262.                                     $cvalue array_diff($cvalue, ['null']);
  7263.                                     if (!empty($cvalue))
  7264.                                         $joinMustString .= " and ";
  7265.                                 }
  7266.                                 if (in_array(''$cvalue)) {
  7267.                                     $joinMustString .= "`$joinTableAlias`.$cfield = '' ";
  7268.                                     $cvalue array_diff($cvalue, ['']);
  7269.                                     if (!empty($cvalue))
  7270.                                         $joinMustString .= " and ";
  7271.                                 }
  7272.                                 $joinMustString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7273.                             } else if ($ctype == '=') {
  7274. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7275. //                            $fullCfieldArray = explode('.', $cfield);
  7276. //                            $aliasInCondition = $fullCfieldArray[0];
  7277. //                            $cfield = $fullCfieldArray[1];
  7278. //                        }
  7279.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7280.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null ";
  7281.                                 else
  7282.                                     $joinMustString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7283.                             } else if ($ctype == '!=') {
  7284.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7285.                                     $joinMustString .= "`$joinTableAlias`.$cfield is not null ";
  7286.                                 else
  7287.                                     $joinMustString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7288.                             } else {
  7289.                                 if (is_string($cvalue))
  7290.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7291.                                 else
  7292.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7293.                             }
  7294.                         }
  7295.                     }
  7296. //            if ($joinMustString != '') {
  7297. //                if ($conditionStr != '')
  7298. //                    $conditionStr .= (" and (" . $joinMustString . ") ");
  7299. //                else
  7300. //                    $conditionStr .= ("  (" . $joinMustString . ") ");
  7301. //            }
  7302.                     if ($joinMustString != '') {
  7303.                         $joinQry .= (' and ' $joinMustString);
  7304. //                        $joinQry.=' and (';
  7305.                     }
  7306.                     $mustBracketDone 0;
  7307.                     $joinAndString '';
  7308. //                    if ($joinTablePrimaryField != '')
  7309. //                        $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7310.                     foreach ($joinAndConditions as $andCondition) {
  7311. //            $conditionStr.=' 1=1 ';
  7312.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  7313.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  7314.                         $aliasInCondition $table;
  7315.                         if (!(strpos($cfield'.') === false)) {
  7316.                             $fullCfieldArray explode('.'$cfield);
  7317.                             $aliasInCondition $fullCfieldArray[0];
  7318.                             $cfield $fullCfieldArray[1];
  7319.                         }
  7320.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  7321.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7322.                             if ($joinAndString != '')
  7323.                                 $joinAndString .= " and ";
  7324.                             if ($ctype == 'like') {
  7325.                                 $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7326.                                 $wordsBySpaces explode(' '$cvalue);
  7327.                                 foreach ($wordsBySpaces as $word) {
  7328.                                     if ($joinAndString != '')
  7329.                                         $joinAndString .= " and ";
  7330.                                     $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7331.                                 }
  7332.                             } else if ($ctype == 'not like') {
  7333.                                 $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7334.                                 $wordsBySpaces explode(' '$cvalue);
  7335.                                 foreach ($wordsBySpaces as $word) {
  7336.                                     if ($joinAndString != '')
  7337.                                         $joinAndString .= " and ";
  7338.                                     $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7339.                                 }
  7340.                             } else if ($ctype == 'not_in') {
  7341.                                 $joinAndString .= " ( ";
  7342.                                 if (in_array('null'$cvalue)) {
  7343.                                     $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  7344.                                     $cvalue array_diff($cvalue, ['null']);
  7345.                                     if (!empty($cvalue))
  7346.                                         $joinAndString .= " and ";
  7347.                                 }
  7348.                                 if (in_array(''$cvalue)) {
  7349.                                     $joinAndString .= "`$joinTableAlias`.$cfield != '' ";
  7350.                                     $cvalue array_diff($cvalue, ['']);
  7351.                                     if (!empty($cvalue))
  7352.                                         $joinAndString .= " and ";
  7353.                                 }
  7354.                                 $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7355.                             } else if ($ctype == 'in') {
  7356.                                 if (in_array('null'$cvalue)) {
  7357.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null";
  7358.                                     $cvalue array_diff($cvalue, ['null']);
  7359.                                     if (!empty($cvalue))
  7360.                                         $joinAndString .= " and ";
  7361.                                 }
  7362.                                 if (in_array(''$cvalue)) {
  7363.                                     $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  7364.                                     $cvalue array_diff($cvalue, ['']);
  7365.                                     if (!empty($cvalue))
  7366.                                         $joinAndString .= " and ";
  7367.                                 }
  7368.                                 $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7369.                             } else if ($ctype == '=') {
  7370. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7371. //                            $fullCfieldArray = explode('.', $cfield);
  7372. //                            $aliasInCondition = $fullCfieldArray[0];
  7373. //                            $cfield = $fullCfieldArray[1];
  7374. //                        }
  7375.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7376.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  7377.                                 else
  7378.                                     $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7379.                             } else if ($ctype == '!=') {
  7380.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7381.                                     $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  7382.                                 else
  7383.                                     $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7384.                             } else {
  7385.                                 if (is_string($cvalue))
  7386.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7387.                                 else
  7388.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7389.                             }
  7390.                         }
  7391.                     }
  7392. //            if ($joinAndString != '') {
  7393. //                if ($conditionStr != '')
  7394. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  7395. //                else
  7396. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  7397. //            }
  7398.                     if ($joinAndString != '') {
  7399.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7400.                             $joinQry .= ' and (';
  7401.                             $mustBracketDone 1;
  7402.                         }
  7403.                         if ($joinQry != '')
  7404.                             $joinQry .= (" and (" $joinAndString ") ");
  7405.                         else
  7406.                             $joinQry .= ("  (" $joinAndString ") ");
  7407.                     }
  7408.                     $joinAndOrString "";
  7409.                     foreach ($joinAndOrConditions as $andOrCondition) {
  7410. //            $conditionStr.=' 1=1 ';
  7411.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  7412.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  7413.                         $aliasInCondition $table;
  7414.                         if (!(strpos($cfield'.') === false)) {
  7415.                             $fullCfieldArray explode('.'$cfield);
  7416.                             $aliasInCondition $fullCfieldArray[0];
  7417.                             $cfield $fullCfieldArray[1];
  7418.                         }
  7419.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  7420.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7421.                             if ($joinAndOrString != '')
  7422.                                 $joinAndOrString .= " or ";
  7423.                             if ($ctype == 'like') {
  7424.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7425.                                 $wordsBySpaces explode(' '$cvalue);
  7426.                                 foreach ($wordsBySpaces as $word) {
  7427.                                     if ($joinAndOrString != '')
  7428.                                         $joinAndOrString .= " or ";
  7429.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7430.                                 }
  7431.                             } else if ($ctype == 'not like') {
  7432.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7433.                                 $wordsBySpaces explode(' '$cvalue);
  7434.                                 foreach ($wordsBySpaces as $word) {
  7435.                                     if ($joinAndOrString != '')
  7436.                                         $joinAndOrString .= " or ";
  7437.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7438.                                 }
  7439.                             } else if ($ctype == 'not_in') {
  7440.                                 $joinAndOrString .= " ( ";
  7441.                                 if (in_array('null'$cvalue)) {
  7442.                                     $joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
  7443.                                     $cvalue array_diff($cvalue, ['null']);
  7444.                                     if (!empty($cvalue))
  7445.                                         $joinAndOrString .= " or ";
  7446.                                 }
  7447.                                 if (in_array(''$cvalue)) {
  7448.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != '' ";
  7449.                                     $cvalue array_diff($cvalue, ['']);
  7450.                                     if (!empty($cvalue))
  7451.                                         $joinAndOrString .= " or ";
  7452.                                 }
  7453.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7454.                             } else if ($ctype == 'in') {
  7455.                                 if (in_array('null'$cvalue)) {
  7456.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null";
  7457.                                     $cvalue array_diff($cvalue, ['null']);
  7458.                                     if (!empty($cvalue))
  7459.                                         $joinAndOrString .= " or ";
  7460.                                 }
  7461.                                 if (in_array(''$cvalue)) {
  7462.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  7463.                                     $cvalue array_diff($cvalue, ['']);
  7464.                                     if (!empty($cvalue))
  7465.                                         $joinAndOrString .= " or ";
  7466.                                 }
  7467.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7468.                             } else if ($ctype == '=') {
  7469. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7470. //                            $fullCfieldArray = explode('.', $cfield);
  7471. //                            $aliasInCondition = $fullCfieldArray[0];
  7472. //                            $cfield = $fullCfieldArray[1];
  7473. //                        }
  7474.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7475.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
  7476.                                 else
  7477.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7478.                             } else if ($ctype == '!=') {
  7479.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7480.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
  7481.                                 else
  7482.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7483.                             } else {
  7484.                                 if (is_string($cvalue))
  7485.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7486.                                 else
  7487.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7488.                             }
  7489.                         }
  7490.                     }
  7491. //            if ($joinAndOrString != '')
  7492. //                $joinQry .= $joinAndOrString;
  7493.                     if ($joinAndOrString != '') {
  7494.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7495.                             $joinQry .= ' and (';
  7496.                             $mustBracketDone 1;
  7497.                         }
  7498.                         if ($joinQry != '')
  7499.                             $joinQry .= (" and (" $joinAndOrString ") ");
  7500.                         else
  7501.                             $joinQry .= ("  (" $joinAndOrString ") ");
  7502.                     }
  7503.                     //pika
  7504.                     $joinOrString "";
  7505.                     foreach ($joinOrConditions as $orCondition) {
  7506. //            $conditionStr.=' 1=1 ';
  7507.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  7508.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  7509.                         $aliasInCondition $table;
  7510.                         if (!(strpos($cfield'.') === false)) {
  7511.                             $fullCfieldArray explode('.'$cfield);
  7512.                             $aliasInCondition $fullCfieldArray[0];
  7513.                             $cfield $fullCfieldArray[1];
  7514.                         }
  7515.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  7516.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7517.                             if ($joinOrString != '' || $joinAndString != '' || $joinMustString != '')
  7518.                                 $joinOrString .= " or ";
  7519.                             if ($ctype == 'like') {
  7520.                                 $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7521.                                 $wordsBySpaces explode(' '$cvalue);
  7522.                                 foreach ($wordsBySpaces as $word) {
  7523.                                     if ($joinOrString != '')
  7524.                                         $joinOrString .= " or ";
  7525.                                     $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7526.                                 }
  7527.                             } else if ($ctype == 'not like') {
  7528.                                 $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7529.                                 $wordsBySpaces explode(' '$cvalue);
  7530.                                 foreach ($wordsBySpaces as $word) {
  7531.                                     if ($joinOrString != '')
  7532.                                         $joinOrString .= " or ";
  7533.                                     $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7534.                                 }
  7535.                             } else if ($ctype == 'not_in') {
  7536.                                 $joinOrString .= " ( ";
  7537.                                 if (in_array('null'$cvalue)) {
  7538.                                     $joinOrString .= " `$joinTableAlias`.$cfield is not null";
  7539.                                     $cvalue array_diff($cvalue, ['null']);
  7540.                                     if (!empty($cvalue))
  7541.                                         $joinOrString .= " or ";
  7542.                                 }
  7543.                                 if (in_array(''$cvalue)) {
  7544.                                     $joinOrString .= "`$joinTableAlias`.$cfield != '' ";
  7545.                                     $cvalue array_diff($cvalue, ['']);
  7546.                                     if (!empty($cvalue))
  7547.                                         $joinOrString .= " or ";
  7548.                                 }
  7549.                                 $joinOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7550.                             } else if ($ctype == 'in') {
  7551.                                 if (in_array('null'$cvalue)) {
  7552.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null";
  7553.                                     $cvalue array_diff($cvalue, ['null']);
  7554.                                     if (!empty($cvalue))
  7555.                                         $joinOrString .= " or ";
  7556.                                 }
  7557.                                 if (in_array(''$cvalue)) {
  7558.                                     $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  7559.                                     $cvalue array_diff($cvalue, ['']);
  7560.                                     if (!empty($cvalue))
  7561.                                         $joinOrString .= " or ";
  7562.                                 }
  7563.                                 $joinOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7564.                             } else if ($ctype == '=') {
  7565. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7566. //                            $fullCfieldArray = explode('.', $cfield);
  7567. //                            $aliasInCondition = $fullCfieldArray[0];
  7568. //                            $cfield = $fullCfieldArray[1];
  7569. //                        }
  7570.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7571.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null ";
  7572.                                 else
  7573.                                     $joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7574.                             } else if ($ctype == '!=') {
  7575.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7576.                                     $joinOrString .= "`$joinTableAlias`.$cfield is not null ";
  7577.                                 else
  7578.                                     $joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7579.                             } else {
  7580.                                 if (is_string($cvalue))
  7581.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7582.                                 else
  7583.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7584.                             }
  7585.                         }
  7586.                     }
  7587. //            if ($joinOrString != '')
  7588. //                $joinQry .= $joinOrString;
  7589.                     if ($joinOrString != '') {
  7590.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7591.                             $joinQry .= ' and (';
  7592.                             $mustBracketDone 1;
  7593.                         }
  7594.                         if ($joinQry != '')
  7595.                             $joinQry .= (" or (" $joinOrString ") ");
  7596.                         else
  7597.                             $joinQry .= ("  (" $joinOrString ") ");
  7598.                     }
  7599.                     if ($joinMustString != '' && $mustBracketDone == 1) {
  7600.                         $joinQry .= ' ) ';
  7601.                     }
  7602. //
  7603. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7604.                 }
  7605.                 $filterQryForCriteria .= $selectQry;
  7606.                 $filterQryForCriteria .= $joinQry;
  7607.                 if ($skipDefaultCompanyId == && $companyId != && !isset($dataConfig['entity_group']))
  7608.                     $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  7609.                 else
  7610.                     $filterQryForCriteria .= " where 1=1 ";
  7611.                 $conditionStr "";
  7612.                 $aliasInCondition $table;
  7613.                 if ($headMarkers != '' && $table == 'acc_accounts_head') {
  7614.                     $markerList explode(','$headMarkers);
  7615.                     $spMarkerQry "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
  7616.                     $markerPassedHeads = [];
  7617.                     foreach ($markerList as $mrkr) {
  7618.                         $spMarkerQry .= " and marker_hash like '%" $mrkr "%'";
  7619.                     }
  7620.                     $spStmt $em->getConnection()->fetchAllAssociative($spMarkerQry);
  7621.              
  7622.                     $spStmtResults $spStmt;
  7623.                     foreach ($spStmtResults as $ggres) {
  7624.                         $markerPassedHeads[] = $ggres['accounts_head_id'];
  7625.                     }
  7626.                     if (!empty($markerPassedHeads)) {
  7627.                         if ($conditionStr != '')
  7628.                             $conditionStr .= " and (";
  7629.                         else
  7630.                             $conditionStr .= " (";
  7631.                         if ($headMarkersStrictMatch != 1) {
  7632.                             foreach ($markerPassedHeads as $mh) {
  7633.                                 $conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" $mh "/%' or ";
  7634.                             }
  7635.                         }
  7636.                         $conditionStr .= "  `$aliasInCondition`.`accounts_head_id` in (" implode(','$markerPassedHeads) . ") ";
  7637.                         $conditionStr .= " )";
  7638.                     }
  7639.                 }
  7640.                 if (isset($restrictionData[$table])) {
  7641.                     $userRestrictionData Users::getUserApplicationAccessSettings($em$userId)['options'];
  7642.                     if (isset($userRestrictionData[$restrictionData[$table]])) {
  7643.                         $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  7644.                         if ($restrictionIdList == null)
  7645.                             $restrictionIdList = [];
  7646.                     }
  7647.                     if (!empty($restrictionIdList)) {
  7648.                         if ($conditionStr != '')
  7649.                             $conditionStr .= " and ";
  7650.                         $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  7651.                     }
  7652.                 }
  7653. //        $aliasInCondition = $table;
  7654.                 if (!empty($setValueArray) || $selectAll == 1) {
  7655.                     if (!empty($setValueArray)) {
  7656.                         if ($conditionStr != '')
  7657.                             $conditionStr .= " and ";
  7658.                         $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  7659.                     }
  7660.                 } else {
  7661.                     $andString '';
  7662.                     foreach ($andConditions as $andCondition) {
  7663. //            $conditionStr.=' 1=1 ';
  7664.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  7665.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  7666.                         $aliasInCondition $table;
  7667.                         if (!(strpos($cfield'.') === false)) {
  7668.                             $fullCfieldArray explode('.'$cfield);
  7669.                             $aliasInCondition $fullCfieldArray[0];
  7670.                             $cfield $fullCfieldArray[1];
  7671.                         }
  7672.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  7673.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7674.                             if ($andString != '')
  7675.                                 $andString .= " and ";
  7676.                             if ($ctype == 'like') {
  7677.                                 $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7678.                                 $wordsBySpaces explode(' '$cvalue);
  7679.                                 foreach ($wordsBySpaces as $word) {
  7680.                                     if ($andString != '')
  7681.                                         $andString .= " and ";
  7682.                                     $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7683.                                 }
  7684.                             } else if ($ctype == 'not like') {
  7685.                                 $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7686.                                 $wordsBySpaces explode(' '$cvalue);
  7687.                                 foreach ($wordsBySpaces as $word) {
  7688.                                     if ($andString != '')
  7689.                                         $andString .= " and ";
  7690.                                     $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7691.                                 }
  7692.                             } else if ($ctype == 'not_in') {
  7693.                                 $andString .= " ( ";
  7694.                                 if (in_array('null'$cvalue)) {
  7695.                                     $andString .= " `$aliasInCondition`.$cfield is not null";
  7696.                                     $cvalue array_diff($cvalue, ['null']);
  7697.                                     if (!empty($cvalue))
  7698.                                         $andString .= " and ";
  7699.                                 }
  7700.                                 if (in_array(''$cvalue)) {
  7701.                                     $andString .= "`$aliasInCondition`.$cfield != '' ";
  7702.                                     $cvalue array_diff($cvalue, ['']);
  7703.                                     if (!empty($cvalue))
  7704.                                         $andString .= " and ";
  7705.                                 }
  7706.                                 $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7707.                             } else if ($ctype == 'in') {
  7708.                                 if (in_array('null'$cvalue)) {
  7709.                                     $andString .= "`$aliasInCondition`.$cfield is null";
  7710.                                     $cvalue array_diff($cvalue, ['null']);
  7711.                                     if (!empty($cvalue))
  7712.                                         $andString .= " and ";
  7713.                                 }
  7714.                                 if (in_array(''$cvalue)) {
  7715.                                     $andString .= "`$aliasInCondition`.$cfield = '' ";
  7716.                                     $cvalue array_diff($cvalue, ['']);
  7717.                                     if (!empty($cvalue))
  7718.                                         $andString .= " and ";
  7719.                                 }
  7720.                                 $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  7721.                             } else if ($ctype == '=') {
  7722.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7723.                                     $andString .= "`$aliasInCondition`.$cfield is null ";
  7724.                                 else
  7725.                                     $andString .= "`$aliasInCondition`.$cfield = $cvalue ";
  7726.                             } else if ($ctype == '!=') {
  7727.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7728.                                     $andString .= "`$aliasInCondition`.$cfield is not null ";
  7729.                                 else
  7730.                                     $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  7731.                             } else {
  7732.                                 if (is_string($cvalue))
  7733.                                     $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  7734.                                 else
  7735.                                     $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  7736.                             }
  7737.                         }
  7738.                     }
  7739.                     if ($andString != '') {
  7740.                         if ($conditionStr != '')
  7741.                             $conditionStr .= (" and (" $andString ") ");
  7742.                         else
  7743.                             $conditionStr .= ("  (" $andString ") ");
  7744.                     }
  7745.                     $orString '';
  7746.                     foreach ($orConditions as $orCondition) {
  7747.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  7748.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  7749.                         $aliasInCondition $table;
  7750.                         if (!(strpos($cfield'.') === false)) {
  7751.                             $fullCfieldArray explode('.'$cfield);
  7752.                             $aliasInCondition $fullCfieldArray[0];
  7753.                             $cfield $fullCfieldArray[1];
  7754.                         }
  7755.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  7756.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7757.                             if ($orString != '')
  7758.                                 $orString .= " or ";
  7759.                             if ($ctype == 'like') {
  7760.                                 $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7761.                                 $wordsBySpaces explode(' '$cvalue);
  7762.                                 foreach ($wordsBySpaces as $word) {
  7763.                                     if ($orString != '')
  7764.                                         $orString .= " or ";
  7765.                                     $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7766.                                 }
  7767.                             } else if ($ctype == 'not like') {
  7768.                                 $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7769.                                 $wordsBySpaces explode(' '$cvalue);
  7770.                                 foreach ($wordsBySpaces as $word) {
  7771.                                     if ($orString != '')
  7772.                                         $orString .= " or ";
  7773.                                     $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7774.                                 }
  7775.                             } else if ($ctype == 'not_in') {
  7776.                                 $orString .= " ( ";
  7777.                                 if (in_array('null'$cvalue)) {
  7778.                                     $orString .= " `$aliasInCondition`.$cfield is not null";
  7779.                                     $cvalue array_diff($cvalue, ['null']);
  7780.                                     if (!empty($cvalue))
  7781.                                         $orString .= " or ";
  7782.                                 }
  7783.                                 if (in_array(''$cvalue)) {
  7784.                                     $orString .= "`$aliasInCondition`.$cfield != '' ";
  7785.                                     $cvalue array_diff($cvalue, ['']);
  7786.                                     if (!empty($cvalue))
  7787.                                         $orString .= " or ";
  7788.                                 }
  7789.                                 $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7790.                             } else if ($ctype == 'in') {
  7791.                                 $orString .= " ( ";
  7792.                                 if (in_array('null'$cvalue)) {
  7793.                                     $orString .= " `$aliasInCondition`.$cfield is null";
  7794.                                     $cvalue array_diff($cvalue, ['null']);
  7795.                                     if (!empty($cvalue))
  7796.                                         $orString .= " or ";
  7797.                                 }
  7798.                                 if (in_array(''$cvalue)) {
  7799.                                     $orString .= "`$aliasInCondition`.$cfield = '' ";
  7800.                                     $cvalue array_diff($cvalue, ['']);
  7801.                                     if (!empty($cvalue))
  7802.                                         $orString .= " or ";
  7803.                                 }
  7804.                                 $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  7805.                             } else if ($ctype == '=') {
  7806.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7807.                                     $orString .= "`$aliasInCondition`.$cfield is null ";
  7808.                                 else
  7809.                                     $orString .= "`$aliasInCondition`.$cfield = $cvalue ";
  7810.                             } else if ($ctype == '!=') {
  7811.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7812.                                     $orString .= "`$aliasInCondition`.$cfield is not null ";
  7813.                                 else
  7814.                                     $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  7815.                             } else {
  7816.                                 if (is_string($cvalue))
  7817.                                     $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  7818.                                 else
  7819.                                     $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  7820.                             }
  7821.                         }
  7822.                     }
  7823.                     if ($orString != '') {
  7824.                         if ($conditionStr != '')
  7825.                             $conditionStr .= (" or (" $orString ") ");
  7826.                         else
  7827.                             $conditionStr .= ("  (" $orString ") ");
  7828.                     }
  7829.                     $andOrString '';
  7830.                     foreach ($andOrConditions as $andOrCondition) {
  7831.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  7832.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  7833.                         $aliasInCondition $table;
  7834.                         if (!(strpos($cfield'.') === false)) {
  7835.                             $fullCfieldArray explode('.'$cfield);
  7836.                             $aliasInCondition $fullCfieldArray[0];
  7837.                             $cfield $fullCfieldArray[1];
  7838.                         }
  7839.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  7840.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7841.                             if ($andOrString != '')
  7842.                                 $andOrString .= " or ";
  7843.                             if ($ctype == 'like') {
  7844.                                 $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7845.                                 $wordsBySpaces explode(' '$cvalue);
  7846.                                 foreach ($wordsBySpaces as $word) {
  7847.                                     if ($andOrString != '')
  7848.                                         $andOrString .= " or ";
  7849.                                     $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7850.                                 }
  7851.                             } else if ($ctype == 'not like') {
  7852.                                 $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7853.                                 $wordsBySpaces explode(' '$cvalue);
  7854.                                 foreach ($wordsBySpaces as $word) {
  7855.                                     if ($andOrString != '')
  7856.                                         $andOrString .= " or ";
  7857.                                     $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7858.                                 }
  7859.                             } else if ($ctype == 'in') {
  7860.                                 $andOrString .= " ( ";
  7861.                                 if (in_array('null'$cvalue)) {
  7862.                                     $andOrString .= " `$aliasInCondition`.$cfield is null";
  7863.                                     $cvalue array_diff($cvalue, ['null']);
  7864.                                     if (!empty($cvalue))
  7865.                                         $andOrString .= " or ";
  7866.                                 }
  7867.                                 if (in_array(''$cvalue)) {
  7868.                                     $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  7869.                                     $cvalue array_diff($cvalue, ['']);
  7870.                                     if (!empty($cvalue))
  7871.                                         $andOrString .= " or ";
  7872.                                 }
  7873.                                 if (!empty($cvalue))
  7874.                                     $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  7875.                                 else
  7876.                                     $andOrString .= "  ) ";
  7877.                             } else if ($ctype == 'not_in') {
  7878.                                 $andOrString .= " ( ";
  7879.                                 if (in_array('null'$cvalue)) {
  7880.                                     $andOrString .= " `$aliasInCondition`.$cfield is not null";
  7881.                                     $cvalue array_diff($cvalue, ['null']);
  7882.                                     if (!empty($cvalue))
  7883.                                         $andOrString .= " or ";
  7884.                                 }
  7885.                                 if (in_array(''$cvalue)) {
  7886.                                     $andOrString .= "`$aliasInCondition`.$cfield != '' ";
  7887.                                     $cvalue array_diff($cvalue, ['']);
  7888.                                     if (!empty($cvalue))
  7889.                                         $andOrString .= " or ";
  7890.                                 }
  7891.                                 if (!empty($cvalue))
  7892.                                     $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7893.                                 else
  7894.                                     $andOrString .= "  ) ";
  7895.                             } else if ($ctype == '=') {
  7896.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7897.                                     $andOrString .= "`$aliasInCondition`.$cfield is null ";
  7898.                                 else
  7899.                                     $andOrString .= "`$aliasInCondition`.$cfield = $cvalue ";
  7900.                             } else if ($ctype == '!=') {
  7901.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7902.                                     $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  7903.                                 else
  7904.                                     $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  7905.                             } else {
  7906.                                 if (is_string($cvalue))
  7907.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  7908.                                 else
  7909.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  7910.                             }
  7911.                         }
  7912.                     }
  7913.                     if ($andOrString != '') {
  7914.                         if ($conditionStr != '')
  7915.                             $conditionStr .= (" and (" $andOrString ") ");
  7916.                         else
  7917.                             $conditionStr .= ("  (" $andOrString ") ");
  7918.                     }
  7919.                 }
  7920.                 $mustStr '';
  7921. ///now must conditions
  7922.                 foreach ($mustConditions as $mustCondition) {
  7923. //            $conditionStr.=' 1=1 ';
  7924.                     $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  7925.                     $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  7926.                     $aliasInCondition $table;
  7927.                     if (!(strpos($cfield'.') === false)) {
  7928.                         $fullCfieldArray explode('.'$cfield);
  7929.                         $aliasInCondition $fullCfieldArray[0];
  7930.                         $cfield $fullCfieldArray[1];
  7931.                     }
  7932.                     $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  7933.                     if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7934.                         if ($mustStr != '')
  7935.                             $mustStr .= " and ";
  7936.                         if ($ctype == 'like') {
  7937.                             $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7938.                             $wordsBySpaces explode(' '$cvalue);
  7939.                             foreach ($wordsBySpaces as $word) {
  7940.                                 if ($mustStr != '')
  7941.                                     $mustStr .= " or ";
  7942.                                 $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7943.                             }
  7944.                             $mustStr .= " )";
  7945.                         } else if ($ctype == 'not like') {
  7946.                             $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7947.                             $wordsBySpaces explode(' '$cvalue);
  7948.                             foreach ($wordsBySpaces as $word) {
  7949.                                 if ($mustStr != '')
  7950.                                     $mustStr .= " and ";
  7951.                                 $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7952.                             }
  7953.                         } else if ($ctype == 'in') {
  7954.                             $mustStr .= " ( ";
  7955.                             if (in_array('null'$cvalue)) {
  7956.                                 $mustStr .= " `$aliasInCondition`.$cfield is null";
  7957.                                 $cvalue array_diff($cvalue, ['null']);
  7958.                                 if (!empty($cvalue))
  7959.                                     $mustStr .= " or ";
  7960.                             }
  7961.                             if (in_array(''$cvalue)) {
  7962.                                 $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  7963.                                 $cvalue array_diff($cvalue, ['']);
  7964.                                 if (!empty($cvalue))
  7965.                                     $mustStr .= " or ";
  7966.                             }
  7967.                             $mustStr .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  7968.                         } else if ($ctype == 'not_in') {
  7969.                             $mustStr .= " ( ";
  7970.                             if (in_array('null'$cvalue)) {
  7971.                                 $mustStr .= " `$aliasInCondition`.$cfield is not null";
  7972.                                 $cvalue array_diff($cvalue, ['null']);
  7973.                                 if (!empty($cvalue))
  7974.                                     $mustStr .= " and ";
  7975.                             }
  7976.                             if (in_array(''$cvalue)) {
  7977.                                 $mustStr .= "`$aliasInCondition`.$cfield != '' ";
  7978.                                 $cvalue array_diff($cvalue, ['']);
  7979.                                 if (!empty($cvalue))
  7980.                                     $mustStr .= " and ";
  7981.                             }
  7982.                             $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7983.                         } else if ($ctype == '=') {
  7984.                             if ($cvalue == 'null' || $cvalue == 'Null')
  7985.                                 $mustStr .= "`$aliasInCondition`.$cfield is null ";
  7986.                             else
  7987.                                 $mustStr .= "`$aliasInCondition`.$cfield = $cvalue ";
  7988.                         } else if ($ctype == '!=') {
  7989.                             if ($cvalue == 'null' || $cvalue == 'Null')
  7990.                                 $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  7991.                             else
  7992.                                 $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  7993.                         } else {
  7994.                             if (is_string($cvalue))
  7995.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  7996.                             else
  7997.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  7998.                         }
  7999.                     }
  8000.                 }
  8001.                 if ($mustStr != '') {
  8002.                     if ($conditionStr != '')
  8003.                         $conditionStr .= (" and (" $mustStr ") ");
  8004.                     else
  8005.                         $conditionStr .= ("  (" $mustStr ") ");
  8006.                 }
  8007.                 if ($conditionStr != '')
  8008.                     $filterQryForCriteria .= (" and (" $conditionStr ") ");
  8009.                 if ($lastChildrenOnly == 1) {
  8010.                     if ($filterQryForCriteria != '')
  8011.                         $filterQryForCriteria .= ' and';
  8012.                     $filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  8013.                 } else if ($parentOnly == 1) {
  8014.                     if ($filterQryForCriteria != '')
  8015.                         $filterQryForCriteria .= ' and';
  8016.                     $filterQryForCriteria .= "`$table`.`$valueField`  in ( select distinct $parentIdField from  $table)";
  8017.                 }
  8018.                 if (!empty($orderByConditions)) {
  8019.                     $filterQryForCriteria .= "  order by ";
  8020.                     $fone 1;
  8021.                     foreach ($orderByConditions as $orderByCondition) {
  8022.                         if ($fone != 1) {
  8023.                             $filterQryForCriteria .= " , ";
  8024.                         }
  8025.                         if (isset($orderByCondition['valueList'])) {
  8026.                             if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  8027.                             if ($orderByCondition['valueList'] == null)
  8028.                                 $orderByCondition['valueList'] = [];
  8029.                             $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  8030.                         } else
  8031.                             $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  8032.                         $fone 0;
  8033.                     }
  8034.                 }
  8035.                 if ($returnTotalMatchedEntriesFlag == 1) {
  8036. //            $stmt = $em->getConnection()->executeStatement($get_kids_sql);
  8037. //            
  8038. //            $get_kids = $stmt;
  8039.                 }
  8040.                 if ($filterQryForCriteria != '')
  8041.                     if (!empty($setValueArray) || $selectAll == 1) {
  8042.                     } else {
  8043.                         if ($itemLimit != '_ALL_')
  8044.                             $filterQryForCriteria .= "  limit $offset$itemLimit ";
  8045.                         else
  8046.                             $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  8047.                     }
  8048.                 $get_kids_sql $filterQryForCriteria;
  8049.                 $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  8050.                 
  8051.                 $get_kids $stmt;
  8052.                 $selectedId 0;
  8053.                 if ($table == 'warehouse_action') {
  8054.                     if (empty($get_kids)) {
  8055.                         $get_kids_sql_2 "select * from warehouse_action";
  8056.                         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql_2);
  8057.                         
  8058.                         $get_kids2 $stmt;
  8059.                         if (empty($get_kids2))
  8060.                             $get_kids GeneralConstant::$warehouse_action_list;
  8061.                     }
  8062.                 }
  8063.                 if (!empty($get_kids)) {
  8064.                     $nextOffset $offset count($get_kids);
  8065.                     $nextOffset++;
  8066.                     foreach ($get_kids as $pa) {
  8067.                         if (!empty($setValueArray) && $selectAll == 0) {
  8068.                             if (!in_array($pa[$valueField], $setValueArray))
  8069.                                 continue;
  8070.                         }
  8071.                         if (!empty($restrictionIdList)) {
  8072.                             if (!in_array($pa[$valueField], $restrictionIdList))
  8073.                                 continue;
  8074.                         }
  8075.                         if ($selectAll == 1) {
  8076.                             $setValueArray[] = $pa[$valueField];
  8077.                             $setValue $pa[$valueField];
  8078.                         } else if (count($get_kids) == && $setDataForSingle == 1) {
  8079.                             $setValueArray[] = $pa[$valueField];
  8080.                             $setValue $pa[$valueField];
  8081.                         }
  8082.                         if ($valueField != '')
  8083.                             $pa['value'] = $pa[$valueField];
  8084.                         $renderedText $renderTextFormat;
  8085.                         $compare_array = [];
  8086.                         if ($renderTextFormat != '') {
  8087.                             $renderedText $renderTextFormat;
  8088.                             $compare_arrayFull = [];
  8089.                             $compare_array = [];
  8090.                             $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  8091.                             );
  8092.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  8093.                             if (isset($compare_arrayFull[0]))
  8094.                                 $compare_array $compare_arrayFull[0];
  8095. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  8096.                             foreach ($compare_array as $cmpdt) {
  8097.                                 $tbr str_replace("__"""$cmpdt);
  8098.                                 if ($tbr != '') {
  8099.                                     if (isset($pa[$tbr])) {
  8100.                                         if ($pa[$tbr] == null)
  8101.                                             $renderedText str_replace($cmpdt''$renderedText);
  8102.                                         else
  8103.                                             $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  8104.                                     } else {
  8105.                                         $renderedText str_replace($cmpdt''$renderedText);
  8106.                                     }
  8107.                                 }
  8108.                             }
  8109.                         }
  8110.                         $pa['rendered_text'] = $renderedText;
  8111.                         $pa['text'] = ($textField != '' $pa[$textField] : '');
  8112. //                $pa['compare_array'] = $compare_array;
  8113.                         foreach ($convertToObjectFieldList as $convField) {
  8114.                             if (isset($pa[$convField])) {
  8115.                                 $taA json_decode($pa[$convField], true);
  8116.                                 if ($taA == null$taA = [];
  8117.                                 $pa[$convField] = $taA;
  8118.                             } else {
  8119.                                 $pa[$convField] = [];
  8120.                             }
  8121.                         }
  8122.                         foreach ($convertDateToStringFieldList as $convField) {
  8123.                             if (is_array($convField)) {
  8124.                                 $fld $convField['field'];
  8125.                                 $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  8126.                             } else {
  8127.                                 $fld $convField;
  8128.                                 $frmt 'Y-m-d H:i:s';
  8129.                             }
  8130.                             if (isset($pa[$fld])) {
  8131.                                 $taA = new \DateTime($pa[$fld]);
  8132.                                 $pa[$fld] = $taA->format($frmt);
  8133.                             }
  8134.                         }
  8135.                         foreach ($convertToUrl as $convField) {
  8136. //
  8137. //                            $fld = $convField;
  8138. //
  8139. //
  8140. //                            if (isset($pa[$fld])) {
  8141. //
  8142. //
  8143. //                                $pa[$fld] =
  8144. //                                    $this->generateUrl(
  8145. //                                        'dashboard', [
  8146. //
  8147. //                                    ], UrlGenerator::ABSOLUTE_URL
  8148. //                                    ).'/'.$pa[$fld];
  8149. //
  8150. //                            }
  8151.                         }
  8152.                         foreach ($fullPathList as $pathField) {
  8153.                             $fld $pathField;
  8154.                             if (isset($pa[$fld])) {
  8155.                                 if ($pa[$fld] !='' && $pa[$fld] !=null) {
  8156.                                     $pa[$fld]=($this->generateUrl(
  8157.                                             'dashboard', [
  8158.                                         ], UrlGenerator::ABSOLUTE_URL
  8159.                                         ).$pa[$fld]);
  8160.                                 }
  8161.                             }
  8162.                         }
  8163.                         $pa['currentTs'] = (new \Datetime())->format('U');
  8164.                         $data[] = $pa;
  8165.                         if ($valueField != '') {
  8166.                             $data_by_id[$pa[$valueField]] = $pa;
  8167.                             $selectedId $pa[$valueField];
  8168.                         }
  8169.                     }
  8170.                 }
  8171.                 if ($dataOnly == 1)
  8172.                     $lastResult = array(
  8173.                         'success' => true,
  8174.                         'data' => $data,
  8175.                         'currentTs' => (new \Datetime())->format('U'),
  8176.                         'restrictionIdList' => $restrictionIdList,
  8177.                         'nextOffset' => $nextOffset,
  8178.                         'totalMatchedEntries' => $totalMatchedEntries,
  8179.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8180.                     );
  8181.                 else
  8182.                     $lastResult = array(
  8183.                         'success' => true,
  8184.                         'data' => $data,
  8185.                         'tableName' => $table,
  8186.                         'setValue' => $setValue,
  8187.                         'currentTs' => (new \Datetime())->format('U'),
  8188.                         'restrictionIdList' => $restrictionIdList,
  8189.                         'andConditions' => $andConditions,
  8190.                         'queryStr' => $queryStringIndividual,
  8191.                         'isMultiple' => $isMultiple,
  8192.                         'nextOffset' => $nextOffset,
  8193.                         'totalMatchedEntries' => $totalMatchedEntries,
  8194.                         'selectorId' => $selectorId,
  8195.                         'setValueArray' => $setValueArray,
  8196.                         'silentChangeSelectize' => $silentChangeSelectize,
  8197.                         'convertToObjectFieldList' => $convertToObjectFieldList,
  8198.                         'conditionStr' => $conditionStr,
  8199. //                    'andStr' => $andString,
  8200. //                    'andOrStr' => $andOrString,
  8201.                         'dataById' => $data_by_id,
  8202.                         'selectedId' => $selectedId,
  8203.                         'dataId' => $dataId,
  8204.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8205.                     );
  8206.             }
  8207.             $allResult[] = $lastResult;
  8208.         }
  8209.         if ($isSingleDataset == 1)
  8210.             return new JsonResponse($lastResult);
  8211.         else
  8212.             return new JsonResponse($allResult);
  8213.     }
  8214.     public function updatePlanningItemSequenceAction(Request $request$queryStr '')
  8215.     {
  8216.         $em $this->getDoctrine()->getManager();
  8217.         $stmt $em->getConnection()->fetchAllAssociative("select  `id` , parent_id, sequence from planning_item where sequence is null 
  8218.             ORDER BY parent_id ASC, id ASC
  8219.                         ");
  8220.         
  8221.         $query_output $stmt;
  8222.         foreach ($query_output as $dupe) {
  8223.             System::updatePlanningItemSequence($em$dupe["id"]);
  8224.         }
  8225.         System::updatePlanningItemSequence(
  8226.             $em,
  8227.             $request->request->get('planningItemId'0),
  8228.             $request->request->get('assignType''_ASSIGN_')   ///can be _MOVE_UP_ or _MOVE_DOWN_
  8229.         );
  8230. //        if($request->query->has('returnJson'))
  8231.         return new JsonResponse(
  8232.             array(
  8233.                 'success' => true,
  8234.                 'data' => [],
  8235.             )
  8236.         );
  8237.     }
  8238.     public function insertDataAjaxAction(Request $request$queryStr '')
  8239.     {
  8240.         $em $this->getDoctrine()->getManager();
  8241. //        if($request->query->has('big_data_test'))
  8242. //        {
  8243. //            for($t=0;$t<$request->request->get('big_data_test',10000);$t++) {
  8244. //                $em = $this->getDoctrine()->getManager('company_group');
  8245. //                $NOTIFICATION = new EntityNotification();
  8246. //                $NOTIFICATION->setAppId(1);
  8247. //                $NOTIFICATION->setCompanyId(0);
  8248. //                $NOTIFICATION->setCompanyId(0);
  8249. //                $NOTIFICATION->setBody('Test Description'.$t);
  8250. //                $NOTIFICATION->setTitle('Test Title'.$t);
  8251. //                $NOTIFICATION->setExpireTs(0);
  8252. //                $NOTIFICATION->setIsBuddybee(0);
  8253. //                $NOTIFICATION->setType(0);
  8254. //                $em->persist($NOTIFICATION);
  8255. //                $em->flush();
  8256. //            }
  8257. //
  8258. //            return new JsonResponse(
  8259. //                array(
  8260. //                    'success' => true,
  8261. //                    'data' => [],
  8262. //
  8263. //
  8264. //                )
  8265. //            );
  8266. //
  8267. //
  8268. //        }
  8269.         if ($request->request->get('entity_group'0)) {
  8270.             $companyId 0;
  8271.             $em $this->getDoctrine()->getManager('company_group');
  8272.         } else
  8273.             $companyId $this->getLoggedUserCompanyId($request);
  8274.         if ($companyId) {
  8275.             $company_data = [];
  8276. //            $company_data = Company::getCompanyData($em, $companyId);
  8277.         } else {
  8278.             $companyId 0;
  8279.             $company_data = [];
  8280.         }
  8281. //        $theEntity= new EntityNotification();
  8282. //        $entityName = 'EntityNotification';
  8283. //
  8284. //        $className='\\CompanyGroupBundle\\Entity\\'.$entityName;
  8285. //
  8286. //
  8287. //            $theEntity= new $className();
  8288.         $dataToAdd $request->request->has('dataToAdd') ? $request->request->get('dataToAdd') : [];
  8289.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8290.         if ($dataToAdd == null$dataToAdd = [];
  8291.         $dataToRemove $request->request->has('dataToRemove') ? $request->request->get('dataToRemove') : [];
  8292.         if (is_string($dataToRemove)) $dataToAdd json_decode($dataToRemovetrue);
  8293.         if ($dataToRemove == null$dataToRemove = [];
  8294.         $relData = [];
  8295.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8296.         $updatedDataList = [];
  8297.         foreach ($dataToAdd as $dataInd => $dat) {
  8298.             $entityName $dat['entityName'];
  8299.             $idField $dat['idField'];
  8300.             $findByField = isset($dat['findByField']) ? $dat['findByField'] : '';
  8301.             $findByValue = isset($dat['findByValue']) ? $dat['findByValue'] : '';
  8302.             $returnRefIndex $dat['returnRefIndex'];
  8303.             $findById $dat['findId'];
  8304.             $dataFields = isset($dat['dataFields']) ? $dat['dataFields'] : [];
  8305.             $noCreation = isset($dat['noCreation']) ? $dat['noCreation'] : 0;
  8306.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  8307.             $preAdditionalSql = isset($dat['preAdditionalSql']) ? $dat['preAdditionalSql'] : '';
  8308.             if ($preAdditionalSql != '') {
  8309. //            if ($entityName == 'PlanningItem') {
  8310. //
  8311. //                $stmt='select disctinct parent_id from planning_item;';
  8312. //                
  8313. //                $get_kids = $stmt;
  8314. //                $p_ids=[];
  8315. //                foreach($get_kids as $g)
  8316. //                {
  8317. //                    $p_ids[]=$g['parent_id'];
  8318. //                }
  8319. //
  8320. //
  8321. //
  8322.                 $stmt $em->getConnection()->executeStatement($preAdditionalSql);
  8323.                 
  8324.                 
  8325. //
  8326. //
  8327.             }
  8328.             if ($entityName == 'PlanningItem') {
  8329.                 $stmt $em->getConnection()->fetchAllAssociative("select  `id` , parent_id, sequence from planning_item where sequence is null
  8330.             ORDER BY parent_id ASC, id ASC
  8331.                         ");
  8332.                 
  8333.                 $query_output $stmt;
  8334.                 foreach ($query_output as $dupe) {
  8335.                     System::updatePlanningItemSequence($em$dupe["id"]);
  8336.                 }
  8337.             }
  8338.             $className = ($request->request->get('entity_group'0) ? '\\CompanyGroupBundle\\Entity\\' '\\ApplicationBundle\\Entity\\') . $entityName;
  8339.             if (
  8340.                 ($findById == || $findById == '_NA_') && $findByField == '' && $noCreation == 0
  8341.             ) {
  8342.                 $theEntity = new $className();
  8343. //                $theEntity= new EntityNotification();
  8344.             } else {
  8345.                 if ($findByField != '') {
  8346.                     $theEntity $em->getRepository($className)->findOneBy(
  8347.                         array
  8348.                         (
  8349.                             $findByField => $findByValue,
  8350.                         )
  8351.                     );
  8352.                 } else {
  8353.                     $theEntity $em->getRepository($className)->findOneBy(
  8354.                         array
  8355.                         (
  8356.                             $idField => $findById,
  8357.                         )
  8358.                     );
  8359.                 }
  8360.             }
  8361.             if (!$theEntity && $noCreation == 0)
  8362.                 $theEntity = new $className();
  8363.             foreach ($dataFields as $dt) {
  8364.                 $setMethod 'set' ucfirst($dt['field']);
  8365.                 $getMethod 'get' ucfirst($dt['field']);
  8366.                 $type = isset($dt['type']) ? $dt['type'] : '_VALUE_';
  8367.                 $action = isset($dt['action']) ? $dt['action'] : '_REPLACE_';
  8368.                 if (method_exists($theEntity$setMethod)) {
  8369.                     $oldValue $theEntity->{$getMethod}();
  8370.                     $newValue $oldValue;
  8371.                     if ($type == '_VALUE_') {
  8372.                         $newValue $dt['value'];
  8373.                     }
  8374.                     if ($type == '_DECIMAL_') {
  8375.                         $newValue $dt['value'];
  8376.                     }
  8377.                     if ($type == '_DATE_') {
  8378.                         $newValue = new \DateTime($dt['value']);
  8379.                     }
  8380.                     if ($type == '_ARRAY_') {
  8381.                         $oldValue json_decode($oldValue);
  8382.                         if ($oldValue == null$oldValue = [];
  8383.                         if ($action == '_REPLACE_') {
  8384.                             $newValue json_encode($dt['value']);
  8385.                         }
  8386.                         if ($action == '_APPEND_') {
  8387.                             $newValue array_merge($oldValuearray_values(array_diff([$dt['value']], $oldValue)));
  8388.                         }
  8389.                         if ($action == '_MERGE_') {
  8390.                             $newValue array_merge($oldValuearray_values(array_diff($dt['value'], $oldValue)));
  8391.                         }
  8392.                         if ($action == '_EXCLUDE_') {
  8393.                             $newValue array_values(array_diff($oldValue, [$dt['value']]));
  8394.                         }
  8395.                         if ($action == '_EXCLUDE_ARRAY_') {
  8396.                             $newValue array_values(array_diff($oldValue$dt['value']));
  8397.                         }
  8398.                         $newValue json_encode($newValue);
  8399.                     }
  8400.                     $theEntity->{$setMethod}($newValue); // `foo!`
  8401. //                    $theEntity->setCompletionPercentage(78); // `foo!`
  8402.                 }
  8403.             }
  8404.             if ($additionalSql != '') {
  8405. //            if ($entityName == 'PlanningItem') {
  8406. //
  8407. //                $stmt='select disctinct parent_id from planning_item;';
  8408. //                
  8409. //                $get_kids = $stmt;
  8410. //                $p_ids=[];
  8411. //                foreach($get_kids as $g)
  8412. //                {
  8413. //                    $p_ids[]=$g['parent_id'];
  8414. //                }
  8415. //
  8416. //
  8417. //
  8418.                 $stmt $em->getConnection()->executeStatement($additionalSql);
  8419.                 
  8420.                 
  8421. //
  8422. //
  8423.             }
  8424.             if (($findById == || $findById == '_NA_') && $noCreation == 0) {
  8425.                 $em->persist($theEntity);
  8426.                 $em->flush();
  8427.                 $getMethod 'get' ucfirst($idField);
  8428.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8429.             } else if ($theEntity) {
  8430.                 $em->flush();
  8431.                 $getMethod 'get' ucfirst($idField);
  8432.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8433.             }
  8434.             if ($entityName == 'PlanningItem') {
  8435.                 $stmt $em->getConnection()->fetchAllAssociative('select distinct parent_id from planning_item;');
  8436.                 
  8437.                 $get_kids $stmt;
  8438.                 $p_ids = [];
  8439.                 foreach ($get_kids as $g) {
  8440.                     $p_ids[] = $g['parent_id'];
  8441.                 }
  8442.                 $stmt $em->getConnection()->executeStatement('UPDATE planning_item d SET d.`has_child` =0 WHERE d.id NOT IN (' implode(','$p_ids) . '); 
  8443.                           UPDATE planning_item d SET d.`has_child` =1 WHERE d.id  IN (' implode(','$p_ids) . ')');
  8444.                 
  8445.                 
  8446.                 $updatedData System::updatePlanningItemSequence($em$theEntity->getId());
  8447.                 $theEntity $updatedData['primaryOne'];
  8448.                 $theEntityUpdated $theEntity;
  8449.                 if ($theEntityUpdated->getEntryType() == 4)///cashflow
  8450.                 {
  8451.                     MiscActions::AddCashFlowProjection($em0, [
  8452.                         'planningItemId' => $theEntityUpdated->getId(),
  8453.                         'fundRequisitionId' => 0,
  8454.                         'concernedPersonId' => 0,
  8455.                         'type' => 1//exp
  8456.                         'subType' => 1//1== khoroch hobe 2: ashbe
  8457.                         'cashFlowType' => 1//2== RCV /in  1: Payment/out
  8458.                         'creationType' => 1//auto
  8459.                         'amountType' => 1//fund
  8460.                         'cashFlowAmount' => 0,
  8461.                         'expAstAmount' => 0,
  8462.                         'accumulatedCashFlowAmount' => 0,
  8463.                         'accumulatedCashFlowBalance' => 0,
  8464.                         'accumulatedExpAstAmount' => 0,
  8465.                         'relevantExpAstHeadId' => 0,
  8466.                         'balancingHeadId' => 0,
  8467.                         'cashFlowHeadId' => 0,
  8468.                         'cashFlowHeadType' => 1,
  8469.                         'relevantProductIds' => [],
  8470.                         'reminderDateTs' => 0,
  8471.                         'cashFlowDateTs' => 0,
  8472.                         'expAstRealizationDateTs' => 0,
  8473.                     ]);
  8474.                 }
  8475.             } else if ($entityName == 'TaskLog') {
  8476.                 $session $request->getSession();
  8477.                 if ($theEntity) {
  8478.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  8479.                     $currTime = new \DateTime();
  8480.                     $options = array(
  8481.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8482.                         'notification_server' => $this->container->getParameter('notification_server'),
  8483.                     );
  8484.                     $positionsArray = [
  8485.                         array(
  8486.                             'employeeId' => $empId,
  8487.                             'userId' => $session->get(UserConstants::USER_ID0),
  8488.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  8489.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  8490.                             'lat' => 23.8623834,
  8491.                             'lng' => 90.3979294,
  8492.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING,
  8493. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  8494.                         )
  8495.                     ];
  8496.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  8497.                     if ($positionsArray == null$positionsArray = [];
  8498.                     $dataByAttId = [];
  8499.                     $workPlaceType '_UNSET_';
  8500.                     foreach ($positionsArray as $findex => $d) {
  8501.                         $sysUserId 0;
  8502.                         $userId 0;
  8503.                         $empId 0;
  8504.                         $dtTs 0;
  8505.                         $timeZoneStr '+0000';
  8506.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  8507.                         if (isset($d['userId'])) $userId $d['userId'];
  8508.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  8509.                         if (isset($d['tsMilSec'])) {
  8510.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  8511.                         }
  8512.                         if ($dtTs == 0) {
  8513.                             $currTsTime = new \DateTime();
  8514.                             $dtTs $currTsTime->format('U');
  8515.                         } else {
  8516.                             $currTsTime = new \DateTime('@' $dtTs);
  8517.                         }
  8518.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  8519.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  8520.                         $EmployeeAttendance $this->getDoctrine()
  8521.                             ->getRepository(EmployeeAttendance::class)
  8522.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  8523.                         if (!$EmployeeAttendance) {
  8524.                             $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8525.                             $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8526.                             $EmployeeAttendance = new EmployeeAttendance;
  8527.                         } else {
  8528.                             if ($EmployeeAttendance->getCurrentLocation() == 'out') {
  8529.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8530.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8531.                             } else {
  8532.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8533.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8534.                             }
  8535.                         }
  8536.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  8537.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  8538.                             $workPlaceType '_STATIC_';
  8539.                         }
  8540.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  8541.                             $dataByAttId[$attendanceInfo->getId()] = array(
  8542.                                 'attendanceInfo' => $attendanceInfo,
  8543.                                 'empId' => $empId,
  8544.                                 'lat' => 0,
  8545.                                 'lng' => 0,
  8546.                                 'address' => 0,
  8547.                                 'sysUserId' => $sysUserId,
  8548.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8549.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8550.                                 'positionArray' => []
  8551.                             );
  8552.                         $posData = array(
  8553.                             'ts' => $dtTs,
  8554.                             'lat' => $d['lat'],
  8555.                             'lng' => $d['lng'],
  8556.                             'marker' => $d['markerId'],
  8557.                             'src' => 2,
  8558.                         );
  8559.                         $posDataArray = array(
  8560.                             $dtTs,
  8561.                             $d['lat'],
  8562.                             $d['lng'],
  8563.                             $d['markerId'],
  8564.                             2
  8565.                         );
  8566.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  8567.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  8568.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  8569.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  8570.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  8571.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  8572.                         if (isset($d['address']))
  8573.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  8574. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  8575.                     }
  8576.                     $response = array(
  8577.                         'success' => true,
  8578.                     );
  8579.                     foreach ($dataByAttId as $attInfoId => $d) {
  8580.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  8581.                             $d['empId'],
  8582.                             $d['sysUserId'],
  8583.                             $d['companyId'],
  8584.                             $d['appId'],
  8585.                             $request,
  8586.                             $d['attendanceInfo'],
  8587.                             $options,
  8588.                             $d['positionArray'],
  8589.                             $d['lat'],
  8590.                             $d['lng'],
  8591.                             $d['address'],
  8592.                             $d['markerId']
  8593.                         );
  8594.                     }
  8595.                     $session->set(UserConstants::USER_CURRENT_TASK_ID$theEntity->getId());
  8596.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$theEntity->getPlanningItemId());
  8597.                 } else {
  8598.                     $session->set(UserConstants::USER_CURRENT_TASK_ID0);
  8599.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID0);
  8600.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  8601.                     $currTime = new \DateTime();
  8602.                     $options = array(
  8603.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8604.                         'notification_server' => $this->container->getParameter('notification_server'),
  8605.                     );
  8606.                     $positionsArray = [
  8607.                         array(
  8608.                             'employeeId' => $empId,
  8609.                             'userId' => $session->get(UserConstants::USER_ID0),
  8610.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  8611.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  8612.                             'lat' => 23.8623834,
  8613.                             'lng' => 90.3979294,
  8614.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT,
  8615. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  8616.                         )
  8617.                     ];
  8618.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  8619.                     if ($positionsArray == null$positionsArray = [];
  8620.                     $dataByAttId = [];
  8621.                     $workPlaceType '_UNSET_';
  8622.                     foreach ($positionsArray as $findex => $d) {
  8623.                         $sysUserId 0;
  8624.                         $userId 0;
  8625.                         $empId 0;
  8626.                         $dtTs 0;
  8627.                         $timeZoneStr '+0000';
  8628.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  8629.                         if (isset($d['userId'])) $userId $d['userId'];
  8630.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  8631.                         if (isset($d['tsMilSec'])) {
  8632.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  8633.                         }
  8634.                         if ($dtTs == 0) {
  8635.                             $currTsTime = new \DateTime();
  8636.                             $dtTs $currTsTime->format('U');
  8637.                         } else {
  8638.                             $currTsTime = new \DateTime('@' $dtTs);
  8639.                         }
  8640.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  8641.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  8642.                         $EmployeeAttendance $this->getDoctrine()
  8643.                             ->getRepository(EmployeeAttendance::class)
  8644.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  8645.                         if (!$EmployeeAttendance) {
  8646.                             continue;
  8647.                         } else {
  8648.                         }
  8649.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  8650.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT) {
  8651.                             $workPlaceType '_STATIC_';
  8652.                         }
  8653.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  8654.                             $dataByAttId[$attendanceInfo->getId()] = array(
  8655.                                 'attendanceInfo' => $attendanceInfo,
  8656.                                 'empId' => $empId,
  8657.                                 'lat' => 0,
  8658.                                 'lng' => 0,
  8659.                                 'address' => 0,
  8660.                                 'sysUserId' => $sysUserId,
  8661.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8662.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8663.                                 'positionArray' => []
  8664.                             );
  8665.                         $posData = array(
  8666.                             'ts' => $dtTs,
  8667.                             'lat' => $d['lat'],
  8668.                             'lng' => $d['lng'],
  8669.                             'marker' => $d['markerId'],
  8670.                             'src' => 2,
  8671.                         );
  8672.                         $posDataArray = array(
  8673.                             $dtTs,
  8674.                             $d['lat'],
  8675.                             $d['lng'],
  8676.                             $d['markerId'],
  8677.                             2
  8678.                         );
  8679.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  8680.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  8681.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  8682.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  8683.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  8684.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  8685.                         if (isset($d['address']))
  8686.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  8687. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  8688.                     }
  8689.                     $response = array(
  8690.                         'success' => true,
  8691.                     );
  8692.                     foreach ($dataByAttId as $attInfoId => $d) {
  8693.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  8694.                             $d['empId'],
  8695.                             $d['sysUserId'],
  8696.                             $d['companyId'],
  8697.                             $d['appId'],
  8698.                             $request,
  8699.                             $d['attendanceInfo'],
  8700.                             $options,
  8701.                             $d['positionArray'],
  8702.                             $d['lat'],
  8703.                             $d['lng'],
  8704.                             $d['address'],
  8705.                             $d['markerId']
  8706.                         );
  8707.                     }
  8708.                 }
  8709.                 $theEntityUpdated $theEntity;
  8710.             } else
  8711.                 $theEntityUpdated $theEntity;
  8712. //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  8713.             $getters = [];
  8714.             if ($theEntityUpdated)
  8715.                 $getters array_filter(get_class_methods($theEntityUpdated), function ($method) {
  8716.                     return 'get' === substr($method03);
  8717.                 });
  8718.             $updatedData = [];
  8719.             foreach ($getters as $getter) {
  8720.                 $indForThis str_replace('get'''$getter);
  8721.                 $indForThis lcfirst($indForThis);
  8722.                 $updatedData[$indForThis] = $theEntityUpdated->{$getter}();
  8723.             }
  8724.             $updatedDataList[$dataInd] = $updatedData;
  8725.         }
  8726.         foreach ($dataToRemove as $dataInd => $dat) {
  8727.             $entityName $dat['entityName'];
  8728.             $idField $dat['idField'];
  8729.             $findById $dat['findId'];
  8730.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  8731.             $theEntityList $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle\\Entity\\' 'ApplicationBundle:') . $entityName)->findBy(
  8732.                 array
  8733.                 (
  8734.                     $idField => $findById,
  8735.                 )
  8736.             );
  8737.             foreach ($theEntityList as $dt) {
  8738.                 $em->remove($dt);
  8739.                 $em->flush();
  8740.             }
  8741.             if ($additionalSql != '') {
  8742. //            if ($entityName == 'PlanningItem') {
  8743. //
  8744. //                $stmt='select disctinct parent_id from planning_item;';
  8745. //                
  8746. //                $get_kids = $stmt;
  8747. //                $p_ids=[];
  8748. //                foreach($get_kids as $g)
  8749. //                {
  8750. //                    $p_ids[]=$g['parent_id'];
  8751. //                }
  8752. //
  8753. //
  8754. //
  8755.                 $stmt $em->getConnection()->executeStatement($additionalSql);
  8756.                 
  8757.                 
  8758. //
  8759. //
  8760.             }
  8761.             $updatedDataList[$dataInd] = [];
  8762.         }
  8763. //        if ($table == '') {
  8764. //            return new JsonResponse(
  8765. //                array(
  8766. //                    'success' => false,
  8767. ////                    'page_title' => 'Product Details',
  8768. ////                    'company_data' => $company_data,
  8769. //                    'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8770. //
  8771. //                )
  8772. //            );
  8773. //        }
  8774. //        if($request->query->has('returnJson'))
  8775.         return new JsonResponse(
  8776.             array(
  8777.                 'success' => true,
  8778.                 'data' => $relData,
  8779.                 'updatedDataList' => $updatedDataList,
  8780.             )
  8781.         );
  8782.     }
  8783.     public function GetAvailableQtyAction(Request $request$id 0)
  8784.     {
  8785.         $em $this->getDoctrine()->getManager();
  8786.         $productId $request->request->has('productId') ? $request->request->get('productId') : 0;
  8787.         $colorId $request->request->has('colorId') ? $request->request->get('colorId') : 0;
  8788.         $dataId $request->request->has('dataId') ? $request->request->get('dataId') : 0;
  8789.         $allowedWarehouseIds $request->request->has('warehouseId') ? [$request->request->get('warehouseId')] : [];
  8790.         $allowedWarehouseActionIds $request->request->has('warehouseActionId') ? [$request->request->get('warehouseActionId')] : [];
  8791.         $qty Inventory::getSellableProductQty($em$productId$allowedWarehouseIds$allowedWarehouseActionIds$colorId);
  8792.         return new JsonResponse(array("success" => true,
  8793.             "qty" => $qty,
  8794.             "dataId" => $dataId,
  8795.         ));
  8796.     }
  8797.     public
  8798.     function labelFormatSelectAjaxAction(Request $request$queryStr '')
  8799.     {
  8800.         $em $this->getDoctrine()->getManager();
  8801.         $companyId $this->getLoggedUserCompanyId($request);
  8802.         $company_data Company::getCompanyData($em$companyId);
  8803.         $data = [];
  8804.         $data_by_id = [];
  8805.         $html '';
  8806.         $productByCodeData = [];
  8807.         if ($queryStr == '_EMPTY_')
  8808.             $queryStr '';
  8809.         if ($request->request->has('query') && $queryStr == '')
  8810.             $queryStr $request->request->get('queryStr');
  8811.         if ($queryStr == '_EMPTY_')
  8812.             $queryStr '';
  8813.         $filterQryForCriteria "select * from label_format where company_id=" $companyId " ";
  8814.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  8815.             $filterQryForCriteria .= " and label_type=" $request->request->get('dataType');
  8816.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  8817.             $filterQryForCriteria .= " and format_id=" $request->request->get('formatId');
  8818.         else if ($queryStr != '')
  8819.             $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' or `format_code` like '%" $queryStr "%') ";
  8820.         if ($filterQryForCriteria != '')
  8821.             $filterQryForCriteria .= "  limit 25";
  8822.         $get_kids_sql $filterQryForCriteria;
  8823. //        if ($request->request->has('productIds'))
  8824. //
  8825. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  8826. //        else if ($request->request->has('productCode'))
  8827. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  8828. //        else if ($filterQryForCriteria!='')
  8829. //            $get_kids_sql = $filterQryForCriteria;
  8830. //
  8831. //        else
  8832. //               $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";
  8833.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  8834.         
  8835.         $get_kids $stmt;
  8836.         $productId 0;
  8837.         if (!empty($get_kids)) {
  8838.             foreach ($get_kids as $product) {
  8839.                 $pa = array();
  8840.                 $pa['id'] = $product['format_id'];
  8841.                 $pa['name'] = $product['name'];
  8842.                 $pa['format_code'] = $product['format_code'] . '. ' $product['name'];
  8843.                 $pa['id_code_name'] = $product['format_id'] . '. ' $product['format_code'] . ' - ' $product['name'] . ' ';
  8844.                 $pa['text'] = $product['name'];
  8845.                 $pa['value'] = $product['format_id'];
  8846.                 $data[] = $pa;
  8847.                 $data_by_id[$product['format_id']] = $pa;
  8848.                 $productId $product['format_id'];
  8849.             }
  8850.         }
  8851. //        if($request->query->has('returnJson'))
  8852.         {
  8853.             return new JsonResponse(
  8854.                 array(
  8855.                     'success' => true,
  8856. //                    'page_title' => 'Product Details',
  8857. //                    'company_data' => $company_data,
  8858.                     'data' => $data,
  8859.                     'dataById' => $data_by_id,
  8860.                     'productId' => $productId,
  8861.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8862. //                    'exId'=>$id,
  8863. //                'productByCodeData' => $productByCodeData,
  8864. //                'productData' => $productData,
  8865. //                'currInvList' => $currInvList,
  8866. //                'productList' => Inventory::ProductList($em, $companyId),
  8867. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  8868. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  8869. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  8870. //                'unitList' => Inventory::UnitTypeList($em),
  8871. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  8872. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  8873. //                'warehouseList' => Inventory::WarehouseList($em),
  8874.                 )
  8875.             );
  8876.         }
  8877.     }
  8878.     public
  8879.     function CategoryListSelectAjaxAction(Request $request$queryStr '')
  8880.     {
  8881.         $em $this->getDoctrine()->getManager();
  8882.         $companyId $this->getLoggedUserCompanyId($request);
  8883.         $company_data Company::getCompanyData($em$companyId);
  8884.         $data = [];
  8885.         $data_by_id = [];
  8886.         $html '';
  8887.         $productByCodeData = [];
  8888.         if ($queryStr == '_EMPTY_')
  8889.             $queryStr '';
  8890.         if ($request->request->has('query') && $queryStr == '')
  8891.             $queryStr $request->request->get('queryStr');
  8892.         if ($queryStr == '_EMPTY_')
  8893.             $queryStr '';
  8894.         $filterQryForCriteria "select * from inv_product_categories where company_id=" $companyId " ";
  8895.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  8896.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  8897.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  8898.         if ($filterQryForCriteria != '')
  8899.             $filterQryForCriteria .= "  limit 25";
  8900.         $get_kids_sql $filterQryForCriteria;
  8901. //        if ($request->request->has('productIds'))
  8902. //
  8903. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  8904. //        else if ($request->request->has('productCode'))
  8905. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  8906. //        else if ($filterQryForCriteria!='')
  8907. //            $get_kids_sql = $filterQryForCriteria;
  8908. //
  8909. //        else
  8910. //               $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";
  8911.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  8912.         
  8913.         $get_kids $stmt;
  8914.         $productId 0;
  8915.         if (!empty($get_kids)) {
  8916.             foreach ($get_kids as $product) {
  8917.                 $pa = array();
  8918.                 $pa['id'] = $product['id'];
  8919.                 $pa['name'] = $product['name'];
  8920.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  8921.                 $pa['globalId'] = $product['global_id'];
  8922.                 $pa['text'] = $product['name'];
  8923.                 $pa['value'] = $product['id'];
  8924.                 $pa['igId'] = $product['ig_id'];
  8925. //                $pa['categoryId'] = $product['category_id'];
  8926. //                $pa['subCategoryId'] = $product['sub_category_id'];
  8927.                 $data[] = $pa;
  8928.                 $data_by_id[$product['id']] = $pa;
  8929.                 $productId $product['id'];
  8930.             }
  8931.         }
  8932. //        if($request->query->has('returnJson'))
  8933.         {
  8934.             return new JsonResponse(
  8935.                 array(
  8936.                     'success' => true,
  8937. //                    'page_title' => 'Product Details',
  8938. //                    'company_data' => $company_data,
  8939.                     'data' => $data,
  8940.                     'dataById' => $data_by_id,
  8941.                     'productId' => $productId,
  8942.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8943. //                    'exId'=>$id,
  8944. //                'productByCodeData' => $productByCodeData,
  8945. //                'productData' => $productData,
  8946. //                'currInvList' => $currInvList,
  8947. //                'productList' => Inventory::ProductList($em, $companyId),
  8948. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  8949. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  8950. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  8951. //                'unitList' => Inventory::UnitTypeList($em),
  8952. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  8953. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  8954. //                'warehouseList' => Inventory::WarehouseList($em),
  8955.                 )
  8956.             );
  8957.         }
  8958.     }
  8959.     public
  8960.     function SubCategoryListSelectAjaxAction(Request $request$queryStr '')
  8961.     {
  8962.         $em $this->getDoctrine()->getManager();
  8963.         $companyId $this->getLoggedUserCompanyId($request);
  8964.         $company_data Company::getCompanyData($em$companyId);
  8965.         $data = [];
  8966.         $data_by_id = [];
  8967.         $html '';
  8968.         $productByCodeData = [];
  8969.         if ($queryStr == '_EMPTY_')
  8970.             $queryStr '';
  8971.         if ($request->request->has('query') && $queryStr == '')
  8972.             $queryStr $request->request->get('queryStr');
  8973.         if ($queryStr == '_EMPTY_')
  8974.             $queryStr '';
  8975.         $filterQryForCriteria "select * from inv_product_sub_categories where company_id=" $companyId " ";
  8976.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  8977.             $filterQryForCriteria .= " and sub_category_id=" $request->request->get('subCategoryId');
  8978.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  8979.             $filterQryForCriteria .= " and category_id=" $request->request->get('categoryId');
  8980.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  8981.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  8982.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  8983.             if ($request->request->get('parentId') != 0)
  8984.                 $filterQryForCriteria .= " and  parent_id=" $request->request->get('parentId');
  8985.             else
  8986.                 $filterQryForCriteria .= " and ( parent_id =0 or parent_id is null ) ";
  8987.         if ($request->request->has('level') && $request->request->get('level') != '')
  8988.             if ($request->request->get('level') != 0)
  8989.                 $filterQryForCriteria .= " and level=" $request->request->get('level');
  8990.             else
  8991.                 $filterQryForCriteria .= " and ( level =0 or level is null) ";
  8992.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  8993.         if ($filterQryForCriteria != '')
  8994.             $filterQryForCriteria .= "  limit 25";
  8995.         $get_kids_sql $filterQryForCriteria;
  8996. //        if ($request->request->has('productIds'))
  8997. //
  8998. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  8999. //        else if ($request->request->has('productCode'))
  9000. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9001. //        else if ($filterQryForCriteria!='')
  9002. //            $get_kids_sql = $filterQryForCriteria;
  9003. //
  9004. //        else
  9005. //               $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";
  9006.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9007.         
  9008.         $get_kids $stmt;
  9009.         $productId 0;
  9010.         if (!empty($get_kids)) {
  9011.             foreach ($get_kids as $product) {
  9012.                 $pa = array();
  9013.                 $pa['id'] = $product['id'];
  9014.                 $pa['name'] = $product['name'];
  9015.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  9016.                 $pa['globalId'] = $product['global_id'];
  9017.                 $pa['parentId'] = $product['parent_id'];
  9018.                 $pa['text'] = $product['name'];
  9019.                 $pa['value'] = $product['id'];
  9020.                 $pa['igId'] = $product['ig_id'];
  9021.                 $pa['categoryId'] = $product['category_id'];
  9022. //                $pa['subCategoryId'] = $product['sub_category_id'];
  9023.                 $data[] = $pa;
  9024.                 $data_by_id[$product['id']] = $pa;
  9025.                 $productId $product['id'];
  9026.             }
  9027.         }
  9028. //        if($request->query->has('returnJson'))
  9029.         {
  9030.             return new JsonResponse(
  9031.                 array(
  9032.                     'success' => true,
  9033. //                    'page_title' => 'Product Details',
  9034. //                    'company_data' => $company_data,
  9035.                     'data' => $data,
  9036.                     'dataById' => $data_by_id,
  9037.                     'productId' => $productId,
  9038.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9039. //                    'exId'=>$id,
  9040. //                'productByCodeData' => $productByCodeData,
  9041. //                'productData' => $productData,
  9042. //                'currInvList' => $currInvList,
  9043. //                'productList' => Inventory::ProductList($em, $companyId),
  9044. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9045. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9046. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9047. //                'unitList' => Inventory::UnitTypeList($em),
  9048. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9049. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9050. //                'warehouseList' => Inventory::WarehouseList($em),
  9051.                 )
  9052.             );
  9053.         }
  9054.     }
  9055.     public
  9056.     function ProductByCodeViewAction(Request $request$id 0)
  9057.     {
  9058.         $em $this->getDoctrine()->getManager();
  9059.         $companyId $this->getLoggedUserCompanyId($request);
  9060.         $company_data Company::getCompanyData($em$companyId);
  9061.         $data = [];
  9062.         $html '';
  9063.         $productByCodeData = [];
  9064.         if ($id != 0) {
  9065.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  9066.                 ->findOneBy(
  9067.                     array(
  9068.                         'productByCodeId' => $id
  9069.                     )
  9070.                 );
  9071.         } else {
  9072.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  9073.                 ->findOneBy(
  9074.                     array(
  9075. //                        'productByCodeId' => $id,
  9076.                         'CompanyId' => $companyId
  9077.                     ), array(
  9078.                         'productByCodeId' => 'DESC'
  9079.                     )
  9080.                 );
  9081.             if ($productByCodeData)
  9082.                 $id $productByCodeData->getProductByCodeId();
  9083.         }
  9084.         if ($id != 0) {
  9085.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  9086.                 ->findOneBy(
  9087.                     array(
  9088.                         'id' => $productByCodeData->getProductId()
  9089.                     )
  9090.                 );
  9091.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  9092.                 ->findBy(
  9093.                     array(
  9094.                         'productId' => $id
  9095.                     )
  9096.                 );
  9097.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  9098.                 array(
  9099.                     'page_title' => 'Product Details',
  9100.                     'company_data' => $company_data,
  9101.                     'productByCodeData' => $productByCodeData,
  9102.                     'productData' => $productData,
  9103.                     'currInvList' => $currInvList,
  9104.                     'exId' => $id,
  9105.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9106.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9107.                     'productList' => Inventory::ProductList($em$companyId),
  9108.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9109.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9110.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9111.                     'unitList' => Inventory::UnitTypeList($em),
  9112.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9113.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9114.                     'warehouseList' => Inventory::WarehouseList($em),
  9115.                 )
  9116.             );
  9117.         } else {
  9118.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  9119.                 array(
  9120.                     'exId' => $id,
  9121.                 )
  9122.             );
  9123.         }
  9124.         if ($request->query->has('returnJson')) {
  9125.             return new JsonResponse(
  9126.                 array(
  9127.                     'success' => true,
  9128.                     'page_title' => 'Product Details',
  9129.                     'company_data' => $company_data,
  9130.                     'renderedHtml' => $html,
  9131.                     'exId' => $id,
  9132. //                'productByCodeData' => $productByCodeData,
  9133. //                'productData' => $productData,
  9134. //                'currInvList' => $currInvList,
  9135. //                'productList' => Inventory::ProductList($em, $companyId),
  9136. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9137. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9138. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9139. //                'unitList' => Inventory::UnitTypeList($em),
  9140. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9141. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9142. //                'warehouseList' => Inventory::WarehouseList($em),
  9143.                 )
  9144.             );
  9145.         } else {
  9146. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  9147. //                ->findBy(
  9148. //                    array(
  9149. ////                        'productByCodeId' => $id,
  9150. //                    'CompanyId'=>$companyId
  9151. //                    )
  9152. //                );
  9153.             $productByCodeList = []; //called by ajax
  9154.             return $this->render('@Inventory/pages/views/product_by_code_view.html.twig',
  9155.                 array(
  9156.                     'page_title' => 'Product Details',
  9157.                     'company_data' => $company_data,
  9158.                     'renderedHtml' => $html,
  9159.                     'exId' => $id,
  9160.                     'productByCodeList' => $productByCodeList,
  9161. //                'productByCodeData' => $productByCodeData,
  9162. //                'productData' => $productData,
  9163. //                'currInvList' => $currInvList,
  9164. //                'productList' => Inventory::ProductList($em, $companyId),
  9165. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9166. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9167. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9168. //                'unitList' => Inventory::UnitTypeList($em),
  9169. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9170. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9171. //                'warehouseList' => Inventory::WarehouseList($em),
  9172.                 )
  9173.             );
  9174.         }
  9175.     }
  9176.     public
  9177.     function ConsumptionSettingsAction(Request $request$id)
  9178.     {
  9179.         $cc_id '';
  9180.         $cc_name '';
  9181.         $em $this->getDoctrine()->getManager();
  9182.         $companyId $this->getLoggedUserCompanyId($request);
  9183.         $consumptionTypeId 0;
  9184.         if ($request->isMethod('POST')) {
  9185.             $new_cc = [];
  9186.             if ($request->request->get('consumptionTypeId') != '' && $request->request->get('consumptionTypeId') != 0) {
  9187.                 $em $this->getDoctrine()->getManager();
  9188.                 $new_cc $this->getDoctrine()
  9189.                     ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  9190.                     ->findOneBy(
  9191.                         array(
  9192.                             'consumptionTypeId' => $request->request->get('consumptionTypeId'),
  9193.                         )
  9194.                     );
  9195.                 $new_cc->setName($request->request->get('name'));
  9196.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9197.                 $new_cc->setCompanyId($companyId);
  9198.                 $em->flush();
  9199.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9200.                 $this->addFlash(
  9201.                     'success',
  9202.                     'Consumption Information Updated'
  9203.                 );
  9204.             } else {
  9205.                 $new_cc = new ConsumptionType();
  9206.                 $new_cc->setName($request->request->get('name'));
  9207.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9208.                 $new_cc->setCompanyId($companyId);
  9209.                 $em->persist($new_cc);
  9210.                 $em->flush();
  9211.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9212.                 $em->flush();
  9213.                 $this->addFlash(
  9214.                     'success',
  9215.                     'New Consumption Type Added'
  9216.                 );
  9217.             }
  9218.         }
  9219.         $extData = [];
  9220.         if ($id != 0) {
  9221.             $extData $this->getDoctrine()
  9222.                 ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  9223.                 ->findOneBy(
  9224.                     array(
  9225.                         'consumptionTypeId' => $id
  9226.                     )
  9227.                 );
  9228. //            $cc_data_list = [];
  9229. //            foreach ($cc_data as $value) {
  9230. //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  9231. //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  9232. //
  9233. //                if ($value->getSupplierCategoryId() == $id) {
  9234. //                    $cc_id = $value->getSupplierCategoryId();
  9235. //                    $cc_name = $value->getName();
  9236. //                }
  9237. //            }
  9238.         }
  9239.         return $this->render('@Inventory/pages/input_forms/consumption_settings.html.twig',
  9240.             array(
  9241.                 'page_title' => 'Consumption Settings',
  9242.                 'consumptionTypeList' => $this->getDoctrine()
  9243.                     ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  9244.                     ->findBy(
  9245.                         array(
  9246.                             'CompanyId' => $companyId
  9247.                         )
  9248.                     ),
  9249.                 'extData' => $extData,
  9250.                 'headList' => Accounts::getParentLedgerHeads($em),
  9251. //                'countryList'=>SalesOrderM::Co
  9252.             )
  9253.         );
  9254.     }
  9255.     public
  9256.     function ProductByCodeCheckAssignPrintAction(Request $request$id 0)
  9257.     {
  9258.         $em $this->getDoctrine()->getManager();
  9259.         $companyId $this->getLoggedUserCompanyId($request);
  9260.         $company_data Company::getCompanyData($em$companyId);
  9261.         $data = [];
  9262.         $html '';
  9263.         $productByCodeData = [];
  9264.         $productDataWeightPackageGm '';
  9265.         $productDataWeightVarianceValue 0;
  9266.         $productDataWeightVarianceType 0;
  9267.         $productByCodeDataObj = [];
  9268.         $dr_id 0;//for dr_id
  9269.         $skipRenderData 0;
  9270.         if ($request->query->has('skipRenderData'))
  9271.             $skipRenderData $request->query->get('skipRenderData');
  9272.         if ($id != 0) {
  9273.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  9274.                 ->findOneBy(
  9275.                     array(
  9276.                         'productByCodeId' => $id
  9277.                     )
  9278.                 );
  9279.         } else {
  9280.             if ($request->query->has('scanCode')) {
  9281.                 $query $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  9282.                     ->createQueryBuilder('p');
  9283.                 if ($request->query->has('assigned')) {
  9284.                     $query->where('p.assigned > :av')
  9285.                         ->setParameter('av'$request->query->get('assigned'));
  9286.                 } else
  9287.                     $query->where("1=0");
  9288.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  9289.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  9290.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  9291.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  9292.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  9293.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  9294.                 $query->setMaxResults(1);
  9295.                 $results $query->getQuery()->getResult();
  9296.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  9297.             } else
  9298.                 $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  9299.                     ->findOneBy(
  9300.                         array(
  9301. //                        'productByCodeId' => $id,
  9302.                             'CompanyId' => $companyId
  9303.                         ), array(
  9304.                             'productByCodeId' => 'DESC'
  9305.                         )
  9306.                     );
  9307.             if ($productByCodeData)
  9308.                 $id $productByCodeData->getProductByCodeId();
  9309.         }
  9310.         if ($id != 0) {
  9311.             $productByCodeDataObj = array(
  9312.                 'salesCode' => $productByCodeData->getSalesCode(),
  9313.                 'sales_code' => $productByCodeData->getSalesCode(),
  9314.                 'sn' => $productByCodeData->getSerialNo(),
  9315.                 'serialNo' => $productByCodeData->getSerialNo(),
  9316.                 'imei1' => $productByCodeData->getImei1(),
  9317.                 'imei2' => $productByCodeData->getImei2(),
  9318.                 'soId' => $productByCodeData->getSalesOrderId(),
  9319.                 'poId' => $productByCodeData->getPurchaseOrderId(),
  9320.                 'irrId' => $productByCodeData->getIrrId(),
  9321.                 'productId' => $productByCodeData->getProductId(),
  9322.                 'productByCodeId' => $productByCodeData->getProductByCodeId(),
  9323.                 'warehouseId' => $productByCodeData->getWarehouseId(),
  9324.                 'warehouseActionId' => $productByCodeData->getWarehouseActionId(),
  9325.                 'stId' => $productByCodeData->getStockTransferId(),
  9326.                 'srId' => $productByCodeData->getStockReceivedNoteId(),
  9327.                 'scmpId' => $productByCodeData->getStockConsumptionNoteId(),
  9328.                 'clientId' => $productByCodeData->getClientId(),
  9329.                 'supplierId' => $productByCodeData->getSupplierId(),
  9330.                 'drId' => $productByCodeData->getDeliveryReceiptId(),
  9331.                 'consumerName' => $productByCodeData->getConsumerName(),
  9332.                 'drItemData' => [],
  9333. //                'salesCodes' => $productByCodeData->getDeliveryReceiptId(),
  9334.             );
  9335.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  9336.                 ->findOneBy(
  9337.                     array(
  9338.                         'id' => $productByCodeData->getProductId()
  9339.                     )
  9340.                 );
  9341.             if ($productByCodeData->getProductionId() != null) {
  9342.                 $productionDataHere $em->getRepository('ApplicationBundle\\Entity\\Production')
  9343.                     ->findOneBy(
  9344.                         array(
  9345.                             'productionId' => $productByCodeData->getProductionId()
  9346.                         )
  9347.                     );
  9348.                 if ($productionDataHere) {
  9349.                     $productDataWeightPackageGm $productionDataHere->getPackageWeight();
  9350.                     $productDataWeightVarianceValue $productionDataHere->getPackageWeightVarianceValue();
  9351.                     $productDataWeightVarianceType $productionDataHere->getPackageWeightVarianceType();
  9352.                 }
  9353.             } else {
  9354.                 if ($productData) {
  9355.                     $productDataWeightPackageGm $productData->getWeight();
  9356.                     $productDataWeightVarianceValue $productData->getWeightVarianceValue();
  9357.                     $productDataWeightVarianceType $productData->getWeightVarianceType();
  9358.                 }
  9359.             }
  9360.             if ($productData) {
  9361.                 $productByCodeDataObj['unitTypeId'] = $productData->getUnitTypeId();
  9362.                 $productByCodeDataObj['purchasePrice'] = $productData->getPurchasePrice();
  9363.                 $productByCodeDataObj['productFdm'] = $productData->getProductFdm();
  9364.                 $productByCodeDataObj['productName'] = $productData->getName();
  9365.                 if ($request->request->has('forSalesReturn') || $request->query->has('forSalesReturn')) {
  9366.                     $QD $this->getDoctrine()
  9367.                         ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  9368.                         ->findOneBy(
  9369.                             array(
  9370.                                 'deliveryReceiptId' => $productByCodeData->getDeliveryReceiptId(),
  9371.                                 'productId' => $productByCodeData->getProductId(),
  9372.                             )
  9373.                         );
  9374. //            if($request->request->get('wareHouseId')!='')
  9375.                     if ($QD) {
  9376.                         $new_pid $QD->getProductId();
  9377.                         $sales_code_range = [];
  9378.                         if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  9379.                             $sales_code_range json_decode($QD->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  9380.                         } else {
  9381.                             $max_int_length strlen((string)PHP_INT_MAX) - 1;
  9382.                             $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$QD->getSalesCodeRange());
  9383.                             $sales_code_range json_decode($json_without_bigintstrue);
  9384.                         }
  9385.                         $p_data = array(
  9386.                             'details_id' => $QD->getId(),
  9387.                             'productId' => $new_pid,
  9388.                             'dr_id' => $productByCodeData->getDeliveryReceiptId(),
  9389.                             'product_name' => $productData->getName(),
  9390.                             'qty' => $QD->getQty(),
  9391.                             'delivered' => $QD->getDelivered(),
  9392.                             'unitTypeId' => $QD->getUnitTypeId(),
  9393.                             'deliverable' => $QD->getDeliverable(),
  9394.                             'balance' => $QD->getBalance(),
  9395.                             'salesCodeRangeStr' => $QD->getSalesCodeRange(),
  9396.                             'salesCodeRange' => $sales_code_range,
  9397.                             'sales_codes' => $sales_code_range,
  9398.                             'sales_price' => $QD->getPrice(),
  9399.                             'purchase_price' => $QD->getCurrentPurchasePrice()
  9400. //                        'delivered'=>$product->getDelivered(),
  9401.                         );
  9402.                         $productByCodeDataObj['drItemData'][] = $p_data;
  9403.                     }
  9404.                 }
  9405.             }
  9406.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  9407.                 ->findBy(
  9408.                     array(
  9409.                         'productId' => $id
  9410.                     )
  9411.                 );
  9412.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  9413.                 array(
  9414.                     'page_title' => 'Details',
  9415.                     'company_data' => $company_data,
  9416.                     'productByCodeData' => $productByCodeData,
  9417.                     'productByCodeDataObj' => $productByCodeDataObj,
  9418.                     'productData' => $productData,
  9419.                     'currInvList' => $currInvList,
  9420.                     'productDataWeightPackageGm' => $productDataWeightPackageGm,
  9421.                     'productDataWeightVarianceValue' => $productDataWeightVarianceValue,
  9422.                     'productDataWeightVarianceType' => $productDataWeightVarianceType,
  9423.                     'exId' => $id,
  9424.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9425.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9426.                     'productList' => Inventory::ProductList($em$companyId),
  9427.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9428.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9429.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9430.                     'unitList' => Inventory::UnitTypeList($em),
  9431.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9432.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9433.                     'warehouseList' => Inventory::WarehouseList($em),
  9434.                 )
  9435.             ));
  9436.         } else {
  9437.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  9438.                 array(
  9439.                     'exId' => $id,
  9440.                 )
  9441.             ));
  9442.         }
  9443.         if ($request->query->has('returnJson')) {
  9444.             return new JsonResponse(
  9445.                 array(
  9446.                     'success' => true,
  9447.                     'page_title' => 'Product Details',
  9448.                     'company_data' => $company_data,
  9449.                     'renderedHtml' => $html,
  9450.                     'exId' => $id,
  9451.                     'productByCodeDataObj' => $productByCodeDataObj,
  9452. //                'productData' => $productData,
  9453. //                'currInvList' => $currInvList,
  9454. //                'productList' => Inventory::ProductList($em, $companyId),
  9455. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9456. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9457. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9458. //                'unitList' => Inventory::UnitTypeList($em),
  9459. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9460. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9461. //                'warehouseList' => Inventory::WarehouseList($em),
  9462.                 )
  9463.             );
  9464.         } else {
  9465. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  9466. //                ->findBy(
  9467. //                    array(
  9468. ////                        'productByCodeId' => $id,
  9469. //                    'CompanyId'=>$companyId
  9470. //                    )
  9471. //                );
  9472.             $productByCodeList = []; //called by ajax
  9473.             return $this->render('@Inventory/pages/views/product_by_code_assign_check_print.html.twig',
  9474.                 array(
  9475.                     'page_title' => 'Serial Manager',
  9476.                     'company_data' => $company_data,
  9477.                     'renderedHtml' => $html,
  9478.                     'exId' => $id,
  9479.                     'productByCodeList' => $productByCodeList,
  9480.                     'productByCodeDataObj' => $productByCodeDataObj,
  9481. //                'productByCodeData' => $productByCodeData,
  9482. //                'productData' => $productData,
  9483. //                'currInvList' => $currInvList,
  9484. //                'productList' => Inventory::ProductList($em, $companyId),
  9485. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9486. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9487. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9488. //                'unitList' => Inventory::UnitTypeList($em),
  9489. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9490. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9491. //                'warehouseList' => Inventory::WarehouseList($em),
  9492.                 )
  9493.             );
  9494.         }
  9495.     }
  9496.     public
  9497.     function TestProductByCodeCheckAssignPrintAction(Request $request$id 0)
  9498.     {
  9499.         $em $this->getDoctrine()->getManager();
  9500.         $companyId $this->getLoggedUserCompanyId($request);
  9501.         $company_data Company::getCompanyData($em$companyId);
  9502.         $data = [];
  9503.         $html '';
  9504.         $productByCodeData = [];
  9505.         $productByCodeDataObj = [];
  9506.         if ($id != 0) {
  9507.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  9508.                 ->findOneBy(
  9509.                     array(
  9510.                         'productByCodeId' => $id
  9511.                     )
  9512.                 );
  9513.         } else {
  9514.             if ($request->query->has('scanCode')) {
  9515.                 $query $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  9516.                     ->createQueryBuilder('p');
  9517.                 if ($request->query->has('assigned')) {
  9518.                     $query->where('p.assigned > :av')
  9519.                         ->setParameter('av'$request->query->get('assigned'));
  9520.                 } else
  9521.                     $query->where("1=0");
  9522.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  9523.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  9524.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  9525.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  9526.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  9527.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  9528.                 $query->setMaxResults(1);
  9529.                 $results $query->getQuery()->getResult();
  9530.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  9531.             } else
  9532.                 $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  9533.                     ->findOneBy(
  9534.                         array(
  9535. //                        'productByCodeId' => $id,
  9536.                             'CompanyId' => $companyId
  9537.                         ), array(
  9538.                             'productByCodeId' => 'DESC'
  9539.                         )
  9540.                     );
  9541.             if ($productByCodeData)
  9542.                 $id $productByCodeData->getProductByCodeId();
  9543.         }
  9544.         if ($id != 0) {
  9545.             $productByCodeDataObj = array(
  9546.                 'sn' => $productByCodeData->getSalesCode(),
  9547.                 'imei1' => $productByCodeData->getImei1(),
  9548.                 'imei2' => $productByCodeData->getImei2(),
  9549.                 'colorId' => $productByCodeData->getColorId(),
  9550.             );
  9551.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  9552.                 ->findOneBy(
  9553.                     array(
  9554.                         'id' => $productByCodeData->getProductId()
  9555.                     )
  9556.                 );
  9557.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  9558.                 ->findBy(
  9559.                     array(
  9560.                         'productId' => $id
  9561.                     )
  9562.                 );
  9563.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  9564.                 array(
  9565.                     'page_title' => 'Details',
  9566.                     'company_data' => $company_data,
  9567.                     'productByCodeData' => $productByCodeData,
  9568.                     'productData' => $productData,
  9569.                     'currInvList' => $currInvList,
  9570.                     'exId' => $id,
  9571.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9572.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9573.                     'productList' => Inventory::ProductList($em$companyId),
  9574.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9575.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9576.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9577.                     'unitList' => Inventory::UnitTypeList($em),
  9578.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9579.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9580.                     'warehouseList' => Inventory::WarehouseList($em),
  9581.                 )
  9582.             );
  9583.         } else {
  9584.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  9585.                 array(
  9586.                     'exId' => $id,
  9587.                 )
  9588.             );
  9589.         }
  9590.         if ($request->query->has('returnJson')) {
  9591.             return new JsonResponse(
  9592.                 array(
  9593.                     'success' => true,
  9594.                     'page_title' => 'Product Details',
  9595.                     'company_data' => $company_data,
  9596.                     'renderedHtml' => $html,
  9597.                     'exId' => $id,
  9598.                     'productByCodeDataObj' => $productByCodeDataObj,
  9599. //                'productData' => $productData,
  9600. //                'currInvList' => $currInvList,
  9601. //                'productList' => Inventory::ProductList($em, $companyId),
  9602. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9603. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9604. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9605. //                'unitList' => Inventory::UnitTypeList($em),
  9606. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9607. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9608. //                'warehouseList' => Inventory::WarehouseList($em),
  9609.                 )
  9610.             );
  9611.         } else {
  9612. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  9613. //                ->findBy(
  9614. //                    array(
  9615. ////                        'productByCodeId' => $id,
  9616. //                    'CompanyId'=>$companyId
  9617. //                    )
  9618. //                );
  9619.             $productByCodeList = []; //called by ajax
  9620.             return $this->render('@Inventory/pages/views/test_product_by_code_assign_check_print.html.twig',
  9621.                 array(
  9622.                     'page_title' => ' Test Serial Manager',
  9623.                     'company_data' => $company_data,
  9624.                     'renderedHtml' => $html,
  9625.                     'exId' => $id,
  9626.                     'productByCodeList' => $productByCodeList,
  9627.                     'productByCodeDataObj' => $productByCodeDataObj,
  9628. //                'productByCodeData' => $productByCodeData,
  9629. //                'productData' => $productData,
  9630. //                'currInvList' => $currInvList,
  9631. //                'productList' => Inventory::ProductList($em, $companyId),
  9632. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9633. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9634. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9635. //                'unitList' => Inventory::UnitTypeList($em),
  9636. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9637. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9638. //                'warehouseList' => Inventory::WarehouseList($em),
  9639.                 )
  9640.             );
  9641.         }
  9642.     }
  9643.     public
  9644.     function DeleteProductAction(Request $request$id '')
  9645.     {
  9646.         $em $this->getDoctrine()->getManager();
  9647.         $idListArray = [];
  9648.         if ($request->isMethod('POST')) {
  9649.             if ($id == 0)
  9650.                 $id $request->request->get('productId');
  9651.             //now check the product closing , if nothing then we cna remove it
  9652.             $query_here $this->getDoctrine()
  9653.                 ->getRepository('ApplicationBundle\\Entity\\InvClosingBalance')
  9654.                 ->findBy(
  9655.                     array(
  9656.                         'productId' => $request->request->get('productId')
  9657.                     )
  9658.                 );
  9659.             if (!empty($query_here)) {
  9660.                 return new JsonResponse(
  9661.                     array(
  9662.                         'success' => false,
  9663.                     )
  9664.                 );
  9665.             } else {
  9666.                 $qry $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')->findBy(array(
  9667.                     'productId' => $id
  9668.                 ));
  9669.                 foreach ($qry as $det) {
  9670.                     //remove any barcoded products
  9671.                     $em->remove($det);
  9672.                     $em->flush();
  9673.                 }
  9674.                 $qry $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findBy(array(
  9675.                     'id' => $id
  9676.                 ));
  9677.                 foreach ($qry as $det) {
  9678.                     //remove any barcoded products
  9679.                     $em->remove($det);
  9680.                     $em->flush();
  9681.                 }
  9682.                 $qry $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')->findBy(array(
  9683.                     'productId' => $id
  9684.                 ));
  9685.                 foreach ($qry as $det) {
  9686.                     //remove any barcoded products
  9687.                     $em->remove($det);
  9688.                     $em->flush();
  9689.                 }
  9690.                 return new JsonResponse(
  9691.                     array(
  9692.                         'success' => true,
  9693.                     )
  9694.                 );
  9695.             }
  9696.         }
  9697.         return new JsonResponse(
  9698.             array(
  9699.                 'success' => false,
  9700.             )
  9701.         );
  9702.     }
  9703.     public
  9704.     function RegisterProductAction(Request $request$idListStr '')
  9705.     {
  9706.         $em $this->getDoctrine()->getManager();
  9707.         $companyId $this->getLoggedUserCompanyId($request);
  9708.         $company_data Company::getCompanyData($em$companyId);
  9709.         $session $request->getSession();
  9710. //        System::setSessionForUser($session );
  9711.         $idListArray = [];
  9712.         if ($idListStr != '')
  9713.             $idListArray explode(','$idListStr);
  9714.         $data = [];
  9715. //        if ($request->isMethod('POST')) {
  9716. //            $post = $request->request;
  9717. //            if ($request->request->get('formatId') != '') {
  9718. //                $query_here = $this->getDoctrine()
  9719. //                    ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  9720. //                    ->findOneBy(
  9721. //                        array(
  9722. //                            'formatId' => $request->request->get('formatId')
  9723. //                        )
  9724. //                    );
  9725. //                if (!empty($query_here))
  9726. //                    $new = $query_here;
  9727. //            } else
  9728. //                $new = new CheckFormat();
  9729. //            $new->setName($request->request->get('name'));
  9730. //            $new->setWidth($request->request->get('width'));
  9731. //            $new->setHeight($request->request->get('height'));
  9732. //            $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
  9733. //            $new->setCheckPayToTop($request->request->get('checkPayToTop'));
  9734. //            $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
  9735. //            $new->setCheckAmountTop($request->request->get('checkAmountTop'));
  9736. //            $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
  9737. //            $new->setCheckAiWTop($request->request->get('checkAiWTop'));
  9738. //            $new->setCheckDateLeft($request->request->get('checkDateLeft'));
  9739. //            $new->setCheckDateTop($request->request->get('checkDateTop'));
  9740. //            $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
  9741. //            $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
  9742. //            $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
  9743. //            $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
  9744. //            $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
  9745. //            $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
  9746. //            $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
  9747. //            $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
  9748. //            $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
  9749. //            $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
  9750. //            $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 1 : 0);
  9751. //            $new->setCheckImage($request->request->get('checkImage'));
  9752. //
  9753. //            $em = $this->getDoctrine()->getManager();
  9754. //            $em->persist($new);
  9755. //            $em->flush();
  9756. //
  9757. //        }
  9758. //        if (!empty($idListArray)) {
  9759. //            $query_here = $this->getDoctrine()
  9760. //                ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  9761. //                ->findBy(
  9762. //                    array(
  9763. //                        'productByCodeId' => $idListArray
  9764. //                    )
  9765. //                );
  9766. //            if (!empty($query_here))
  9767. //                $data = $query_here;
  9768. //
  9769. //        }
  9770. //        else if ($request->query->has('formatId')) {
  9771. //            $query_here = $this->getDoctrine()
  9772. //                ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  9773. //                ->findOneBy(
  9774. //                    array(
  9775. //                        'formatId' => $request->query->get('formatId')
  9776. //                    )
  9777. //                );
  9778. //            if (!empty($query_here))
  9779. //                $data = $query_here;
  9780. //        }
  9781.         $data = [];
  9782.         $html '';
  9783.         $productByCodeData = [];
  9784.         if ($request->query->has('returnJson')) {
  9785.             return new JsonResponse(
  9786.                 array(
  9787.                     'success' => true,
  9788.                     'page_title' => 'Product Details',
  9789.                     'company_data' => $company_data,
  9790.                     'renderedHtml' => $html,
  9791.                     'data' => $data,
  9792.                     'idListArray' => $idListArray,
  9793. //                    'exId'=>$id,
  9794. //                'productByCodeData' => $productByCodeData,
  9795. //                'productData' => $productData,
  9796. //                'currInvList' => $currInvList,
  9797. //                'productList' => Inventory::ProductList($em, $companyId),
  9798. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9799. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9800. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9801. //                'unitList' => Inventory::UnitTypeList($em),
  9802. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9803. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9804. //                'warehouseList' => Inventory::WarehouseList($em),
  9805.                 )
  9806.             );
  9807.         } else {
  9808.             return $this->render('@Inventory/pages/input_forms/register_product.html.twig',
  9809.                 array(
  9810.                     'page_title' => 'Register Product',
  9811.                     'company_data' => $company_data,
  9812.                     'renderedHtml' => $html,
  9813. //                    'exIdList'=>$i,
  9814.                     'idListArray' => $idListArray,
  9815.                     'data' => $data,
  9816.                     'productByCodeList' => [],
  9817.                     'productByCodeData' => [],
  9818.                     'productList' => Inventory::ProductList($em$companyId),
  9819.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9820.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9821.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9822.                     'unitList' => Inventory::UnitTypeList($em),
  9823.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9824.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9825.                     'warehouseList' => Inventory::WarehouseList($em),
  9826.                 )
  9827.             );
  9828.         }
  9829.     }
  9830.     public
  9831.     function BrandViewAction(Request $request)
  9832.     {
  9833.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  9834.             array(
  9835.                 'page_title' => 'Stock Return'
  9836.             )
  9837.         );
  9838.     }
  9839.     public
  9840.     function PrintTableDataAction(Request $request)
  9841.     {
  9842.         $em $this->getDoctrine()->getManager();
  9843.         $company_data Company::getCompanyData($em1);
  9844.         $data = [];
  9845.         $print_title "test";
  9846.         $document_mark = array(
  9847.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  9848.             'copy' => ''
  9849.         );
  9850.         $mis_data = [];
  9851.         $p 1;
  9852.         return $this->render('@Inventory/pages/print/print_table_data.html.twig',
  9853.             array(
  9854.                 'page_title' => 'Data Report',
  9855.                 'data' => $data,
  9856.                 'page_header' => 'Report',
  9857.                 'print_title' => $print_title,
  9858.                 'document_type' => 'Journal voucher',
  9859.                 'document_mark_image' => $document_mark['original'],
  9860.                 'page_header_sub' => 'Add',
  9861. //                'type_list'=>$type_list,
  9862.                 'mis_data' => $mis_data,
  9863.                 'item_data' => [],
  9864.                 'received' => 2,
  9865.                 'return' => 1,
  9866.                 'total_w_vat' => 1,
  9867.                 'total_vat' => 1,
  9868.                 'total_wo_vat' => 1,
  9869.                 'invoice_id' => 'abcd1234',
  9870.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  9871.                 'created_by' => 'created by',
  9872.                 'created_at' => '',
  9873.                 'red' => 0,
  9874.                 'company_name' => $company_data->getName(),
  9875.                 'company_data' => $company_data,
  9876.                 'company_address' => $company_data->getAddress(),
  9877.                 'company_image' => $company_data->getImage(),
  9878.                 'p' => $p
  9879.             )
  9880.         );
  9881.     }
  9882.     public
  9883.     function ReplacementReportAction(Request $request)
  9884.     {
  9885.         $qry_data = array(
  9886.             'warehouseId' => [0],
  9887.             'igId' => [0],
  9888.             'brandId' => [0],
  9889.             'categoryId' => [0],
  9890.             'actionTagId' => [0],
  9891.         );
  9892.         $em $this->getDoctrine()->getManager();
  9893.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  9894.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  9895.         $data_searched = [];
  9896.         $companyId $this->getLoggedUserCompanyId($request);
  9897.         $company_data Company::getCompanyData($em$companyId);
  9898.         $data = [];
  9899.         $print_title "Inventory Report";
  9900.         $document_mark = array(
  9901.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  9902.             'copy' => ''
  9903.         );
  9904.         $post_data $request->request;
  9905.         $start_date $post_data->has('start_date') ? $post_data->get('start_date') : '';
  9906.         $end_date $post_data->has('end_date') ? $post_data->get('end_date') : '';
  9907.         if ($request->isMethod('POST'))
  9908.             $method 'POST';
  9909.         else
  9910.             $method 'GET';
  9911.         {
  9912. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  9913.             $data_searched Inventory::GetReplacementReportData($this->getDoctrine()->getManager(),
  9914.                 $request->request$method,
  9915.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  9916.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  9917.                 return new JsonResponse(
  9918.                     array(
  9919.                         'page_title' => 'Inventory ',
  9920.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  9921.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  9922.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  9923.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  9924.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  9925.                         'action_tag' => $warehouse_action_list,
  9926.                         'start_date' => $start_date,
  9927.                         'end_date' => $end_date,
  9928.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  9929.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  9930.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  9931.                         'data_searched' => $data_searched,
  9932.                         'success' => empty($data_searched['query_result']) ? false true
  9933.                     )
  9934.                 );
  9935.             }
  9936.             if ($request->request->get('print_data_enabled') == 1) {
  9937.                 $print_sub_title "";
  9938.                 return $this->render('@Inventory/pages/print/print_replacement_report.html.twig',
  9939.                     array(
  9940.                         'page_title' => 'Replacement Report',
  9941.                         'page_header' => 'Report',
  9942.                         'print_title' => $print_title,
  9943.                         'document_type' => 'Journal voucher',
  9944.                         'document_mark_image' => $document_mark['original'],
  9945.                         'page_header_sub' => 'Add',
  9946.                         'item_data' => [],
  9947.                         'received' => 2,
  9948.                         'return' => 1,
  9949.                         'total_w_vat' => 1,
  9950.                         'total_vat' => 1,
  9951.                         'total_wo_vat' => 1,
  9952.                         'invoice_id' => 'abcd1234',
  9953.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  9954.                         'created_by' => 'created by',
  9955.                         'created_at' => '',
  9956.                         'red' => 0,
  9957.                         'company_name' => $company_data->getName(),
  9958.                         'company_data' => $company_data,
  9959.                         'company_address' => $company_data->getAddress(),
  9960.                         'company_image' => $company_data->getImage(),
  9961.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  9962.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  9963.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  9964.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  9965.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  9966.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  9967.                         'action_tag' => $warehouse_action_list,
  9968.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  9969.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  9970.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  9971.                         'start_date' => $start_date,
  9972.                         'end_date' => $end_date,
  9973.                         'data_searched' => $data_searched
  9974.                     )
  9975.                 );
  9976.             }
  9977.         }
  9978.         return $this->render('@Inventory/pages/report/replacement_report.html.twig',
  9979.             array(
  9980.                 'page_title' => 'Replacement Report',
  9981.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  9982.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  9983.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  9984.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  9985.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  9986. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  9987.                 'action_tag' => $warehouse_action_list,
  9988.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  9989.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  9990.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  9991.                 'start_date' => $start_date,
  9992.                 'end_date' => $end_date,
  9993.                 'data_searched' => $data_searched,
  9994.                 'success' => empty($data_searched['query_result']) ? false true
  9995.             )
  9996.         );
  9997.     }
  9998.     public
  9999.     function InventoryViewAction(Request $request)
  10000.     {
  10001.         $qry_data = array(
  10002.             'warehouseId' => [0],
  10003.             'igId' => [0],
  10004.             'brandId' => [0],
  10005.             'categoryId' => [0],
  10006.             'actionTagId' => [0],
  10007.         );
  10008.         $em $this->getDoctrine()->getManager();
  10009.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  10010.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  10011.         $data_searched = [];
  10012.         $companyId $this->getLoggedUserCompanyId($request);
  10013.         $company_data Company::getCompanyData($em$companyId);
  10014.         $data = [];
  10015.         $print_title "Inventory Report";
  10016.         $document_mark = array(
  10017.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10018.             'copy' => ''
  10019.         );
  10020.         if ($request->isMethod('POST'))
  10021.             $method 'POST';
  10022.         else
  10023.             $method 'GET';
  10024.         {
  10025. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  10026.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  10027.                 $request->request$method,
  10028.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  10029.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  10030.                 return new JsonResponse(
  10031.                     array(
  10032.                         'page_title' => 'Inventory ',
  10033.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10034.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10035.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10036.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10037.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10038.                         'action_tag' => $warehouse_action_list,
  10039.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10040.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10041.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10042.                         'data_searched' => $data_searched,
  10043.                         'success' => empty($data_searched['query_result']) ? false true
  10044.                     )
  10045.                 );
  10046.             }
  10047.             if ($request->request->get('print_data_enabled') == 1) {
  10048.                 $print_sub_title "";
  10049.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  10050.                     array(
  10051.                         'page_title' => 'Inventory Report',
  10052.                         'page_header' => 'Report',
  10053.                         'print_title' => $print_title,
  10054.                         'document_type' => 'Journal voucher',
  10055.                         'document_mark_image' => $document_mark['original'],
  10056.                         'page_header_sub' => 'Add',
  10057.                         'item_data' => [],
  10058.                         'received' => 2,
  10059.                         'return' => 1,
  10060.                         'total_w_vat' => 1,
  10061.                         'total_vat' => 1,
  10062.                         'total_wo_vat' => 1,
  10063.                         'invoice_id' => 'abcd1234',
  10064.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  10065.                         'created_by' => 'created by',
  10066.                         'created_at' => '',
  10067.                         'red' => 0,
  10068.                         'company_name' => $company_data->getName(),
  10069.                         'company_data' => $company_data,
  10070.                         'company_address' => $company_data->getAddress(),
  10071.                         'company_image' => $company_data->getImage(),
  10072.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10073.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10074.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10075.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10076.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10077.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10078.                         'action_tag' => $warehouse_action_list,
  10079.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10080.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10081.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10082.                         'data_searched' => $data_searched
  10083.                     )
  10084.                 );
  10085.             }
  10086.         }
  10087.         return $this->render('@Inventory/pages/report/inventory_view.html.twig',
  10088.             array(
  10089.                 'page_title' => 'Inventory',
  10090.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10091.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10092.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10093.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10094.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10095. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10096.                 'action_tag' => $warehouse_action_list,
  10097.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10098.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10099.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10100.                 'data_searched' => $data_searched
  10101.             )
  10102.         );
  10103.     }
  10104.     public
  10105.     function GrnListAction(Request $request)
  10106.     {
  10107.         $q $this->getDoctrine()
  10108.             ->getRepository('ApplicationBundle\\Entity\\Grn')
  10109.             ->findBy(
  10110.                 array(
  10111.                     'status' => GeneralConstant::ACTIVE,
  10112. //                    'approved' =>  GeneralConstant::APPROVED,
  10113.                 )
  10114.             );
  10115.         $stage_list = array(
  10116.             => 'Pending',
  10117.             => 'Pending',
  10118.             => 'Complete',
  10119.             => 'Partial',
  10120.         );
  10121.         $data = [];
  10122.         foreach ($q as $entry) {
  10123.             $data[] = array(
  10124.                 'doc_date' => $entry->getGrnDate(),
  10125.                 'id' => $entry->getGrnId(),
  10126.                 'doc_hash' => $entry->getDocumentHash(),
  10127.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  10128.                 'stage' => $stage_list[$entry->getStage()]
  10129.             );
  10130.         }
  10131.         return $this->render('@Inventory/pages/views/grn_list.html.twig',
  10132.             array(
  10133.                 'page_title' => 'Grn List',
  10134.                 'data' => $data
  10135.             )
  10136.         );
  10137.     }
  10138.     public
  10139.     function ViewGrnAction(Request $request$id)
  10140.     {
  10141.         $em $this->getDoctrine()->getManager();
  10142.         $dt Inventory::GetGrnDetails($em$id);
  10143.         return $this->render('@Inventory/pages/views/view_grn.html.twig',
  10144.             array(
  10145.                 'page_title' => 'View',
  10146.                 'data' => $dt,
  10147.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  10148.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10149.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10150.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10151.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10152.                     $id,
  10153.                     $dt['created_by'],
  10154.                     $dt['edited_by'])
  10155.             )
  10156.         );
  10157.     }
  10158.     public
  10159.     function PrintGrnAction(Request $request$id)
  10160.     {
  10161.         $em $this->getDoctrine()->getManager();
  10162.         $dt Inventory::GetGrnDetails($em$id);
  10163.         $company_data Company::getCompanyData($em1);
  10164.         $document_mark = array(
  10165.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10166.             'copy' => ''
  10167.         );
  10168.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10169.             $html $this->renderView('@Inventory/pages/print/print_received_note.html.twig',
  10170.                 array(
  10171.                     //full array here
  10172.                     'pdf' => true,
  10173.                     'page_title' => 'Grn',
  10174.                     'export' => 'pdf,print',
  10175.                     'data' => $dt,
  10176.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10177.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10178.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10179.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10180.                         $id,
  10181.                         $dt['created_by'],
  10182.                         $dt['edited_by']),
  10183.                     'document_mark_image' => $document_mark['original'],
  10184.                     'company_name' => $company_data->getName(),
  10185.                     'company_data' => $company_data,
  10186.                     'company_address' => $company_data->getAddress(),
  10187.                     'company_image' => $company_data->getImage(),
  10188.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10189.                     'red' => 0
  10190.                 )
  10191.             );
  10192.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10193. //                'orientation' => 'landscape',
  10194. //                'enable-javascript' => true,
  10195. //                'javascript-delay' => 1000,
  10196.                 'no-stop-slow-scripts' => false,
  10197.                 'no-background' => false,
  10198.                 'lowquality' => false,
  10199.                 'encoding' => 'utf-8',
  10200. //            'images' => true,
  10201. //            'cookie' => array(),
  10202.                 'dpi' => 300,
  10203.                 'image-dpi' => 300,
  10204. //                'enable-external-links' => true,
  10205. //                'enable-internal-links' => true
  10206.             ));
  10207.             return new Response(
  10208.                 $pdf_response,
  10209.                 200,
  10210.                 array(
  10211.                     'Content-Type' => 'application/pdf',
  10212.                     'Content-Disposition' => 'attachment; filename="grn.pdf"'
  10213.                 )
  10214.             );
  10215.         }
  10216.         return $this->render('@Inventory/pages/print/print_received_note.html.twig',
  10217.             array(
  10218.                 'page_title' => 'Grn',
  10219.                 'export' => 'pdf,print',
  10220.                 'data' => $dt,
  10221.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10222.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10223.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10224.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10225.                     $id,
  10226.                     $dt['created_by'],
  10227.                     $dt['edited_by']),
  10228.                 'document_mark_image' => $document_mark['original'],
  10229.                 'company_name' => $company_data->getName(),
  10230.                 'company_data' => $company_data,
  10231.                 'company_address' => $company_data->getAddress(),
  10232.                 'company_image' => $company_data->getImage(),
  10233.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10234.                 'red' => 0
  10235.             )
  10236.         );
  10237.     }
  10238.     public
  10239.     function PrintGrnBarcodeAction(Request $request$id)
  10240.     {
  10241.         $em $this->getDoctrine()->getManager();
  10242.         $dt Inventory::GetGrnDetails($em$id);
  10243.         $company_data Company::getCompanyData($em1);
  10244.         $repeatCount 1;
  10245.         if ($request->query->has('repeatCount'))
  10246.             $repeatCount $request->query->get('repeatCount');
  10247.         $document_mark = array(
  10248.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10249.             'copy' => ''
  10250.         );
  10251.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10252.             $html $this->renderView('@Inventory/pages/print/print_grn_barcodes.html.twig',
  10253.                 array(
  10254.                     //full array here
  10255.                     'pdf' => true,
  10256.                     'page_title' => 'Grn Barcodes',
  10257.                     'export' => 'print',
  10258.                     'data' => $dt,
  10259.                     'repeatCount' => $repeatCount,
  10260.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10261.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10262.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10263.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10264.                         $id,
  10265.                         $dt['created_by'],
  10266.                         $dt['edited_by']),
  10267.                     'document_mark_image' => $document_mark['original'],
  10268.                     'company_name' => $company_data->getName(),
  10269.                     'company_data' => $company_data,
  10270.                     'company_address' => $company_data->getAddress(),
  10271.                     'company_image' => $company_data->getImage(),
  10272.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10273.                     'red' => 0
  10274.                 )
  10275.             );
  10276.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10277. //                'orientation' => 'landscape',
  10278.                 'enable-javascript' => true,
  10279. //                'javascript-delay' => 1000,
  10280.                 'no-stop-slow-scripts' => false,
  10281.                 'no-background' => false,
  10282.                 'lowquality' => false,
  10283.                 'encoding' => 'utf-8',
  10284. //            'images' => true,
  10285. //            'cookie' => array(),
  10286.                 'dpi' => 300,
  10287.                 'image-dpi' => 300,
  10288. //                'enable-external-links' => true,
  10289. //                'enable-internal-links' => true
  10290.             ));
  10291.             return new Response(
  10292.                 $pdf_response,
  10293.                 200,
  10294.                 array(
  10295.                     'Content-Type' => 'application/pdf',
  10296.                     'Content-Disposition' => 'attachment; filename="grn_barcodes.pdf"'
  10297.                 )
  10298.             );
  10299.         }
  10300.         return $this->render('@Inventory/pages/print/print_grn_barcodes.html.twig',
  10301.             array(
  10302.                 'page_title' => 'Grn barcodes',
  10303. //                'export'=>'pdf,print',
  10304.                 'data' => $dt,
  10305.                 'repeatCount' => $repeatCount,
  10306.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10307.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10308.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10309.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10310.                     $id,
  10311.                     $dt['created_by'],
  10312.                     $dt['edited_by']),
  10313.                 'document_mark_image' => $document_mark['original'],
  10314.                 'company_name' => $company_data->getName(),
  10315.                 'company_data' => $company_data,
  10316.                 'company_address' => $company_data->getAddress(),
  10317.                 'company_image' => $company_data->getImage(),
  10318.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10319.                 'red' => 0
  10320.             )
  10321.         );
  10322.     }
  10323.     public
  10324.     function GenerateBarcodeAction(Request $request$type$id$item_id)
  10325.     {
  10326.         $em $this->getDoctrine()->getManager();
  10327.         $repeatCount 1;
  10328.         $spec_item_id 0;
  10329.         $skip_ids = [];
  10330.         $clearUnnecessaryOnly 0;
  10331.         if ($request->query->has('skipIds'))
  10332.             $skip_ids $request->query->get('skipIds');
  10333.         if ($request->query->has('clearUnnecessaryOnly'))
  10334.             $clearUnnecessaryOnly $request->query->get('clearUnnecessaryOnly');
  10335.         if ($type == 'srcv') {
  10336.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')->findOneBy(
  10337.                 array(
  10338.                     'stockReceivedNoteId' => $id
  10339.                 )
  10340.             );
  10341.             if ($item_id == '_single_') {
  10342.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findBy(
  10343.                     array(
  10344.                         'stockReceivedNoteId' => $id,
  10345. //                        'id' => $item_id
  10346.                     )
  10347.                 );
  10348.             } else {
  10349.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findBy(
  10350.                     array(
  10351.                         'stockReceivedNoteId' => $id,
  10352.                         'id' => $item_id
  10353.                     )
  10354.                 );
  10355.             }
  10356.             $inv_acc_data = [
  10357.                 'fa_amount' => 0,
  10358.                 'tg_amount' => 0,
  10359.             ];
  10360.             $inv_acc_data_by_head = [
  10361.             ];
  10362.             $new_non_delivered_sales_code_range = [];
  10363.             foreach ($doc_item_data as $entry) {
  10364.                 //adding transaction
  10365.                 $sales_code_range_ser = [];
  10366.                 if (in_array($entry->getId(), $skip_ids))
  10367.                     continue;
  10368.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  10369.                     ->findOneBy(
  10370.                         array(
  10371.                             'id' => $entry->getProductId()
  10372.                         )
  10373.                     );
  10374.                 $stitem $em->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  10375.                     ->findOneBy(
  10376.                         array(
  10377.                             'id' => $entry->getStockTransferItemId(),
  10378.                             'productId' => $entry->getProductId()
  10379.                         )
  10380.                     );
  10381.                 if ($product) {
  10382.                     if ($product->getHasSerial() == 1) {
  10383.                         //clear if exists
  10384.                         if ($clearUnnecessaryOnly == 1) {
  10385.                             $get_kids_sql "DELETE FROM product_by_code
  10386.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10387. //                $get_kids_sql .=' ORDER BY name ASC';
  10388.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  10389.                             
  10390.                             $em->flush();
  10391.                         } else {
  10392.                             $get_kids_sql "DELETE FROM product_by_code
  10393.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10394. //                $get_kids_sql .=' ORDER BY name ASC';
  10395.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  10396.                             
  10397.                             $em->flush();
  10398.                         }
  10399. //                        $check_here = $stmt;
  10400.                         //now addng product by code
  10401.                         $sales_code_range = [];
  10402.                         if ($doc_data->getType() == || $doc_data->getType() == 4) {
  10403. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10404. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10405.                             $product_action_tag_id $entry->getWarehouseActionId();
  10406.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getQty(),
  10407.                                 $doc_data->getStockReceivedNoteDate(), $entry->getWarrantyMon(), 0$doc_data->getCompanyId(), $entry->getWarehouseId(),
  10408.                                 $entry->getWarehouseActionId(), $entry->getPurchaseCodeRange(), nullnullnullnull$doc_data->getStockReceivedNoteId()
  10409.                             );
  10410.                             $sales_code_range $barcodeData['sales_code_range'];
  10411.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  10412.                             $em->flush();
  10413.                         }
  10414. //                        else {
  10415. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10416. //
  10417. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10418. //                            } else {
  10419. //
  10420. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10421. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10422. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10423. //                            }
  10424. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10425. //
  10426. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10427. //                            } else {
  10428. //
  10429. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10430. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10431. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10432. //                            }
  10433. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10434. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10435. //                            $new_non_delivered_sales_code_range = [];
  10436. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10437. //                                if (!(in_array($ndsc, $sales_code_range)))
  10438. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10439. //                            }
  10440. //                            if ($sales_code_range != null) {
  10441. //                                foreach ($sales_code_range as $ind => $dt) {
  10442. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10443. //                                        ->findOneBy(
  10444. //                                            array(
  10445. //                                                'salesCode' => [$dt],
  10446. //                                                'productId' => $entry->getProductId()
  10447. //                                            )
  10448. //                                        );
  10449. //
  10450. //                                    if ($np) {
  10451. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10452. //                                        $np->setProductId($entry->getProductId());
  10453. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10454. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10455. //                                        $np->setPosition(1);//in warehouse
  10456. //                                        $np->setStockReceivedNoteId($id);
  10457. //
  10458. //
  10459. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10460. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10461. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10462. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10463. //                                            'direction' => 'in',
  10464. //                                            'warehouseId' => $entry->getWarehouseId(),
  10465. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10466. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10467. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10468. //                                        );
  10469. //                                        $np->setTransactionHistory(json_encode(
  10470. //                                            $trans_history
  10471. //                                        ));
  10472. //
  10473. //
  10474. //                                        $em->persist($np);
  10475. //                                        $em->flush();
  10476. //                                    }
  10477. //                                }
  10478. //                            }
  10479. //                        }
  10480.                     }
  10481.                 }
  10482.                 //adding transaction
  10483.                 if ($stitem) {
  10484.                     $stitem->setNonDeliveredSalesCodeRange(json_encode($new_non_delivered_sales_code_range));
  10485.                 }
  10486.                 $spec_item_id $entry->getId();
  10487.                 if ($item_id == '_single_') {
  10488.                     break;
  10489.                 }
  10490.             }
  10491.         }
  10492.         if ($type == 'irr') {
  10493.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacement')->findOneBy(
  10494.                 array(
  10495.                     'itemReceivedAndReplacementId' => $id
  10496.                 )
  10497.             );
  10498.             if ($item_id == '_single_') {
  10499.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacementItem')->findBy(
  10500.                     array(
  10501.                         'itemReceivedAndReplacementId' => $id,
  10502. //                        'id' => $item_id
  10503.                     )
  10504.                 );
  10505.             } else {
  10506.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacementItem')->findBy(
  10507.                     array(
  10508.                         'itemReceivedAndReplacementId' => $id,
  10509.                         'id' => $item_id
  10510.                     )
  10511.                 );
  10512.             }
  10513.             $inv_acc_data = [
  10514.                 'fa_amount' => 0,
  10515.                 'tg_amount' => 0,
  10516.             ];
  10517.             $inv_acc_data_by_head = [
  10518.             ];
  10519.             $new_non_delivered_sales_code_range = [];
  10520.             foreach ($doc_item_data as $entry) {
  10521.                 //adding transaction
  10522.                 $sales_code_range_ser = [];
  10523.                 if (in_array($entry->getId(), $skip_ids))
  10524.                     continue;
  10525.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  10526.                     ->findOneBy(
  10527.                         array(
  10528.                             'id' => $entry->getReceivedProductId()
  10529.                         )
  10530.                     );
  10531.                 if ($product) {
  10532.                     if ($product->getHasSerial() == 1) {
  10533.                         //clear if exists
  10534. //                        if($clearUnnecessaryOnly==1) {
  10535. //                            $get_kids_sql = "DELETE FROM product_by_code
  10536. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10537. ////                $get_kids_sql .=' ORDER BY name ASC';
  10538. //
  10539. //                            $stmt = $em->getConnection()->executeStatement($get_kids_sql);
  10540. //                            
  10541. //                            $em->flush();
  10542. //                        }
  10543. //                        else{
  10544. //                            $get_kids_sql = "DELETE FROM product_by_code
  10545. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10546. ////                $get_kids_sql .=' ORDER BY name ASC';
  10547. //
  10548. //                            $stmt = $em->getConnection()->executeStatement($get_kids_sql);
  10549. //                            
  10550. //                            $em->flush();
  10551. //                        }
  10552. //                        $check_here = $stmt;
  10553.                         //now addng product by code
  10554.                         $sales_code_range = [];
  10555.                         if ($entry->getReceivedQty() > 0) {
  10556. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10557. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10558. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  10559.                             $barcodeData Inventory::GenerateBarcode($em$entry->getReceivedProductId(), $entry->getReceivedQty(),
  10560.                                 $doc_data->getItemReceivedAndReplacementDate(), 00$doc_data->getCompanyId(), $entry->getReceivedWarehouseId(),
  10561.                                 $entry->getReceivedWarehouseActionId(), nullnullnullnullnullnullnullnull$doc_data->getItemReceivedAndReplacementId()
  10562.                             );
  10563.                             $sales_code_range $barcodeData['sales_code_range'];
  10564.                             $entry->setReceivedCodeRange(json_encode($sales_code_range));
  10565.                             $em->flush();
  10566.                         }
  10567. //                        else {
  10568. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10569. //
  10570. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10571. //                            } else {
  10572. //
  10573. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10574. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10575. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10576. //                            }
  10577. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10578. //
  10579. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10580. //                            } else {
  10581. //
  10582. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10583. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10584. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10585. //                            }
  10586. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10587. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10588. //                            $new_non_delivered_sales_code_range = [];
  10589. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10590. //                                if (!(in_array($ndsc, $sales_code_range)))
  10591. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10592. //                            }
  10593. //                            if ($sales_code_range != null) {
  10594. //                                foreach ($sales_code_range as $ind => $dt) {
  10595. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10596. //                                        ->findOneBy(
  10597. //                                            array(
  10598. //                                                'salesCode' => [$dt],
  10599. //                                                'productId' => $entry->getProductId()
  10600. //                                            )
  10601. //                                        );
  10602. //
  10603. //                                    if ($np) {
  10604. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10605. //                                        $np->setProductId($entry->getProductId());
  10606. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10607. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10608. //                                        $np->setPosition(1);//in warehouse
  10609. //                                        $np->setStockReceivedNoteId($id);
  10610. //
  10611. //
  10612. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10613. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10614. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10615. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10616. //                                            'direction' => 'in',
  10617. //                                            'warehouseId' => $entry->getWarehouseId(),
  10618. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10619. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10620. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10621. //                                        );
  10622. //                                        $np->setTransactionHistory(json_encode(
  10623. //                                            $trans_history
  10624. //                                        ));
  10625. //
  10626. //
  10627. //                                        $em->persist($np);
  10628. //                                        $em->flush();
  10629. //                                    }
  10630. //                                }
  10631. //                            }
  10632. //                        }
  10633.                     }
  10634.                 }
  10635.                 //adding transaction
  10636.                 $spec_item_id $entry->getId();
  10637.                 if ($item_id == '_single_') {
  10638.                     break;
  10639.                 }
  10640.             }
  10641.         }
  10642.         if ($type == 'prdcn') {
  10643.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\Production')->findOneBy(
  10644.                 array(
  10645.                     'productionId' => $id
  10646.                 )
  10647.             );
  10648.             if ($item_id == '_single_') {
  10649.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findBy(
  10650.                     array(
  10651.                         'productionId' => $id,
  10652. //                        'id' => $item_id
  10653.                     )
  10654.                 );
  10655.             } else {
  10656.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findBy(
  10657.                     array(
  10658.                         'productionId' => $id,
  10659.                         'id' => $item_id
  10660.                     )
  10661.                 );
  10662.             }
  10663.             $inv_acc_data = [
  10664.                 'fa_amount' => 0,
  10665.                 'tg_amount' => 0,
  10666.             ];
  10667.             $inv_acc_data_by_head = [
  10668.             ];
  10669.             $new_non_delivered_sales_code_range = [];
  10670.             foreach ($doc_item_data as $entry) {
  10671.                 //adding transaction
  10672.                 $sales_code_range_ser = [];
  10673.                 if (in_array($entry->getId(), $skip_ids))
  10674.                     continue;
  10675.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  10676.                     ->findOneBy(
  10677.                         array(
  10678.                             'id' => $entry->getProductId()
  10679.                         )
  10680.                     );
  10681.                 if ($product) {
  10682.                     if ($product->getHasSerial() == 1) {
  10683.                         //clear if exists
  10684. //                        if($clearUnnecessaryOnly==1) {
  10685. //                            $get_kids_sql = "DELETE FROM product_by_code
  10686. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10687. ////                $get_kids_sql .=' ORDER BY name ASC';
  10688. //
  10689. //                            $stmt = $em->getConnection()->executeStatement($get_kids_sql);
  10690. //                            
  10691. //                            $em->flush();
  10692. //                        }
  10693. //                        else{
  10694. //                            $get_kids_sql = "DELETE FROM product_by_code
  10695. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10696. ////                $get_kids_sql .=' ORDER BY name ASC';
  10697. //
  10698. //                            $stmt = $em->getConnection()->executeStatement($get_kids_sql);
  10699. //                            
  10700. //                            $em->flush();
  10701. //                        }
  10702. //                        $check_here = $stmt;
  10703.                         //now addng product by code
  10704.                         $sales_code_range = [];
  10705.                         if ($entry->getProducedQty() > 0) {
  10706. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10707. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10708. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  10709.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getProducedQty(),
  10710.                                 $doc_data->getProductionDate(), 00$doc_data->getCompanyId(), $entry->getWarehouseId(),
  10711.                                 $entry->getProducedItemActionTagId(), nullnullnullnullnullnullnull$doc_data->getProductionId(), null
  10712.                             );
  10713.                             $sales_code_range $barcodeData['sales_code_range'];
  10714.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  10715.                             $em->flush();
  10716.                         }
  10717. //                        else {
  10718. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10719. //
  10720. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10721. //                            } else {
  10722. //
  10723. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10724. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10725. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10726. //                            }
  10727. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10728. //
  10729. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10730. //                            } else {
  10731. //
  10732. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10733. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10734. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10735. //                            }
  10736. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10737. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10738. //                            $new_non_delivered_sales_code_range = [];
  10739. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10740. //                                if (!(in_array($ndsc, $sales_code_range)))
  10741. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10742. //                            }
  10743. //                            if ($sales_code_range != null) {
  10744. //                                foreach ($sales_code_range as $ind => $dt) {
  10745. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10746. //                                        ->findOneBy(
  10747. //                                            array(
  10748. //                                                'salesCode' => [$dt],
  10749. //                                                'productId' => $entry->getProductId()
  10750. //                                            )
  10751. //                                        );
  10752. //
  10753. //                                    if ($np) {
  10754. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10755. //                                        $np->setProductId($entry->getProductId());
  10756. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10757. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10758. //                                        $np->setPosition(1);//in warehouse
  10759. //                                        $np->setStockReceivedNoteId($id);
  10760. //
  10761. //
  10762. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10763. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10764. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10765. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10766. //                                            'direction' => 'in',
  10767. //                                            'warehouseId' => $entry->getWarehouseId(),
  10768. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10769. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10770. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10771. //                                        );
  10772. //                                        $np->setTransactionHistory(json_encode(
  10773. //                                            $trans_history
  10774. //                                        ));
  10775. //
  10776. //
  10777. //                                        $em->persist($np);
  10778. //                                        $em->flush();
  10779. //                                    }
  10780. //                                }
  10781. //                            }
  10782. //                        }
  10783.                     }
  10784.                 }
  10785.                 //adding transaction
  10786.                 $spec_item_id $entry->getId();
  10787.                 if ($item_id == '_single_') {
  10788.                     break;
  10789.                 }
  10790.             }
  10791.         }
  10792.         return new JsonResponse(array(
  10793.             'success' => $spec_item_id != true false,
  10794.             'skipIds' => [],
  10795.             'spec_item_id' => $spec_item_id
  10796.         ));
  10797. //        return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  10798. //            array(
  10799. //                'page_title' => 'Srcv barcodes',
  10800. ////                'export'=>'pdf,print',
  10801. //                'data' => $dt,
  10802. //                'repeatCount' => $repeatCount,
  10803. //                'item_id' => $item_id,
  10804. //                'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  10805. //                    $id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10806. //                'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10807. //                    array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  10808. //                    $id,
  10809. //                    $dt['created_by'],
  10810. //                    $dt['edited_by']),
  10811. //                'document_mark_image' => $document_mark['original'],
  10812. //                                    'company_name' => $company_data->getName(),
  10813. //                    'company_data'=>$company_data,
  10814. //                'company_address' => $company_data->getAddress(),
  10815. //                'company_image' => $company_data->getImage(),
  10816. //                'invoice_footer' => $company_data->getInvoiceFooter(),
  10817. //                'red' => 0
  10818. //
  10819. //            )
  10820. //        );
  10821.     }
  10822.     public
  10823.     function PrintLabelAction(Request $request$id)
  10824.     {
  10825.         $em $this->getDoctrine()->getManager();
  10826. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  10827.         $repeatCount 1;
  10828.         $assignProductId '';
  10829.         $productByCodeIds = [];
  10830.         $print_selection_type 1;
  10831.         $print_selection_string 1;
  10832.         $assignLabelFormatId 0;
  10833.         $assignColorId 0;
  10834.         $assignProductionScheduleId 0;
  10835.         $warehouseId '';
  10836.         $warehouseActionId '';
  10837.         $toAssignPosition '';
  10838.         $printFlag $request->request->has('printFlag') ? $request->request->get('printFlag') : 1;
  10839.         $returnJson $request->request->has('returnJson') ? $request->request->get('returnJson') : 0;
  10840.         if ($returnJson == 1)
  10841.             $printFlag 0;
  10842.         $companyId $this->getLoggedUserCompanyId($request);
  10843.         if ($request->query->has('repeatCount'))
  10844.             $repeatCount $request->query->get('repeatCount');
  10845.         if ($request->request->has('print_selection_type'))
  10846.             $print_selection_type $request->request->get('print_selection_type');
  10847.         if ($request->request->has('print_selection_string'))
  10848.             $print_selection_string $request->request->get('print_selection_string');
  10849.         if ($request->request->has('productByCodeIds'))
  10850.             $productByCodeIds json_decode($request->request->get('productByCodeIds'), true);
  10851.         if ($request->request->has('formatId'))
  10852.             $assignLabelFormatId $request->request->get('formatId');
  10853.         if ($printFlag == 0) {
  10854.             if ($request->request->has('productSelector'))
  10855.                 $assignProductId $request->request->get('productSelector');
  10856.             if ($request->request->has('colorId'))
  10857.                 $assignColorId $request->request->get('colorId');
  10858.             if ($request->request->has('productionScheduleId'))
  10859.                 $assignProductionScheduleId $request->request->get('productionScheduleId');
  10860.             if ($request->request->has('warehouseId'))
  10861.                 $warehouseId $request->request->get('warehouseId');
  10862.             if ($request->request->has('warehouseActionId'))
  10863.                 $warehouseActionId $request->request->get('warehouseActionId');
  10864.             if ($request->request->has('position'))
  10865.                 $toAssignPosition $request->request->get('position');
  10866.             if ($assignColorId == '')
  10867.                 $assignColorId 0;
  10868.         }
  10869.         if ($productByCodeIds == null)
  10870.             $productByCodeIds = [];
  10871.         $productByCodeData = [];
  10872.         $productList = [];
  10873.         $productIds = [];
  10874.         if ($print_selection_type == 2) {
  10875.             //range
  10876.             $productByCodeIds Inventory::getIdsFromIdSelectionStr($print_selection_string);
  10877.         }
  10878.         $labelData = [
  10879.             'formatId' => 0
  10880.         ];
  10881.         $formatId 0;
  10882.         if (!empty($productByCodeIds)) {
  10883.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10884.                 ->findBy(
  10885.                     array(
  10886.                         'productByCodeId' => $productByCodeIds
  10887.                     )
  10888.                 );
  10889.             foreach ($productByCodeData as $d) {
  10890.                 if ($d->getStage() < 10$d->setStage(11);
  10891.                 if ($assignProductId != '') {
  10892.                     $d->setProductId($assignProductId);
  10893.                 }
  10894.                 if ($assignColorId != 0) {
  10895.                     $d->setColorId($assignColorId);
  10896.                 } else {
  10897.                     $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  10898.                         ->findOneBy(
  10899.                             array(
  10900.                                 'id' => $assignProductId
  10901.                             )
  10902.                         );
  10903.                     if ($productData) {
  10904.                         $d->setColorId($productData->getDefaultColorId());
  10905.                     }
  10906.                 }
  10907.                 if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  10908.                     $d->setDefaultLabelFormatId($assignLabelFormatId);
  10909.                     $d->setDeviceLabelFormatId($assignLabelFormatId);
  10910.                 }
  10911.                 $toAssignPosition != '' $d->setPosition($toAssignPosition) : '';
  10912.                 $warehouseId != '' $d->setWarehouseId($warehouseId) : '';
  10913.                 $warehouseActionId != '' $d->setWarehouseActionId($warehouseActionId) : '';
  10914.                 if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  10915.                     $d->setProductionScheduleId($assignProductionScheduleId);
  10916.                     $productionSchedule $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  10917.                         ->findOneBy(
  10918.                             array(
  10919.                                 'productionScheduleId' => $assignProductionScheduleId
  10920.                             )
  10921.                         );
  10922.                     if ($productionSchedule) {
  10923.                         if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  10924.                             //becuase it will assigned at previous lines
  10925.                         } else {
  10926.                             $d->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  10927.                             $d->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  10928.                         }
  10929.                         $d->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  10930.                         $d->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  10931.                     }
  10932.                 }
  10933.                 $em->flush();
  10934.                 if ($d->getProductId() != '' || $d->getProductId() != null)
  10935.                     $productIds[] = $d->getProductId();
  10936.                 $formatId $d->getDeviceLabelFormatId();
  10937.             }
  10938.         }
  10939.         $labelFormatHere $em->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  10940.             ->findOneBy(
  10941.                 array(
  10942.                     'formatId' => $formatId,
  10943. //                        'CompanyId' => $companyId
  10944.                 )
  10945.             );
  10946.         if ($labelFormatHere) {
  10947.             $formatData json_decode($labelFormatHere->getFormatData(), true);
  10948.             if ($formatData == null$formatData = [];
  10949.             $labelData = array(
  10950.                 'id' => $labelFormatHere->getFormatId(),
  10951.                 'formatId' => $labelFormatHere->getFormatId(),
  10952.                 'labelType' => $labelFormatHere->getLabelType(),
  10953.                 'name' => $labelFormatHere->getName(),
  10954.                 'width' => $labelFormatHere->getWidth(),
  10955.                 'pageWidth' => $labelFormatHere->getPageWidth(),
  10956.                 'height' => $labelFormatHere->getheight(),
  10957.                 'pageHeight' => $labelFormatHere->getPageHeight(),
  10958.                 'formatData' => $formatData,
  10959.             );
  10960.         }
  10961.         $productList Inventory::ProductList($em$this->getLoggedUserCompanyId($request), 10''$productIds);
  10962.         $company_data Company::getCompanyData($em1);
  10963.         $document_mark = array(
  10964.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10965.             'copy' => ''
  10966.         );
  10967.         $dt $productByCodeData;
  10968.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10969.             $html $this->renderView('@Inventory/pages/print/print_label.html.twig',
  10970.                 array(
  10971.                     //full array here
  10972.                     'pdf' => true,
  10973.                     'page_title' => 'Device Labels',
  10974.                     'export' => 'print',
  10975.                     'repeatCount' => $repeatCount,
  10976.                     'labelData' => $labelData,
  10977.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10978. //                    'item_id' => $item_id,
  10979.                     'data' => $dt,
  10980.                     'productList' => $productList,
  10981.                     'approval_data' => [],
  10982.                     'document_log' => [],
  10983.                     'document_mark_image' => $document_mark['original'],
  10984.                     'company_name' => $company_data->getName(),
  10985.                     'company_data' => $company_data,
  10986.                     'company_address' => $company_data->getAddress(),
  10987.                     'company_image' => $company_data->getImage(),
  10988.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10989.                     'red' => 0
  10990.                 )
  10991.             );
  10992.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10993. //                'orientation' => 'landscape',
  10994.                 'enable-javascript' => true,
  10995. //                'javascript-delay' => 1000,
  10996.                 'no-stop-slow-scripts' => false,
  10997.                 'no-background' => false,
  10998.                 'lowquality' => false,
  10999.                 'encoding' => 'utf-8',
  11000. //            'images' => true,
  11001. //            'cookie' => array(),
  11002.                 'dpi' => 300,
  11003.                 'image-dpi' => 300,
  11004. //                'enable-external-links' => true,
  11005. //                'enable-internal-links' => true
  11006.             ));
  11007.             return new Response(
  11008.                 $pdf_response,
  11009.                 200,
  11010.                 array(
  11011.                     'Content-Type' => 'application/pdf',
  11012.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11013.                 )
  11014.             );
  11015.         }
  11016.         $url $this->generateUrl(
  11017.             'print_label'
  11018.         );
  11019.         if ($returnJson == && $printFlag == 0) {
  11020. //                    $dr = $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findBy(
  11021. //                        array(
  11022. //                            'salesOrderId' => $orderId, ///material
  11023. //
  11024. //                        )
  11025. //                    );
  11026.             return new JsonResponse(array(
  11027.                 'success' => true,
  11028. //                        'documentHash' => $order->getDocumentHash(),
  11029. //                'documentId' => $receiptId,
  11030. //                'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
  11031. //
  11032. //                'viewUrl' => $url . "/" . $receiptId,
  11033.             ));
  11034.         } else return $this->render('@Inventory/pages/print/print_label.html.twig',
  11035.             array(
  11036.                 'page_title' => 'Product Labels',
  11037. //                'export'=>'pdf,print',
  11038.                 'data' => $dt,
  11039.                 'productList' => $productList,
  11040.                 'repeatCount' => $repeatCount,
  11041. //                'item_id' => $item_id,
  11042.                 'labelData' => $labelData,
  11043.                 'brandList' => Inventory::GetBrandList($em$companyId),
  11044.                 'approval_data' => [],
  11045.                 'document_log' => [],
  11046.                 'document_mark_image' => $document_mark['original'],
  11047.                 'company_name' => $company_data->getName(),
  11048.                 'company_data' => $company_data,
  11049.                 'company_address' => $company_data->getAddress(),
  11050.                 'company_image' => $company_data->getImage(),
  11051.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11052.                 'red' => 0
  11053.             )
  11054.         );
  11055.     }
  11056.     public
  11057.     function PrintCartonLabelAction(Request $request$id)
  11058.     {
  11059.         $em $this->getDoctrine()->getManager();
  11060. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11061.         $repeatCount 1;
  11062.         $assignProductId '';
  11063.         $productByCodeIds = [];
  11064.         $cartonId 0;
  11065.         if ($id != 0)
  11066.             $cartonId $id;
  11067.         $colorText '';
  11068.         $weightText '';
  11069.         if ($request->query->has('repeatCount'))
  11070.             $repeatCount $request->query->get('repeatCount');
  11071.         if ($request->request->has('printCartonId'))
  11072.             $cartonId $request->request->get('printCartonId');
  11073.         if ($request->request->has('printCartonColorText'))
  11074.             $colorText $request->request->get('printCartonColorText');
  11075.         if ($request->request->has('printCartonWeightText'))
  11076.             $weightText $request->request->get('printCartonWeightText');
  11077.         $labelData = [
  11078.             'formatId' => 0
  11079.         ];
  11080.         if ($productByCodeIds == null)
  11081.             $productByCodeIds = [];
  11082.         $productByCodeData = [];
  11083.         $cartonData = [];
  11084.         $product = [];
  11085.         if ($cartonId != 0) {
  11086.             $cartonData $em->getRepository('ApplicationBundle\\Entity\\Carton')
  11087.                 ->findOneBy(
  11088.                     array(
  11089.                         'id' => $cartonId
  11090.                     )
  11091.                 );
  11092.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11093.                 ->findBy(
  11094.                     array(
  11095.                         'cartonId' => $cartonId
  11096.                     )
  11097.                 );
  11098. //            if(!empty($productByCodeData))
  11099. //                $product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  11100. //                ->findOneBy(
  11101. //                    array(
  11102. //                        'id' => $productByCodeData[0]->getProductId()
  11103. //                    )
  11104. //                );
  11105. //            else
  11106.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  11107.                 ->findOneBy(
  11108.                     array(
  11109.                         'id' => $cartonData->getProductId()
  11110.                     )
  11111.                 );
  11112.             $formatId $cartonData->getCartonLabelFormatId();
  11113.             $labelFormatHere $em->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  11114.                 ->findOneBy(
  11115.                     array(
  11116.                         'formatId' => $formatId,
  11117. //                        'CompanyId' => $companyId
  11118.                     )
  11119.                 );
  11120.             if ($labelFormatHere) {
  11121.                 $formatData json_decode($labelFormatHere->getFormatData(), true);
  11122.                 if ($formatData == null$formatData = [];
  11123.                 $labelData = array(
  11124.                     'id' => $labelFormatHere->getFormatId(),
  11125.                     'formatId' => $labelFormatHere->getFormatId(),
  11126.                     'labelType' => $labelFormatHere->getLabelType(),
  11127.                     'name' => $labelFormatHere->getName(),
  11128.                     'width' => $labelFormatHere->getWidth(),
  11129.                     'pageWidth' => $labelFormatHere->getPageWidth(),
  11130.                     'height' => $labelFormatHere->getheight(),
  11131.                     'pageHeight' => $labelFormatHere->getPageHeight(),
  11132.                     'formatData' => $formatData,
  11133.                 );
  11134.             }
  11135.         }
  11136.         $company_data Company::getCompanyData($em1);
  11137.         $document_mark = array(
  11138.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11139.             'copy' => ''
  11140.         );
  11141.         $dt $productByCodeData;
  11142.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11143.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  11144.                 array(
  11145.                     //full array here
  11146.                     'pdf' => true,
  11147.                     'page_title' => 'Carton Labels',
  11148.                     'export' => 'print',
  11149.                     'labelData' => $labelData,
  11150.                     'repeatCount' => $repeatCount,
  11151. //                    'item_id' => $item_id,
  11152.                     'data' => $dt,
  11153.                     'cartonData' => $cartonData,
  11154.                     'product' => $product,
  11155.                     'colorText' => $colorText,
  11156.                     'weightText' => $weightText,
  11157.                     'approval_data' => [],
  11158.                     'document_log' => [],
  11159.                     'document_mark_image' => $document_mark['original'],
  11160.                     'company_name' => $company_data->getName(),
  11161.                     'company_data' => $company_data,
  11162.                     'company_address' => $company_data->getAddress(),
  11163.                     'company_image' => $company_data->getImage(),
  11164.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11165.                     'red' => 0
  11166.                 )
  11167.             );
  11168.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11169. //                'orientation' => 'landscape',
  11170.                 'enable-javascript' => true,
  11171. //                'javascript-delay' => 1000,
  11172.                 'no-stop-slow-scripts' => false,
  11173.                 'no-background' => false,
  11174.                 'lowquality' => false,
  11175.                 'encoding' => 'utf-8',
  11176. //            'images' => true,
  11177. //            'cookie' => array(),
  11178.                 'dpi' => 300,
  11179.                 'image-dpi' => 300,
  11180. //                'enable-external-links' => true,
  11181. //                'enable-internal-links' => true
  11182.             ));
  11183.             return new Response(
  11184.                 $pdf_response,
  11185.                 200,
  11186.                 array(
  11187.                     'Content-Type' => 'application/pdf',
  11188.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11189.                 )
  11190.             );
  11191.         }
  11192.         if ($request->query->has('previewOnly')) {
  11193.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  11194.                 array(
  11195.                     'page_title' => 'Carton Labels',
  11196. //                'export'=>'pdf,print',
  11197.                     'data' => $dt,
  11198.                     'skip_parameters' => 1,
  11199.                     'labelData' => $labelData,
  11200.                     'cartonData' => $cartonData,
  11201.                     'product' => $product,
  11202.                     'colorText' => $colorText,
  11203.                     'weightText' => $weightText,
  11204.                     'repeatCount' => $repeatCount,
  11205. //                'item_id' => $item_id,
  11206.                     'approval_data' => [],
  11207.                     'document_log' => [],
  11208.                     'document_mark_image' => $document_mark['original'],
  11209.                     'company_name' => $company_data->getName(),
  11210.                     'company_data' => $company_data,
  11211.                     'company_address' => $company_data->getAddress(),
  11212.                     'company_image' => $company_data->getImage(),
  11213.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11214.                     'red' => 0
  11215.                 )
  11216.             );
  11217.             if ($request->query->has('returnJson')) {
  11218.                 return new JsonResponse(
  11219.                     array(
  11220.                         'success' => true,
  11221.                         'page_title' => 'Product Details',
  11222.                         'company_data' => $company_data,
  11223.                         'renderedHtml' => $html,
  11224. //                'productData' => $productData,
  11225. //                'currInvList' => $currInvList,
  11226. //                'productList' => Inventory::ProductList($em, $companyId),
  11227. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11228. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11229. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11230. //                'unitList' => Inventory::UnitTypeList($em),
  11231. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11232. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11233. //                'warehouseList' => Inventory::WarehouseList($em),
  11234.                     )
  11235.                 );
  11236.             }
  11237.         }
  11238.         return $this->render('@Inventory/pages/print/print_carton_label.html.twig',
  11239.             array(
  11240.                 'page_title' => 'Carton Labels',
  11241. //                'export'=>'pdf,print',
  11242.                 'data' => $dt,
  11243.                 'cartonData' => $cartonData,
  11244.                 'product' => $product,
  11245. //                'productByCodeData' => $productByCodeData,
  11246.                 'colorText' => $colorText,
  11247.                 'weightText' => $weightText,
  11248.                 'repeatCount' => $repeatCount,
  11249.                 'labelData' => $labelData,
  11250. //                'item_id' => $item_id,
  11251.                 'approval_data' => [],
  11252.                 'document_log' => [],
  11253.                 'document_mark_image' => $document_mark['original'],
  11254.                 'company_name' => $company_data->getName(),
  11255.                 'company_data' => $company_data,
  11256.                 'company_address' => $company_data->getAddress(),
  11257.                 'company_image' => $company_data->getImage(),
  11258.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11259.                 'red' => 0
  11260.             )
  11261.         );
  11262.     }
  11263.     public
  11264.     function AssignInfoToProductByCodeAction(Request $request$id)
  11265.     {
  11266.         $em $this->getDoctrine()->getManager();
  11267.         $companyId $this->getLoggedUserCompanyId($request);
  11268. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11269.         $cartonId '';
  11270.         $passStatus 5;
  11271.         $assignProductId '';
  11272.         $assignProductionId '';
  11273.         $assignProductionScheduleId '';
  11274.         $gbWeightGm '';
  11275.         $dvWeightGm '';
  11276.         $cartonWeightGm '';
  11277.         if ($request->request->has('cartonId'))
  11278.             $cartonId $request->request->get('cartonId');
  11279.         if ($request->request->has('passStatus'))
  11280.             $passStatus $request->request->get('passStatus');
  11281.         if ($request->request->has('productByCodeId'))
  11282.             $id $request->request->get('productByCodeId');
  11283.         if ($request->request->has('productId'))
  11284.             $assignProductId $request->request->get('productId');
  11285.         if ($request->request->has('productionId'))
  11286.             $assignProductionId $request->request->get('productionId');
  11287.         if ($request->request->has('productionScheduleId'))
  11288.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  11289.         if ($request->request->has('gbWeightGm'))
  11290.             $gbWeightGm $request->request->get('gbWeightGm');
  11291.         if ($request->request->has('dvWeightGm'))
  11292.             $dvWeightGm $request->request->get('dvWeightGm');
  11293.         if ($request->request->has('cartonWeightGm'))
  11294.             $cartonWeightGm $request->request->get('cartonWeightGm');
  11295.         $cartonAssignedAlready 0;
  11296.         $otherData = array(
  11297.             'currentCartonBalance' => 0,
  11298.             'currentCartonCapacity' => 0,
  11299.             'currentCartonAssigned' => 0,
  11300.             'currentCartonFull' => 0,
  11301.         );
  11302.         if ($id != && $id != '') {
  11303.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11304.                 ->findOneBy(
  11305.                     array(
  11306.                         'productByCodeId' => $id
  11307.                     )
  11308.                 );
  11309.             if ($assignProductId != ''$productByCodeData->setProductId($assignProductId);
  11310.             if ($productByCodeData->getCartonId() != '' || $productByCodeData->getCartonId() != null)
  11311.                 $cartonAssignedAlready 1;
  11312.             else if ($cartonId != ''$productByCodeData->setCartonId($cartonId);
  11313.             if ($dvWeightGm != ''$productByCodeData->setSingleWeightGm($dvWeightGm);
  11314.             if ($gbWeightGm != '') {
  11315.                 $productByCodeData->setPackagedWeightGm($gbWeightGm);
  11316.             }
  11317.             $colorText '_NA_';
  11318.             if ($passStatus != 5$productByCodeData->setStage($passStatus);
  11319.             $productByCodeData->setCompanyId($companyId);
  11320.             if ($assignProductionId != '') {
  11321.                 $productByCodeData->setProductionId($assignProductionId);
  11322.                 $productionData $em->getRepository('ApplicationBundle\\Entity\\Production')
  11323.                     ->findOneBy(
  11324.                         array(
  11325.                             'productionId' => $assignProductionId
  11326.                         )
  11327.                     );
  11328.                 if ($assignProductId != '' && $assignProductId != null && $assignProductId != 0)
  11329.                     $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  11330.                         array(
  11331.                             'productionId' => $assignProductionId,
  11332.                             'productId' => $assignProductId,
  11333.                             'type' => 1,
  11334.                         )
  11335.                     );
  11336.                 else
  11337.                     $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  11338.                         array(
  11339.                             'productionId' => $assignProductionId,
  11340. //                            'productId' => $assignProductId,
  11341.                             'type' => 1,
  11342.                         )
  11343.                     );
  11344.                 $assignProductionScheduleId $productionData->getProductionScheduleId();
  11345.                 if ($productionItemData) {
  11346.                     $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11347.                     $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11348.                     $productByCodeData->setPosition(1);//in inventory
  11349.                     $productByCodeData->setSerialAssigned(1);
  11350.                     $productByCodeData->setColorId($productionItemData->getColorId());
  11351.                     $productByCodeData->setColorText($productionItemData->getColorText());
  11352.                     $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11353.                     $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11354.                     if ($passStatus == 1)//passed
  11355.                     {
  11356. //                    $transDate = new \DateTime();
  11357. //                    Inventory::addItemToInventoryCompact($em,
  11358. //                        $productionItemData->getProductId(),
  11359. //                        $productionItemData->getWarehouseId(),
  11360. //                        $productionItemData->getWarehouseId(),
  11361. //                        $productionData->getProducedItemActionTagId(),
  11362. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11363. //                        $transDate,
  11364. //                        1,
  11365. //                        1,
  11366. //                        $entry['valueAdd'],
  11367. //                        $entry['valueSub'],
  11368. //                        $entry['price'],
  11369. //                        $this->getLoggedUserCompanyId($request),
  11370. //                        0,
  11371. //                        $entry['entity'],
  11372. //                        $entry['entityId'],
  11373. //                        $entry['entityDocHash']
  11374. //                    );
  11375.                     }
  11376.                     $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  11377.                     if ($transHistory == null)
  11378.                         $transHistory = [];
  11379.                     $transHistory[] = array(
  11380.                         'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  11381.                         'direction' => 'in',
  11382.                         'warehouseId' => $productionItemData->getWarehouseId(),
  11383.                         'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  11384.                         'fromWarehouseId' => 0,
  11385.                         'fromWarehouseActionId' => //stock of goods
  11386.                     );
  11387.                     $productByCodeData->setTransactionHistory(json_encode($transHistory));
  11388.                 }
  11389.             }
  11390.             if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  11391.                 $productByCodeData->setProductionScheduleId($assignProductionScheduleId);
  11392.                 $productionSchedule $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  11393.                     ->findOneBy(
  11394.                         array(
  11395.                             'productionScheduleId' => $assignProductionScheduleId
  11396.                         )
  11397.                     );
  11398.                 if ($productionSchedule) {
  11399.                     $productByCodeData->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  11400.                     $productByCodeData->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  11401.                     $productByCodeData->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  11402.                     $productByCodeData->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  11403.                     if ($productByCodeData->getProductionId() == null || $productByCodeData->getProductionId() == '' || $productByCodeData->getProductionId() == 0) {
  11404.                         $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  11405.                             array(
  11406.                                 'productionScheduleId' => $assignProductionScheduleId,
  11407.                                 'productId' => $productionSchedule->getProducedProductId(),
  11408.                                 'type' => 1,
  11409.                             )
  11410.                         );
  11411. //                        $assignProductionScheduleId=$productionData->getProductionScheduleId();
  11412.                         if ($productionItemData) {
  11413.                             $productByCodeData->setProductionId($productionItemData->getProductionId());
  11414.                             $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11415.                             $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11416.                             $productByCodeData->setPosition(1);//in inventory
  11417.                             $productByCodeData->setSerialAssigned(1);
  11418.                             $productByCodeData->setColorId($productionItemData->getColorId());
  11419.                             $productByCodeData->setColorText($productionItemData->getColorText());
  11420.                             $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11421.                             $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11422.                             if ($passStatus == 1)//passed
  11423.                             {
  11424. //                    $transDate = new \DateTime();
  11425. //                    Inventory::addItemToInventoryCompact($em,
  11426. //                        $productionItemData->getProductId(),
  11427. //                        $productionItemData->getWarehouseId(),
  11428. //                        $productionItemData->getWarehouseId(),
  11429. //                        $productionData->getProducedItemActionTagId(),
  11430. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11431. //                        $transDate,
  11432. //                        1,
  11433. //                        1,
  11434. //                        $entry['valueAdd'],
  11435. //                        $entry['valueSub'],
  11436. //                        $entry['price'],
  11437. //                        $this->getLoggedUserCompanyId($request),
  11438. //                        0,
  11439. //                        $entry['entity'],
  11440. //                        $entry['entityId'],
  11441. //                        $entry['entityDocHash']
  11442. //                    );
  11443.                             }
  11444.                             $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  11445.                             if ($transHistory == null)
  11446.                                 $transHistory = [];
  11447.                             $transHistory[] = array(
  11448.                                 'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  11449.                                 'direction' => 'in',
  11450.                                 'warehouseId' => $productionItemData->getWarehouseId(),
  11451.                                 'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  11452.                                 'fromWarehouseId' => 0,
  11453.                                 'fromWarehouseActionId' => //stock of goods
  11454.                             );
  11455.                             $productByCodeData->setTransactionHistory(json_encode($transHistory));
  11456.                         }
  11457.                     }
  11458.                 }
  11459.             }
  11460. //                $productByCodeData->setPurchaseWarrantyLastDate($new_pwld);
  11461.             $em->flush();
  11462.             //now adding carton
  11463.         }
  11464.         if ($cartonId != '') {
  11465.             $carton $em->getRepository('ApplicationBundle\\Entity\\Carton')
  11466.                 ->findOneBy(
  11467.                     array(
  11468.                         'id' => $cartonId
  11469.                     )
  11470.                 );
  11471.             if ($cartonWeightGm != ''$carton->setCartonWeightGm($cartonWeightGm);
  11472.             $otherData['currentCartonCapacity'] = $carton->getCartonCapacityCount();
  11473.             if ($cartonAssignedAlready == 0)
  11474.                 $carton->setCartonAssignedCount(($carton->getCartonAssignedCount()) + 1);
  11475.             $otherData['currentCartonAssigned'] = $carton->getCartonAssignedCount();
  11476.             $otherData['currentCartonBalance'] = $otherData['currentCartonCapacity'] - $otherData['currentCartonAssigned'];
  11477.             if ($otherData['currentCartonAssigned'] >= $otherData['currentCartonCapacity'])
  11478.                 $otherData['currentCartonFull'] = 1;
  11479.             $em->flush();
  11480.         }
  11481.         if ($cartonId != '') {
  11482. //                    if($cartonAssignedAlready==1)
  11483. //                    {
  11484.             $productByCodeDataListForThisCarton $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11485.                 ->findBy(
  11486.                     array(
  11487.                         'cartonId' => $cartonId
  11488.                     )
  11489.                 );
  11490.             $carton $em->getRepository('ApplicationBundle\\Entity\\Carton')
  11491.                 ->findOneBy(
  11492.                     array(
  11493.                         'id' => $cartonId
  11494.                     )
  11495.                 );
  11496.             $total_carton_predicted_weight 0;
  11497.             $colorTextList = [];
  11498.             $cartonProductByCodeIds = [];
  11499.             foreach ($productByCodeDataListForThisCarton as $pikamaster) {
  11500.                 if (!in_array($pikamaster->getProductByCodeId(), $cartonProductByCodeIds))
  11501.                     $cartonProductByCodeIds[] = $pikamaster->getProductByCodeId();
  11502.                 if (!in_array($pikamaster->getColorText(), $colorTextList) && $pikamaster->getColorText() != null)
  11503.                     $colorTextList[] = $pikamaster->getColorText();
  11504.                 $total_carton_predicted_weight += ($pikamaster->getPackagedWeightGm());
  11505.                 if ($passStatus != 5)
  11506.                     if ($pikamaster->getStage() < $passStatus)
  11507.                         $pikamaster->setStage($passStatus);
  11508.             }
  11509.             if ($carton)
  11510.                 $carton->setCartonCalculatedWeightGm($total_carton_predicted_weight);
  11511.             if ($passStatus != 5)
  11512.                 $carton->setStage($passStatus);
  11513.             $carton->setColors(implode(','$colorTextList));
  11514.             $carton->setCartonProductByCodeIds(json_encode($cartonProductByCodeIds));
  11515.             $em->flush();
  11516.         }
  11517.         return new JsonResponse(array(
  11518.             'success' => true,
  11519.             'otherData' => $otherData,
  11520.         ));
  11521.     }
  11522.     public
  11523.     function RefreshCartonListAction(Request $request$id)
  11524.     {
  11525.         $em $this->getDoctrine()->getManager();
  11526. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11527.         $cartonListArray = [];
  11528.         $cartonList = [];
  11529.         $assignableCartonList = [];
  11530.         $assignableCartonListArray = [];
  11531.         $assignable 0;
  11532.         $cartonId '';
  11533.         $passStatus 5;
  11534.         $assignProductId '';
  11535.         $assignProductionId '';
  11536.         $assignProductionScheduleId '';
  11537.         if ($request->request->has('productionId'))
  11538.             $assignProductionId $request->request->get('productionId');
  11539.         if ($request->request->has('productionScheduleId'))
  11540.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  11541.         if ($request->request->has('assignable'))
  11542.             $assignable $request->request->get('assignable');
  11543.         $cartonAssignedAlready 0;
  11544.         $otherData = array(
  11545.             'currentCartonBalance' => 0,
  11546.             'currentCartonCapacity' => 0,
  11547.             'currentCartonAssigned' => 0,
  11548.             'currentCartonFull' => 0,
  11549.         );
  11550.         //1st get all cartons for this production id
  11551.         $cartonList $em->getRepository('ApplicationBundle\\Entity\\Carton')
  11552.             ->findBy(
  11553.                 array(
  11554. //                    'productionId' => $assignProductionId,
  11555.                     'productionScheduleId' => $assignProductionScheduleId
  11556.                 )
  11557.             );
  11558.         $foundAssignable 0;
  11559.         $setId 0;
  11560.         $lastdmySer '';
  11561.         foreach ($cartonList as $carton) {
  11562.             $cartonData = array(
  11563.                 'id' => $carton->getId(),
  11564.                 'name' => $carton->getCartonNumber(),
  11565.                 'colors' => $carton->getColors(),
  11566.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  11567.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  11568.             );
  11569.             $cartonListArray[] = $cartonData;
  11570.             $cartonList[$cartonData['id']] = $cartonData;
  11571.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  11572.                 $foundAssignable 1;
  11573.                 $setId $cartonData['id'];
  11574.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  11575.                 $assignableCartonListArray[] = $cartonData;
  11576.             }
  11577.         }
  11578.         if ($assignable == && $foundAssignable == 0) {
  11579. //            $productionData = $em->getRepository('ApplicationBundle\\Entity\\Production')
  11580. //                ->findOneBy(
  11581. //                    array(
  11582. //                        'productionId' => $assignProductionId
  11583. //                    )
  11584. //                );
  11585.             $productionScheduleData $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  11586.                 ->findOneBy(
  11587.                     array(
  11588.                         'productionScheduleId' => $assignProductionScheduleId
  11589.                     )
  11590.                 );
  11591.             $productId 0;
  11592.             $product = [];
  11593.             $productModel '';
  11594.             if ($productionScheduleData)
  11595.                 $productId $productionScheduleData->getProducedProductId();
  11596. //            $productionItem = $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')
  11597. //                ->findOneBy(
  11598. //                    array(
  11599. //                        'productionId' => $assignProductionId,
  11600. //                        'type' => 1
  11601. //                    )
  11602. //                );
  11603.             if ($productId != 0) {
  11604. //                    $productId = $productionItem->getProductId();
  11605.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  11606.                     ->findOneBy(
  11607.                         array(
  11608.                             'id' => $productId,
  11609.                         )
  11610.                     );
  11611.                 $productModel $product->getModelNo();
  11612.             }
  11613.             $carton = new Carton();
  11614.             $carton_capacity $productionScheduleData->getCartonCapacity();
  11615.             $carton->setProductId($productId);
  11616.             $carton->setProductionId($assignProductionId);
  11617.             $carton->setProductionScheduleId($assignProductionScheduleId);
  11618.             if ($productionScheduleData) {
  11619.                 $carton->setCartonLabelFormatId($productionScheduleData->getCartonLabelFormatId());
  11620.             }
  11621.             $carton->setCartonCapacityCount($carton_capacity == null $carton_capacity);
  11622.             $carton->setCartonAssignedCount(0);
  11623.             $carton->setCompanyId($this->getLoggedUserCompanyId($request));
  11624.             $today = new \DateTime();
  11625.             $dmy $productModel '-' . ($today->format('m')) . '-' . ($today->format('Y')) . '-' $productionScheduleData->getBatchNumber();
  11626.             $ser 0;
  11627.             $carton->setCartonNumberDmy($dmy);
  11628.             $carton->setCartonNumberLastSer(* (($today->format('h')) . '' . ($today->format('i'))));
  11629.             $carton->setCartonNumber($dmy '-' . ($today->format('h')) . '' . ($today->format('i')));
  11630.             $em->persist($carton);
  11631.             $em->flush();
  11632.             $cartonData = array(
  11633.                 'id' => $carton->getId(),
  11634.                 'name' => $carton->getCartonNumber(),
  11635.                 'colors' => $carton->getColors(),
  11636.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  11637.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  11638.             );
  11639.             $cartonListArray[] = $cartonData;
  11640.             $cartonList[$cartonData['id']] = $cartonData;
  11641.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  11642.                 $foundAssignable 1;
  11643.                 $setId $cartonData['id'];
  11644.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  11645.                 $assignableCartonListArray[] = $cartonData;
  11646.             }
  11647.         }
  11648.         return new JsonResponse(array(
  11649.             'success' => true,
  11650.             'cartonList' => $cartonList,
  11651.             'cartonListArray' => $cartonListArray,
  11652.             'assignableCartonList' => $assignableCartonList,
  11653.             'assignableCartonListArray' => $assignableCartonListArray,
  11654.             'setId' => $setId,
  11655.         ));
  11656.     }
  11657.     public
  11658.     function PrintDrBarcodeAction(Request $request$id$item_id)
  11659.     {
  11660.         $em $this->getDoctrine()->getManager();
  11661.         $dt Inventory::GetDrDetails($em$id$item_id);
  11662.         $repeatCount 1;
  11663.         if ($request->query->has('repeatCount'))
  11664.             $repeatCount $request->query->get('repeatCount');
  11665.         $company_data Company::getCompanyData($em1);
  11666.         $document_mark = array(
  11667.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11668.             'copy' => ''
  11669.         );
  11670.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11671.             $html $this->renderView('@Inventory/pages/print/print_dr_barcodes.html.twig',
  11672.                 array(
  11673.                     //full array here
  11674.                     'pdf' => true,
  11675.                     'page_title' => 'Challan Barcodes',
  11676.                     'export' => 'print',
  11677.                     'repeatCount' => $repeatCount,
  11678.                     'item_id' => $item_id,
  11679.                     'data' => $dt,
  11680.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11681.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11682.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11683.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  11684.                         $id,
  11685.                         $dt['created_by'],
  11686.                         $dt['edited_by']),
  11687.                     'document_mark_image' => $document_mark['original'],
  11688.                     'company_name' => $company_data->getName(),
  11689.                     'company_data' => $company_data,
  11690.                     'company_address' => $company_data->getAddress(),
  11691.                     'company_image' => $company_data->getImage(),
  11692.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11693.                     'red' => 0
  11694.                 )
  11695.             );
  11696.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11697. //                'orientation' => 'landscape',
  11698.                 'enable-javascript' => true,
  11699. //                'javascript-delay' => 1000,
  11700.                 'no-stop-slow-scripts' => false,
  11701.                 'no-background' => false,
  11702.                 'lowquality' => false,
  11703.                 'encoding' => 'utf-8',
  11704. //            'images' => true,
  11705. //            'cookie' => array(),
  11706.                 'dpi' => 300,
  11707.                 'image-dpi' => 300,
  11708. //                'enable-external-links' => true,
  11709. //                'enable-internal-links' => true
  11710.             ));
  11711.             return new Response(
  11712.                 $pdf_response,
  11713.                 200,
  11714.                 array(
  11715.                     'Content-Type' => 'application/pdf',
  11716.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  11717.                 )
  11718.             );
  11719.         }
  11720.         return $this->render('@Inventory/pages/print/print_dr_barcodes.html.twig',
  11721.             array(
  11722.                 'page_title' => 'Challan barcodes',
  11723. //                'export'=>'pdf,print',
  11724.                 'data' => $dt,
  11725.                 'repeatCount' => $repeatCount,
  11726.                 'item_id' => $item_id,
  11727.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11728.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11729.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11730.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  11731.                     $id,
  11732.                     $dt['created_by'],
  11733.                     $dt['edited_by']),
  11734.                 'document_mark_image' => $document_mark['original'],
  11735.                 'company_name' => $company_data->getName(),
  11736.                 'company_data' => $company_data,
  11737.                 'company_address' => $company_data->getAddress(),
  11738.                 'company_image' => $company_data->getImage(),
  11739.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11740.                 'red' => 0
  11741.             )
  11742.         );
  11743.     }
  11744.     public
  11745.     function PrintIrrBarcodeAction(Request $request$id$item_id)
  11746.     {
  11747.         $em $this->getDoctrine()->getManager();
  11748.         $dt Inventory::GetIrrDetails($em$id$item_id);
  11749.         $repeatCount 1;
  11750.         if ($request->query->has('repeatCount'))
  11751.             $repeatCount $request->query->get('repeatCount');
  11752.         $company_data Company::getCompanyData($em1);
  11753.         $document_mark = array(
  11754.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11755.             'copy' => ''
  11756.         );
  11757.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11758.             $html $this->renderView('@Inventory/pages/print/print_irr_barcodes.html.twig',
  11759.                 array(
  11760.                     //full array here
  11761.                     'pdf' => true,
  11762.                     'page_title' => 'Sales Return Barcodes',
  11763.                     'export' => 'print',
  11764.                     'repeatCount' => $repeatCount,
  11765.                     'item_id' => $item_id,
  11766.                     'data' => $dt,
  11767.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  11768.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11769.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11770.                         array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  11771.                         $id,
  11772.                         $dt['created_by'],
  11773.                         $dt['edited_by']),
  11774.                     'document_mark_image' => $document_mark['original'],
  11775.                     'company_name' => $company_data->getName(),
  11776.                     'company_data' => $company_data,
  11777.                     'company_address' => $company_data->getAddress(),
  11778.                     'company_image' => $company_data->getImage(),
  11779.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11780.                     'red' => 0
  11781.                 )
  11782.             );
  11783.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11784. //                'orientation' => 'landscape',
  11785.                 'enable-javascript' => true,
  11786. //                'javascript-delay' => 1000,
  11787.                 'no-stop-slow-scripts' => false,
  11788.                 'no-background' => false,
  11789.                 'lowquality' => false,
  11790.                 'encoding' => 'utf-8',
  11791. //            'images' => true,
  11792. //            'cookie' => array(),
  11793.                 'dpi' => 300,
  11794.                 'image-dpi' => 300,
  11795. //                'enable-external-links' => true,
  11796. //                'enable-internal-links' => true
  11797.             ));
  11798.             return new Response(
  11799.                 $pdf_response,
  11800.                 200,
  11801.                 array(
  11802.                     'Content-Type' => 'application/pdf',
  11803.                     'Content-Disposition' => 'attachment; filename="irr_barcodes.pdf"'
  11804.                 )
  11805.             );
  11806.         }
  11807.         return $this->render('@Inventory/pages/print/print_irr_barcodes.html.twig',
  11808.             array(
  11809.                 'page_title' => 'Sales Return barcodes',
  11810. //                'export'=>'pdf,print',
  11811.                 'data' => $dt,
  11812.                 'repeatCount' => $repeatCount,
  11813.                 'item_id' => $item_id,
  11814.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  11815.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11816.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11817.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  11818.                     $id,
  11819.                     $dt['created_by'],
  11820.                     $dt['edited_by']),
  11821.                 'document_mark_image' => $document_mark['original'],
  11822.                 'company_name' => $company_data->getName(),
  11823.                 'company_data' => $company_data,
  11824.                 'company_address' => $company_data->getAddress(),
  11825.                 'company_image' => $company_data->getImage(),
  11826.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11827.                 'red' => 0
  11828.             )
  11829.         );
  11830.     }
  11831.     public
  11832.     function PrintSrcvBarcodeAction(Request $request$id$item_id)
  11833.     {
  11834.         $em $this->getDoctrine()->getManager();
  11835.         $dt Inventory::GetSrcvDetails($em$id$item_id);
  11836.         $repeatCount 1;
  11837.         if ($request->query->has('repeatCount'))
  11838.             $repeatCount $request->query->get('repeatCount');
  11839.         $company_data Company::getCompanyData($em1);
  11840.         $document_mark = array(
  11841.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11842.             'copy' => ''
  11843.         );
  11844.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11845.             $html $this->renderView('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  11846.                 array(
  11847.                     //full array here
  11848.                     'pdf' => true,
  11849.                     'page_title' => 'Grn Barcodes',
  11850.                     'export' => 'print',
  11851.                     'repeatCount' => $repeatCount,
  11852.                     'item_id' => $item_id,
  11853.                     'data' => $dt,
  11854.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11855.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11856.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11857.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11858.                         $id,
  11859.                         $dt['created_by'],
  11860.                         $dt['edited_by']),
  11861.                     'document_mark_image' => $document_mark['original'],
  11862.                     'company_name' => $company_data->getName(),
  11863.                     'company_data' => $company_data,
  11864.                     'company_address' => $company_data->getAddress(),
  11865.                     'company_image' => $company_data->getImage(),
  11866.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11867.                     'red' => 0
  11868.                 )
  11869.             );
  11870.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11871. //                'orientation' => 'landscape',
  11872.                 'enable-javascript' => true,
  11873. //                'javascript-delay' => 1000,
  11874.                 'no-stop-slow-scripts' => false,
  11875.                 'no-background' => false,
  11876.                 'lowquality' => false,
  11877.                 'encoding' => 'utf-8',
  11878. //            'images' => true,
  11879. //            'cookie' => array(),
  11880.                 'dpi' => 300,
  11881.                 'image-dpi' => 300,
  11882. //                'enable-external-links' => true,
  11883. //                'enable-internal-links' => true
  11884.             ));
  11885.             return new Response(
  11886.                 $pdf_response,
  11887.                 200,
  11888.                 array(
  11889.                     'Content-Type' => 'application/pdf',
  11890.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  11891.                 )
  11892.             );
  11893.         }
  11894.         return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  11895.             array(
  11896.                 'page_title' => 'Srcv barcodes',
  11897. //                'export'=>'pdf,print',
  11898.                 'data' => $dt,
  11899.                 'repeatCount' => $repeatCount,
  11900.                 'item_id' => $item_id,
  11901.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11902.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11903.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11904.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11905.                     $id,
  11906.                     $dt['created_by'],
  11907.                     $dt['edited_by']),
  11908.                 'document_mark_image' => $document_mark['original'],
  11909.                 'company_name' => $company_data->getName(),
  11910.                 'company_data' => $company_data,
  11911.                 'company_address' => $company_data->getAddress(),
  11912.                 'company_image' => $company_data->getImage(),
  11913.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11914.                 'red' => 0
  11915.             )
  11916.         );
  11917.     }
  11918. //product by code
  11919.     public
  11920.     function ImeiListExcelUploadAction(Request $request)
  11921.     {
  11922.         $lastIndex $request->request->get('lastIndex'0);
  11923.         if ($request->isMethod('POST')) {
  11924.             $post $request->request;
  11925.             if ($request->request->has('chunkData')) {
  11926.                 //now getting the relevant checks
  11927.                 $check_list = [];
  11928.                 $csv_data $request->request->get('chunkData', []);
  11929.                 $em $this->getDoctrine()->getManager();
  11930.                 foreach ($csv_data as $ind => $data_row) {
  11931. //                    if ($ind == 1)
  11932. //                        continue;
  11933.                     $np $this->getDoctrine()
  11934.                         ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11935.                         ->findOneBy(
  11936.                             array(
  11937.                                 'salesCode' => isset($data_row[4]) ? $data_row[4] : 0,
  11938. //                    'approved' =>  GeneralConstant::APPROVED,
  11939.                             )
  11940.                         );
  11941.                     if (!$np)
  11942.                         $np = new ProductByCode();
  11943. //                    $np = new ProductByCode();
  11944.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  11945.                     if (isset($data_row[1])) $np->setProductId($data_row[1]);
  11946.                     if (isset($data_row[0])) $np->setLcNumber($data_row[0]);
  11947.                     if (isset($data_row[2])) $np->setCartonNumber($data_row[2]);
  11948.                     if (isset($data_row[3])) $np->setSerialNo($data_row[3]);
  11949.                     $np->setSerialAssigned(isset($data_row[10]) ? $data_row[10] : 0);
  11950.                     if (isset($data_row[4])) $np->setImei1($data_row[4]);
  11951.                     if (isset($data_row[5])) $np->setImei2($data_row[5]);
  11952.                     if (isset($data_row[6])) $np->setImei3($data_row[6]);
  11953.                     if (isset($data_row[7])) $np->setImei4($data_row[7]);
  11954.                     if (isset($data_row[8])) $np->setBtMac($data_row[8]);
  11955.                     if (isset($data_row[9])) $np->setWlanMac($data_row[9]);
  11956.                     $np->setWarehouseId(isset($data_row[11]) ? $data_row[11] : 0);
  11957.                     $np->setWarehouseActionId(isset($data_row[12]) ? $data_row[12] : 0);
  11958.                     $np->setPosition(isset($data_row[13]) ? $data_row[13] : 0);//in inventory
  11959.                     $np->setPurchaseOrderId(0);
  11960.                     $np->setGrnId(0);
  11961.                     $np->setStage(0);
  11962.                     if (isset($data_row[3])) $np->setSalesCodeRange(json_encode([$data_row[3]]));
  11963. //                $np->setSalesCode($data_row[3]);
  11964.                     if (isset($data_row[4])) $np->setSalesCode($data_row[4]); //IMEI
  11965.                     $np->setSalesCodeSer(0);
  11966.                     $np->setSalesCodeDmy('');
  11967.                     $np->setPurchaseCodeRange("");
  11968.                     $np->setPurchaseReceiptDate(null);
  11969.                     $np->setLastInDate(null);
  11970.                     $np->setStatus(GeneralConstant::ACTIVE);
  11971.                     $np->setTransactionHistory(json_encode([
  11972.                         ]
  11973.                     ));
  11974.                     $np->setPurchaseWarrantyLastDate(null);
  11975.                     $em->persist($np);
  11976.                     $em->flush();
  11977.                 }
  11978.                 return new JsonResponse(array(
  11979.                     "success" => true,
  11980.                     "lastIndex" => $lastIndex,
  11981.                     "file_path" => '',
  11982.                     "csv_data" => $csv_data,
  11983.                     //                "debug_data"=>System::encryptSignature($r)
  11984.                 ));
  11985.             } else {
  11986.                 $path "";
  11987.                 $file_path "";
  11988.                 //            var_dump($request->files);
  11989.                 //        var_dump($request->getFile());
  11990.                 foreach ($request->files as $uploadedFile) {
  11991.                     //            if($uploadedFile->getImage())
  11992.                     //                var_dump($uploadedFile->getFile());
  11993.                     //                var_dump($uploadedFile);
  11994.                     if ($uploadedFile != null) {
  11995.                         $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  11996.                         $path $fileName;
  11997.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  11998.                         if (!file_exists($upl_dir)) {
  11999.                             mkdir($upl_dir0777true);
  12000.                         }
  12001.                         $file $uploadedFile->move($upl_dir$path);
  12002.                     }
  12003.                 }
  12004.                 //        print_r($file);
  12005.                 if ($path != "")
  12006.                     $file_path 'uploads/FileUploads/' $path;
  12007.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  12008.                 //
  12009.                 //            $img_file = file_get_contents($g_path);
  12010.                 //            $r=base64_encode($img_file);
  12011.                 $row 1;
  12012.                 $csv_data = [];
  12013.                 if (($handle fopen($g_path"r")) !== FALSE) {
  12014.                     while (($data fgetcsv($handle1000",")) !== FALSE) {
  12015.                         $num count($data);
  12016.                         $csv_data[$row] = $data;
  12017.                         //                    echo "<p> $num fields in line $row: <br /></p>\n";
  12018.                         $row++;
  12019.                         //                    for ($c=0; $c < $num; $c++) {
  12020.                         //                        echo $data[$c] . "<br />\n";
  12021.                         //                    }
  12022.                     }
  12023.                     fclose($handle);
  12024.                 }
  12025.                 //now getting the relevant checks
  12026.                 $check_list = [];
  12027.                 $em $this->getDoctrine()->getManager();
  12028.                 foreach ($csv_data as $ind => $data_row) {
  12029.                     if ($ind == 1)
  12030.                         continue;
  12031.                     $np = new ProductByCode();
  12032.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  12033.                     $np->setProductId($data_row[1]);
  12034.                     $np->setLcNumber($data_row[0]);
  12035.                     $np->setCartonNumber($data_row[2]);
  12036.                     $np->setSerialNo($data_row[3]);
  12037.                     $np->setSerialAssigned(0);
  12038.                     $np->setImei1($data_row[4]);
  12039.                     $np->setImei2($data_row[5]);
  12040.                     $np->setImei3($data_row[6]);
  12041.                     $np->setImei4($data_row[7]);
  12042.                     $np->setBtMac($data_row[8]);
  12043.                     $np->setWlanMac($data_row[9]);
  12044.                     $np->setWarehouseId(0);
  12045.                     $np->setWarehouseActionId(0);
  12046.                     $np->setPosition(0);//in inventory
  12047.                     $np->setPurchaseOrderId(0);
  12048.                     $np->setGrnId(0);
  12049.                     $np->setStage(0);
  12050.                     $np->setSalesCodeRange(json_encode([$data_row[3]]));
  12051. //                $np->setSalesCode($data_row[3]);
  12052.                     $np->setSalesCode($data_row[4]); //IMEI
  12053.                     $np->setSalesCodeSer(0);
  12054.                     $np->setSalesCodeDmy('');
  12055.                     $np->setPurchaseCodeRange("");
  12056.                     $np->setPurchaseReceiptDate(null);
  12057.                     $np->setLastInDate(null);
  12058.                     $np->setStatus(GeneralConstant::ACTIVE);
  12059.                     $np->setTransactionHistory(json_encode([
  12060.                         ]
  12061.                     ));
  12062.                     $np->setPurchaseWarrantyLastDate(null);
  12063.                     $em->persist($np);
  12064.                     $em->flush();
  12065.                 }
  12066.                 return new JsonResponse(array(
  12067.                     "success" => true,
  12068.                     "lastIndex" => $lastIndex,
  12069.                     "file_path" => $file_path,
  12070.                     "csv_data" => $csv_data,
  12071.                     //                "debug_data"=>System::encryptSignature($r)
  12072.                 ));
  12073.             }
  12074.         }
  12075.         return new JsonResponse(array(
  12076.             "success" => false,
  12077.             "file_path" => '',
  12078.             "csv_data" => [],
  12079.             "lastIndex" => $lastIndex,
  12080.         ));
  12081.     }
  12082.     public
  12083.     function ProductByCodeListAction(Request $request)
  12084.     {
  12085.         $em $this->getDoctrine()->getManager();
  12086.         $companyId $this->getLoggedUserCompanyId($request);
  12087.         $listData Inventory::GetProductListForProductByCodeListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  12088.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  12089.             if ($request->query->has('dataTableQry')) {
  12090.                 return new JsonResponse(
  12091.                     $listData
  12092.                 );
  12093.             }
  12094.         }
  12095.         $q = [];
  12096. //        $q = $this->getDoctrine()
  12097. //            ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12098. //            ->findBy(
  12099. //                array(
  12100. //                    'status' => GeneralConstant::ACTIVE,
  12101. ////                    'approved' =>  GeneralConstant::APPROVED,
  12102. //                )
  12103. //
  12104. //            );
  12105.         //temp start
  12106. //        foreach($q as $np) {
  12107. //            if($np->getPosition()==1) {   /// only starting ones or in warehouse ones
  12108. //                $temp_obj = json_decode($np->getTransactionHistory());
  12109. //                if ($temp_obj != null) {
  12110. //                    $transHistory = [];
  12111. //                    $transHistory[] = $temp_obj;
  12112. //                    $np->setTransactionHistory(json_encode($transHistory));
  12113. //                }
  12114. //            }
  12115. //            $em->flush();
  12116. //        }
  12117.         ///temp end
  12118.         $stage_list = array(
  12119.             => 'Pending',
  12120.             => 'Pending',
  12121.             => 'Complete',
  12122.             => 'Partial',
  12123.         );
  12124.         $data = [];
  12125. //        foreach($q as $entry)
  12126. //        {
  12127. //            $data[]=array(
  12128. //                'doc_date'=>$entry->getStockRequisitionDate(),
  12129. //                'id'=>$entry->getStockRequisitionId(),
  12130. //                'doc_hash'=>$entry->getDocumentHash(),
  12131. //                'approval_status'=>GeneralConstant::$approvalStatus[$entry->getApproved()],
  12132. //                'stage'=>$stage_list[$entry->getStage()]
  12133. //
  12134. //            );
  12135. //        }
  12136.         return $this->render('@Inventory/pages/views/product_by_code_list.html.twig',
  12137.             array(
  12138.                 'page_title' => 'Product List',
  12139.                 'data' => $q,
  12140. //                'listData' => $listData,
  12141.                 'products' => Inventory::ProductList($em),
  12142.                 'warehouseList' => Inventory::WarehouseList($em)
  12143.             )
  12144.         );
  12145.     }
  12146. //SR
  12147.     public
  12148.     function SrListAction(Request $request)
  12149.     {
  12150.         $q $this->getDoctrine()
  12151.             ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  12152.             ->findBy(
  12153.                 array(
  12154.                     'status' => GeneralConstant::ACTIVE,
  12155. //                    'approved' =>  GeneralConstant::APPROVED,
  12156.                 )
  12157.                 ,
  12158.                 array(
  12159.                     'stockRequisitionDate' => 'DESC'
  12160.                 )
  12161.             );
  12162.         $stage_list = array(
  12163.             => 'Pending',
  12164.             => 'Pending',
  12165.             => 'Complete',
  12166.             => 'Partial',
  12167.         );
  12168.         $data = [];
  12169.         foreach ($q as $entry) {
  12170.             $data[] = array(
  12171.                 'doc_date' => $entry->getStockRequisitionDate(),
  12172.                 'id' => $entry->getStockRequisitionId(),
  12173.                 'doc_hash' => $entry->getDocumentHash(),
  12174.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12175.                 'stage' => $stage_list[$entry->getStage()],
  12176.                 'indentTagged' => $entry->getIndentTagged(),
  12177.                 'srIds' => $entry->getSrIds(),
  12178.                 'irIds' => $entry->getIrIds(),
  12179.                 'prIds' => $entry->getPrIds(),
  12180.                 'poIds' => $entry->getPoIds(),
  12181.             );
  12182.         }
  12183.         return $this->render('@Inventory/pages/views/sr_list.html.twig',
  12184.             array(
  12185.                 'page_title' => 'Stock Requisition List',
  12186.                 'data' => $data
  12187.             )
  12188.         );
  12189.     }
  12190.     public
  12191.     function ViewSrAction(Request $request$id)
  12192.     {
  12193.         $em $this->getDoctrine()->getManager();
  12194.         $dt Inventory::GetSrDetails($em$id);
  12195.         return $this->render('@Inventory/pages/views/view_stock_requisition.html.twig',
  12196.             array(
  12197.                 'page_title' => 'Stock requisition',
  12198.                 'data' => $dt,
  12199.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12200.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12201.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12202.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12203.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12204.                     $id,
  12205.                     $dt['created_by'],
  12206.                     $dt['edited_by'])
  12207.             )
  12208.         );
  12209.     }
  12210.     public
  12211.     function PrintSrAction(Request $request$id)
  12212.     {
  12213.         $em $this->getDoctrine()->getManager();
  12214.         $dt Inventory::GetSrDetails($em$id);
  12215.         $company_data Company::getCompanyData($em1);
  12216.         $document_mark = array(
  12217.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12218.             'copy' => ''
  12219.         );
  12220.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12221.             $html $this->renderView('@Inventory/pages/print/print_sr.html.twig',
  12222.                 array(
  12223.                     //full array here
  12224.                     'pdf' => true,
  12225.                     'page_title' => 'Stock Requisition',
  12226.                     'export' => 'pdf,print',
  12227.                     'data' => $dt,
  12228.                     'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12229.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12230.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12231.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12232.                         array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12233.                         $id,
  12234.                         $dt['created_by'],
  12235.                         $dt['edited_by']),
  12236.                     'document_mark_image' => $document_mark['original'],
  12237.                     'company_name' => $company_data->getName(),
  12238.                     'company_data' => $company_data,
  12239.                     'company_address' => $company_data->getAddress(),
  12240.                     'company_image' => $company_data->getImage(),
  12241.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12242.                     'red' => 0
  12243.                 )
  12244.             );
  12245.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12246. //                'orientation' => 'landscape',
  12247. //                'enable-javascript' => true,
  12248. //                'javascript-delay' => 1000,
  12249.                 'no-stop-slow-scripts' => false,
  12250.                 'no-background' => false,
  12251.                 'lowquality' => false,
  12252.                 'encoding' => 'utf-8',
  12253. //            'images' => true,
  12254. //            'cookie' => array(),
  12255.                 'dpi' => 300,
  12256.                 'image-dpi' => 300,
  12257. //                'enable-external-links' => true,
  12258. //                'enable-internal-links' => true
  12259.             ));
  12260.             return new Response(
  12261.                 $pdf_response,
  12262.                 200,
  12263.                 array(
  12264.                     'Content-Type' => 'application/pdf',
  12265.                     'Content-Disposition' => 'attachment; filename="stock_requisition_' $id '.pdf"'
  12266.                 )
  12267.             );
  12268.         }
  12269.         return $this->render('@Inventory/pages/print/print_sr.html.twig',
  12270.             array(
  12271.                 'page_title' => 'Stock Requisition',
  12272.                 'export' => 'pdf,print',
  12273.                 'data' => $dt,
  12274.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12275.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12276.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12277.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12278.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12279.                     $id,
  12280.                     $dt['created_by'],
  12281.                     $dt['edited_by']),
  12282.                 'document_mark_image' => $document_mark['original'],
  12283.                 'company_name' => $company_data->getName(),
  12284.                 'company_data' => $company_data,
  12285.                 'company_address' => $company_data->getAddress(),
  12286.                 'company_image' => $company_data->getImage(),
  12287.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12288.                 'red' => 0
  12289.             )
  12290.         );
  12291.     }
  12292. //IR
  12293.     public
  12294.     function IrListAction(Request $request)
  12295.     {
  12296.         $q $this->getDoctrine()
  12297.             ->getRepository('ApplicationBundle\\Entity\\StoreRequisition')
  12298.             ->findBy(
  12299.                 array(
  12300.                     'status' => GeneralConstant::ACTIVE,
  12301. //                    'approved' =>  GeneralConstant::APPROVED,
  12302.                 ),
  12303.                 array(
  12304.                     'storeRequisitionDate' => 'DESC'
  12305.                 )
  12306.             );
  12307.         $stage_list = array(
  12308.             => 'Pending',
  12309.             => 'Pending',
  12310.             => 'Complete',
  12311.             => 'Partial',
  12312.         );
  12313.         $data = [];
  12314.         foreach ($q as $entry) {
  12315.             $data[] = array(
  12316.                 'doc_date' => $entry->getStoreRequisitionDate(),
  12317.                 'id' => $entry->getStoreRequisitionId(),
  12318.                 'doc_hash' => $entry->getDocumentHash(),
  12319.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12320.                 'stage' => $stage_list[$entry->getStage()],
  12321.                 'prTagged' => $entry->getIndentTagged(),
  12322.                 'srIds' => $entry->getSrIds(),
  12323.                 'irIds' => $entry->getIrIds(),
  12324.                 'prIds' => $entry->getPrIds(),
  12325.                 'poIds' => $entry->getPoIds(),
  12326.             );
  12327.         }
  12328.         return $this->render('@Inventory/pages/views/ir_list.html.twig',
  12329.             array(
  12330.                 'page_title' => 'Indent Requisition List',
  12331.                 'data' => $data
  12332.             )
  12333.         );
  12334.     }
  12335.     public
  12336.     function ViewIrAction(Request $request$id)
  12337.     {
  12338.         $em $this->getDoctrine()->getManager();
  12339.         $dt Inventory::GetIrDetails($em$id);
  12340.         return $this->render('@Inventory/pages/views/view_indent_requisition.html.twig',
  12341.             array(
  12342.                 'page_title' => 'Indent',
  12343.                 'data' => $dt,
  12344.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12345.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12346.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12347.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12348.                     $id,
  12349.                     $dt['created_by'],
  12350.                     $dt['edited_by'])
  12351.             )
  12352.         );
  12353.     }
  12354.     public
  12355.     function PrintIrAction(Request $request$id)
  12356.     {
  12357.         $em $this->getDoctrine()->getManager();
  12358.         $dt Inventory::GetIrDetails($em$id);
  12359.         $company_data Company::getCompanyData($em1);
  12360.         $document_mark = array(
  12361.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12362.             'copy' => ''
  12363.         );
  12364.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12365.             $html $this->renderView('@Inventory/pages/print/print_ir.html.twig',
  12366.                 array(
  12367.                     //full array here
  12368.                     'pdf' => true,
  12369.                     'page_title' => 'Indent Requisition',
  12370.                     'export' => 'pdf,print',
  12371.                     'data' => $dt,
  12372.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12373.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12374.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12375.                         array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12376.                         $id,
  12377.                         $dt['created_by'],
  12378.                         $dt['edited_by']),
  12379.                     'document_mark_image' => $document_mark['original'],
  12380.                     'company_name' => $company_data->getName(),
  12381.                     'company_data' => $company_data,
  12382.                     'company_address' => $company_data->getAddress(),
  12383.                     'company_image' => $company_data->getImage(),
  12384.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12385.                     'red' => 0
  12386.                 )
  12387.             );
  12388.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12389. //                'orientation' => 'landscape',
  12390. //                'enable-javascript' => true,
  12391. //                'javascript-delay' => 1000,
  12392.                 'no-stop-slow-scripts' => false,
  12393.                 'no-background' => false,
  12394.                 'lowquality' => false,
  12395.                 'encoding' => 'utf-8',
  12396. //            'images' => true,
  12397. //            'cookie' => array(),
  12398.                 'dpi' => 300,
  12399.                 'image-dpi' => 300,
  12400. //                'enable-external-links' => true,
  12401. //                'enable-internal-links' => true
  12402.             ));
  12403.             return new Response(
  12404.                 $pdf_response,
  12405.                 200,
  12406.                 array(
  12407.                     'Content-Type' => 'application/pdf',
  12408.                     'Content-Disposition' => 'attachment; filename="indent_' $id '.pdf"'
  12409.                 )
  12410.             );
  12411.         }
  12412.         return $this->render('@Inventory/pages/print/print_ir.html.twig',
  12413.             array(
  12414.                 'page_title' => 'Indent Requisition',
  12415.                 'export' => 'pdf,print',
  12416.                 'data' => $dt,
  12417.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12418.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12419.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12420.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12421.                     $id,
  12422.                     $dt['created_by'],
  12423.                     $dt['edited_by']),
  12424.                 'document_mark_image' => $document_mark['original'],
  12425.                 'company_name' => $company_data->getName(),
  12426.                 'company_data' => $company_data,
  12427.                 'company_address' => $company_data->getAddress(),
  12428.                 'company_image' => $company_data->getImage(),
  12429.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12430.                 'red' => 0
  12431.             )
  12432.         );
  12433.     }
  12434. //PR
  12435.     public
  12436.     function PrListAction(Request $request)
  12437.     {
  12438.         $q $this->getDoctrine()
  12439.             ->getRepository('ApplicationBundle\\Entity\\PurchaseRequisition')
  12440.             ->findBy(
  12441.                 array(
  12442.                     'status' => GeneralConstant::ACTIVE,
  12443. //                    'approved' =>  GeneralConstant::APPROVED,
  12444.                 ),
  12445.                 array(
  12446.                     'purchaseRequisitionDate' => 'DESC'
  12447.                 )
  12448.             );
  12449.         $stage_list = array(
  12450.             => 'Pending',
  12451.             => 'Pending',
  12452.             => 'Complete',
  12453.             => 'Partial',
  12454.         );
  12455.         $data = [];
  12456.         foreach ($q as $entry) {
  12457.             $data[] = array(
  12458.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  12459.                 'id' => $entry->getPurchaseRequisitionId(),
  12460.                 'doc_hash' => $entry->getDocumentHash(),
  12461.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12462.                 'acquisition_status' => $entry->getAcquisitionStatus(),
  12463.                 'acquisition_start_date' => $entry->getAcquisitionStartDate(),
  12464.                 'acquisition_end_date' => $entry->getAcquisitionEndDate(),
  12465.                 'acquisition_method' => $entry->getquotationAcquisitionMethod(),
  12466.                 'poTagged' => $entry->getPoTagged(),
  12467.                 'typeHash' => $entry->getTypehash(),
  12468.                 'srIds' => $entry->getSrIds(),
  12469.                 'irIds' => $entry->getIrIds(),
  12470.                 'prIds' => $entry->getPrIds(),
  12471.                 'poIds' => $entry->getPoIds(),
  12472.             );
  12473.         }
  12474.         return $this->render('@Inventory/pages/views/pr_list.html.twig',
  12475.             array(
  12476.                 'page_title' => 'Purchase Requisition List',
  12477.                 'data' => $data
  12478.             )
  12479.         );
  12480.     }
  12481.     public
  12482.     function ServiceRequisitionListAction(Request $request)
  12483.     {
  12484.         $q $this->getDoctrine()
  12485.             ->getRepository('ApplicationBundle\\Entity\\PurchaseRequisition')
  12486.             ->findBy(
  12487.                 array(
  12488.                     'status' => GeneralConstant::ACTIVE,
  12489. //                    'approved' =>  GeneralConstant::APPROVED,
  12490.                 ),
  12491.                 array(
  12492.                     'purchaseRequisitionDate' => 'DESC'
  12493.                 )
  12494.             );
  12495.         $stage_list = array(
  12496.             => 'Pending',
  12497.             => 'Pending',
  12498.             => 'Complete',
  12499.             => 'Partial',
  12500.         );
  12501.         $data = [];
  12502.         foreach ($q as $entry) {
  12503.             $data[] = array(
  12504.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  12505.                 'id' => $entry->getPurchaseRequisitionId(),
  12506.                 'doc_hash' => $entry->getDocumentHash(),
  12507.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12508.                 'poTagged' => $entry->getPoTagged(),
  12509.                 'typeHash' => $entry->getTypehash(),
  12510.                 'srIds' => $entry->getSrIds(),
  12511.                 'irIds' => $entry->getIrIds(),
  12512.                 'prIds' => $entry->getPrIds(),
  12513.                 'poIds' => $entry->getPoIds(),
  12514.             );
  12515.         }
  12516.         return $this->render('@Inventory/pages/views/service_requisition_list.html.twig',
  12517.             array(
  12518.                 'page_title' => 'Service Requisition List',
  12519.                 'data' => $data
  12520.             )
  12521.         );
  12522.     }
  12523.     public
  12524.     function ViewPrAction(Request $request$id)
  12525.     {
  12526.         $em $this->getDoctrine()->getManager();
  12527.         $dt Inventory::GetPrDetails($em$id);
  12528.         $companyId $this->getLoggedUserCompanyId($request);
  12529.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  12530.             array(
  12531.                 'page_title' => 'Purchase Requisition',
  12532.                 'data' => $dt,
  12533.                 'branchList' => Client::BranchList($em$companyId),
  12534.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12535.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12536.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12537.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12538.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12539.                     $id,
  12540.                     $dt['created_by'],
  12541.                     $dt['edited_by'])
  12542.             )
  12543.         );
  12544.     }
  12545.     public
  12546.     function ViewServiceRequisitionAction(Request $request$id)
  12547.     {
  12548.         $em $this->getDoctrine()->getManager();
  12549.         $dt Inventory::GetPrDetails($em$id);
  12550.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  12551.             array(
  12552.                 'page_title' => 'Service Requisition',
  12553.                 'data' => $dt,
  12554.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12555.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12556.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12557.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12558.                     $id,
  12559.                     $dt['created_by'],
  12560.                     $dt['edited_by'])
  12561.             )
  12562.         );
  12563.     }
  12564.     public
  12565.     function PrintPrAction(Request $request$id)
  12566.     {
  12567.         $em $this->getDoctrine()->getManager();
  12568.         $dt Inventory::GetPrDetails($em$id);
  12569.         $companyId $this->getLoggedUserCompanyId($request);
  12570.         $company_data Company::getCompanyData($em$companyId);
  12571.         $document_mark = array(
  12572.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12573.             'copy' => ''
  12574.         );
  12575.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12576.             $html $this->renderView('@Inventory/pages/print/print_pr.html.twig',
  12577.                 array(
  12578.                     //full array here
  12579.                     'pdf' => true,
  12580.                     'page_title' => 'Purchase Requisition',
  12581.                     'export' => 'pdf,print',
  12582.                     'data' => $dt,
  12583.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12584.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12585.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12586.                         array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12587.                         $id,
  12588.                         $dt['created_by'],
  12589.                         $dt['edited_by']),
  12590.                     'document_mark_image' => $document_mark['original'],
  12591.                     'branchList' => Client::BranchList($em$companyId),
  12592.                     'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12593.                     'company_name' => $company_data->getName(),
  12594.                     'company_data' => $company_data,
  12595.                     'company_address' => $company_data->getAddress(),
  12596.                     'company_image' => $company_data->getImage(),
  12597.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12598.                     'red' => 0
  12599.                 )
  12600.             );
  12601.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12602. //                'orientation' => 'landscape',
  12603. //                'enable-javascript' => true,
  12604. //                'javascript-delay' => 1000,
  12605.                 'no-stop-slow-scripts' => false,
  12606.                 'no-background' => false,
  12607.                 'lowquality' => false,
  12608.                 'encoding' => 'utf-8',
  12609. //            'images' => true,
  12610. //            'cookie' => array(),
  12611.                 'dpi' => 300,
  12612.                 'image-dpi' => 300,
  12613. //                'enable-external-links' => true,
  12614. //                'enable-internal-links' => true
  12615.             ));
  12616.             return new Response(
  12617.                 $pdf_response,
  12618.                 200,
  12619.                 array(
  12620.                     'Content-Type' => 'application/pdf',
  12621.                     'Content-Disposition' => 'attachment; filename="purchase_requisition_' $id '.pdf"'
  12622.                 )
  12623.             );
  12624.         }
  12625.         return $this->render('@Inventory/pages/print/print_pr.html.twig',
  12626.             array(
  12627.                 'page_title' => 'Purchase Requisition',
  12628.                 'export' => 'pdf,print',
  12629.                 'data' => $dt,
  12630.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12631.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12632.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12633.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12634.                     $id,
  12635.                     $dt['created_by'],
  12636.                     $dt['edited_by']),
  12637.                 'document_mark_image' => $document_mark['original'],
  12638.                 'company_name' => $company_data->getName(),
  12639.                 'company_data' => $company_data,
  12640.                 'branchList' => Client::BranchList($em$companyId),
  12641.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12642.                 'company_address' => $company_data->getAddress(),
  12643.                 'company_image' => $company_data->getImage(),
  12644.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12645.                 'red' => 0
  12646.             )
  12647.         );
  12648.     }
  12649.     public
  12650.     function CreateSecondaryDeliveryReceiptAction(Request $request)
  12651.     {
  12652.         $em $this->getDoctrine()->getManager();
  12653.         $companyId $this->getLoggedUserCompanyId($request);
  12654.         $userBranchIdList $request->getSession()->get('branchIdList');
  12655.         if ($userBranchIdList == null$userBranchIdList = [];
  12656.         $userBranchId $request->getSession()->get('branchId');
  12657.         if ($request->isMethod('POST')) {
  12658.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  12659.             $dochash $request->request->get('docHash'); //change
  12660.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12661.             $approveRole 1;  //created
  12662.             $approveHash $request->request->get('approvalHash');
  12663.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  12664.                 $loginId$approveRole$approveHash)
  12665.             ) {
  12666.                 $this->addFlash(
  12667.                     'error',
  12668.                     'Sorry Couldnot insert Data.'
  12669.                 );
  12670.             } else {
  12671.                 $receiptId SalesOrderM::CreateNewSecondaryDeliveryReceipt($this->getDoctrine()->getManager(), $request->request,
  12672.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  12673.                     $this->getLoggedUserCompanyId($request));
  12674.                 //now add Approval info
  12675.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12676.                 $approveRole 1;  //created
  12677.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12678.                     $receiptId,
  12679.                     $loginId,
  12680.                     $approveRole,
  12681.                     $request->request->get('approvalHash'));
  12682.                 $options = array(
  12683.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  12684.                     'notification_server' => $this->container->getParameter('notification_server'),
  12685.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  12686.                     'url' => $this->generateUrl(
  12687.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  12688.                         ['entity_view_route_path_name']
  12689.                     )
  12690.                 );
  12691.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  12692.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12693.                     $receiptId,
  12694.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  12695.                 );
  12696.                 $this->addFlash(
  12697.                     'success',
  12698.                     'New Delivery Receipt Created'
  12699.                 );
  12700.                 $url $this->generateUrl(
  12701.                     'view_delivery_receipt'
  12702.                 );
  12703.                 return $this->redirect($url "/" $receiptId);
  12704.             }
  12705.         }
  12706.         $debugData = [];
  12707. //        $dr_data=$em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findOneBy(
  12708. //            array(
  12709. //                'deliveryReceiptId'=>$dr_id
  12710. //            )
  12711. //        );
  12712.         $new_swld = new \DateTime('2017-07-09');
  12713. //        if ($entry->getWarranty() > 0)
  12714. //            $new_swld->modify('+' . $entry->getWarranty() . ' month');
  12715.         $debugData[] = $new_swld->format('Y-m-d');
  12716.         $debugData[] = $new_swld;
  12717. //        $debugData[]=$dr_data->getDeliveryReceiptDate();
  12718.         $debugData[] = '+' '1' ' month';
  12719.         $branchList Client::BranchList($em$companyId, [], $userBranchIdList);
  12720.         $warehouseIds = [];
  12721.         foreach ($branchList as $br) {
  12722.             $warehouseIds[] = $br['warehouseId'];
  12723.         }
  12724.         return $this->render('@Inventory/pages/input_forms/secondaryDeliveryReceipt.html.twig',
  12725.             array(
  12726.                 'page_title' => 'New Delivery Receipt',
  12727.                 'ExistingClients' => Accounts::getClientLedgerHeads($em),
  12728.                 'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($em),
  12729.                 'ClientList' => SalesOrderM::GetSecondaryClientList($em),
  12730.                 'warehouse' => Inventory::WarehouseList($em$companyId$warehouseIds),
  12731.                 'salesOrders' => SalesOrderM::SecondarySalesOrderListPendingDelivery($em$warehouseIds),
  12732.                 'salesOrdersArray' => SalesOrderM::SecondarySalesOrderListPendingDeliveryArray($em$warehouseIds),
  12733.                 'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
  12734.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
  12735.                 'debugData' => $debugData,
  12736.             )
  12737.         );
  12738.     }
  12739.     public
  12740.     function AddUnitTypeAction(Request $request$id 0)
  12741.     {
  12742.         $em $this->getDoctrine()->getManager();
  12743.         $companyId $this->getLoggedUserCompanyId($request);
  12744.         if ($request->isMethod('POST')) {
  12745.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12746.             $unitType = new UnitType();
  12747.             $unitType->setName($request->request->get('name'));
  12748.             $unitType->setStatus(1);
  12749.             $em->persist($unitType);
  12750.             $em->flush();
  12751.             $this->addFlash(
  12752.                 'success',
  12753.                 'Unit Type Added'
  12754.             );
  12755.         }
  12756.         $unitTypeDeatails $em->getRepository(UnitType::class)->findAll();
  12757.         return $this->render('@Inventory/pages/input_forms/addUnitType.html.twig',
  12758.             array(
  12759.                 'page_title' => 'Add Unit Type',
  12760.                 'unitTypeDeatails' => $unitTypeDeatails
  12761.             )
  12762.         );
  12763.     }
  12764.     public function AddSpecTypeAction(Request $request$id 0)
  12765.     {
  12766.         $em $this->getDoctrine()->getManager();
  12767.         $companyId $this->getLoggedUserCompanyId($request);
  12768.         if ($request->isMethod('POST')) {
  12769.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12770.             $specType = new SpecType();
  12771.             $specType->setName($request->request->get('name'));
  12772.             $specType->setStatus(1);
  12773.             $em->persist($specType);
  12774.             $em->flush();
  12775.             $this->addFlash(
  12776.                 'success',
  12777.                 'Spec Type Added'
  12778.             );
  12779.         }
  12780.         $specTypeDeatails $em->getRepository(SpecType::class)->findAll();
  12781.         return $this->render('@Inventory/pages/input_forms/addSpecType.html.twig',
  12782.             array(
  12783.                 'page_title' => 'Add Spec Type',
  12784.                 'specTypeDeatails' => $specTypeDeatails
  12785.             )
  12786.         );
  12787.     }
  12788.     public
  12789.     function SubcategoryListAction()
  12790.     {
  12791.         return $this->render('@Inventory/pages/input_forms/subCategoryList.html.twig',
  12792.             array(
  12793.                 'page_title' => 'Sub Category List',
  12794.             )
  12795.         );
  12796.     }
  12797.     public function SyncProductAction(Request $request$id)
  12798.     {
  12799.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  12800.         $em_local $this->getDoctrine()->getManager();
  12801.         if ($systemType == '_ERP_') {
  12802.             $product $em_local->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($id);
  12803.             if (!$product) {
  12804.                 return new JsonResponse(['error' => 'Product not found'], 404);
  12805.             }
  12806.             // Get category details
  12807.             $category $em_local->getRepository('ApplicationBundle\\Entity\\InvProductCategories')->find($product->getCategoryId());
  12808.             $brand $em_local -> getRepository('ApplicationBundle\\Entity\\BrandCompany')->find($product->getBrandCompany());
  12809.             $productData = [];
  12810.             $categoryData = [];
  12811.             $brandData = [];
  12812.             // Get product fields
  12813.             $reflectionClass = new \ReflectionClass($product);
  12814.             foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  12815.                 if (strpos($method->getName(), 'get') === 0) {
  12816.                     $property lcfirst(str_replace('get'''$method->getName()));
  12817.                     $productData[$property] = $method->invoke($product);
  12818.                 }
  12819.             }
  12820.             // Get category fields
  12821.             if ($category) {
  12822.                 $categoryReflection = new \ReflectionClass($category);
  12823.                 foreach ($categoryReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  12824.                     if (strpos($method->getName(), 'get') === 0) {
  12825.                         $property lcfirst(str_replace('get'''$method->getName()));
  12826.                         $categoryData[$property] = $method->invoke($category);
  12827.                     }
  12828.                 }
  12829.             }
  12830.             // Brand data
  12831.             if ($brand) {
  12832.                 $brandReflection = new \ReflectionClass($brand);
  12833.                 foreach ($brandReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  12834.                     if (strpos($method->getName(), 'get') === 0) {
  12835.                         $property lcfirst(str_replace('get'''$method->getName()));
  12836.                         $brandData[$property] = $method->invoke($brand);
  12837.                     }
  12838.                 }
  12839.             }
  12840.             // Store product data in pending_data
  12841.             $product->setPendingData(json_encode($productData));
  12842.             $em_local->flush();
  12843.             // Send  product,brand & category to central
  12844.             $syncData = [
  12845.                 'product' => $productData,
  12846.                 'category' => $categoryData,
  12847.                 'brand' => $brandData
  12848.             ];
  12849.             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/product_sync/' $id;
  12850.             $curl curl_init();
  12851.             curl_setopt_array($curl, [
  12852.                 CURLOPT_RETURNTRANSFER => true,
  12853.                 CURLOPT_POST => true,
  12854.                 CURLOPT_URL => $urlToCall,
  12855.                 CURLOPT_CONNECTTIMEOUT => 10,
  12856.                 CURLOPT_SSL_VERIFYPEER => false,
  12857.                 CURLOPT_SSL_VERIFYHOST => false,
  12858.                 CURLOPT_HTTPHEADER => [],
  12859.                 CURLOPT_POSTFIELDS => ['syncData' => json_encode($syncData)]
  12860.             ]);
  12861.             $retData curl_exec($curl);
  12862.             $errData curl_error($curl);
  12863.             curl_close($curl);
  12864.             if ($errData) {
  12865.                 return new JsonResponse(['error' => $errData], 500);
  12866.             }
  12867.             $retDataObj json_decode($retDatatrue);
  12868.             if (isset($retDataObj['globalId'])) {
  12869.                 $product->setGlobalId($retDataObj['globalId']);
  12870.                 $em_local->flush();
  12871.             }
  12872.             return new JsonResponse(['message' => 'Product (pending) and category synced to central server!']);
  12873.         }
  12874.         // CENTRAL SYSTEM PROCESSING
  12875.         else if ($systemType == '_CENTRAL_') {
  12876.             $requestData $request->get('syncData');
  12877.             if (!$requestData) {
  12878.                 return new JsonResponse(['error' => 'Invalid data received'], 400);
  12879.             }
  12880.             $requestData json_decode($requestDatatrue);
  12881.             $productData $requestData['product'] ?? null;
  12882.             $categoryData $requestData['category'] ?? null;
  12883.             $brandData $requestData['brand'] ?? null;
  12884.             if (!$productData) {
  12885.                 return new JsonResponse(['error' => 'Product data missing'], 400);
  12886.             }
  12887.             // Process product (Store in pending_data)
  12888.             $product $em_local->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($productData['id']) ?? new InvProducts();
  12889.             // Store in pending_data until approval
  12890.             $product->setPendingData(json_encode($productData));
  12891.             $this->ApproveProductAction($id);
  12892.             $em_local->persist($product);
  12893.             // Process category (Save directly)
  12894.             if ($categoryData) {
  12895.                 $category $em_local->getRepository('ApplicationBundle\\Entity\\InvProductCategories')->find($categoryData['id']) ?? new InvProductCategories();
  12896.                 foreach ($categoryData as $field => $value) {
  12897.                     if ($field === 'id') continue;
  12898.                     $setterMethod 'set' ucfirst($field);
  12899.                     if (method_exists($category$setterMethod)) {
  12900.                         $category->$setterMethod($value);
  12901.                     }
  12902.                 }
  12903.                 $em_local->persist($category);
  12904.             }
  12905.             // process brand data
  12906.             if($brandData){
  12907.                 $brand $em_local->getRepository('ApplicationBundle\\Entity\\BrandCompany')->find($brandData['id']) ?? new BrandCompany();
  12908.                 foreach ($brandData as $field => $value){
  12909.                     if($field === 'id') continue;
  12910.                     $setterMethod 'set'.ucfirst($field);
  12911.                     if(method_exists($brand,$setterMethod)){
  12912.                         $brand->$setterMethod($value);
  12913.                     }
  12914.                 }
  12915.                 $em_local->persist($brand);
  12916.             }
  12917.             $em_local->flush();
  12918.             return new JsonResponse(['globalId' => $product->getId()]);
  12919.         }
  12920.         return new JsonResponse("Product (pending) and category updated successfully in central!");
  12921.     }
  12922.     public function CheckGlobalProductAction(Request $request)
  12923.     {
  12924.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  12925.         if ($systemType !== '_CENTRAL_') {
  12926.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  12927.         }
  12928.         $em $this->getDoctrine()->getManager();
  12929.         $igName      trim($request->request->get('igName'''));
  12930.         $productName trim($request->request->get('productName'''));
  12931.         $modelNo     trim($request->request->get('modelNo'''));
  12932.         if (!$igName || !$productName) {
  12933.             return new JsonResponse(['success' => false'found' => false'message' => 'igName and productName are required']);
  12934.         }
  12935.         $ig $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(['name' => $igName'type' => 1]);
  12936.         if (!$ig) {
  12937.             return new JsonResponse(['success' => true'found' => false]);
  12938.         }
  12939.         $product null;
  12940.         if ($modelNo) {
  12941.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'modelNo' => $modelNo]);
  12942.         }
  12943.         if (!$product) {
  12944.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'name' => $productName]);
  12945.         }
  12946.         if (!$product) {
  12947.             return new JsonResponse(['success' => true'found' => false]);
  12948.         }
  12949.         return new JsonResponse(['success' => true'found' => true'globalId' => $product->getGlobalId() ?: $product->getId()]);
  12950.     }
  12951.     public function SearchGlobalProductsAction(Request $request)
  12952.     {
  12953.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  12954.         if ($systemType !== '_CENTRAL_') {
  12955.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  12956.         }
  12957.         $em          $this->getDoctrine()->getManager();
  12958.         $query       trim($request->request->get('query'''));
  12959.         $igName      trim($request->request->get('igName'''));
  12960.         $modelNo     trim($request->request->get('modelNo'''));
  12961.         $globalId    = (int)$request->request->get('globalId'0);
  12962.         $limit       min((int)$request->request->get('limit'10), 25);
  12963.         if ($globalId 0) {
  12964.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  12965.             if (!$product) {
  12966.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  12967.             }
  12968.             if (!$product) {
  12969.                 return new JsonResponse(['success' => true'count' => 0'results' => []]);
  12970.             }
  12971.             $ig $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->find($product->getIgId());
  12972.             return new JsonResponse(['success' => true'count' => 1'results' => [
  12973.                 $this->buildGlobalProductRow($em$product$ig),
  12974.             ]]);
  12975.         }
  12976.         if (strlen($query) < && !$modelNo) {
  12977.             return new JsonResponse(['success' => false'message' => 'query must be at least 2 characters'], 400);
  12978.         }
  12979.         $conn $em->getConnection();
  12980.         // The central catalog DB is lean â€” it may not carry the full ERP inventory schema
  12981.         // (e.g. inv_product_brand). A LEFT JOIN still hard-fails on a missing table, so only join
  12982.         // the enrichment tables that actually exist; absent ones fall back to an empty literal.
  12983.         $existingTables = [];
  12984.         $productCols = [];
  12985.         try {
  12986.             foreach ($this->dbalFetchAllAssoc(
  12987.                 $conn,
  12988.                 "SELECT table_name AS t FROM information_schema.tables WHERE table_schema = DATABASE()"
  12989.             ) as $r) {
  12990.                 $existingTables[strtolower($r['t'])] = true;
  12991.             }
  12992.             // Also detect which COLUMNS exist on inv_products â€” a lean central may be missing
  12993.             // optional columns (description, alias, model_no, global_id, sync_flag, â€¦).
  12994.             foreach ($this->dbalFetchAllAssoc(
  12995.                 $conn,
  12996.                 "SELECT column_name AS c FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'inv_products'"
  12997.             ) as $r) {
  12998.                 $productCols[strtolower($r['c'])] = true;
  12999.             }
  13000.         } catch (\Throwable $e) { /* detection failed â†’ assume everything exists (old behaviour) */ }
  13001.         $hasTable = function ($t) use ($existingTables) {
  13002.             return empty($existingTables) || isset($existingTables[strtolower($t)]);
  13003.         };
  13004.         $hasCol = function ($c) use ($productCols) {
  13005.             return empty($productCols) || isset($productCols[strtolower($c)]);
  13006.         };
  13007.         $hasModelNo $hasCol('model_no');
  13008.         $where = [];
  13009.         $params = [];
  13010.         if ($query !== '') {
  13011.             $where[] = $hasModelNo '(p.name LIKE :q OR p.model_no LIKE :q)' 'p.name LIKE :q';
  13012.             $params['q'] = '%' $query '%';
  13013.         }
  13014.         if ($modelNo !== '' && $hasModelNo) {
  13015.             $where[] = 'p.model_no LIKE :model';
  13016.             $params['model'] = '%' $modelNo '%';
  13017.         }
  13018.         if ($igName !== '' && $hasTable('inv_item_group')) {
  13019.             $where[] = 'ig.name = :igName';
  13020.             $params['igName'] = $igName;
  13021.         }
  13022.         $whereSql $where ? ('WHERE ' implode(' AND '$where)) : '';
  13023.         // Base columns on inv_products â€” include only those that exist; missing ones become ''.
  13024.         $baseColumns = [
  13025.             ['id',          'p.id'],
  13026.             ['name',        'p.name'],
  13027.             ['modelNo',     'p.model_no'],
  13028.             ['productFdm',  'p.product_fdm'],
  13029.             ['globalId',    'p.global_id'],
  13030.             ['syncFlag',    'p.sync_flag'],
  13031.             ['description''p.description'],
  13032.             ['alias',       'p.alias'],
  13033.         ];
  13034.         $selects = [];
  13035.         foreach ($baseColumns as $bc) {
  13036.             list($as$col) = $bc;
  13037.             $rawCol substr($col2); // strip "p."
  13038.             if ($hasCol($rawCol)) {
  13039.                 $selects[] = ($rawCol === $as) ? $col : ($col ' AS ' $as);
  13040.             } else {
  13041.                 $selects[] = "'' AS $as";
  13042.             }
  13043.         }
  13044.         $joins '';
  13045.         $enrich = [
  13046.             ['inv_item_group',            'ig',  'ig.id = p.ig_id',                              'ig.name',       'igName'],
  13047.             ['inv_product_categories',    'cat''cat.id = p.category_id',                       'cat.name',      'categoryName'],
  13048.             ['inv_product_sub_categories','sub''sub.id = p.sub_category_id',                   'sub.name',      'subCategoryName'],
  13049.             ['brand_company',             'br',  'br.id = p.brand_company',                      'br.name',       'brandName'],
  13050.             ['unit_type',                 'ut',  'ut.id = p.unit_type_id',                       'ut.name',       'uomName'],
  13051.             ['inv_product_images',        'img''img.product_id = p.id AND img.is_default = 1''img.file_name''image'],
  13052.         ];
  13053.         foreach ($enrich as $e) {
  13054.             list($tbl$alias$on$col$as) = $e;
  13055.             if ($hasTable($tbl)) {
  13056.                 $selects[] = "$col AS $as";
  13057.                 $joins   .= "\n                LEFT JOIN $tbl $alias ON $on";
  13058.             } else {
  13059.                 $selects[] = "'' AS $as";
  13060.             }
  13061.         }
  13062.         // ORDER BY: exact-name first; the model_no tier only when that column exists.
  13063.         $orderSql "ORDER BY CASE WHEN p.name = :exactName THEN 0 ";
  13064.         if ($hasModelNo) {
  13065.             $orderSql .= "WHEN p.model_no = :exactModel THEN 1 ";
  13066.         }
  13067.         $orderSql .= "ELSE 2 END, p.name ASC";
  13068.         $sql "SELECT " implode(', '$selects) . "
  13069.                 FROM inv_products p" $joins "
  13070.                 $whereSql
  13071.                 $orderSql
  13072.                 LIMIT :lim";
  13073.         $params['exactName']  = $query ?: '';
  13074.         if ($hasModelNo) {
  13075.             $params['exactModel'] = $modelNo ?: $query;
  13076.         }
  13077.         $params['lim']        = $limit;
  13078.         $types = [];
  13079.         foreach ($params as $key => $val) {
  13080.             $types[$key] = is_int($val) ? \PDO::PARAM_INT : \PDO::PARAM_STR;
  13081.         }
  13082.         $rows $this->dbalFetchAllAssoc($conn$sql$params$types);
  13083.         foreach ($rows as &$row) {
  13084.             $row['globalId'] = (int)($row['globalId'] ?: $row['id']);
  13085.         }
  13086.         return new JsonResponse(['success' => true'count' => count($rows), 'results' => $rows]);
  13087.     }
  13088.     /**
  13089.      * Fetch all rows as associative arrays, portable across Doctrine DBAL versions.
  13090.      * The central server runs an older DBAL where fetchAllAssociative() does not exist â€” fall
  13091.      * back to the legacy Connection::fetchAll(). Both accept ($sql, $params, $types).
  13092.      */
  13093.     private function dbalFetchAllAssoc($conn$sql, array $params = [], array $types = [])
  13094.     {
  13095.         if (method_exists($conn'fetchAllAssociative')) {
  13096.             return $conn->fetchAllAssociative($sql$params$types);
  13097.         }
  13098.         return $conn->fetchAll($sql$params$types);
  13099.     }
  13100.     private function buildGlobalProductRow($em$product$ig)
  13101.     {
  13102.         $categoryName '';
  13103.         $subCategoryName '';
  13104.         $brandName '';
  13105.         $uomName '';
  13106.         // Enrichment tables may be absent on a lean central DB â€” never let a missing one break the row.
  13107.         try {
  13108.             if ($product->getCategoryId()) {
  13109.                 $cat $em->getRepository('ApplicationBundle\\Entity\\InvProductCategories')->find($product->getCategoryId());
  13110.                 if ($cat$categoryName $cat->getName();
  13111.             }
  13112.         } catch (\Throwable $e) { /* table absent */ }
  13113.         try {
  13114.             if ($product->getSubCategoryId()) {
  13115.                 $sub $em->getRepository('ApplicationBundle\\Entity\\InvProductSubCategories')->find($product->getSubCategoryId());
  13116.                 if ($sub$subCategoryName $sub->getName();
  13117.             }
  13118.         } catch (\Throwable $e) { /* table absent */ }
  13119.         try {
  13120.             if ($product->getBrandCompany()) {
  13121.                 $br $em->getRepository('ApplicationBundle\\Entity\\BrandCompany')->find($product->getBrandCompany());
  13122.                 if ($br$brandName $br->getName();
  13123.             }
  13124.         } catch (\Throwable $e) { /* table absent */ }
  13125.         try {
  13126.             if ($product->getUnitTypeId()) {
  13127.                 $ut $em->getRepository('ApplicationBundle\\Entity\\UnitType')->find($product->getUnitTypeId());
  13128.                 if ($ut$uomName $ut->getName();
  13129.             }
  13130.         } catch (\Throwable $e) { /* table absent */ }
  13131.         return [
  13132.             'id'              => $product->getId(),
  13133.             'globalId'        => $product->getGlobalId() ?: $product->getId(),
  13134.             'name'            => $product->getName(),
  13135.             'modelNo'         => $product->getModelNo(),
  13136.             'productFdm'      => $product->getProductFdm(),
  13137.             'description'     => $product->getNote(),
  13138.             'alias'           => $product->getAlias(),
  13139.             'igName'          => $ig $ig->getName() : '',
  13140.             'categoryName'    => $categoryName,
  13141.             'subCategoryName' => $subCategoryName,
  13142.             'brandName'       => $brandName,
  13143.             'uomName'         => $uomName,
  13144.             'image'           => '',
  13145.         ];
  13146.     }
  13147.     public function RegisterGlobalProductAction(Request $request)
  13148.     {
  13149.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  13150.         if ($systemType !== '_CENTRAL_') {
  13151.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  13152.         }
  13153.         $em $this->getDoctrine()->getManager();
  13154.         $igName      trim($request->request->get('igName'''));
  13155.         $productName trim($request->request->get('productName'''));
  13156.         $modelNo     trim($request->request->get('modelNo'''));
  13157.         $productFdm  $request->request->get('productFdm''');
  13158.         if (!$igName || !$productName) {
  13159.             return new JsonResponse(['success' => false'message' => 'igName and productName are required'], 400);
  13160.         }
  13161.         $ig $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(['name' => $igName'type' => 1]);
  13162.         if (!$ig) {
  13163.             $ig = new \ApplicationBundle\Entity\InvItemGroup();
  13164.             $ig->setName($igName);
  13165.             $ig->setType(1);
  13166.             $em->persist($ig);
  13167.             $em->flush();
  13168.             $ig->setGlobalId($ig->getId());
  13169.             $em->flush();
  13170.         }
  13171.         // Race-condition guard: check again after potential ig creation
  13172.         $existing null;
  13173.         if ($modelNo) {
  13174.             $existing $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'modelNo' => $modelNo]);
  13175.         }
  13176.         if (!$existing) {
  13177.             $existing $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'name' => $productName]);
  13178.         }
  13179.         if ($existing) {
  13180.             return new JsonResponse(['success' => true'globalId' => $existing->getGlobalId() ?: $existing->getId()]);
  13181.         }
  13182.         $product = new \ApplicationBundle\Entity\InvProducts();
  13183.         $product->setName($productName);
  13184.         $product->setModelNo($modelNo);
  13185.         $product->setProductFdm($productFdm);
  13186.         $product->setIgId($ig->getId());
  13187.         $product->setSyncFlag(2);
  13188.         $em->persist($product);
  13189.         $em->flush();
  13190.         $product->setGlobalId($product->getId());
  13191.         $em->flush();
  13192.         return new JsonResponse(['success' => true'globalId' => $product->getId()]);
  13193.     }
  13194.     public function PushGlobalProductToErpsAction(Request $request)
  13195.     {
  13196.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  13197.         if ($systemType !== '_CENTRAL_') {
  13198.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  13199.         }
  13200.         $globalId = (int)$request->request->get('globalId'0);
  13201.         $data     $request->request->get('data', []);
  13202.         if (!$globalId) {
  13203.             return new JsonResponse(['success' => false'message' => 'globalId is required'], 400);
  13204.         }
  13205.         $em_goc $this->getDoctrine()->getManager('company_group');
  13206.         $em_goc->getConnection()->connect();
  13207.         if (!$em_goc->getConnection()->isConnected()) {
  13208.             return new JsonResponse(['success' => false'message' => 'Cannot connect to company_group DB'], 500);
  13209.         }
  13210.         $gocList $em_goc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy(['active' => 1]);
  13211.         $seenServers = [];
  13212.         $results = [];
  13213.         foreach ($gocList as $entry) {
  13214.             $serverAddress rtrim(
  13215.                 $entry->getCurrentServerDomainFullLink() ?: $entry->getCompanyGroupServerDomainFullLink(),
  13216.                 '/'
  13217.             );
  13218.             if (!$serverAddress || isset($seenServers[$serverAddress])) continue;
  13219.             $seenServers[$serverAddress] = true;
  13220.             $curl curl_init();
  13221.             curl_setopt_array($curl, [
  13222.                 CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  13223.                 CURLOPT_URL => $serverAddress '/api/sync_product_from_central',
  13224.                 CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 15,
  13225.                 CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  13226.                 CURLOPT_POSTFIELDS => http_build_query(['globalId' => $globalId'data' => $data]),
  13227.             ]);
  13228.             $response  curl_exec($curl);
  13229.             $curlError curl_error($curl);
  13230.             curl_close($curl);
  13231.             $results[$serverAddress] = $curlError
  13232.                 ? ['error' => $curlError]
  13233.                 : json_decode($responsetrue);
  13234.         }
  13235.         return new JsonResponse(['success' => true'pushed' => count($seenServers), 'results' => $results]);
  13236.     }
  13237.     public function SuggestProductUpdateAction(Request $request)
  13238.     {
  13239.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  13240.         if ($systemType !== '_CENTRAL_') {
  13241.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  13242.         }
  13243.         $em             $this->getDoctrine()->getManager();
  13244.         $globalId       = (int)$request->request->get('globalId'0);
  13245.         $suggestedFields $request->request->get('suggestedFields', []);
  13246.         $suggestedBy    = (int)$request->request->get('suggestedBy'0);
  13247.         $sourceNote     trim($request->request->get('sourceNote'''));
  13248.         if (!$globalId || empty($suggestedFields)) {
  13249.             return new JsonResponse(['success' => false'message' => 'globalId and suggestedFields are required'], 400);
  13250.         }
  13251.         // validate: igId and modelNo cannot be suggested for change
  13252.         $forbidden = ['igId''ig_id''modelNo''model_no'];
  13253.         foreach ($forbidden as $f) {
  13254.             if (isset($suggestedFields[$f])) {
  13255.                 return new JsonResponse(['success' => false'message' => "Field '{$f}' is a global identity anchor and cannot be changed"], 422);
  13256.             }
  13257.         }
  13258.         $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  13259.         if (!$product) {
  13260.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  13261.         }
  13262.         if (!$product) {
  13263.             return new JsonResponse(['success' => false'message' => 'Product not found on central'], 404);
  13264.         }
  13265.         $suggestion = new \ApplicationBundle\Entity\InvProductCentralSuggestion();
  13266.         $suggestion->setGlobalId($globalId);
  13267.         $suggestion->setSuggestedFields(json_encode($suggestedFields));
  13268.         $suggestion->setSuggestedBy($suggestedBy ?: null);
  13269.         $suggestion->setSourceNote($sourceNote ?: null);
  13270.         $suggestion->setStatus(\ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_PENDING);
  13271.         $em->persist($suggestion);
  13272.         $em->flush();
  13273.         return new JsonResponse(['success' => true'suggestionId' => $suggestion->getId()]);
  13274.     }
  13275.     public function ApproveProductAction(Request $request$id)
  13276.     {
  13277.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  13278.         if ($systemType !== '_CENTRAL_') {
  13279.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  13280.         }
  13281.         $em         $this->getDoctrine()->getManager();
  13282.         $approvedBy = (int)$request->request->get('approvedBy'0);
  13283.         $suggestion $em->getRepository('ApplicationBundle\\Entity\\InvProductCentralSuggestion')->find((int)$id);
  13284.         if (!$suggestion) {
  13285.             return new JsonResponse(['error' => 'Suggestion not found'], 404);
  13286.         }
  13287.         if ($suggestion->getStatus() !== \ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_PENDING) {
  13288.             return new JsonResponse(['error' => 'Suggestion already ' $suggestion->getStatus()], 409);
  13289.         }
  13290.         $globalId $suggestion->getGlobalId();
  13291.         $product  $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  13292.         if (!$product) {
  13293.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  13294.         }
  13295.         if (!$product) {
  13296.             return new JsonResponse(['error' => 'Central product not found for globalId ' $globalId], 404);
  13297.         }
  13298.         $fields   $suggestion->getSuggestedFieldsArray();
  13299.         $locked   = ['igId''ig_id''modelNo''model_no''id''globalId'];
  13300.         $applied  = [];
  13301.         foreach ($fields as $field => $value) {
  13302.             if (in_array($field$lockedtrue)) continue;
  13303.             $setter 'set' ucfirst($field);
  13304.             if (method_exists($product$setter)) {
  13305.                 $product->$setter($value);
  13306.                 $applied[$field] = $value;
  13307.             }
  13308.         }
  13309.         $em->flush();
  13310.         // mark suggestion approved
  13311.         $suggestion->setStatus(\ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_APPROVED);
  13312.         $suggestion->setApprovedBy($approvedBy ?: null);
  13313.         $suggestion->setApprovedAt(new \DateTime());
  13314.         $em->flush();
  13315.         // propagate approved changes to all linked ERP servers
  13316.         $em_goc $this->getDoctrine()->getManager('company_group');
  13317.         $gocList = [];
  13318.         try {
  13319.             $gocList $em_goc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy(['active' => 1]);
  13320.         } catch (\Exception $e) {}
  13321.         $seenServers = [];
  13322.         $pushResults = [];
  13323.         foreach ($gocList as $entry) {
  13324.             $serverAddress rtrim(
  13325.                 $entry->getCurrentServerDomainFullLink() ?: $entry->getCompanyGroupServerDomainFullLink(),
  13326.                 '/'
  13327.             );
  13328.             if (!$serverAddress || isset($seenServers[$serverAddress])) continue;
  13329.             $seenServers[$serverAddress] = true;
  13330.             $curl curl_init();
  13331.             curl_setopt_array($curl, [
  13332.                 CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  13333.                 CURLOPT_URL => $serverAddress '/api/sync_product_from_central',
  13334.                 CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 15,
  13335.                 CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  13336.                 CURLOPT_POSTFIELDS => http_build_query(['globalId' => $globalId'data' => $applied]),
  13337.             ]);
  13338.             $response  curl_exec($curl);
  13339.             $curlError curl_error($curl);
  13340.             curl_close($curl);
  13341.             $pushResults[$serverAddress] = $curlError
  13342.                 ? ['error' => $curlError]
  13343.                 : json_decode($responsetrue);
  13344.         }
  13345.         return new JsonResponse([
  13346.             'success'     => true,
  13347.             'globalId'    => $globalId,
  13348.             'appliedFields' => array_keys($applied),
  13349.             'pushedTo'    => count($seenServers),
  13350.             'pushResults' => $pushResults,
  13351.         ]);
  13352.     }
  13353.     public function RejectProductSuggestionAction(Request $request$id)
  13354.     {
  13355.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  13356.         if ($systemType !== '_CENTRAL_') {
  13357.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  13358.         }
  13359.         $em           $this->getDoctrine()->getManager();
  13360.         $rejectedBy   = (int)$request->request->get('rejectedBy'0);
  13361.         $rejectionNote trim($request->request->get('rejectionNote'''));
  13362.         $suggestion $em->getRepository('ApplicationBundle\\Entity\\InvProductCentralSuggestion')->find((int)$id);
  13363.         if (!$suggestion) {
  13364.             return new JsonResponse(['error' => 'Suggestion not found'], 404);
  13365.         }
  13366.         if ($suggestion->getStatus() !== \ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_PENDING) {
  13367.             return new JsonResponse(['error' => 'Suggestion already ' $suggestion->getStatus()], 409);
  13368.         }
  13369.         $suggestion->setStatus(\ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_REJECTED);
  13370.         $suggestion->setRejectedBy($rejectedBy ?: null);
  13371.         $suggestion->setRejectedAt(new \DateTime());
  13372.         $suggestion->setRejectionNote($rejectionNote ?: null);
  13373.         $em->flush();
  13374.         return new JsonResponse(['success' => true'suggestionId' => $suggestion->getId()]);
  13375.     }
  13376. }