src/ApplicationBundle/Controller/InventoryController.php line 8480

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Controller;
  3. use ApplicationBundle\Constants\AccountsConstant;
  4. use ApplicationBundle\Constants\GeneralConstant;
  5. use ApplicationBundle\Constants\HumanResourceConstant;
  6. use ApplicationBundle\Constants\InventoryConstant;
  7. use ApplicationBundle\Constants\LabelConstant;
  8. use ApplicationBundle\Entity\BrandCompany;
  9. use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
  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: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: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: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: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("templating");
  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 CreateProductAction(Request $request$id 0)
  347.     {
  348.         $ex_id 0;
  349.         $prod_det = [];
  350.         $product_duplicate 0;
  351.         $group_type 1;//item
  352.         $em $this->getDoctrine()->getManager();
  353.         $companyId $this->getLoggedUserCompanyId($request);
  354.         $route $request->get('_route');
  355.         if ($route == 'create_service')
  356.             $group_type 2;//service
  357.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  358.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  359.         if ($request->isMethod('POST')) {
  360.             if ($id == 0)
  361.                 $id $request->request->has('ex_id') ? $request->request->get('ex_id') : 0;
  362.             if ($id == 0) {
  363.                 if ($group_type == 2)
  364.                     $ext_pr $this->getDoctrine()
  365.                         ->getRepository('ApplicationBundle:AccService')
  366.                         ->findOneBy(
  367.                             array(
  368.                                 'serviceName' => $request->request->get('name'),
  369.                             )
  370.                         );
  371.                 else
  372.                     $ext_pr $this->getDoctrine()
  373.                         ->getRepository('ApplicationBundle:InvProducts')
  374.                         ->findOneBy(
  375.                             array(
  376.                                 'name' => $request->request->get('name'),
  377.                             )
  378.                         );
  379.                 if ($ext_pr)
  380.                     $product_duplicate 1;
  381.             }
  382.             if ($product_duplicate == 1) {
  383.                 $this->addFlash(
  384.                     'error',
  385.                     'Duplicate Entry Found'
  386.                 );
  387.             } else {
  388.                 $image_list = [];
  389.                 $defaultImage "";
  390.                 $defaultImageUploadedFile null;
  391.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  392.                 if ($group_type == 2) {
  393.                     $ig $this->getDoctrine()
  394.                         ->getRepository('ApplicationBundle:InvItemGroup')
  395.                         ->findOneBy(
  396.                             array(
  397.                                 'id' => $request->request->get('itemgroupId')
  398.                             )
  399.                         );
  400.                     $defaultPurchaseActionTagId $request->request->get('defaultPurchaseActionTagId''');
  401.                     $ledgerHitAs $request->request->get('ledgerHitAs''');
  402.                     $defaultExpenseId $request->request->get('defaultExpenseId''');
  403.                     Inventory::CreateNewService(
  404.                         $this->getDoctrine()->getManager(),
  405.                         $request->request->get('ex_id'),
  406.                         $request->request->get('name'),
  407.                         $companyId,
  408.                         $request->request->get('typeId'),
  409.                         $request->request->get('categoryId'),
  410.                         $request->request->get('brandCompany'),
  411.                         $request->request->get('subCategoryId'),
  412.                         $request->request->get('itemgroupId'),
  413.                         $request->request->get('unitTypeId'),
  414.                         $request->request->get('note'),
  415.                         $request->request->get('alias'''),
  416.                         $request->request->get('categorization_1'''),
  417.                         $request->request->get('categorization_2'''),
  418.                         $request->request->get('categorization_3'''),
  419.                         $request->request->get('categorization_4'''),
  420.                         $request->request->get('purchasePrice'0),
  421.                         $request->request->get('salesPrice'0),
  422.                         $request->request->get('productFdm'''),
  423.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  424.                         ($ledgerHitAs != '') ? $ledgerHitAs $ig->getLedgerHitAs(),
  425.                         ($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId $ig->getDefaultPurchaseActionTagId(),
  426.                         ($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId $ig->getDefaultExpenseId()
  427.                     );
  428.                     $this->addFlash(
  429.                         'success',
  430.                         'Service Have Been Added/Updated'
  431.                     );
  432.                 } else {
  433.                     $ig $this->getDoctrine()
  434.                         ->getRepository('ApplicationBundle:InvItemGroup')
  435.                         ->findOneBy(
  436.                             array(
  437.                                 'id' => $request->request->get('itemgroupId')
  438.                             )
  439.                         );
  440.                     $defaultPurchaseActionTagId $request->request->get('defaultPurchaseActionTagId''');
  441.                     $ledgerHitAs $request->request->get('ledgerHitAs''');
  442.                     $defaultExpenseId $request->request->get('defaultExpenseId''');
  443.                     $crateData = [];
  444.                     foreach ($request->request->get('product_crate', []) as $crateIndex => $crateId) {
  445.                         $crateData[] = array(
  446.                             'id' => $crateId,
  447.                             'qty' => $request->request->get('product_qty', [])[$crateIndex],
  448.                         );
  449.                     }
  450.                     $specData = [];
  451.                     foreach ($request->request->get('spec', []) as $specIndex => $specId) {
  452.                         $specData[] = array(
  453.                             'id' => $specId,
  454.                             'value' => $request->request->get('spec_value', [])[$specIndex],
  455.                         );
  456.                     }
  457.                     $sizesData = [];
  458.                     foreach ($request->request->get('product_size', []) as $sizeIndex => $crateId) {
  459.                         $sizesData[] = array(
  460.                             'size' => $request->request->get('product_size', [])[$sizeIndex],
  461.                             'dimension' => $request->request->get('product_dimension', [])[$sizeIndex],
  462.                             'dimensionUnitType' => $request->request->get('product_dimension_unit_type', [])[$sizeIndex],
  463.                             'weight' => $request->request->get('product_weight', [])[$sizeIndex],
  464.                             'weightUnitType' => $request->request->get('product_weight_unit_type', [])[$sizeIndex],
  465.                         );
  466.                     }
  467.                     Inventory::CreateNewProduct(
  468.                         $this->getDoctrine()->getManager(),
  469.                         $request->request->get('ex_id'0),
  470.                         $request->request->get('name'''),
  471.                         $request->request->get('model_no'''),
  472.                         $this->getLoggedUserCompanyId($request),
  473.                         $request->request->get('typeId'1),
  474.                         $request->request->get('categoryId'null),
  475.                         $request->request->get('hasSerial'null),
  476.                         $ig->getDraccountsHeadId(),
  477.                         $ig->getCraccountsHeadId(),
  478.                         ($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId $ig->getDefaultPurchaseActionTagId(),
  479.                         $ig->getVatAsExpenseFlag(),
  480.                         $request->request->get('brandCompany'null),
  481.                         $request->request->get('subCategoryId'null),
  482.                         $request->request->get('yearlyDepreciation'0),
  483.                         $request->request->get('purchaseWarrantyMonths'0),
  484.                         $request->request->get('salesWarrantyMonths'0),
  485.                         $request->request->get('startingBalanceUnit'0),
  486.                         $request->request->get('reorderLevel'0),
  487.                         $request->request->get('note'''),
  488.                         $request->request->get('alias'''),
  489.                         $request->request->get('itemgroupId'null),
  490.                         $request->request->get('unitTypeId'null),
  491.                         $request->request->get('hsCode'''),
  492.                         $request->request->get('skuCode'''),
  493.                         $request->files->get('dataSheets', []),
  494.                         $request->request->get('partId'''),
  495.                         $request->request->get('productCode'''),
  496.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  497.                         $request->request->get('purchasePrice'0),
  498.                         $request->request->get('salesPrice'0),
  499.                         $request->files->get('product_default_image'null),
  500.                         $upl_dir,
  501.                         $request->files->get('product_images', []),
  502.                         $request->request->get('expiryDays'0),
  503.                         $request->request->get('dimension'''),
  504.                         $request->request->get('dimensionUnitTypeId'0),
  505.                         $request->request->get('productFdm'''),
  506.                         $request->request->get('weight'''),
  507.                         $request->request->get('weightUnitTypeId'0),
  508.                         $request->request->get('specification'null),
  509.                         $request->request->get('ingredient'null),
  510.                         $request->request->get('nutrition'null),
  511.                         $request->request->get('segregatePriceByColorsFlag'null),
  512.                         $request->request->get('segregatePriceBySizesFlag'null),
  513.                         $request->request->get('categorization_1'''),
  514.                         $request->request->get('categorization_2'''),
  515.                         $request->request->get('categorization_3'''),
  516.                         $request->request->get('categorization_4'''),
  517.                         $request->request->get('weightVarianceValue'0),
  518.                         $request->request->get('weightVarianceType'0),
  519.                         $request->request->get('singleWeight'''),
  520.                         $request->request->get('singleWeightUnitTypeId'0),
  521.                         $request->request->get('singleWeightVarianceValue'0),
  522.                         $request->request->get('singleWeightVarianceType'0),
  523.                         $request->request->get('cartonWeightVarianceValue'0),
  524.                         $request->request->get('cartonWeightVarianceType'0),
  525.                         $request->request->get('cartonCapacityCount'0),
  526.                         $request->request->get('tac'''),
  527.                         $request->request->get('sellable'0),
  528.                         $request->request->get('abstract'0),
  529.                         $request->request->get('tags'''),
  530.                         $request->request->get('markerFlags'''),
  531.                         $request->request->get('defaultColorId'0),
  532.                         $request->request->get('product_color', []),
  533.                         $request->request->get('product_size', []),
  534.                         ($ledgerHitAs != '') ? $ledgerHitAs $ig->getLedgerHitAs(),
  535.                         ($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId $ig->getDefaultExpenseId(),
  536.                         $crateData,
  537.                         $sizesData,
  538.                         $specData
  539.                     );
  540.                     $this->addFlash(
  541.                         'success',
  542.                         'Product Have Been Added/Updated'
  543.                     );
  544.                 }
  545.             }
  546.             if ($request->request->has('returnJson')) {
  547.                 return new JsonResponse(array(
  548.                     'success' => true
  549.                 ));
  550.             }
  551.             if ($group_type == 2)
  552.                 return $this->redirectToRoute("create_service");
  553.             else
  554.                 return $this->redirectToRoute("create_product");
  555.         }
  556.         if ($id != 0) {
  557.             $ex_id $id;
  558.             if ($group_type == 2)
  559.                 $prod_det $this->getDoctrine()->getRepository('ApplicationBundle:AccService')->findOneBy(array(
  560.                     'serviceId' => $id//for now for stock of goods
  561. //                    'opening_locked'=>0
  562.                 ));
  563.             else
  564.                 $prod_det $this->getDoctrine()->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
  565.                     'id' => $id//for now for stock of goods
  566. //                    'opening_locked'=>0
  567.                 ));
  568.         }
  569.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  570.             'name' => 'warehouse_action_1'//for now for stock of goods
  571.         ));
  572.         return $this->render('@Inventory/pages/input_forms/create_product.html.twig',
  573.             array(
  574.                 'page_title' => $group_type == 'Service Entry' 'Product Entry',
  575.                 'group_type' => $group_type,
  576.                 'inv_head' => $inv_head $inv_head->getData() : '',
  577. //                'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  578.                 'services' => Inventory::ServiceList($this->getDoctrine()->getManager()),
  579.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  580.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  581.                 'itemgroup' => Inventory::ItemGroupList($em$companyId$group_type),
  582.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  583.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  584.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager(), 1),
  585.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  586.                 'ex_id' => $ex_id,
  587.                 'warehouse_action_list' => $warehouse_action_list,
  588.                 'warehouse_action_list_array' => $warehouse_action_list_array,
  589.                 'markerFlags' => InventoryConstant::$SPECIAL_MARKER_ARRAY,
  590.                 'ex_prod_det' => $prod_det
  591.             )
  592.         );
  593.     }
  594.     public function ProductListAction(Request $request)
  595.     {
  596.         $em $this->getDoctrine()->getManager();
  597.         $companyId $this->getLoggedUserCompanyId($request);
  598.         $listData Inventory::GetProductListForProductListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  599.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  600.             if ($request->query->has('dataTableQry')) {
  601.                 return new JsonResponse(
  602.                     $listData
  603.                 );
  604.             }
  605.         }
  606.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  607.             'name' => 'warehouse_action_1'//for now for stock of goods
  608.         ));
  609.         return $this->render('@Inventory/pages/views/product_list.html.twig',
  610.             array(
  611.                 'page_title' => 'Product List',
  612.                 'inv_head' => $inv_head $inv_head->getData() : '',
  613. //                'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  614.                 'products' => [],
  615.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  616.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  617.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  618.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  619.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  620. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  621.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  622.             )
  623.         );
  624.     }
  625.     public function SalesVsDeliveryListAction(Request $request)
  626.     {
  627.         $em $this->getDoctrine()->getManager();
  628.         $session $request->getSession();
  629.         $userType $session->get(UserConstants::USER_TYPE);
  630.         $userId $session->get(UserConstants::USER_ID);
  631.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  632.             'approved' => GeneralConstant::APPROVED,
  633. //            'stage' => GeneralConstant::STAGE_PENDING
  634.         );
  635.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  636.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  637.         }
  638. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  639. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  640. //            $selectiveDocumentsFlag=1; //by default will show only selective
  641. //            if(isset($userRestrictions['canSeeAllSo'])) {
  642. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  643. //                    $selectiveDocumentsFlag = 0;
  644. //                }
  645. //            }
  646. //
  647. //            if($selectiveDocumentsFlag==1)
  648. //            {
  649. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  650. //            }
  651. //        }
  652.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  653.             'name' => 'warehouse_action_1'//for now for stock of goods
  654.         ));
  655.         if ($request->query->has('queryDate')) {
  656.             $date = new \DateTime($request->query->get('queryDate'));
  657.         } else {
  658.             $today = new \DateTime();
  659.             $todayStr $today->format('Y-m-d');
  660.             $date = new \DateTime($todayStr);
  661.         }
  662.         $orderQryArray['salesOrderDate'] = $date;
  663.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrder')->findBy($orderQryArray);
  664.         $so_ids = [];
  665.         $so_data = [];
  666.         $so_item_ids = [];
  667.         $so_item_data = [];
  668.         foreach ($salesOrders as $salesOrder) {
  669.             if ($salesOrder->getSalesOrderDate() > $date)
  670.                 continue;
  671.             $so_ids[] = $salesOrder->getSalesOrderId();
  672.             $so_data[$salesOrder->getSalesOrderId()] = array(
  673.                 "id" => $salesOrder->getSalesOrderId(),
  674.                 "documentHash" => $salesOrder->getDocumentHash(),
  675.                 "clientId" => $salesOrder->getClientId(),
  676.             );
  677.         }
  678.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrderItem')->findBy(array(
  679.             'salesOrderId' => $so_ids,
  680.         ));
  681.         foreach ($salesOrderItems as $salesOrderItem) {
  682.             $so_item_ids[] = $salesOrderItem->getId();
  683.             $so_item_data[$salesOrderItem->getId()] = array(
  684.                 "id" => $salesOrderItem->getId(),
  685.                 "productId" => $salesOrderItem->getProductId(),
  686.                 "productName" => $salesOrderItem->getProductNameFdm(),
  687.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  688.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  689.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  690. //                "documentHash"=>$salesOrder->getDocumentHash(),
  691.                 "qty" => $salesOrderItem->getQty(),
  692.                 "transitQty" => $salesOrderItem->getTransitQty(),
  693.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  694.             );
  695.         }
  696.         return $this->render('@Inventory/pages/views/sales_vs_delivery_status.html.twig',
  697.             array(
  698.                 'page_title' => 'Order Vs. Disperse',
  699.                 'inv_head' => $inv_head $inv_head->getData() : '',
  700.                 'so_data' => $so_data,
  701.                 'queryDate' => $date,
  702.                 'so_item_data' => $so_item_data,
  703.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  704.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  705.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  706.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  707.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  708.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  709.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  710. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  711.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  712.             )
  713.         );
  714.     }
  715.     public function DeliveryPendingOrderListAction(Request $request)
  716.     {
  717.         $em $this->getDoctrine()->getManager();
  718.         $session $request->getSession();
  719.         $userType $session->get(UserConstants::USER_TYPE);
  720.         $userId $session->get(UserConstants::USER_ID);
  721.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  722.             'approved' => GeneralConstant::APPROVED,
  723.             'stage' => GeneralConstant::STAGE_PENDING
  724.         );
  725.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  726.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  727.         }
  728. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  729. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  730. //            $selectiveDocumentsFlag=1; //by default will show only selective
  731. //            if(isset($userRestrictions['canSeeAllSo'])) {
  732. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  733. //                    $selectiveDocumentsFlag = 0;
  734. //                }
  735. //            }
  736. //
  737. //            if($selectiveDocumentsFlag==1)
  738. //            {
  739. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  740. //            }
  741. //        }
  742.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  743.             'name' => 'warehouse_action_1'//for now for stock of goods
  744.         ));
  745.         if ($request->query->has('queryDate')) {
  746.             $date = new \DateTime($request->query->get('queryDate'));
  747.         } else {
  748.             $today = new \DateTime();
  749.             $todayStr $today->format('Y-m-d');
  750.             $date = new \DateTime($todayStr);
  751.         }
  752. //        $orderQryArray['salesOrderDate'] = $date;
  753.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrder')->findBy($orderQryArray);
  754.         $so_ids = [];
  755.         $so_data = [];
  756.         $so_item_ids = [];
  757.         $so_item_data = [];
  758.         foreach ($salesOrders as $salesOrder) {
  759.             if ($salesOrder->getSalesOrderDate() > $date)
  760.                 continue;
  761.             $so_ids[] = $salesOrder->getSalesOrderId();
  762.             $so_data[$salesOrder->getSalesOrderId()] = array(
  763.                 "id" => $salesOrder->getSalesOrderId(),
  764.                 "documentHash" => $salesOrder->getDocumentHash(),
  765.                 "clientId" => $salesOrder->getClientId(),
  766.             );
  767.         }
  768.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrderItem')->findBy(array(
  769.             'salesOrderId' => $so_ids,
  770.         ));
  771.         foreach ($salesOrderItems as $salesOrderItem) {
  772.             $so_item_ids[] = $salesOrderItem->getId();
  773.             $so_item_data[$salesOrderItem->getId()] = array(
  774.                 "id" => $salesOrderItem->getId(),
  775.                 "productId" => $salesOrderItem->getProductId(),
  776.                 "productName" => $salesOrderItem->getProductNameFdm(),
  777.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  778.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  779.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  780. //                "documentHash"=>$salesOrder->getDocumentHash(),
  781.                 "qty" => $salesOrderItem->getQty(),
  782.                 "transitQty" => $salesOrderItem->getTransitQty(),
  783.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  784.             );
  785.         }
  786.         return $this->render('@Inventory/pages/views/delivery_pending_order_list.html.twig',
  787.             array(
  788.                 'page_title' => 'Pending Delivery',
  789.                 'inv_head' => $inv_head $inv_head->getData() : '',
  790.                 'so_data' => $so_data,
  791.                 'queryDate' => $date,
  792.                 'so_item_data' => $so_item_data,
  793.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  794.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  795.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  796.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  797.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  798.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  799.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  800. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  801.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  802.             )
  803.         );
  804.     }
  805.     public function ItemGroupAction(Request $request$id 0)
  806.     {
  807.         $ex_id 0;
  808.         $det = [];
  809.         $em $this->getDoctrine()->getManager();
  810.         $companyId $this->getLoggedUserCompanyId($request);
  811.         $group_type 1;//item
  812.         $route $request->get('_route');
  813.         if ($route == 'service_group')
  814.             $group_type 2;//service
  815.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  816.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  817.         if ($request->isMethod('POST')) {
  818.             Inventory::CreateItemGroup($this->getDoctrine()->getManager(),
  819.                 $request->request->get('ex_id'),
  820.                 $this->getLoggedUserCompanyId($request),
  821.                 $request->request,
  822.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  823.         }
  824.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  825.             'name' => 'warehouse_action_1'//for now for stock of goods
  826.         ));
  827.         if ($id != 0) {
  828.             $ex_id $id;
  829.             $det $this->getDoctrine()->getRepository('ApplicationBundle:InvItemGroup')->findOneBy(array(
  830.                 'id' => $id//for now for stock of goods
  831. //                    'opening_locked'=>0
  832.             ));
  833.         }
  834.         return $this->render('@Inventory/pages/input_forms/item_group.html.twig',
  835.             array(
  836.                 'page_title' => $group_type == "Item Groups" "Service Groups",
  837.                 'inv_head' => $inv_head $inv_head->getData() : '',
  838.                 'group_type' => $group_type,
  839.                 'igList' => Inventory::ItemGroupList($em$companyId$group_type),
  840.                 'warehouse_action_list' => $warehouse_action_list,
  841. //                'data'=>Inventory::ItemGroupFormRelatedData($this->getDoctrine()->getManager()),
  842.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  843.                 'ex_id' => $ex_id,
  844.                 'ex_det' => $det
  845.             )
  846.         );
  847.     }
  848.     public function addStartingOpeningInOutAction(Request $request$refreshed_opening 0)
  849.     {
  850.         //be very careful!!
  851.         $em $this->getDoctrine()->getManager();
  852. //        $last_refresh_date="";
  853.         //steps
  854.         //1. set all inventory to their opening position
  855.         $assign_list = array();
  856.         $data = array();
  857.         if ($refreshed_opening == 0) {
  858.             $new_cc $em
  859.                 ->getRepository('ApplicationBundle:AccSettings')
  860.                 ->findOneBy(
  861.                     array(
  862.                         'name' => 'accounting_year_start',
  863.                     )
  864.                 );
  865.             $date_start = new \DateTime($new_cc->getData());
  866.             $date_start_str $date_start->format('Y-m-d');
  867.             $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  868. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  869.             $stmt $em->getConnection()->prepare($closingQuery);
  870.             $stmt->execute();
  871.             $iniClosing $stmt->fetchAll();
  872. //                $stmt = $em->getConnection()->prepare($transQuery);
  873. //                $stmt->execute();
  874. //                $iniTrans = $stmt->fetchAll();
  875.             $singleClosing_byProductId = array();
  876.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  877.             foreach ($iniClosing as $item) {
  878.                 if (!isset($singleClosing_byProductId[$item['product_id']])) {
  879.                     $singleClosing_byProductId[$item['product_id']] = array(
  880.                         'date' => $item['date'],
  881.                         'qtyAdd' => $item['qty_addition'],
  882.                         'qtySub' => '0',
  883.                         'valueAdd' => $item['addition'],
  884.                         'valueSub' => '0',
  885.                         'fromWarehouse' => 0,
  886.                         'toWarehouse' => $item['warehouse_id'],
  887.                         'fromWarehouseSub' => 0,
  888.                         'toWarehouseSub' => $item['action_tag_id'],
  889.                         'price' => ($item['addition'] / $item['qty_addition'])
  890.                     );
  891.                 }
  892.             }
  893.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  894. //                foreach ($iniTrans as $item) {
  895. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  896. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  897. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  898. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  899. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  900. //                    }
  901. //                }
  902.             foreach ($singleClosing_byProductId as $key => $item) {
  903.                 if (!isset($data[$key])) {
  904.                     $data[$key][] = $item;
  905.                 }
  906.             }
  907.             //now that we go the data we can empty the closing table
  908. //                $get_kids_sql ='UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  909. //    truncate `inv_closing_balance`;
  910. //    truncate `inventory_storage`;
  911. //    truncate `inv_item_transaction`;';
  912. //                $stmt = $em->getConnection()->prepare($get_kids_sql);
  913. //                $stmt->execute();
  914. //                $stmt->closeCursor();
  915. //                $stmt->fetchAll();
  916.             $total_inv_value_in 0;
  917.             foreach ($data as $key => $item) {
  918.                 if (!empty($item)) {
  919.                     foreach ($item as $entry) {
  920.                         $transDate = new \DateTime($entry['date']);
  921.                         $new = new InvItemInOut();
  922.                         $new->setProductId($key);
  923.                         $new->setWarehouseId($entry['toWarehouse']);
  924.                         $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  925.                         $new->setActionTagId($entry['toWarehouseSub']);
  926.                         $new->setTransactionDate($transDate);
  927.                         $new->setQty($entry['qtyAdd']);
  928.                         $new->setPrice($entry['price']);
  929.                         $new->setAmount($entry['qtyAdd'] * $entry['price']);
  930.                         $new->setEntity(0);// opening =0
  931.                         $new->setEntityId(0);// opening =0
  932.                         $new->setDebitCreditHeadId(0);// opening =0
  933.                         $new->setVoucherIds(null);// opening =0
  934.                         $em->persist($new);
  935.                         $em->flush();
  936.                         $total_inv_value_in += $entry['qtyAdd'] * $entry['price'];
  937.                     }
  938.                 }
  939.             }
  940.             $refreshed_opening 1;
  941. //                $terminate=1;
  942. //                $last_refresh_date=$last_refresh_date_obj->format('Y-m-d');
  943.             return new JsonResponse(array(
  944.                 "success" => true,
  945.             ));
  946.             //now call the function which will add the 1st ever entry or opening entry
  947.         }
  948.         //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  949.         return new JsonResponse(array(
  950.             "success" => false,
  951.         ));
  952.     }
  953.     public function RefreshInventoryAction(Request $request$refreshed_opening 0)
  954.     {
  955.         //be very careful!!
  956.         $em $this->getDoctrine()->getManager();
  957.         $refreshed_opening 0;
  958.         $last_refresh_date "";
  959.         $last_refresh_date_obj "";
  960.         $terminate 0;
  961.         $companyId $this->getLoggedUserCompanyId($request);
  962.         $modifyAccTransaction $request->request->has('modify_acc_trans_flag') ? $request->request->get('modify_acc_trans_flag') : 0;
  963.         $modifyProductionPrice $request->request->has('modify_production_price') ? $request->request->get('modify_production_price') : 0;
  964. //        $last_refresh_date="";
  965.         if ($request->isMethod('POST')) {
  966.             //steps
  967.             //1. set all inventory to their opening position
  968.             $assign_list = array();
  969.             $data = array();
  970.             if ($request->request->has('inventory_refreshed'))
  971.                 $refreshed_opening $request->request->get('inventory_refreshed');
  972.             if ($request->request->has('last_refresh_date'))
  973.                 $last_refresh_date $request->request->get('last_refresh_date');
  974.             if ($refreshed_opening == 0) {
  975. //                System::log_it($this->container->getParameter('kernel.root_dir'), "",
  976. //                    'inventory_refresh_debug', 0); //last er 1 is append
  977.                 $new_cc $em
  978.                     ->getRepository('ApplicationBundle:AccSettings')
  979.                     ->findOneBy(
  980.                         array(
  981.                             'name' => 'accounting_year_start',
  982.                         )
  983.                     );
  984.                 $date_start = new \DateTime($new_cc->getData());
  985.                 $date_start_str $date_start->format('Y-m-d');
  986.                 $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  987. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  988.                 $stmt $em->getConnection()->prepare($closingQuery);
  989.                 $stmt->execute();
  990.                 $iniClosing $stmt->fetchAll();
  991. //                $stmt = $em->getConnection()->prepare($transQuery);
  992. //                $stmt->execute();
  993. //                $iniTrans = $stmt->fetchAll();
  994.                 $singleClosing_byProductId = array();
  995.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  996.                 foreach ($iniClosing as $item) {
  997.                     if (!isset($singleClosing_byProductId[$item['product_id']])) {
  998.                         $singleClosing_byProductId[$item['product_id']] = array(
  999.                             'date' => $item['date'],
  1000.                             'qtyAdd' => $item['qty_addition'],
  1001.                             'qtySub' => '0',
  1002.                             'valueAdd' => $item['addition'],
  1003.                             'valueSub' => '0',
  1004.                             'fromWarehouse' => 0,
  1005.                             'toWarehouse' => $item['warehouse_id'],
  1006.                             'fromWarehouseSub' => 0,
  1007.                             'toWarehouseSub' => $item['action_tag_id'],
  1008.                             'price' => $item['qty_addition'] != ? ($item['addition'] / $item['qty_addition']) : $item['addition']
  1009.                         );
  1010.                     }
  1011.                 }
  1012.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1013. //                foreach ($iniTrans as $item) {
  1014. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  1015. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  1016. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  1017. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  1018. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  1019. //                    }
  1020. //                }
  1021.                 foreach ($singleClosing_byProductId as $key => $item) {
  1022.                     if (!isset($data[$key])) {
  1023.                         $data[$key][] = $item;
  1024.                     }
  1025.                 }
  1026.                 //new one
  1027.                 //chekc if ultra opening stock received note exists if not create it
  1028.                 $mo $em
  1029.                     ->getRepository('ApplicationBundle:StockReceivedNote')
  1030.                     ->findOneBy(
  1031.                         array(
  1032.                             'documentHash' => '_MASTER_OPENING_',
  1033.                             'typeHash' => 'SR',
  1034.                             'prefixHash' => 4,
  1035.                             'assocHash' => '_MASTER_OPENING_',
  1036.                             'numberHash' => 1,
  1037.                         )
  1038.                     );
  1039.                 if (!$mo) {
  1040.                     //doensot exist to add :)
  1041. //                    $products = $post_data->get('products');
  1042. //                    $qty = $post_data->get('qty');
  1043. //                    $note = $post_data->get('note');
  1044.                     $new = new StockReceivedNote();
  1045.                     $new->setStockReceivedNoteDate(new \DateTime($date_start_str));
  1046.                     $new->setCompanyId($companyId);
  1047.                     $new->setDocumentHash('_MASTER_OPENING_');
  1048.                     $new->setTypeHash('SR');
  1049.                     $new->setPrefixHash(4);
  1050.                     $new->setAssocHash('_MASTER_OPENING_');
  1051.                     $new->setNumberHash(1);
  1052.                     $new->setCreditHeadId(0);
  1053.                     $new->setStockTransferId(0);
  1054.                     $new->setSalesOrderId(0);
  1055.                     $new->setType(4);
  1056.                     $new->setStatus(GeneralConstant::ACTIVE);
  1057.                     $new->setWarehouseId(0);
  1058.                     $new->setNote('');
  1059.                     $new->setAutoCreated(1);
  1060.                     $new->setApproved(GeneralConstant::APPROVED);
  1061. //        $new->setIndentTagged(0);
  1062.                     $new->setStage(GeneralConstant::STAGE_COMPLETE);
  1063.                     $new->setCreatedLoginId(0);
  1064.                     $new->setEditedLoginId(0);
  1065.                     $em->persist($new);
  1066.                     $em->flush();
  1067.                     $SRID $new->getStockReceivedNoteId();
  1068.                     $last_refresh_date_obj $new->getStockReceivedNoteDate();
  1069.                     //now add items to details
  1070.                     foreach ($data as $key => $item) {
  1071.                         if (!empty($item)) {
  1072.                             foreach ($item as $entry) {
  1073.                                 $transDate = new \DateTime($entry['date']);
  1074.                                 if ($last_refresh_date_obj == '') {
  1075.                                     $last_refresh_date_obj $transDate;
  1076.                                 } else if ($transDate $last_refresh_date_obj) {
  1077.                                     $last_refresh_date_obj $transDate;
  1078.                                 }
  1079.                                 $new = new StockReceivedNoteItem();
  1080.                                 $new->setStockReceivedNoteId($SRID);
  1081.                                 $new->setStockTransferItemId(0);
  1082.                                 $salesCodeRange = [];
  1083.                                 $salesCodeRangeStr '';
  1084.                                 $new->setSalesCodeRange("[" $salesCodeRangeStr "]");
  1085.                                 $new->setQty($entry['qtyAdd']);
  1086.                                 $new->setPrice($entry['price']);
  1087.                                 $new->setBalance($entry['qtyAdd']);
  1088.                                 $new->setProductId($key);
  1089.                                 $new->setWarrantyMon(0);
  1090.                                 $new->setWarehouseId($entry['toWarehouse']);
  1091.                                 $new->setWarehouseActionId($entry['toWarehouseSub']);
  1092.                                 $em->persist($new);
  1093.                                 $em->flush();
  1094.                             }
  1095.                         }
  1096.                     }
  1097. //                    for ($i = 0; $i < count($products); $i++) {
  1098. //
  1099. //
  1100. //                        $srItem = self::CreateNewStockReceivedNoteItem($em, $post_data, $i, $new->getStockReceivedNoteId(), $LoginID);
  1101. //                    }
  1102.                 }
  1103.                 if ($mo)
  1104.                     $last_refresh_date_obj $mo->getStockReceivedNoteDate();
  1105.                 $last_refresh_date_obj->modify('-1 day');///new so that it willstart form this day on next call
  1106.                 //new ends
  1107.                 //now that we go the data we can empty the closing table
  1108.                 $get_kids_sql "UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  1109. UPDATE `purchase_order` SET expense_amount=0, expense_pending_balance_amount=0, grn_tag_pending_expense_invoice_ids='[]' WHERE 1;
  1110.     truncate `inv_closing_balance`;
  1111.     truncate `inventory_storage`;
  1112.     truncate `inv_item_transaction`;";
  1113.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  1114.                 $stmt->execute();
  1115.                 $stmt->closeCursor();
  1116. //                $stmt->fetchAll();
  1117. //                foreach ($data as $key => $item) {
  1118. //                    if (!empty($item)) {
  1119. //                        foreach ($item as $entry) {
  1120. //                            $transDate = new \DateTime($entry['date']);
  1121. //                            Inventory::addItemToInventoryCompact($em,
  1122. //                                $key,
  1123. //                                $entry['fromWarehouse'],
  1124. //                                $entry['toWarehouse'],
  1125. //                                $entry['fromWarehouseSub'],
  1126. //                                $entry['toWarehouseSub'],
  1127. //                                $transDate,
  1128. //                                $entry['qtyAdd'],
  1129. //                                $entry['qtySub'],
  1130. //                                $entry['valueAdd'],
  1131. //                                $entry['valueSub'],
  1132. //                                $entry['price'],
  1133. //                                $this->getLoggedUserCompanyId($request));
  1134. //                            if ($last_refresh_date_obj == '') {
  1135. //                                $last_refresh_date_obj = $transDate;
  1136. //                            } else if ($transDate < $last_refresh_date_obj) {
  1137. //                                $last_refresh_date_obj = $transDate;
  1138. //                            }
  1139. //                        }
  1140. //                    }
  1141. //                }
  1142.                 $refreshed_opening 1;
  1143. //                $terminate=1;
  1144.                 if ($last_refresh_date_obj == "") {
  1145.                     $last_refresh_date $date_start_str;
  1146.                 } else {
  1147.                     $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1148.                 }
  1149.                 return new JsonResponse(array(
  1150.                     "success" => true,
  1151.                     "last_refresh_date" => $last_refresh_date,
  1152.                     "inventory_refreshed" => $refreshed_opening
  1153.                 ));
  1154.                 //now call the function which will add the 1st ever entry or opening entry
  1155.             }
  1156.             //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  1157.             if ($last_refresh_date != '')
  1158.                 $last_refresh_date_obj = new \DateTime($last_refresh_date);
  1159.             else {
  1160.                 $new_cc $em
  1161.                     ->getRepository('ApplicationBundle:AccSettings')
  1162.                     ->findOneBy(
  1163.                         array(
  1164.                             'name' => 'accounting_year_start',
  1165.                         )
  1166.                     );
  1167.                 $last_refresh_date_obj = new \DateTime($new_cc->getData());
  1168.                 $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1169.             }
  1170.             $last_refresh_date_obj->modify('+1 day');
  1171.             $today = new \DateTime();
  1172.             if ($last_refresh_date_obj $today) {
  1173.                 $terminate 1;
  1174.             }
  1175.             $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1176.             //ok now we got the date so get grn item on this date
  1177.             //GRN
  1178.             $query "SELECT grn_item.*, grn.grn_date, grn.document_hash from  grn_item
  1179.               join grn on grn.grn_id=grn_item.grn_id
  1180.             where grn.grn_date ='" $last_refresh_date " 00:00:00' and grn.approved=1";
  1181.             $stmt $em->getConnection()->prepare($query);
  1182.             $stmt->execute();
  1183.             $queryData $stmt->fetchAll();
  1184.             $grn_ids = [];
  1185.             foreach ($queryData as $item) {
  1186.                 $data[$item['product_id']][] = array(
  1187.                     'date' => $last_refresh_date,
  1188.                     'entity' => array_flip(GeneralConstant::$Entity_list)['Grn'],
  1189.                     'entityId' => $item['grn_id'],
  1190.                     'colorId' => $item['color_id'],
  1191.                     'sizeId' => $item['size_id'],
  1192.                     'entityDocHash' => $item['document_hash'],
  1193.                     'qtyAdd' => $item['qty'],
  1194.                     'qtySub' => 0,
  1195.                     'valueAdd' => ($item['qty'] * $item['price_with_expense']),
  1196.                     'valueSub' => 0,
  1197.                     'price' => $item['price_with_expense'],
  1198.                     'fromWarehouse' => 0,
  1199.                     'toWarehouse' => $item['warehouse_id'],
  1200.                     'fromWarehouseSub' => 0,
  1201. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1202.                     'toWarehouseSub' => $item['warehouse_action_id']
  1203.                 );
  1204.                 if (!in_array($item['grn_id'], $grn_ids))
  1205.                     $grn_ids[] = $item['grn_id'];
  1206.             }
  1207.             //now add grns
  1208.             foreach ($data as $key => $item) {
  1209.                 if (!empty($item)) {
  1210.                     foreach ($item as $entry) {
  1211.                         $transDate = new \DateTime($entry['date']);
  1212.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1213.                             $key,
  1214.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1215.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1216.                             $entry['fromWarehouse'],
  1217.                             $entry['toWarehouse'],
  1218.                             $entry['fromWarehouseSub'],
  1219.                             $entry['toWarehouseSub'],
  1220.                             $transDate,
  1221.                             $entry['qtyAdd'],
  1222.                             $entry['qtySub'],
  1223.                             $entry['valueAdd'],
  1224.                             $entry['valueSub'],
  1225.                             $entry['price'],
  1226.                             $this->getLoggedUserCompanyId($request),
  1227.                             0,
  1228.                             $entry['entity'],
  1229.                             $entry['entityId'],
  1230.                             $entry['entityDocHash'],
  1231.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_SUPPLER
  1232.                         );
  1233.                         if ($last_refresh_date_obj == '') {
  1234.                             $last_refresh_date_obj $transDate;
  1235.                         } else if ($transDate $last_refresh_date_obj) {
  1236.                             $last_refresh_date_obj $transDate;
  1237.                         }
  1238.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1239.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1240.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1241.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1242.                             "",
  1243.                             'inventory_refresh_debug'1); //last er 1 is append
  1244.                     }
  1245.                 }
  1246.             }
  1247.             ///adding grn vouhcer mod here too incase it wasnot in the distributed IG for heads
  1248. //            $grn=$em->getRepository('ApplicationBundle:Grn')->findBy(array(
  1249. //                'grnId'=>$grn_ids,
  1250. //                'modifyVoucherFlag'=>1 //have to add this flag
  1251. //            ));
  1252.             foreach ($grn_ids as $grn_id) {
  1253.                 if ($modifyAccTransaction == 1)
  1254.                     Inventory::ModifyGrnTransactions($em$grn_id1);
  1255.                 else
  1256.                     Inventory::ModifyGrnTransactions($em$grn_id);
  1257.             }
  1258.             //adding voucher ends
  1259.             $inv_head_list_by_wa = [];
  1260.             $inv_head_list = [];
  1261.             $cogs_head 0;
  1262.             $cogs_head 0;
  1263.             $internal_proj 0;
  1264. //            if ($project) {
  1265. //                if ($project->getProjectType() == 2) {
  1266. //                    $cogs_head = $project->getInternalProjectAssetHeadId();
  1267. //                    $internal_proj = 1;
  1268. //                } else {
  1269. //                    $cogs_head_qry = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1270. //                        'name' => 'cogs'
  1271. //                    ));
  1272. //                    $cogs_head = $cogs_head_qry->getData();
  1273. //                }
  1274. //            } else {
  1275.             $cogs_head_qry $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1276.                 'name' => 'cogs'
  1277.             ));
  1278.             $cogs_head $cogs_head_qry->getData();
  1279. //            }
  1280.             $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');
  1281.             foreach ($warehouse_action_list as $wa) {
  1282.                 $inv_head_data $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1283.                         'name' => 'warehouse_action_' $wa['id'])
  1284.                 );
  1285.                 if ($inv_head_data) {
  1286.                     $inv_head_list_by_wa[$wa['id']] = $inv_head_data->getData();
  1287.                     $inv_head_list[] = $inv_head_data->getData();
  1288.                 }
  1289.             }
  1290.             $data = [];
  1291.             //____________STOCK_RECEIVED___________________
  1292.             $docEntity "StockReceivedNote";
  1293.             $docEntityIdField "stockReceivedNoteId";
  1294.             $accTransactionDataByDocId = [];
  1295.             $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
  1296.               join stock_received_note on stock_received_note.stock_received_note_id=stock_received_note_item.stock_received_note_id
  1297.             where stock_received_note.stock_received_note_date ='" $last_refresh_date " 00:00:00' and stock_received_note.approved=1";
  1298.             $stmt $em->getConnection()->prepare($query);
  1299.             $stmt->execute();
  1300.             $queryData $stmt->fetchAll();
  1301.             $grn_ids = [];
  1302.             foreach ($queryData as $item) {
  1303.                 $data[$item['product_id']][] = array(
  1304.                     'date' => $last_refresh_date,
  1305.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  1306.                     'entityId' => $item['stock_received_note_id'],
  1307.                     'colorId' => $item['color_id'],
  1308.                     'sizeId' => $item['size_id'],
  1309.                     'type' => $item['type'],
  1310.                     'entityDocHash' => $item['document_hash'],
  1311.                     'qtyAdd' => $item['qty'],
  1312.                     'qtySub' => 0,
  1313.                     'valueAdd' => ($item['qty'] * $item['price']),
  1314.                     'valueSub' => 0,
  1315.                     'price' => $item['price'],
  1316.                     'fromWarehouse' => 0,
  1317.                     'toWarehouse' => $item['warehouse_id'],
  1318.                     'fromWarehouseSub' => 0,
  1319. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1320.                     'toWarehouseSub' => $item['warehouse_action_id']
  1321.                 );
  1322. //                if (!in_array($item['grn_id'], $grn_ids))
  1323. //                    $grn_ids[] = $item['grn_id'];
  1324.             }
  1325.             foreach ($data as $key => $item) {
  1326.                 if (!empty($item)) {
  1327.                     foreach ($item as $entry) {
  1328.                         $transDate = new \DateTime($entry['date']);
  1329.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1330.                             $key,
  1331.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1332.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1333.                             $entry['fromWarehouse'],
  1334.                             $entry['toWarehouse'],
  1335.                             $entry['fromWarehouseSub'],
  1336.                             $entry['toWarehouseSub'],
  1337.                             $transDate,
  1338.                             $entry['qtyAdd'],
  1339.                             $entry['qtySub'],
  1340.                             $entry['valueAdd'],
  1341.                             $entry['valueSub'],
  1342.                             $entry['price'],
  1343.                             $this->getLoggedUserCompanyId($request),
  1344.                             0,
  1345.                             $entry['entity'],
  1346.                             $entry['entityId'],
  1347.                             $entry['entityDocHash'],
  1348.                             $entry['type'] == ?
  1349.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_OPENING :
  1350.                                 ($entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_STOCK_IN :
  1351.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT)
  1352.                         );
  1353.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1354.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1355.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1356.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1357.                             "",
  1358.                             'inventory_refresh_debug'1); //last er 1 is append
  1359.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1360.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1361.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  1362.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  1363.                         else
  1364.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  1365.                         if ($last_refresh_date_obj == '') {
  1366.                             $last_refresh_date_obj $transDate;
  1367.                         } else if ($transDate $last_refresh_date_obj) {
  1368.                             $last_refresh_date_obj $transDate;
  1369.                         }
  1370.                     }
  1371.                 }
  1372.             }
  1373.             if ($modifyAccTransaction == 1) {
  1374.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1375.                     $docHere $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  1376.                         $docEntityIdField => $docId,
  1377.                     ));;
  1378.                     if ($docHere) {
  1379.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1380.                         if ($curr_v_ids == null)
  1381.                             $curr_v_ids = [];
  1382.                         $skipVids = [];
  1383.                         $toChangeVid 0;
  1384.                         $voucher null;
  1385.                         foreach ($curr_v_ids as $vid) {
  1386.                             if (in_array($vid$skipVids))
  1387.                                 continue;
  1388.                             $skipVids[] = $vid//to prevent duplicate query
  1389.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1390.                                 'transactionId' => $vid,
  1391.                             ));;
  1392.                             if ($voucher) {
  1393.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1394.                                     $toChangeVid $vid;
  1395.                                 } else {
  1396.                                     continue;
  1397.                                 }
  1398.                             }
  1399.                         }
  1400.                         if ($toChangeVid == 0) {
  1401.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1402.                                 $em,
  1403.                                 $docHere->getStockReceivedNoteDate()->format('Y-m-d'),
  1404.                                 0,
  1405.                                 AccountsConstant::VOUCHER_JOURNAL,
  1406.                                 'Journal For Stock Received Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  1407.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1408.                                 'JV',
  1409.                                 'GN',
  1410.                                 0,
  1411.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1412.                                 0,
  1413.                                 $docHere->getCreatedLoginId(),
  1414.                                 $docHere->getCompanyId(),
  1415.                                 '',
  1416.                                 0,
  1417.                                 1
  1418.                             );
  1419.                             $em->flush();
  1420.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1421.                                 'transactionId' => $toChangeVid,
  1422.                             ));;
  1423.                         }
  1424.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  1425.                         $tot_inv_amount 0;
  1426.                         foreach ($transData as $k => $v) {
  1427.                             $tot_inv_amount += ($v);
  1428.                             Accounts::CreateNewTransactionDetails($em,
  1429.                                 '',
  1430.                                 $toChangeVid,
  1431.                                 Generic::CurrToInt($v),
  1432.                                 $k,
  1433.                                 'Inventory Inward For - ' $docHere->getDocumentHash(),
  1434.                                 AccountsConstant::DEBIT,
  1435.                                 0,
  1436.                                 [],
  1437.                                 [],
  1438.                                 $docHere->getCreatedLoginId()
  1439.                             );
  1440.                         }
  1441.                         $stockReceivedType $docHere->getType();
  1442.                         $to_balance_head 0;
  1443.                         if (in_array($stockReceivedType, [23]))
  1444.                             $to_balance_head $docHere->getCreditHeadId();
  1445.                         else {
  1446.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1447.                                     'name' => 'inv_on_transit_head')
  1448.                             );
  1449.                             if ($inv_transit_head)
  1450.                                 $to_balance_head $inv_transit_head->getData();
  1451.                         }
  1452.                         Accounts::CreateNewTransactionDetails($em,
  1453.                             '',
  1454.                             $toChangeVid,
  1455.                             Generic::CurrToInt($tot_inv_amount),
  1456.                             $to_balance_head,
  1457.                             in_array($stockReceivedType, [23]) ? 'Balancing of Stock in Items for -' $docHere->getDocumentHash() : 'In Transit Items for -' $docHere->getDocumentHash(),
  1458.                             AccountsConstant::CREDIT,
  1459.                             0,
  1460.                             [],
  1461.                             [],
  1462.                             $docHere->getCreatedLoginId()
  1463.                         );
  1464.                         if ($voucher)
  1465.                             $voucher->setTransactionAmount($tot_inv_amount);
  1466.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1467.                         if ($curr_v_ids != null)
  1468.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1469.                         else
  1470.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1471.                         $em->flush();
  1472. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  1473.                     }
  1474.                 }
  1475.             }
  1476.             $data = [];
  1477.             $query "SELECT purchase_invoice.* from  purchase_invoice
  1478. where purchase_invoice.purchase_invoice_date ='" $last_refresh_date " 00:00:00' and purchase_invoice.approved=1
  1479.             ";
  1480.             $stmt $em->getConnection()->prepare($query);
  1481.             $stmt->execute();
  1482.             $queryData $stmt->fetchAll();
  1483.             foreach ($queryData as $pi) {
  1484.                 $transDate = new \DateTime($pi['purchase_invoice_date']);
  1485.                 if ($last_refresh_date_obj == '') {
  1486.                     $last_refresh_date_obj $transDate;
  1487.                 } else if ($transDate $last_refresh_date_obj) {
  1488.                     $last_refresh_date_obj $transDate;
  1489.                 }
  1490.                 Accounts::CalibrateProductPriceWithPi($em$pi['purchase_invoice_id'], 1);
  1491.             }
  1492.             $data = [];
  1493.             $query "SELECT expense_invoice.* from  expense_invoice
  1494. where expense_invoice.expense_invoice_date ='" $last_refresh_date " 00:00:00' and expense_invoice.approved=1 and
  1495.             expense_invoice_type_id=1";
  1496.             $stmt $em->getConnection()->prepare($query);
  1497.             $stmt->execute();
  1498.             $queryData $stmt->fetchAll();
  1499.             foreach ($queryData as $ei) {
  1500.                 $transDate = new \DateTime($ei['expense_invoice_date']);
  1501.                 if ($last_refresh_date_obj == '') {
  1502.                     $last_refresh_date_obj $transDate;
  1503.                 } else if ($transDate $last_refresh_date_obj) {
  1504.                     $last_refresh_date_obj $transDate;
  1505.                 }
  1506.                 $grn_ids json_decode($ei['grn_id_list'], true);
  1507.                 if ($grn_ids == null)
  1508.                     $grn_ids = [];
  1509. //                if (!empty($grn_ids)) {
  1510. //
  1511. //
  1512. //                        if ($ei->getExpenseInvocationStrategyOnGrn() != 2) {
  1513. //                            $grn = $em->getRepository('ApplicationBundle:Grn')->findBy(array(
  1514. //                                'purchaseOrderId' => $ei->getPurchaseOrderId()
  1515. //                            ));
  1516. //
  1517. //                        }
  1518. //                        else
  1519. //                        {
  1520. //                            $po = $em->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(array(
  1521. //                                'purchaseOrderId' => $ei['purchase_order_id']
  1522. //                            ));
  1523. //
  1524. //                            if ($po) {
  1525. //                                $po->setExpenseAmount($po->getExpenseAmount() + $ei['invoice_amount']);
  1526. //                            }
  1527. //                            continue; //grn expense will be there anyway
  1528. //                        }
  1529. //
  1530. //
  1531. //
  1532. //                }
  1533.                 Accounts::CalibrateProductPriceWithExpense($em$ei['expense_invoice_id']);
  1534. //                $po = $em->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(array(
  1535. //                    'purchaseOrderId' => $ei['purchase_order_id']
  1536. //                ));
  1537. //
  1538. //
  1539. //                //first get the total valuation
  1540. //                if ($po) {
  1541. //                    $total_product_value = 0;
  1542. //                    $total_pending_expense = 0;
  1543. //                    $po_item_data = $em->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(array(
  1544. ////                'productId' => $item->getProductId(),
  1545. //                        'purchaseOrderId' => $ei['purchase_order_id']
  1546. //                    ));
  1547. //
  1548. //
  1549. //                    foreach ($po_item_data as $it) {
  1550. ////                    $product = $em->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
  1551. ////                        'id' => $item->getProductId()
  1552. ////                    ));
  1553. //
  1554. //                        $poqty = $it->getReceived();
  1555. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);
  1556. //                        $total_product_value += (1 * $po_price);
  1557. //
  1558. //
  1559. //                    }
  1560. //
  1561. //
  1562. //                    //now we know the total grn price value. lets get the fraction increase
  1563. //                    $total_pending_expense = $ei['invoice_amount'];
  1564. //                    if ($total_product_value != 0)
  1565. //                        $fraction_increase = ($total_pending_expense) / ($total_product_value);
  1566. //                    else
  1567. //                        $fraction_increase = 0;
  1568. //
  1569. //                    foreach ($po_item_data as $it) {
  1570. //                        $item = $it;
  1571. //                        $product = $em->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
  1572. //                            'id' => $it->getProductId()
  1573. //                        ));
  1574. //                        if (!$product)
  1575. //                            continue;
  1576. //
  1577. ////                    $items_in_inventory=$em->getRepository('ApplicationBundle:InventoryStorage')->findBy(array(
  1578. ////                        'productId'=>$item->getProductId()
  1579. ////                    ));
  1580. //
  1581. //                        $poqty = $it->getReceived();
  1582. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);;
  1583. //
  1584. //                        $existing_qty = $product->getQty();;
  1585. //
  1586. //
  1587. //                        $increased_po_price = ($po_price * $fraction_increase);
  1588. //
  1589. //                        //now lets see homuch is the total price
  1590. //                        $new_purchase_price = $product->getPurchasePrice();
  1591. //
  1592. //                        if ($increased_po_price != 0) {
  1593. //                            $last_grn_item = $em->getRepository('ApplicationBundle:GrnItem')->findOneBy(array(
  1594. //                                'purchaseOrderItemId' => $item->getId()
  1595. //                            ));
  1596. //                            if ($last_grn_item) {
  1597. //
  1598. //                                $data[$last_grn_item->getProductId()][] = array(
  1599. //                                    'date' => $last_refresh_date,
  1600. //
  1601. //                                    'entity' => array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  1602. //                                    'entityId' => $ei['expense_invoice_id'],
  1603. //                                    'colorId' => $last_grn_item->getColorId(),
  1604. //                                    'sizeId' => $last_grn_item->getSizeId(),
  1605. //                                    'entityDocHash' => $ei['document_hash'],
  1606. //                                    'qtyAdd' => 0,
  1607. //                                    'qtySub' => 0,
  1608. //                                    'valueAdd' => $increased_po_price,
  1609. ////                                    'valueAdd' => $increased_po_price>=0?$increased_po_price:0,
  1610. ////                    'valueSub' => ($item['qty'] * $item['price']),
  1611. ////                                    'valueSub' => $increased_po_price<0?((-1)*$increased_po_price):0,
  1612. //                                    'valueSub' => 0,
  1613. //                                    'price' => '_UNSET_',
  1614. //                                    'fromWarehouse' => 0,
  1615. //                                    'toWarehouse' => $last_grn_item->getWarehouseId(),
  1616. //                                    'fromWarehouseSub' => 0,
  1617. ////                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1618. //                                    'toWarehouseSub' => $last_grn_item->getWarehouseActionId()
  1619. //                                );
  1620. //
  1621. ////                                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);
  1622. ////
  1623. ////                                $total_item_price = $increased_po_price + ($product->getPurchasePrice() * ($existing_qty));
  1624. ////                                if ($existing_qty != 0)
  1625. ////                                    $new_purchase_price = $total_item_price / $existing_qty;
  1626. //
  1627. //
  1628. //                                $total_pending_expense -= $increased_po_price;
  1629. //                            }
  1630. //                        }
  1631. //                    }
  1632. //
  1633. //
  1634. //
  1635. //
  1636. //
  1637. //
  1638. //                } else {
  1639. //                    continue;
  1640. //                }
  1641.             }
  1642.             $data = [];
  1643.             //____________STOCK_TRANSFER___________________
  1644.             $docEntity "StockTransfer";
  1645.             $docEntityIdField "stockTransferId";
  1646.             $accTransactionDataByDocId = [];
  1647.             $query "SELECT stock_transfer_item.*,  stock_transfer.stock_transfer_date, stock_transfer.document_hash, stock_transfer.transfer_action_type from  stock_transfer_item
  1648.               join stock_transfer on stock_transfer.stock_transfer_id=stock_transfer_item.stock_transfer_id
  1649.             where stock_transfer.stock_transfer_date ='" $last_refresh_date " 00:00:00' and stock_transfer.approved=1";
  1650.             $stmt $em->getConnection()->prepare($query);
  1651.             $stmt->execute();
  1652.             $queryData $stmt->fetchAll();
  1653.             $grn_ids = [];
  1654.             foreach ($queryData as $item) {
  1655.                 $data[$item['product_id']][] = array(
  1656.                     'date' => $last_refresh_date,
  1657.                     'transfer_action_type' => $item['transfer_action_type'],
  1658.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  1659.                     'entityId' => $item['stock_transfer_id'],
  1660.                     'colorId' => $item['color_id'],
  1661.                     'sizeId' => $item['size_id'],
  1662.                     'entityDocHash' => $item['document_hash'],
  1663.                     'qtyAdd' => $item['transfer_action_type'] == $item['qty'] : 0,
  1664.                     'qtySub' => $item['qty'],
  1665.                     'valueAdd' => 0,
  1666. //                    'valueSub' => ($item['qty'] * $item['price']),
  1667.                     'valueSub' => '_AUTO_',
  1668.                     'price' => $item['price'],
  1669.                     'fromWarehouse' => $item['warehouse_id'],
  1670.                     'toWarehouse' => $item['transfer_action_type'] == $item['to_warehouse_id'] : 0,
  1671.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  1672. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1673.                     'toWarehouseSub' => $item['transfer_action_type'] == $item['to_warehouse_action_id'] : 0
  1674.                 );
  1675. //                if (!in_array($item['grn_id'], $grn_ids))
  1676. //                    $grn_ids[] = $item['grn_id'];
  1677.             }
  1678.             //now add grns
  1679.             foreach ($data as $key => $item) {
  1680.                 if (!empty($item)) {
  1681.                     foreach ($item as $entry) {
  1682.                         $transDate = new \DateTime($entry['date']);
  1683.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1684.                             $key,
  1685.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1686.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1687.                             $entry['fromWarehouse'],
  1688.                             $entry['toWarehouse'],
  1689.                             $entry['fromWarehouseSub'],
  1690.                             $entry['toWarehouseSub'],
  1691.                             $transDate,
  1692.                             $entry['qtyAdd'],
  1693.                             $entry['qtySub'],
  1694.                             $entry['valueAdd'],
  1695.                             $entry['valueSub'],
  1696.                             $entry['price'],
  1697.                             $this->getLoggedUserCompanyId($request),
  1698.                             0,
  1699.                             $entry['entity'],
  1700.                             $entry['entityId'],
  1701.                             $entry['entityDocHash'],
  1702.                             $entry['transfer_action_type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_INTER_WAREHOUSE GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT
  1703.                         );
  1704.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1705.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1706.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1707.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1708.                             "",
  1709.                             'inventory_refresh_debug'1); //last er 1 is append
  1710.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1711.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1712.                         if ($entry['transfer_action_type'] == 4) {
  1713.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  1714.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtySub'] * $modifiedData['slot_cost_price'];
  1715.                             else
  1716.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  1717.                         }
  1718.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  1719.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  1720.                         else
  1721.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  1722.                         if ($last_refresh_date_obj == '') {
  1723.                             $last_refresh_date_obj $transDate;
  1724.                         } else if ($transDate $last_refresh_date_obj) {
  1725.                             $last_refresh_date_obj $transDate;
  1726.                         }
  1727.                     }
  1728.                 }
  1729.             }
  1730.             if ($modifyAccTransaction == 1) {
  1731.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1732.                     $docHere $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  1733.                         $docEntityIdField => $docId,
  1734.                     ));;
  1735.                     if ($docHere) {
  1736.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1737.                         if ($curr_v_ids == null)
  1738.                             $curr_v_ids = [];
  1739.                         $skipVids = [];
  1740.                         $toChangeVid 0;
  1741.                         $voucher null;
  1742.                         foreach ($curr_v_ids as $vid) {
  1743.                             if (in_array($vid$skipVids))
  1744.                                 continue;
  1745.                             $skipVids[] = $vid//to prevent duplicate query
  1746.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1747.                                 'transactionId' => $vid,
  1748.                             ));;
  1749.                             if ($voucher) {
  1750.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1751.                                     $toChangeVid $vid;
  1752.                                 } else {
  1753.                                     continue;
  1754.                                 }
  1755.                             }
  1756.                         }
  1757.                         if ($toChangeVid == 0) {
  1758.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1759.                                 $em,
  1760.                                 $docHere->getStockTransferDate()->format('Y-m-d'),
  1761.                                 0,
  1762.                                 AccountsConstant::VOUCHER_JOURNAL,
  1763.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  1764.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1765.                                 'JV',
  1766.                                 'GN',
  1767.                                 0,
  1768.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1769.                                 0,
  1770.                                 $docHere->getCreatedLoginId(),
  1771.                                 $docHere->getCompanyId(),
  1772.                                 '',
  1773.                                 0,
  1774.                                 1
  1775.                             );
  1776.                             $em->flush();
  1777.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1778.                                 'transactionId' => $toChangeVid,
  1779.                             ));;
  1780.                         }
  1781.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  1782.                         $tot_inv_amount 0;
  1783.                         foreach ($transData as $k => $v) {
  1784.                             $tot_inv_amount += ($v);
  1785.                             Accounts::CreateNewTransactionDetails($em,
  1786.                                 '',
  1787.                                 $toChangeVid,
  1788.                                 Generic::CurrToInt($v),
  1789.                                 $k,
  1790.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  1791.                                 $v >= AccountsConstant::DEBIT AccountsConstant::CREDIT,
  1792.                                 0,
  1793.                                 [],
  1794.                                 [],
  1795.                                 $docHere->getCreatedLoginId()
  1796.                             );
  1797.                         }
  1798. //                        $stockReceivedType = $docHere->getType();
  1799.                         $to_balance_head 0;
  1800.                         if ($docHere->getTransferActionType() == 4) {
  1801.                         } else {
  1802.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1803.                                     'name' => 'inv_on_transit_head')
  1804.                             );
  1805.                             if ($inv_transit_head)
  1806.                                 $to_balance_head $inv_transit_head->getData();
  1807.                         }
  1808.                         if ($to_balance_head != 0) {
  1809.                             Accounts::CreateNewTransactionDetails($em,
  1810.                                 '',
  1811.                                 $toChangeVid,
  1812.                                 Generic::CurrToInt($tot_inv_amount),
  1813.                                 $to_balance_head,
  1814.                                 'In Transit Items for -' $docHere->getDocumentHash(),
  1815.                                 $tot_inv_amount >= AccountsConstant::CREDIT AccountsConstant::DEBIT,
  1816.                                 0,
  1817.                                 [],
  1818.                                 [],
  1819.                                 $docHere->getCreatedLoginId()
  1820.                             );
  1821.                         }
  1822.                         if ($voucher)
  1823.                             $voucher->setTransactionAmount($tot_inv_amount);
  1824.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1825.                         if ($curr_v_ids != null)
  1826.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1827.                         else
  1828.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1829.                         $em->flush();
  1830. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  1831.                     }
  1832.                 }
  1833.             }
  1834.             $data = [];
  1835.             //____________IRR___________________
  1836.             $docEntity "ItemReceivedAndReplacement";
  1837.             $docEntityIdField "itemReceivedAndReplacementId";
  1838.             $accTransactionDataByDocId = [];
  1839.             $query "SELECT irr_item.*,  item_received_replacement.irr_date, item_received_replacement.document_hash from  irr_item
  1840.               join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  1841.             where item_received_replacement.irr_date ='" $last_refresh_date " 00:00:00' and item_received_replacement.approved=1";
  1842.             $stmt $em->getConnection()->prepare($query);
  1843.             $stmt->execute();
  1844.             $queryData $stmt->fetchAll();
  1845.             $irr_add_data = [];
  1846.             $irr_replace_data = [];
  1847.             $irr_dispose_data = [];
  1848.             foreach ($queryData as $item) {
  1849.                 $irr_add_data[$item['received_product_id']][] = array(
  1850.                     'date' => $last_refresh_date,
  1851.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1852.                     'entityId' => $item['irr_id'],
  1853.                     'colorId' => $item['received_product_color_id'],
  1854.                     'sizeId' => $item['received_product_color_id'],
  1855.                     'entityDocHash' => $item['document_hash'],
  1856.                     'qtyAdd' => $item['received_qty'],
  1857.                     'qtySub' => 0,
  1858.                     'valueAdd' => ($item['received_qty'] * $item['received_unit_purchase_price']),
  1859.                     'valueSub' => 0,
  1860.                     'price' => $item['received_unit_purchase_price'],
  1861.                     'fromWarehouse' => 0,
  1862.                     'toWarehouse' => $item['received_warehouse_id'],
  1863.                     'fromWarehouseSub' => 0,
  1864.                     'toWarehouseSub' => $item['received_warehouse_action_id']
  1865.                 );
  1866.                 $irr_replace_data[$item['replaced_product_id']][] = array(
  1867.                     'date' => $last_refresh_date,
  1868.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1869.                     'entityId' => $item['irr_id'],
  1870.                     'colorId' => $item['replaced_product_color_id'],
  1871.                     'sizeId' => $item['replaced_product_color_id'],
  1872.                     'entityDocHash' => $item['document_hash'],
  1873.                     'qtyAdd' => 0,
  1874.                     'qtySub' => $item['replaced_qty'],
  1875.                     'valueAdd' => 0,
  1876.                     'valueSub' => ($item['replaced_qty'] * $item['replaced_unit_purchase_price']),
  1877.                     'price' => $item['replaced_unit_purchase_price'],
  1878.                     'fromWarehouse' => $item['replaced_warehouse_id'],
  1879.                     'toWarehouse' => 0,
  1880.                     'fromWarehouseSub' => $item['replaced_warehouse_action_id'],
  1881.                     'toWarehouseSub' => 0
  1882.                 );
  1883.                 $irr_dispose_data[$item['received_product_id']][] = array(
  1884.                     'date' => $last_refresh_date,
  1885.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1886.                     'entityId' => $item['irr_id'],
  1887.                     'colorId' => $item['received_product_color_id'],
  1888.                     'sizeId' => $item['received_product_size_id'],
  1889.                     'entityDocHash' => $item['document_hash'],
  1890.                     'qtyAdd' => 0,
  1891.                     'qtySub' => $item['dispose_qty'],
  1892.                     'valueAdd' => 0,
  1893.                     'valueSub' => ($item['dispose_qty'] * $item['received_unit_purchase_price']),
  1894.                     'price' => $item['received_unit_purchase_price'],
  1895.                     'fromWarehouse' => $item['received_warehouse_id'],
  1896.                     'toWarehouse' => 0,
  1897.                     'fromWarehouseSub' => $item['received_warehouse_id'],
  1898.                     'toWarehouseSub' => 0
  1899.                 );
  1900.             }
  1901.             //now add irrs
  1902.             foreach ($irr_add_data as $key => $item) {
  1903.                 if (!empty($item)) {
  1904.                     foreach ($item as $entry) {
  1905.                         $transDate = new \DateTime($entry['date']);
  1906.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1907.                             $key,
  1908.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1909.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1910.                             $entry['fromWarehouse'],
  1911.                             $entry['toWarehouse'],
  1912.                             $entry['fromWarehouseSub'],
  1913.                             $entry['toWarehouseSub'],
  1914.                             $transDate,
  1915.                             $entry['qtyAdd'],
  1916.                             $entry['qtySub'],
  1917.                             $entry['valueAdd'],
  1918.                             $entry['valueSub'],
  1919.                             $entry['price'],
  1920.                             $this->getLoggedUserCompanyId($request),
  1921.                             0,
  1922.                             $entry['entity'],
  1923.                             $entry['entityId'],
  1924.                             $entry['entityDocHash'],
  1925.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  1926.                         );
  1927.                         if ($modifiedData)
  1928.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1929.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1930.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1931.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1932.                                 "",
  1933.                                 'inventory_refresh_debug'1); //last er 1 is append
  1934.                         if ($last_refresh_date_obj == '') {
  1935.                             $last_refresh_date_obj $transDate;
  1936.                         } else if ($transDate $last_refresh_date_obj) {
  1937.                             $last_refresh_date_obj $transDate;
  1938.                         }
  1939.                     }
  1940.                 }
  1941.             }
  1942.             foreach ($irr_replace_data as $key => $item) {
  1943.                 if (!empty($item)) {
  1944.                     foreach ($item as $entry) {
  1945.                         $transDate = new \DateTime($entry['date']);
  1946.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1947.                             $key,
  1948.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1949.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1950.                             $entry['fromWarehouse'],
  1951.                             $entry['toWarehouse'],
  1952.                             $entry['fromWarehouseSub'],
  1953.                             $entry['toWarehouseSub'],
  1954.                             $transDate,
  1955.                             $entry['qtyAdd'],
  1956.                             $entry['qtySub'],
  1957.                             $entry['valueAdd'],
  1958.                             $entry['valueSub'],
  1959.                             $entry['price'],
  1960.                             $this->getLoggedUserCompanyId($request),
  1961.                             0,
  1962.                             $entry['entity'],
  1963.                             $entry['entityId'],
  1964.                             $entry['entityDocHash']);
  1965.                         if ($modifiedData)
  1966.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1967.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1968.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1969.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1970.                                 "",
  1971.                                 'inventory_refresh_debug'1); //last er 1 is append
  1972.                         if ($last_refresh_date_obj == '') {
  1973.                             $last_refresh_date_obj $transDate;
  1974.                         } else if ($transDate $last_refresh_date_obj) {
  1975.                             $last_refresh_date_obj $transDate;
  1976.                         }
  1977.                     }
  1978.                 }
  1979.             }
  1980.             foreach ($irr_dispose_data as $key => $item) {
  1981.                 if (!empty($item)) {
  1982.                     foreach ($item as $entry) {
  1983.                         $transDate = new \DateTime($entry['date']);
  1984.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1985.                             $key,
  1986.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1987.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1988.                             $entry['fromWarehouse'],
  1989.                             $entry['toWarehouse'],
  1990.                             $entry['fromWarehouseSub'],
  1991.                             $entry['toWarehouseSub'],
  1992.                             $transDate,
  1993.                             $entry['qtyAdd'],
  1994.                             $entry['qtySub'],
  1995.                             $entry['valueAdd'],
  1996.                             $entry['valueSub'],
  1997.                             $entry['price'],
  1998.                             $this->getLoggedUserCompanyId($request),
  1999.                             0,
  2000.                             $entry['entity'],
  2001.                             $entry['entityId'],
  2002.                             $entry['entityDocHash'],
  2003.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2004.                         );
  2005.                         if ($modifiedData)
  2006.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2007.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2008.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2009.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2010.                                 "",
  2011.                                 'inventory_refresh_debug'1); //last er 1 is append
  2012.                         if ($last_refresh_date_obj == '') {
  2013.                             $last_refresh_date_obj $transDate;
  2014.                         } else if ($transDate $last_refresh_date_obj) {
  2015.                             $last_refresh_date_obj $transDate;
  2016.                         }
  2017.                     }
  2018.                 }
  2019.             }
  2020.             $data = [];
  2021.             //____________DELIVERY_RECEIPT___________________
  2022.             $docEntity "DeliveryReceipt";
  2023.             $docEntityIdField "deliveryReceiptId";
  2024.             $accTransactionDataByDocId = [];
  2025.             $query "SELECT delivery_receipt_item.*, delivery_receipt.delivery_receipt_date, delivery_receipt.document_hash, delivery_receipt.skip_inventory_hit from  delivery_receipt_item
  2026.               join delivery_receipt on delivery_receipt.delivery_receipt_id=delivery_receipt_item.delivery_receipt_id
  2027.             where delivery_receipt.delivery_receipt_date ='" $last_refresh_date " 00:00:00' and delivery_receipt.approved=1";
  2028.             $stmt $em->getConnection()->prepare($query);
  2029.             $stmt->execute();
  2030.             $queryData $stmt->fetchAll();
  2031.             foreach ($queryData as $item) {
  2032.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  2033.                     ->findOneBy(
  2034.                         array(
  2035.                             'id' => $item['product_id']
  2036.                         )
  2037.                     );
  2038.                 $curr_purchase_price $product->getPurchasePrice();
  2039.                 if ($item['skip_inventory_hit'] != 1) {
  2040.                     $data[$item['product_id']][] = array(
  2041.                         'date' => $last_refresh_date,
  2042.                         'entity' => array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  2043.                         'entityId' => $item['delivery_receipt_id'],
  2044.                         'colorId' => $item['color_id'],
  2045.                         'sizeId' => $item['size_id'],
  2046.                         'entityDocHash' => $item['document_hash'],
  2047.                         'qtyAdd' => 0,
  2048.                         'qtySub' => ($item['qty'] * $item['unit_multiplier']),
  2049.                         'valueAdd' => 0,
  2050.                         'valueSub' => '_AUTO_',
  2051.                         'price' => $curr_purchase_price,
  2052.                         'fromWarehouse' => $item['warehouse_id'],
  2053.                         'toWarehouse' => 0,
  2054.                         'fromWarehouseSub' => $item['warehouse_action_id'] != null $item['warehouse_action_id'] : GeneralConstant::WAREHOUSE_ACTION_GOODS,
  2055.                         'toWarehouseSub' => 0
  2056.                     );
  2057.                 }
  2058.                 $get_kids_sql "UPDATE `delivery_receipt_item` SET current_purchase_price='" $curr_purchase_price "' WHERE id=" $item['id'] . ";";
  2059.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  2060.                 $stmt->execute();
  2061.             }
  2062.             foreach ($data as $key => $item) {
  2063.                 if (!empty($item)) {
  2064.                     foreach ($item as $entry) {
  2065.                         $transDate = new \DateTime($entry['date']);
  2066.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2067.                             $key,
  2068.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2069.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2070.                             $entry['fromWarehouse'],
  2071.                             $entry['toWarehouse'],
  2072.                             $entry['fromWarehouseSub'],
  2073.                             $entry['toWarehouseSub'],
  2074.                             $transDate,
  2075.                             $entry['qtyAdd'],
  2076.                             $entry['qtySub'],
  2077.                             $entry['valueAdd'],
  2078.                             $entry['valueSub'],
  2079.                             $entry['price'],
  2080.                             $this->getLoggedUserCompanyId($request),
  2081.                             0,
  2082.                             $entry['entity'],
  2083.                             $entry['entityId'],
  2084.                             $entry['entityDocHash'],
  2085.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2086.                         );
  2087.                         if ($modifiedData)
  2088.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2089.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2090.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2091.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2092.                                 "",
  2093.                                 'inventory_refresh_debug'1); //last er 1 is append
  2094.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2095.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  2096.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2097.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2098.                         else
  2099.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2100.                         if ($last_refresh_date_obj == '') {
  2101.                             $last_refresh_date_obj $transDate;
  2102.                         } else if ($transDate $last_refresh_date_obj) {
  2103.                             $last_refresh_date_obj $transDate;
  2104.                         }
  2105.                     }
  2106.                 }
  2107.             }
  2108.             if ($modifyAccTransaction == 1) {
  2109.                 //for now we are suuming there is only receipt without confirmation needed
  2110.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2111.                     $docHereDr $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  2112.                         $docEntityIdField => $docId,
  2113.                     ));;
  2114.                     $so $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
  2115.                         array(
  2116.                             'salesOrderId' => $docHereDr->getSalesOrderId()
  2117.                         )
  2118.                     );
  2119.                     $query $em->getRepository('ApplicationBundle:SalesInvoice')
  2120.                         ->createQueryBuilder('p');
  2121.                     $query->where('p.salesOrderId = :soID')
  2122.                         ->setParameter('soID'$docHereDr->getSalesOrderId());
  2123.                     $query->andWhere("p.deliveryReceiptIds LIKE '%" $docId "%' ");
  2124.                     $query->setMaxResults(1);
  2125.                     $results $query->getQuery()->getResult();
  2126.                     $docHere null;
  2127.                     if (!empty($results))
  2128.                         $docHere $results[0];
  2129.                     if ($docHere) {
  2130.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2131.                         if ($curr_v_ids == null)
  2132.                             $curr_v_ids = [];
  2133.                         $skipVids = [];
  2134.                         $toChangeVid 0;
  2135.                         $voucher null;
  2136.                         foreach ($curr_v_ids as $vid) {
  2137.                             if (in_array($vid$skipVids))
  2138.                                 continue;
  2139.                             $skipVids[] = $vid//to prevent duplicate query
  2140.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2141.                                 'transactionId' => $vid,
  2142.                             ));;
  2143.                             if ($voucher) {
  2144.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2145.                                     $toChangeVid $vid;
  2146.                                 } else {
  2147.                                     continue;
  2148.                                 }
  2149.                                 if (strpos($voucher->getDescription(), 'Inventory') !== false) {
  2150. //                                    echo "Word Found!";
  2151.                                     $toChangeVid $vid;
  2152.                                 } else {
  2153.                                     continue;
  2154.                                 }
  2155.                             }
  2156.                         }
  2157.                         if ($toChangeVid == 0) {
  2158.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2159.                                 $em,
  2160.                                 $docHere->getSalesInvoiceDate()->format('Y-m-d'),
  2161.                                 0,
  2162.                                 AccountsConstant::VOUCHER_JOURNAL,
  2163.                                 'Journal For Inventory balance for Sales Invoice ' $docHere->getDocumentHash(),
  2164.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2165.                                 'JV',
  2166.                                 'GN',
  2167.                                 0,
  2168.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2169.                                 0,
  2170.                                 $docHere->getCreatedLoginId(),
  2171.                                 $docHere->getCompanyId(),
  2172.                                 '',
  2173.                                 0,
  2174.                                 1,
  2175.                                 0''$so->getBranchId(),
  2176.                                 AccountsConstant::INVOICE_REVENUE_JOURNAL,
  2177.                                 array_flip(GeneralConstant::$Entity_list)['SalesInvoice'], $docHere->getSalesInvoiceId(), $docHere->getDocumentHash()
  2178.                             );
  2179.                             $em->flush();
  2180.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2181.                                 'transactionId' => $toChangeVid,
  2182.                             ));;
  2183.                         }
  2184. //                        DeleteDocument::AccTransactions($em, $toChangeVid, 0);
  2185.                         //now remove cogs or inventory related transactions
  2186.                         $voucherDetails $em->getRepository('ApplicationBundle:AccTransactionDetails')->findBy(array(
  2187.                             'transactionId' => $toChangeVid,
  2188.                         ));;
  2189.                         foreach ($voucherDetails as $vdtls) {
  2190.                             if (in_array($vdtls->getAccountsHeadId(), $inv_head_list)) {
  2191.                                 $em->remove($vdtls);
  2192.                                 $em->flush();
  2193.                             }
  2194.                             if ($cogs_head == $vdtls->getAccountsHeadId()) {
  2195.                                 $em->remove($vdtls);
  2196.                                 $em->flush();
  2197.                             }
  2198.                         }
  2199.                         $tot_inv_amount 0;
  2200.                         foreach ($transData as $k => $v) {
  2201.                             $tot_inv_amount += ($v);
  2202.                             Accounts::CreateNewTransactionDetails($em,
  2203.                                 '',
  2204.                                 $toChangeVid,
  2205.                                 Generic::CurrToInt($v),
  2206.                                 $k,
  2207.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2208.                                 AccountsConstant::DEBIT,
  2209.                                 0,
  2210.                                 [],
  2211.                                 [],
  2212.                                 $docHere->getCreatedLoginId()
  2213.                             );
  2214.                         }
  2215. //                        $stockReceivedType = $docHere->getType();
  2216.                         $to_balance_head 0;
  2217. //                        if ($docHere->getTransferActionType() == 4)
  2218.                         if (1) {
  2219.                         } else {
  2220.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  2221.                                     'name' => 'inv_on_transit_head')
  2222.                             );
  2223.                             if ($inv_transit_head)
  2224.                                 $to_balance_head $inv_transit_head->getData();
  2225.                         }
  2226.                         if ($to_balance_head != 0) {
  2227.                             Accounts::CreateNewTransactionDetails($em,
  2228.                                 '',
  2229.                                 $toChangeVid,
  2230.                                 Generic::CurrToInt($tot_inv_amount),
  2231.                                 $to_balance_head,
  2232.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  2233.                                 AccountsConstant::CREDIT,
  2234.                                 0,
  2235.                                 [],
  2236.                                 [],
  2237.                                 $docHere->getCreatedLoginId()
  2238.                             );
  2239.                         }
  2240.                         if ($voucher)
  2241.                             $voucher->setTransactionAmount($tot_inv_amount);
  2242.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2243.                         if ($curr_v_ids != null)
  2244.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2245.                         else
  2246.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2247.                         $em->flush();
  2248. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2249.                     }
  2250.                 }
  2251.             }
  2252.             $data = [];
  2253.             //____________STOCK_CONSUMPTION___________________
  2254.             $docEntity "StockConsumptionNote";
  2255.             $docEntityIdField "stockConsumptionNoteId";
  2256.             $accTransactionDataByDocId = [];
  2257.             $query "SELECT stock_consumption_note_item.*,  stock_consumption_note.stock_consumption_note_date, stock_consumption_note.document_hash, stock_consumption_note.data
  2258.               from  stock_consumption_note_item
  2259.               join stock_consumption_note on stock_consumption_note.stock_consumption_note_id=stock_consumption_note_item.stock_consumption_note_id
  2260.             where stock_consumption_note.stock_consumption_note_date ='" $last_refresh_date " 00:00:00' and stock_consumption_note.approved=1";
  2261.             $stmt $em->getConnection()->prepare($query);
  2262.             $stmt->execute();
  2263.             $queryData $stmt->fetchAll();
  2264.             $consumption_data = [];
  2265.             $produced_data = [];
  2266.             $checked_stcm_ids = [];
  2267.             foreach ($queryData as $item) {
  2268. //                $product=$em->getRepository('ApplicationBundle:InvProducts')
  2269. //                    ->findOneBy(
  2270. //                        array(
  2271. //                            'id'=>$item['product_id']
  2272. //                        )
  2273. //                    );
  2274. //
  2275. //                $curr_purchase_price=$product->getPurchasePrice();
  2276.                 if (!in_array($item['stock_consumption_note_id'], $checked_stcm_ids)) {
  2277.                     $conversion_data json_decode($item['data'], true);
  2278.                     if ($conversion_data == null)
  2279.                         $conversion_data = [];
  2280.                     if (isset($conversion_data['conversionData'])) {
  2281.                         if (isset($conversion_data['conversionData']['converted_products'])) {
  2282.                             $curr_spec_data $conversion_data['conversionData'];
  2283.                             foreach ($curr_spec_data['converted_products'] as $pika_key => $val) {
  2284.                                 $consumption_data[$val][] = array(
  2285.                                     'date' => $last_refresh_date,
  2286.                                     'type' => 2,
  2287.                                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2288.                                     'entityId' => $item['stock_consumption_note_id'],
  2289.                                     'colorId' => isset($curr_spec_data['converted_product_colors'][$pika_key]) ? ($curr_spec_data['converted_product_colors'][$pika_key]) : 0,
  2290.                                     'sizeId' => isset($curr_spec_data['converted_product_sizes'][$pika_key]) ? ($curr_spec_data['converted_product_sizes'][$pika_key]) : 0,
  2291.                                     'entityDocHash' => $item['document_hash'],
  2292.                                     'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_units'][$pika_key]) : 0,
  2293.                                     'qtySub' => 0,
  2294.                                     '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,
  2295.                                     'valueSub' => 0,
  2296.                                     'price' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_unit_price'][$pika_key]) : 0,
  2297.                                     'fromWarehouse' => 0,
  2298.                                     'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key]) ? ($curr_spec_data['converted_warehouseId'][$pika_key]) : 0,
  2299.                                     'fromWarehouseSub' => 0,
  2300.                                     'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key]) ? ($curr_spec_data['converted_warehouseActionId'][$pika_key]) : 0
  2301.                                 );
  2302.                             }
  2303.                         }
  2304.                     }
  2305. //                    if(isset($conversion_data['expenseCost'] ))
  2306. //                    if(isset($conversion_data['expenseCost']['expense_heads'] ))
  2307. //                    {
  2308. //                        $curr_spec_data=$conversion_data['expenseCost'];
  2309. //                        foreach($curr_spec_data['expense_heads'] as $pika_key=>$val)
  2310. //                        {
  2311. //
  2312. //                            $consumption_data[$val][] = array(
  2313. //                                'date' => $last_refresh_date,
  2314. //                                'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2315. //                                'entityId' => $item['stock_consumption_note_id'],
  2316. //                                'entityDocHash' => $item['document_hash'],
  2317. //                                'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_units'][$pika_key]):0,
  2318. //                                'qtySub' => 0,
  2319. //                                '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,
  2320. //                                'valueSub' => 0,
  2321. //                                'price' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_unit_price'][$pika_key]):0,
  2322. //                                'fromWarehouse' => 0,
  2323. //                                'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key])?(1*$curr_spec_data['converted_warehouseId'][$pika_key]):0,
  2324. //                                'fromWarehouseSub' => 0,
  2325. //                                'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key])?(1*$curr_spec_data['converted_warehouseActionId'][$pika_key]):0
  2326. //                            );
  2327. //                        }
  2328. //                    }
  2329.                     $checked_stcm_ids[] = $item['stock_consumption_note_id'];
  2330.                 }
  2331.                 $consumption_data[$item['product_id']][] = array(
  2332.                     'date' => $last_refresh_date,
  2333.                     'type' => 1,
  2334.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2335.                     'entityId' => $item['stock_consumption_note_id'],
  2336.                     'colorId' => $item['color_id'],
  2337.                     'sizeId' => $item['size_id'],
  2338.                     'entityDocHash' => $item['document_hash'],
  2339.                     'qtyAdd' => 0,
  2340.                     'qtySub' => ($item['qty'] * 1),
  2341.                     'valueAdd' => 0,
  2342.                     'valueSub' => (($item['qty']) * ($item['price'])),
  2343.                     'price' => $item['price'],
  2344.                     'fromWarehouse' => $item['warehouse_id'],
  2345.                     'toWarehouse' => 0,
  2346.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  2347.                     'toWarehouseSub' => 0
  2348.                 );
  2349. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2350. //                $stmt = $em->getConnection()->prepare($get_kids_sql);
  2351. //                $stmt->execute();
  2352.             }
  2353.             foreach ($consumption_data as $key => $item) {
  2354.                 if (!empty($item)) {
  2355.                     foreach ($item as $entry) {
  2356.                         $transDate = new \DateTime($entry['date']);
  2357.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2358.                             $key,
  2359.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2360.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2361.                             $entry['fromWarehouse'],
  2362.                             $entry['toWarehouse'],
  2363.                             $entry['fromWarehouseSub'],
  2364.                             $entry['toWarehouseSub'],
  2365.                             $transDate,
  2366.                             $entry['qtyAdd'],
  2367.                             $entry['qtySub'],
  2368.                             $entry['valueAdd'],
  2369.                             $entry['valueSub'],
  2370.                             $entry['price'],
  2371.                             $this->getLoggedUserCompanyId($request),
  2372.                             0,
  2373.                             $entry['entity'],
  2374.                             $entry['entityId'],
  2375.                             $entry['entityDocHash'],
  2376.                             $entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION
  2377.                         );
  2378.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2379.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2380.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2381.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2382.                             "",
  2383.                             'inventory_refresh_debug'1); //last er 1 is append
  2384.                         if ($last_refresh_date_obj == '') {
  2385.                             $last_refresh_date_obj $transDate;
  2386.                         } else if ($transDate $last_refresh_date_obj) {
  2387.                             $last_refresh_date_obj $transDate;
  2388.                         }
  2389.                     }
  2390.                 }
  2391.             }
  2392.             $data = [];
  2393.             //____________PRODUCTION___________________
  2394.             $docEntity "Production";
  2395.             $docEntityIdField "productionId";
  2396.             $accTransactionDataByDocId = [];
  2397.             $consumedAmountByProductionId = [];
  2398.             $query "SELECT * from production_process_settings
  2399.             where approved=1 order by production_process_settings_id asc  ";
  2400.             $stmt $em->getConnection()->prepare($query);
  2401.             $stmt->execute();
  2402.             $processList $stmt->fetchAll();
  2403. //            $processList=[];
  2404.             foreach ($processList as $process) {
  2405.                 $query "SELECT production_entry_item.*,  production.production_date, production.document_hash
  2406.               from  production_entry_item
  2407.               join production on production_entry_item.production_id=production.production_id
  2408.             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  ";
  2409.                 $stmt $em->getConnection()->prepare($query);
  2410.                 $stmt->execute();
  2411.                 $queryData $stmt->fetchAll();
  2412.                 $produced_data = [];
  2413.                 $rejected_data = [];
  2414.                 $consumed_data = [];
  2415.                 foreach ($queryData as $item) {
  2416. //                $product=$em->getRepository('ApplicationBundle:InvProducts')
  2417. //                    ->findOneBy(
  2418. //                        array(
  2419. //                            'id'=>$item['product_id']
  2420. //                        )
  2421. //                    );
  2422. //
  2423. //                $curr_purchase_price=$product->getPurchasePrice();
  2424.                     if ($item['price'] == '')
  2425.                         $item['price'] = 0;
  2426.                     if ($item['price'] < 0)
  2427.                         $item['price'] = 0;
  2428.                     $item['production_nature_id'];
  2429.                     $consumed_data[$item['product_id']][] = array(
  2430.                         'date' => $last_refresh_date,
  2431.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2432.                         'entityId' => $item['production_id'],
  2433.                         'colorId' => $item['color_id'],
  2434.                         'sizeId' => $item['size_id'],
  2435.                         'entityDocHash' => $item['document_hash'],
  2436.                         'qtyAdd' => 0,
  2437.                         'qtySub' => ($item['additional_consumed_qty'] * 1) + ($item['consumed_qty']),
  2438.                         'valueAdd' => 0,
  2439.                         'valueSub' => '_AUTO_',
  2440.                         'price' => $item['price'],
  2441.                         'fromWarehouse' => $item['warehouse_id'],
  2442.                         'toWarehouse' => 0,
  2443.                         'fromWarehouseSub' => $item['consumed_item_action_tag_id'],
  2444.                         'toWarehouseSub' => 0,
  2445.                         'production_nature_id' => $item['production_nature_id'],
  2446.                     );
  2447.                     $produced_data[$item['product_id']][] = array(
  2448.                         'date' => $last_refresh_date,
  2449.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2450.                         'entityId' => $item['production_id'],
  2451.                         'colorId' => $item['color_id'],
  2452.                         'sizeId' => $item['size_id'],
  2453.                         'entityDocHash' => $item['document_hash'],
  2454.                         'qtyAdd' => ($item['accepted_qty'] * 1),
  2455.                         'qtySub' => 0,
  2456.                         'valueAdd' => (($item['accepted_qty'] * 1) * ($item['price'])),
  2457.                         'valueSub' => 0,
  2458.                         'price' => $item['price'],
  2459.                         'fromWarehouse' => 0,
  2460.                         'toWarehouse' => $item['warehouse_id'],
  2461.                         'fromWarehouseSub' => 0,
  2462.                         'toWarehouseSub' => $item['produced_item_action_tag_id'],
  2463.                         'production_nature_id' => $item['production_nature_id'],
  2464.                     );
  2465.                     $rejected_data[$item['product_id']][] = array(
  2466.                         'date' => $last_refresh_date,
  2467.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2468.                         'entityId' => $item['production_id'],
  2469.                         'colorId' => $item['color_id'],
  2470.                         'sizeId' => $item['size_id'],
  2471.                         'entityDocHash' => $item['document_hash'],
  2472.                         'qtyAdd' => ($item['rejected_qty'] * 1),
  2473.                         'qtySub' => 0,
  2474.                         'valueAdd' => (($item['rejected_qty'] * 1) * ($item['price'])),
  2475.                         'valueSub' => 0,
  2476.                         'price' => $item['price'],
  2477.                         'fromWarehouse' => 0,
  2478.                         'toWarehouse' => $item['warehouse_id'],
  2479.                         'fromWarehouseSub' => 0,
  2480.                         'toWarehouseSub' => $item['rejected_item_action_tag_id'],
  2481.                         'production_nature_id' => $item['production_nature_id'],
  2482.                     );
  2483. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2484. //                $stmt = $em->getConnection()->prepare($get_kids_sql);
  2485. //                $stmt->execute();
  2486.                 }
  2487.                 foreach ($consumed_data as $key => $item) {
  2488.                     if (!empty($item)) {
  2489.                         foreach ($item as $entry) {
  2490.                             $transDate = new \DateTime($entry['date']);
  2491.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2492.                                 $key,
  2493.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2494.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2495.                                 $entry['fromWarehouse'],
  2496.                                 $entry['toWarehouse'],
  2497.                                 $entry['fromWarehouseSub'],
  2498.                                 $entry['toWarehouseSub'],
  2499.                                 $transDate,
  2500.                                 $entry['qtyAdd'],
  2501.                                 $entry['qtySub'],
  2502.                                 $entry['valueAdd'],
  2503.                                 $entry['valueSub'],
  2504.                                 $entry['price'],
  2505.                                 $this->getLoggedUserCompanyId($request),
  2506.                                 0,
  2507.                                 $entry['entity'],
  2508.                                 $entry['entityId'],
  2509.                                 $entry['entityDocHash'],
  2510.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION);
  2511.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2512.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2513.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2514.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2515.                                 "",
  2516.                                 'inventory_refresh_debug'1); //last er 1 is append
  2517.                             if (!isset($consumedAmountByProductionId[$entry['entityId']]))
  2518.                                 $consumedAmountByProductionId[$entry['entityId']] = ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2519.                             else
  2520.                                 $consumedAmountByProductionId[$entry['entityId']] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2521.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2522.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  2523.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2524.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2525.                             else
  2526.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2527.                             if ($last_refresh_date_obj == '') {
  2528.                                 $last_refresh_date_obj $transDate;
  2529.                             } else if ($transDate $last_refresh_date_obj) {
  2530.                                 $last_refresh_date_obj $transDate;
  2531.                             }
  2532.                         }
  2533.                     }
  2534.                 }
  2535.                 foreach ($produced_data as $key => $item) {
  2536.                     if (!empty($item)) {
  2537.                         foreach ($item as $entry) {
  2538.                             $transDate = new \DateTime($entry['date']);
  2539.                             $productionNature $entry['production_nature_id'];
  2540.                             if (in_array($productionNature, [12])) {
  2541.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2542.                                     $key,
  2543.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2544.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2545.                                     $entry['fromWarehouse'],
  2546.                                     $entry['toWarehouse'],
  2547.                                     $entry['fromWarehouseSub'],
  2548.                                     $entry['toWarehouseSub'],
  2549.                                     $transDate,
  2550.                                     $entry['qtyAdd'],
  2551.                                     $entry['qtySub'],
  2552. //                                $entry['valueAdd'],
  2553.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2554.                                     $entry['valueSub'],
  2555.                                     $entry['price'],
  2556.                                     $this->getLoggedUserCompanyId($request),
  2557.                                     0,
  2558.                                     $entry['entity'],
  2559.                                     $entry['entityId'],
  2560.                                     $entry['entityDocHash'],
  2561.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2562.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2563.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2564.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2565.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2566.                                     "",
  2567.                                     'inventory_refresh_debug'1); //last er 1 is append
  2568.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2569.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2570.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2571.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2572.                                 else
  2573.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2574. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2575. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2576. //                            else
  2577. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2578.                             } else {
  2579.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2580.                                     $key,
  2581.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2582.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2583.                                     $entry['fromWarehouse'],
  2584.                                     $entry['toWarehouse'],
  2585.                                     $entry['fromWarehouseSub'],
  2586.                                     $entry['toWarehouseSub'],
  2587.                                     $transDate,
  2588.                                     0,
  2589.                                     0,
  2590. //                                $entry['valueAdd'],
  2591.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2592.                                     0,
  2593.                                     $entry['price'],
  2594.                                     $this->getLoggedUserCompanyId($request),
  2595.                                     0,
  2596.                                     $entry['entity'],
  2597.                                     $entry['entityId'],
  2598.                                     $entry['entityDocHash'],
  2599.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2600.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2601.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2602.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2603.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2604.                                     "",
  2605.                                     'inventory_refresh_debug'1); //last er 1 is append
  2606.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2607.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2608.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2609.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2610.                                 else
  2611.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2612. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2613. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2614. //                            else
  2615. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2616.                             }
  2617.                             if ($last_refresh_date_obj == '') {
  2618.                                 $last_refresh_date_obj $transDate;
  2619.                             } else if ($transDate $last_refresh_date_obj) {
  2620.                                 $last_refresh_date_obj $transDate;
  2621.                             }
  2622.                         }
  2623.                     }
  2624.                 }
  2625.                 foreach ($rejected_data as $key => $item) {
  2626.                     if (!empty($item)) {
  2627.                         foreach ($item as $entry) {
  2628.                             $transDate = new \DateTime($entry['date']);
  2629.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2630.                                 $key,
  2631.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2632.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2633.                                 $entry['fromWarehouse'],
  2634.                                 $entry['toWarehouse'],
  2635.                                 $entry['fromWarehouseSub'],
  2636.                                 $entry['toWarehouseSub'],
  2637.                                 $transDate,
  2638.                                 $entry['qtyAdd'],
  2639.                                 $entry['qtySub'],
  2640.                                 $entry['valueAdd'],
  2641.                                 $entry['valueSub'],
  2642.                                 $entry['price'],
  2643.                                 $this->getLoggedUserCompanyId($request),
  2644.                                 0,
  2645.                                 $entry['entity'],
  2646.                                 $entry['entityId'],
  2647.                                 $entry['entityDocHash'],
  2648.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2649.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2650.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2651.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2652.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2653.                                 "",
  2654.                                 'inventory_refresh_debug'1); //last er 1 is append
  2655.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2656.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  2657.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2658.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = (-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2659.                             else
  2660.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ((-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2661.                             if ($last_refresh_date_obj == '') {
  2662.                                 $last_refresh_date_obj $transDate;
  2663.                             } else if ($transDate $last_refresh_date_obj) {
  2664.                                 $last_refresh_date_obj $transDate;
  2665.                             }
  2666.                         }
  2667.                     }
  2668.                 }
  2669.             }
  2670.             if ($modifyAccTransaction == 1) {
  2671.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2672.                     $docHere $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  2673.                         $docEntityIdField => $docId,
  2674.                     ));;
  2675.                     if ($docHere) {
  2676.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2677.                         if ($curr_v_ids == null)
  2678.                             $curr_v_ids = [];
  2679.                         $skipVids = [];
  2680.                         $toChangeVid 0;
  2681.                         $voucher null;
  2682.                         foreach ($curr_v_ids as $vid) {
  2683.                             if (in_array($vid$skipVids))
  2684.                                 continue;
  2685.                             $skipVids[] = $vid//to prevent duplicate query
  2686.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2687.                                 'transactionId' => $vid,
  2688.                             ));;
  2689.                             if ($voucher) {
  2690.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2691.                                     $toChangeVid $vid;
  2692.                                 } else {
  2693.                                     continue;
  2694.                                 }
  2695.                             }
  2696.                         }
  2697.                         if ($toChangeVid == 0) {
  2698.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2699.                                 $em,
  2700.                                 $docHere->getProductionDate()->format('Y-m-d'),
  2701.                                 0,
  2702.                                 AccountsConstant::VOUCHER_JOURNAL,
  2703.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  2704.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2705.                                 'JV',
  2706.                                 'GN',
  2707.                                 0,
  2708.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2709.                                 0,
  2710.                                 $docHere->getCreatedLoginId(),
  2711.                                 $docHere->getCompanyId(),
  2712.                                 '',
  2713.                                 0,
  2714.                                 1
  2715.                             );
  2716.                             $em->flush();
  2717.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2718.                                 'transactionId' => $toChangeVid,
  2719.                             ));;
  2720.                         }
  2721.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  2722.                         $tot_inv_amount 0;
  2723.                         foreach ($transData as $k => $v) {
  2724.                             $tot_inv_amount += ($v);
  2725.                             Accounts::CreateNewTransactionDetails($em,
  2726.                                 '',
  2727.                                 $toChangeVid,
  2728.                                 Generic::CurrToInt($v),
  2729.                                 $k,
  2730.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2731.                                 AccountsConstant::DEBIT,
  2732.                                 0,
  2733.                                 [],
  2734.                                 [],
  2735.                                 $docHere->getCreatedLoginId()
  2736.                             );
  2737.                         }
  2738. //                        $stockReceivedType = $docHere->getType();
  2739.                         $to_balance_head 0;
  2740. //                        if ($docHere->getTransferActionType() == 4)
  2741.                         if (1) {
  2742.                         } else {
  2743.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  2744.                                     'name' => 'inv_on_transit_head')
  2745.                             );
  2746.                             if ($inv_transit_head)
  2747.                                 $to_balance_head $inv_transit_head->getData();
  2748.                         }
  2749.                         if ($to_balance_head != 0) {
  2750.                             Accounts::CreateNewTransactionDetails($em,
  2751.                                 '',
  2752.                                 $toChangeVid,
  2753.                                 Generic::CurrToInt($tot_inv_amount),
  2754.                                 $to_balance_head,
  2755.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  2756.                                 AccountsConstant::CREDIT,
  2757.                                 0,
  2758.                                 [],
  2759.                                 [],
  2760.                                 $docHere->getCreatedLoginId()
  2761.                             );
  2762.                         }
  2763.                         if ($voucher)
  2764.                             $voucher->setTransactionAmount($tot_inv_amount);
  2765.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2766.                         if ($curr_v_ids != null)
  2767.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2768.                         else
  2769.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2770.                         $em->flush();
  2771. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2772.                     }
  2773.                 }
  2774.             }
  2775.             if ($terminate == 0) {
  2776.                 return new JsonResponse(array(
  2777.                     "success" => true,
  2778.                     "last_refresh_date" => $last_refresh_date,
  2779.                     "inventory_refreshed" => $refreshed_opening
  2780.                 ));
  2781.             } else {
  2782.                 return new JsonResponse(array(
  2783.                     "success" => false,
  2784.                     "last_refresh_date" => $last_refresh_date,
  2785.                     "inventory_refreshed" => $refreshed_opening
  2786.                 ));
  2787.             }
  2788.         }
  2789.         return new JsonResponse(array(
  2790.             "success" => false,
  2791.             "last_refresh_date" => $last_refresh_date,
  2792.             "inventory_refreshed" => $refreshed_opening
  2793.         ));
  2794.         //2 .now make an array with necessary data based on challan and grn for now willl need consumption later
  2795.         //broken into transactions not closing
  2796.         //structure---> $data['productId']=array(
  2797.         //'date'=>'2017-09-02 00:00:00'
  2798.         //'qtyAdd'=>'2'
  2799.         //'qtySub'=>'0'
  2800.         //'valueAdd'=>'2000'
  2801.         //'valueSub'=>'0'
  2802.         //'fromWarehouse'=>'0'
  2803.         //'toWarehouse'=>'0'
  2804.         //'fromWarehouseSub'=>'0'
  2805.         //'toWarehouseSub'=>'0'
  2806.         //)
  2807.         //
  2808.     }
  2809.     public function OpeningItemAction(Request $request)
  2810.     {
  2811.         $em $this->getDoctrine()->getManager();
  2812.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  2813.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  2814.         if ($request->isMethod('POST')) {
  2815.             $pp trim($request->request->get('purchasePrice'));
  2816. //replace comma with space
  2817.             $pp str_replace(","""$pp);
  2818.             if ($request->request->get('productId') != '') {
  2819.                 foreach ($request->request->get('warehouseId') as $key => $value) {
  2820.                     $data = array(
  2821.                         'productId' => $request->request->get('productId'),
  2822.                         'warehouseId' => $request->request->get('warehouseId')[$key],
  2823.                         'warehouseActionId' => $request->request->get('warehouseActionId')[$key],
  2824.                         'purchasePrice' => $pp,
  2825.                         'date' => new \DateTime($request->request->get('date')),
  2826.                         'qty' => $request->request->get('qty')[$key],
  2827.                     );
  2828.                     $transDate = new \DateTime($request->request->get('date'));
  2829.                     $new = new InvItemInOut();
  2830.                     $new->setProductId($request->request->get('productId'));
  2831.                     $new->setWarehouseId($request->request->get('warehouseId')[$key]);
  2832.                     $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  2833.                     $new->setActionTagId($request->request->get('warehouseActionId')[$key]);
  2834.                     $new->setTransactionDate($transDate);
  2835.                     $new->setQty($request->request->get('qty')[$key]);
  2836.                     $new->setPrice($pp);
  2837.                     $new->setAmount($request->request->get('qty')[$key] * $pp);
  2838.                     $new->setEntity(0);// opening =0
  2839.                     $new->setEntityId(0);// opening =0
  2840.                     $new->setDebitCreditHeadId(0);// opening =0
  2841.                     $new->setVoucherIds(null);// opening =0
  2842.                     $em->persist($new);
  2843.                     $em->flush();
  2844. //                    $total_inv_value_in_by_id += $request->request->get('qty')[$key] * $pp;
  2845.                     Inventory::AddOpeningInventoryStock($em$data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2846.                 }
  2847.             }
  2848.         }
  2849.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  2850.             'name' => 'warehouse_action_1'//for now for stock of goods
  2851.         ));
  2852.         return $this->render('@Inventory/pages/input_forms/opening_item_assign.html.twig',
  2853.             array(
  2854.                 'page_title' => "Opening Items",
  2855.                 'inv_head' => $inv_head $inv_head->getData() : '',
  2856.                 'products' => $this->getDoctrine()->getRepository('ApplicationBundle:InvProducts')->findBy(array(
  2857.                     'status' => GeneralConstant::ACTIVE//for now for stock of goods
  2858. //                    'opening_locked'=>0
  2859.                 )),
  2860.                 'warehouseList' => Inventory::WarehouseList($em),
  2861.                 'warehouseActionList' => $warehouse_action_list
  2862.             )
  2863.         );
  2864.     }
  2865.     public function CreateProductCategoryAction(Request $request)
  2866.     {
  2867.         if ($request->isMethod('POST')) {
  2868.             $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));
  2869.             if ($cat_data['id'] != '')
  2870.                 return new JsonResponse(array("success" => true'cat_data' => $cat_data));
  2871.         }
  2872.         return new JsonResponse(array("success" => false,));
  2873. //        return $this->redirectToRoute("create_product");
  2874.     }
  2875.     public function CreateProductSubCategoryAction(Request $request)
  2876.     {
  2877.         if ($request->isMethod('POST')) {
  2878.             $spec_data Inventory::CreateSubCategory($this->getDoctrine()->getManager(),
  2879.                 $this->getLoggedUserCompanyId($request), $request->request->get('spec_name'),
  2880.                 $request->request->get('level'0),
  2881.                 $request->request->get('parentId'0),
  2882.                 $request->request->get('itemgroupId'),
  2883.                 $request->request->get('categoryId'),
  2884.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2885.             if ($spec_data['id'] != '')
  2886.                 return new JsonResponse(array("success" => true'spec_data' => $spec_data));
  2887.         }
  2888.         return new JsonResponse(array("success" => false,));
  2889. //        return $this->redirectToRoute("create_product");
  2890.     }
  2891.     public function CreateProductBrandAction(Request $request)
  2892.     {
  2893.         if ($request->isMethod('POST')) {
  2894.             $data Inventory::CreateBrand($this->getDoctrine()->getManager(),
  2895.                 $this->getLoggedUserCompanyId($request), $request->request->get('brand_name'),
  2896.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2897.             if ($data['id'] != '')
  2898.                 return new JsonResponse(array("success" => true'data' => $data));
  2899.         }
  2900.         return new JsonResponse(array("success" => false,));
  2901. //        return $this->redirectToRoute("create_product");
  2902.     }
  2903.     public function CreateIssueNoteAction(Request $request)
  2904.     {
  2905.         return $this->render('@Inventory/pages/input_forms/issue_note.html.twig',
  2906.             array(
  2907.                 'page_title' => 'Issue Note'
  2908.             )
  2909.         );
  2910.     }
  2911.     public function ProcessDraftDeliveryReceiptAction(Request $request$id 0)
  2912.     {
  2913.         $em $this->getDoctrine()->getManager();
  2914.         $companyId $this->getLoggedUserCompanyId($request);
  2915.         $extId $id;
  2916.         $receiptId $id;
  2917.         $allowed 0;
  2918.         if ($request->isMethod('POST')) {
  2919.             $receiptId $request->request->get('deliveryReceiptId');
  2920.             $QD $this->getDoctrine()
  2921.                 ->getRepository('ApplicationBundle:DeliveryReceipt')
  2922.                 ->findOneBy(
  2923.                     array(
  2924.                         'deliveryReceiptId' => $receiptId
  2925.                     ),
  2926.                     array()
  2927.                 );
  2928.             $soId $QD->getSalesOrderId();
  2929.             $drData = [];
  2930.             $dr_item_data $em->getRepository('ApplicationBundle:DeliveryReceiptItem')->findBy(
  2931.                 array(
  2932.                     'deliveryReceiptId' => $receiptId,
  2933.                 )
  2934.             );
  2935.             foreach ($dr_item_data as $dr_item) {
  2936.                 $drData[] = array(
  2937.                     'soItemId' => $dr_item->getSalesorderItemId(),
  2938.                     'qty' => $dr_item->getQty()
  2939.                 );
  2940.             }
  2941. //            $drData=[
  2942. //                ['soItemId'=>9,'qty'=>9],
  2943. //                ['soItemId'=>9,'qty'=>9],
  2944. //                ['soItemId'=>9,'qty'=>9],
  2945. //            ];
  2946.             $toGetSoItemsId = [];
  2947.             $toGetDoItemsId = [];
  2948.             $drDataBySoItemId = [];
  2949.             $drDataByDoItemId = [];
  2950.             $so $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(array(
  2951.                 'salesOrderId' => $soId   //$id is soId
  2952.             ));
  2953.             if ($so->getDeliveryOrderSkipFlag() == 1) {
  2954.                 foreach ($drData as $pp) {
  2955.                     $toGetSoItemsId[] = $pp['soItemId'];
  2956.                     $drDataBySoItemId[$pp['soItemId']] = $pp;
  2957.                 }
  2958.             } else {
  2959.                 foreach ($drData as $pp) {
  2960.                     $toGetDoItemsId[] = $pp['soItemId'];
  2961.                     $drDataByDoItemId[$pp['soItemId']] = $pp;
  2962.                 }
  2963.                 $do_item_data $em->getRepository('ApplicationBundle:DeliveryOrderItem')->findBy(
  2964.                     array(
  2965.                         'salesorderId' => $id,
  2966.                         'id' => $toGetDoItemsId
  2967.                     )
  2968.                 );
  2969.                 foreach ($do_item_data as $dd) {
  2970.                     $toGetSoItemsId[] = $dd->getSalesorderItemId();
  2971.                     $drDataBySoItemId[$dd->getSalesorderItemId()] = $drDataByDoItemId[$dd->getId()];
  2972.                 }
  2973. //                $do_item_data = $em->getRepository('ApplicationBundle:SalesOrderItem')->findOneBy(
  2974. //                    array(
  2975. ////                'salesOrderId'=>$post_data->get('soId', null),
  2976. //                        'id' => $post_data->get('do_details_id')[$key]
  2977. //                    )
  2978. //                );
  2979.             }
  2980.             $so_item_data $em->getRepository('ApplicationBundle:SalesOrderItem')->findBy(
  2981.                 array(
  2982.                     'salesOrderId' => $soId,
  2983.                     'id' => $toGetSoItemsId
  2984.                 )
  2985.             );
  2986.             $prev_so_amount $so->getSoAmount();
  2987.             $total_discounted_amount 0;
  2988.             $total_product_amount 0;
  2989.             $total_discount 0;
  2990.             $total_special_discount $so->getSpecialDiscountAmount();
  2991.             $total_special_discount_rate $so->getSpecialDiscountRate();
  2992.             foreach ($so_item_data as $item) {
  2993.                 $qty $drDataBySoItemId[$item->getId()]['qty'];
  2994.                 $price $item->getPrice();
  2995.                 $amount $qty $price;
  2996.                 $discountAmount $amount * ($item->getDiscountRate() / 100);
  2997.                 $discountedAmount $amount $discountAmount;
  2998.                 $total_discounted_amount += $discountedAmount;
  2999.                 $total_discount += $discountAmount;
  3000.                 $total_product_amount += $amount;
  3001.             }
  3002.             $aitRate $so->getAitRate();
  3003.             $vatRate $so->getVatRate();
  3004.             if ($aitRate == '' || $aitRate == null$aitRate 0;
  3005.             if ($vatRate == '' || $vatRate == null$vatRate 0;
  3006. //        $so->setVatRate($post->get('vat_rate', null));
  3007.             $vatAmount $total_discounted_amount * ($vatRate 100);
  3008.             $aitAmount $total_discounted_amount * ($aitRate 100);
  3009.             $total_sales_amount $total_discounted_amount $vatAmount $aitAmount $total_special_discount;
  3010.             //now get client
  3011.             $client $em->getRepository('ApplicationBundle:AccClients')->findOneBy(array(
  3012.                 'clientId' => $so->getClientId(),
  3013.             ));
  3014.             if ($client->getCreditLimitEnabled() != 1) {
  3015.                 $allowed 1;
  3016.             } else {
  3017.                 $creditLimit $client->getCreditLimit();
  3018.                 $due $client->getClientDue();
  3019.                 if ($creditLimit >= ($due $total_sales_amount))
  3020.                     $allowed 1;
  3021.             }
  3022.             //now package data
  3023.             if ($allowed == 0) {
  3024.                 return new JsonResponse(array(
  3025.                     'success' => false,
  3026. //                        'documentHash' => $order->getDocumentHash(),
  3027.                     'documentId' => $receiptId,
  3028.                     'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3029.                     'viewUrl' => '',
  3030.                 ));
  3031.             }
  3032.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  3033.             $dochash $request->request->get('docHash'); //change
  3034.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3035.             $approveRole 1;  //created
  3036.             $approveHash $request->request->get('approvalHash');
  3037.             $receiptId $request->request->get('deliveryReceiptId');
  3038.             $sig DocValidation::isSignatureOk($em$loginId$approveHash);
  3039. //            $this->addFlash(
  3040. //                'success',
  3041. //                'New Transaction Added.'
  3042. //            );
  3043.             $success $sig == false true;
  3044.             if ($success == true) {
  3045.                 $QD $this->getDoctrine()
  3046.                     ->getRepository('ApplicationBundle:DeliveryReceipt')
  3047.                     ->findOneBy(
  3048.                         array(
  3049.                             'deliveryReceiptId' => $receiptId
  3050.                         ),
  3051.                         array()
  3052.                     );
  3053.                 $draftFlag $QD->getDraftFlag();
  3054.                 if ($draftFlag == 1) {
  3055.                     //now add Approval info
  3056.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3057.                     $approveRole 1;  //created
  3058.                     System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3059.                         $receiptId,
  3060.                         $loginId,
  3061.                         $approveRole,
  3062.                         $request->request->get('approvalHash'));
  3063.                     $options = array(
  3064.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3065.                         'notification_server' => $this->container->getParameter('notification_server'),
  3066.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3067.                         'url' => $this->generateUrl(
  3068.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  3069.                             ['entity_view_route_path_name']
  3070.                         )
  3071.                     );
  3072.                     System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3073.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3074.                         $receiptId,
  3075.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3076.                     );
  3077.                     $QD->setDraftFlag(0);
  3078.                     $em->flush();
  3079.                 }
  3080.                 $url $this->generateUrl(
  3081.                     'view_delivery_receipt'
  3082.                 );
  3083.                 if ($request->request->has('returnJson')) {
  3084. //                    $dr = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  3085. //                        array(
  3086. //                            'salesOrderId' => $orderId, ///material
  3087. //
  3088. //                        )
  3089. //                    );
  3090.                     return new JsonResponse(array(
  3091.                         'success' => true,
  3092. //                        'documentHash' => $order->getDocumentHash(),
  3093.                         'documentId' => $receiptId,
  3094.                         'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3095.                         'viewUrl' => $url "/" $receiptId,
  3096.                     ));
  3097.                 } else {
  3098.                     $this->addFlash(
  3099.                         'success',
  3100.                         'Action Successful'
  3101.                     );
  3102.                     return $this->redirect($url "/" $receiptId);
  3103.                 }
  3104.             }
  3105.         }
  3106.         return new JsonResponse(array(
  3107.             'success' => false,
  3108. //                        'documentHash' => $order->getDocumentHash(),
  3109.             'documentId' => $receiptId,
  3110.             'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3111.             'viewUrl' => '',
  3112.         ));
  3113.     }
  3114.     public function CreateServiceChallanAction(Request $request)
  3115.     {
  3116.         $em $this->getDoctrine()->getManager();
  3117.         if ($request->isMethod('POST')) {
  3118.             $entity_id array_flip(GeneralConstant::$Entity_list)['ServiceChallan']; //change
  3119.             $dochash $request->request->get('docHash'); //change
  3120.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3121.             $approveRole $request->request->get('approvalRole');
  3122.             $approveHash $request->request->get('approvalHash');
  3123.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  3124.                 $loginId$approveRole$approveHash)
  3125.             ) {
  3126.                 $this->addFlash(
  3127.                     'error',
  3128.                     'Sorry Could not insert Data.'
  3129.                 );
  3130.             } else {
  3131.                 $receiptId SalesOrderM::CreateNewServiceChallan($this->getDoctrine()->getManager(), $request->request,
  3132.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  3133.                     $this->getLoggedUserCompanyId($request));
  3134.                 //now add Approval info
  3135.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3136. //                $approveRole = 1;  //created
  3137.                 $options = array(
  3138.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3139.                     'notification_server' => $this->container->getParameter('notification_server'),
  3140.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3141.                     'url' => $this->generateUrl(
  3142.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ServiceChallan']]
  3143.                         ['entity_view_route_path_name']
  3144.                     )
  3145.                 );
  3146.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3147.                     array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3148.                     $receiptId,
  3149.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3150.                 );
  3151.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3152.                     $receiptId,
  3153.                     $loginId,
  3154.                     $approveRole,
  3155.                     $request->request->get('approvalHash'));
  3156.                 $this->addFlash(
  3157.                     'success',
  3158.                     'New Service Challan Created'
  3159.                 );
  3160.                 $url $this->generateUrl(
  3161.                     'view_service_challan'
  3162.                 );
  3163.                 return $this->redirect($url "/" $receiptId);
  3164.             }
  3165.         }
  3166.         return $this->render('@Inventory/pages/input_forms/create_service_challan.html.twig',
  3167.             array(
  3168.                 'page_title' => 'New Service Challan',
  3169.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  3170.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  3171.                 'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  3172.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  3173.                 'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
  3174.                 'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
  3175.                 'deliveryOrders' => SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
  3176.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
  3177.                 'serviceList' => Inventory::ServiceList($em$this->getLoggedUserCompanyId($request))
  3178.             )
  3179.         );
  3180.     }
  3181.     public function GetItemListForDrAction(Request $request)
  3182.     {
  3183.         $em $this->getDoctrine()->getManager();
  3184.         $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3185.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3186.         if ($request->isMethod('POST')) {
  3187.             $em $this->getDoctrine();
  3188.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3189.             );
  3190.             $Content = [];
  3191.             $Transport_data = [];
  3192.             $Lul_data = [];
  3193.             if ($request->request->get('doId') != '')
  3194.                 $find_array['deliveryOrderId'] = $request->request->get('doId');
  3195. //            if($request->request->get('warehouseId')!='')
  3196. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3197.             $QD $this->getDoctrine()
  3198.                 ->getRepository('ApplicationBundle:DeliveryOrderItem')
  3199.                 ->findBy(
  3200.                     $find_array,
  3201.                     array()
  3202.                 );
  3203. //            if($request->request->get('wareHouseId')!='')
  3204.             $DO $this->getDoctrine()
  3205.                 ->getRepository('ApplicationBundle:DeliveryOrder')
  3206.                 ->findOneBy(
  3207.                     $find_array,
  3208.                     array()
  3209.                 );
  3210.             $sendData = array(
  3211. //                'salesType'=>$SO->getSalesType(),
  3212. //                'packageData'=>[],
  3213.                 'productList' => [],
  3214. //                'productListByPackage'=>[],
  3215.             );
  3216.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3217.             $pckg_item_cross_match_data = [];
  3218.             $unitList Inventory::UnitTypeList($em);
  3219.             $colorList Inventory::GetColorList($em);
  3220.             foreach ($QD as $product) {
  3221. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  3222.                 if (($product->getBalance()) <= 0)
  3223.                     continue;
  3224.                 $fdm $product->getProductFdm();
  3225.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3226.                 $find_query = array();
  3227.                 $soItem $this->getDoctrine()
  3228.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  3229.                     ->findOneBy(
  3230.                         array(
  3231.                             'id' => $product->getSalesorderItemId()
  3232.                         )
  3233.                     );
  3234.                 if (!$soItem)
  3235.                     continue;
  3236. //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3237. //                $soBalance = $soItem->getBalance();
  3238.                 $soBalance $soItem->getQty();
  3239. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3240. //                $doBalance = $product->getBalance();
  3241.                 $doBalance $product->getQty();
  3242.                 //now check if any so ir do item id there that is at
  3243.                 //least pending
  3244.                 $approvalPendingDrs $this->getDoctrine()
  3245.                     ->getRepository('ApplicationBundle:DeliveryReceipt')
  3246.                     ->findBy(
  3247.                         array(
  3248.                             'deliveryOrderId' => $DO->getDeliveryOrderId(),
  3249.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3250.                         )
  3251.                     );
  3252.                 foreach ($approvalPendingDrs as $appPendDr) {
  3253.                     $appPendDrItem $this->getDoctrine()
  3254.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3255.                         ->findOneBy(
  3256.                             array(
  3257.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3258.                                 'salesorderItemId' => $product->getSalesorderItemId()
  3259.                             )
  3260.                         );
  3261.                     if ($appPendDrItem) {
  3262.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3263.                             $soBalance $soBalance $appPendDrItem->getQty();
  3264.                             $doBalance $doBalance $appPendDrItem->getQty();
  3265.                         }
  3266.                     }
  3267.                 }
  3268.                 $colorId $product->getColorId();
  3269.                 $size $product->getSizeId();
  3270. //                $find_query['colorId']=
  3271.                 if ($productData['productId'] != 0) {
  3272.                     $find_query['productId'] = $productData['productId'];
  3273.                     if ($colorId == '' || $colorId == || $colorId == null)
  3274.                         $colorId $productData['defaultColorId'];
  3275.                     if ($size == '' || $size == || $size == null)
  3276.                         $size $productData['defaultSize'];
  3277.                     $find_query['productId'] = $productData['productId'];
  3278.                 } else {
  3279.                     if ($productData['igId'] != 0) {
  3280.                         $find_query['igId'] = $productData['igId'];
  3281.                     }
  3282.                     if ($productData['categoryId'] != 0) {
  3283.                         $find_query['categoryId'] = $productData['categoryId'];
  3284.                     }
  3285.                     if ($productData['subCategoryId'] != 0) {
  3286.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3287.                     }
  3288.                     if ($productData['brandId'] != 0) {
  3289.                         $find_query['brandId'] = $productData['brandId'];
  3290.                     }
  3291.                 }
  3292.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3293.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3294.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3295. //                    $find_query['color'] = $colorId;
  3296.                 } else
  3297.                     $find_query['color'] = $colorId;
  3298.                 if ($size == '' || $size == || $size == null) {
  3299. //                    $find_query['size'] = $size;
  3300.                 } else
  3301.                     $find_query['size'] = 0;
  3302.                 $inventory_by_warehouse_list $this->getDoctrine()
  3303.                     ->getRepository('ApplicationBundle:InventoryStorage')
  3304.                     ->findBy(
  3305.                         $find_query,
  3306.                         array()
  3307.                     );
  3308.                 $new_pid $productData['productId'];
  3309.                 $p_data = array(
  3310.                     'details_id' => $product->getId(),
  3311. //                        'productId'=>$new_pid,
  3312.                     'productIdList' => [],
  3313.                     'multList' => [],
  3314.                     'drItemIds' => [],
  3315.                     'drItemQty' => [],
  3316.                     'drItemCodeIds' => [],
  3317.                     'drItemCartonIds' => [],
  3318.                     'colorIds' => [],
  3319.                     'colorNames' => [],
  3320.                     'sizeIds' => [],
  3321.                     'productNameList' => [],
  3322.                     'availableInventoryList' => [],
  3323.                     'warehouseActionId' => [],
  3324.                     'warehouseActionName' => [],
  3325.                     'availableBarcodes' => [],
  3326.                     'availableBarcodesStr' => [],
  3327. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3328. //                        'available_inventory'=>0,
  3329. //                        'package_id'=>$product->getPackageId(),
  3330.                     'qty' => $product->getQty(),
  3331.                     'delivered' => $product->getDelivered(),
  3332. //                    'deliverable' => $product->getDeliverable() - $product->getTransitQty(),
  3333.                     'deliverable' => min($soBalance$doBalance),
  3334. //                    'balance' => $product->getBalance(),
  3335.                     'balance' => min($soBalance$doBalance),
  3336.                     'productNameFdm' => $product->getProductNameFdm(),
  3337.                     'productFdm' => $product->getProductFdm(),
  3338. //                        'delivered'=>$product->getDelivered(),
  3339.                 );
  3340.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  3341.                     if ($inventory_by_warehouse->getQty() <= 0)
  3342.                         continue;
  3343.                     $unitType $product->getUnitTypeId();
  3344.                     $mult_unit 1;
  3345.                     if ($drId != 0) {
  3346.                         $drItem $this->getDoctrine()
  3347.                             ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3348.                             ->findOneBy(
  3349.                                 array(
  3350.                                     'deliveryReceiptId' => $drId,
  3351.                                     'productId' => $inventory_by_warehouse->getProductId(),
  3352.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  3353.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  3354.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  3355.                                 )
  3356.                             );
  3357.                         if ($drItem) {
  3358.                             $p_data['drItemIds'][] = $drItem->getId();
  3359.                             $p_data['drItemQty'][] = $drItem->getQty();
  3360.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  3361.                             if ($codes == null)
  3362.                                 $codes = [];
  3363.                             $p_data['drItemCodeIds'][] = $codes;
  3364.                             $codes json_decode($drItem->getCartonIds(), true);
  3365.                             if ($codes == null)
  3366.                                 $codes = [];
  3367.                             $p_data['drItemCartonIds'][] = $codes;
  3368.                         } else {
  3369.                             $p_data['drItemIds'][] = 0;
  3370.                             $p_data['drItemQty'][] = 0;
  3371.                             $p_data['drItemCodeIds'][] = 0;
  3372.                             $p_data['drItemCartonIds'][] = 0;
  3373.                         }
  3374.                     } else {
  3375.                         $p_data['drItemIds'][] = 0;
  3376.                         $p_data['drItemQty'][] = 0;
  3377.                         $p_data['drItemCodeIds'][] = 0;
  3378.                         $p_data['drItemCartonIds'][] = 0;
  3379.                     }
  3380.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  3381.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  3382.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  3383.                         }
  3384.                     };
  3385.                     if ($mult_unit == 0)
  3386.                         $mult_unit 1;
  3387.                     $inv_product_id $inventory_by_warehouse->getProductId();
  3388.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  3389.                     $p_data['multList'][] = $mult_unit;
  3390.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  3391.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  3392.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  3393.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  3394.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  3395. //                        $p_data['availableInventoryList'][]=$inventory_by_warehouse?(($inventory_by_warehouse->getQty())*$mult_unit):0;
  3396.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  3397.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  3398.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  3399.                 }
  3400.                 $sendData['productList'][] = $p_data;
  3401.             }
  3402.             //now package data
  3403.             if ($sendData) {
  3404.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3405.             }
  3406.             return new JsonResponse(array("success" => false));
  3407.         }
  3408.         return new JsonResponse(array("success" => false));
  3409.     }
  3410.     public function GetItemListForDrBySoAction(Request $request)
  3411.     {
  3412.         $em $this->getDoctrine()->getManager();
  3413.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3414.         if ($request->isMethod('POST')) {
  3415.             $em $this->getDoctrine();
  3416.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3417. //                'type'=>1//product only
  3418.             );
  3419.             $find_item_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3420.                 'type' => 1//product only
  3421.             );
  3422.             $Content = [];
  3423.             $Transport_data = [];
  3424.             $Lul_data = [];
  3425.             $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3426.             if ($request->request->get('soId') != '') {
  3427.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3428.                 $find_item_array['salesOrderId'] = $request->request->get('soId');
  3429.             }
  3430. //            if($request->request->get('warehouseId')!='')
  3431. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3432.             $QD $this->getDoctrine()
  3433.                 ->getRepository('ApplicationBundle:SalesOrderItem')
  3434.                 ->findBy(
  3435.                     $find_item_array,
  3436.                     array()
  3437.                 );
  3438. //            if($request->request->get('wareHouseId')!='')
  3439.             $DO $this->getDoctrine()
  3440.                 ->getRepository('ApplicationBundle:SalesOrder')
  3441.                 ->findOneBy(
  3442.                     $find_array,
  3443.                     array()
  3444.                 );
  3445.             $sendData = array(
  3446. //                'salesType'=>$SO->getSalesType(),
  3447. //                'packageData'=>[],
  3448.                 'productList' => [],
  3449. //                'productListByPackage'=>[],
  3450.             );
  3451.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3452.             $pckg_item_cross_match_data = [];
  3453.             $unitList Inventory::UnitTypeList($em);
  3454.             $colorList Inventory::GetColorList($em);
  3455.             foreach ($QD as $product) {
  3456.                 if (($product->getBalance() - $product->getTransitQty()) <= 0)
  3457.                     continue;
  3458.                 //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3459. //                $soBalance = $soItem->getBalance();
  3460.                 $soBalance $product->getQty();
  3461. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3462. //                $doBalance = $product->getBalance();
  3463. //                $doBalance = 0;
  3464.                 //now check if any so ir do item id there that is at
  3465.                 //least pending
  3466.                 $approvalPendingDrs $this->getDoctrine()
  3467.                     ->getRepository('ApplicationBundle:DeliveryReceipt')
  3468.                     ->findBy(
  3469.                         array(
  3470.                             'salesOrderId' => $DO->getSalesOrderId(),
  3471.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3472.                         )
  3473.                     );
  3474.                 foreach ($approvalPendingDrs as $appPendDr) {
  3475.                     $appPendDrItem $this->getDoctrine()
  3476.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3477.                         ->findOneBy(
  3478.                             array(
  3479.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3480. //                                'salesorderItemId' => $product->getId(),
  3481.                                 'salesorderItemId' => $product->getId()
  3482.                             )
  3483.                         );
  3484.                     if ($appPendDrItem) {
  3485.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3486.                             $soBalance $soBalance $appPendDrItem->getQty();
  3487.                         }
  3488. //                        $doBalance=$doBalance-$appPendDrItem->getQty();
  3489.                     }
  3490.                 }
  3491.                 $fdm $product->getProductFdm();
  3492.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3493.                 $find_query = array();
  3494.                 $colorId $product->getColorId();
  3495.                 $size $product->getSizeId();
  3496. //                $find_query['colorId']=
  3497.                 if ($productData['productId'] != 0) {
  3498.                     $find_query['productId'] = $productData['productId'];
  3499.                     if ($colorId == '' || $colorId == || $colorId == null)
  3500.                         $colorId $productData['defaultColorId'];
  3501.                     if ($size == '' || $size == || $size == null)
  3502.                         $size $productData['defaultSize'];
  3503.                 } else {
  3504.                     if ($productData['igId'] != 0) {
  3505.                         $find_query['igId'] = $productData['igId'];
  3506.                     }
  3507.                     if ($productData['categoryId'] != 0) {
  3508.                         $find_query['categoryId'] = $productData['categoryId'];
  3509.                     }
  3510.                     if ($productData['subCategoryId'] != 0) {
  3511.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3512.                     }
  3513.                     if ($productData['brandId'] != 0) {
  3514.                         $find_query['brandId'] = $productData['brandId'];
  3515.                     }
  3516.                 }
  3517.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3518.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3519.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3520. //                    $find_query['color'] = $colorId;
  3521.                 } else
  3522.                     $find_query['color'] = $colorId;
  3523.                 if ($size == '' || $size == || $size == null) {
  3524. //                    $find_query['size'] = $size;
  3525.                 } else
  3526.                     $find_query['size'] = 0;
  3527.                 $inventory_by_warehouse_list $this->getDoctrine()
  3528.                     ->getRepository('ApplicationBundle:InventoryStorage')
  3529.                     ->findBy(
  3530.                         $find_query,
  3531.                         array()
  3532.                     );
  3533.                 $new_pid $productData['productId'];
  3534.                 $unitType $product->getUnitTypeId();
  3535.                 $p_data = array(
  3536.                     'details_id' => $product->getId(),
  3537.                     'unitType' => $unitType,
  3538.                     'productIdList' => [],
  3539.                     'multList' => [],
  3540.                     'drItemIds' => [],
  3541.                     'drItemQty' => [],
  3542.                     'drItemCodeIds' => [],
  3543.                     'drItemCartonIds' => [],
  3544.                     'colorIds' => [],
  3545.                     'colorNames' => [],
  3546.                     'sizeIds' => [],
  3547.                     'productNameList' => [],
  3548.                     'availableInventoryList' => [],
  3549.                     'warehouseActionId' => [],
  3550.                     'warehouseActionName' => [],
  3551.                     'availableBarcodes' => [],
  3552.                     'availableBarcodesStr' => [],
  3553. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3554. //                        'available_inventory'=>0,
  3555. //                        'package_id'=>$product->getPackageId(),
  3556.                     'qty' => $product->getQty(),
  3557.                     'delivered' => $product->getDelivered(),
  3558. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  3559. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  3560.                     'deliverable' => $soBalance,
  3561. //                    'deliverable' => $product->getBalance(),
  3562.                     'balance' => $soBalance,
  3563. //                    'balance' => $product->getBalance(),
  3564.                     'productNameFdm' => $product->getProductNameFdm(),
  3565.                     'productFdm' => $product->getProductFdm(),
  3566. //                        'delivered'=>$product->getDelivered(),
  3567.                 );
  3568.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  3569.                     if ($inventory_by_warehouse->getQty() <= 0)
  3570.                         continue;
  3571.                     $mult_unit 1;
  3572.                     if ($drId != 0) {
  3573.                         $drItem $this->getDoctrine()
  3574.                             ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3575.                             ->findOneBy(
  3576.                                 array(
  3577.                                     'deliveryReceiptId' => $drId,
  3578.                                     'productId' => $inventory_by_warehouse->getProductId(),
  3579.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  3580.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  3581.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  3582.                                 )
  3583.                             );
  3584.                         if ($drItem) {
  3585.                             $p_data['drItemIds'][] = $drItem->getId();
  3586.                             $p_data['drItemQty'][] = $drItem->getQty();
  3587.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  3588.                             if ($codes == null)
  3589.                                 $codes = [];
  3590.                             $p_data['drItemCodeIds'][] = $codes;
  3591.                             $codes json_decode($drItem->getCartonIds(), true);
  3592.                             if ($codes == null)
  3593.                                 $codes = [];
  3594.                             $p_data['drItemCartonIds'][] = $codes;
  3595.                         } else {
  3596.                             $p_data['drItemIds'][] = 0;
  3597.                             $p_data['drItemQty'][] = 0;
  3598.                             $p_data['drItemCodeIds'][] = 0;
  3599.                             $p_data['drItemCartonIds'][] = 0;
  3600.                         }
  3601.                     } else {
  3602.                         $p_data['drItemIds'][] = 0;
  3603.                         $p_data['drItemQty'][] = 0;
  3604.                         $p_data['drItemCodeIds'][] = 0;
  3605.                         $p_data['drItemCartonIds'][] = 0;
  3606.                     }
  3607.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  3608.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  3609.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  3610.                         }
  3611.                     };
  3612.                     if ($mult_unit == 0)
  3613.                         $mult_unit 1;
  3614.                     $inv_product_id $inventory_by_warehouse->getProductId();
  3615.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  3616.                     $p_data['multList'][] = $mult_unit;
  3617.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  3618.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  3619.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  3620.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  3621.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  3622.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  3623.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  3624.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  3625.                 }
  3626.                 $sendData['productList'][] = $p_data;
  3627.             }
  3628.             //now package data
  3629.             if ($sendData) {
  3630.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3631.             }
  3632.             return new JsonResponse(array("success" => false));
  3633.         }
  3634.         return new JsonResponse(array("success" => false));
  3635.     }
  3636.     public function GetItemListForStockReqBySoAction(Request $request)
  3637.     {
  3638.         $em $this->getDoctrine()->getManager();
  3639.         if ($request->isMethod('POST')) {
  3640.             $em $this->getDoctrine();
  3641.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3642.             );
  3643.             $Content = [];
  3644.             $Transport_data = [];
  3645.             $Lul_data = [];
  3646.             $find_array['serviceId'] = [0null];
  3647.             $sendData = array(
  3648. //                'salesType'=>$SO->getSalesType(),
  3649. //                'packageData'=>[],
  3650.                 'productList' => [],
  3651. //                'productListByPackage'=>[],
  3652.             );
  3653.             if ($request->request->get('soId') != '') {
  3654.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3655. //            if($request->request->get('warehouseId')!='')
  3656. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3657.                 $QD $this->getDoctrine()
  3658.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  3659.                     ->findBy(
  3660.                         $find_array,
  3661.                         array()
  3662.                     );
  3663. //            if($request->request->get('wareHouseId')!='')
  3664. //            $DO = $this->getDoctrine()
  3665. //                ->getRepository('ApplicationBundle:SalesOrder')
  3666. //                ->findOneBy(
  3667. //                    $find_array,
  3668. //                    array()
  3669. //                );
  3670.                 $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3671.                 $pckg_item_cross_match_data = [];
  3672.                 $unitList Inventory::UnitTypeList($em);
  3673.                 foreach ($QD as $product) {
  3674. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  3675. //                    continue;
  3676.                     $fdm $product->getProductFdm();
  3677.                     $unitType $product->getUnitTypeId();
  3678.                     $p_data = array(
  3679.                         'details_id' => $product->getId(),
  3680.                         'unitType' => $unitType,
  3681.                         'productIdList' => [],
  3682.                         'multList' => [],
  3683.                         'productNameList' => [],
  3684.                         'availableInventoryList' => [],
  3685.                         'warehouseActionId' => [],
  3686.                         'warehouseActionName' => [],
  3687.                         'availableBarcodes' => [],
  3688.                         'availableBarcodesStr' => [],
  3689. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3690. //                        'available_inventory'=>0,
  3691. //                        'package_id'=>$product->getPackageId(),
  3692.                         'qty' => $product->getQty(),
  3693.                         'delivered' => $product->getDelivered(),
  3694. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  3695. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  3696.                         'deliverable' => $product->getBalance(),
  3697.                         'balance' => $product->getBalance(),
  3698.                         'productNameFdm' => $product->getProductNameFdm(),
  3699.                         'productFdm' => $product->getProductFdm(),
  3700. //                        'delivered'=>$product->getDelivered(),
  3701.                     );
  3702.                     $sendData['productList'][] = $p_data;
  3703.                 }
  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 GetBarcodesListForStAction(Request $request)
  3714.     {
  3715.         $em $this->getDoctrine()->getManager();
  3716.         $sendData = [];
  3717.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3718.         if ($request->isMethod('POST')) {
  3719.             $em $this->getDoctrine();
  3720.             $find_query = array();
  3721.             $find_query['warehouseId'] = $request->request->get('warehouseId');
  3722.             $find_query['actionTagId'] = $request->request->get('warehouseActionId');
  3723.             $find_query['productId'] = $request->request->get('productId');
  3724.             $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3725.             $inventory_by_warehouse_list $this->getDoctrine()
  3726.                 ->getRepository('ApplicationBundle:InventoryStorage')
  3727.                 ->findBy(
  3728.                     $find_query,
  3729.                     array()
  3730.                 );
  3731.             $new_pid $request->request->get('productId');
  3732.             $p_data = array();
  3733.             //now get bacodes if available
  3734. //                    $query = "SELECT product_by_code_id, GROUP_CONCAT(DISTINCT sales_code SEPARATOR ',') sales_code_list_str
  3735. //FROM product_by_code
  3736. //where company_id=" . $this->getLoggedUserCompanyId($request).
  3737. //                        " and product_id=".$inv_product_id.
  3738. //                        " and warehouse_id=".$inventory_by_warehouse->getWarehouseId().
  3739. //                        " and warehouse_action_id=".$inventory_by_warehouse->getActionTagId();
  3740. //                        " GROUP BY product_by_code_id" ;
  3741.             $query "SELECT product_by_code_id, sales_code
  3742. FROM product_by_code
  3743. where company_id=" $this->getLoggedUserCompanyId($request) .
  3744.                 " and product_id=" $request->request->get('productId') .
  3745.                 " and warehouse_id=" $request->request->get('warehouseId') .
  3746.                 " and warehouse_action_id=" $request->request->get('warehouseActionId');
  3747.             $stmt $em->getConnection()->prepare($query);
  3748.             $stmt->execute();
  3749.             $results $stmt->fetchAll();
  3750.             $sales_code_list_str '';
  3751.             foreach ($results as $pika => $result) {
  3752.                 if ($pika != 0)
  3753.                     $sales_code_list_str .= ',';
  3754.                 $sales_code_list_str .= str_pad($result['sales_code'], 13'0'STR_PAD_LEFT);
  3755.             }
  3756.             if ($results) {
  3757.                 $p_data['availableBarcodes'] = $sales_code_list_str != '' || $sales_code_list_str != null
  3758.                     explode(','$sales_code_list_str) : [];
  3759.                 $p_data['availableBarcodesStr'] = $sales_code_list_str != '' || $sales_code_list_str != null
  3760.                     $sales_code_list_str "";
  3761. //
  3762.             } else {
  3763.                 $p_data['availableBarcodes'] = [];
  3764.                 $p_data['availableBarcodesStr'] = "";
  3765. //
  3766.             }
  3767.             $sendData $p_data;
  3768.         }
  3769.         //now package data
  3770.         if (!empty($sendData['availableBarcodes'])) {
  3771.             return new JsonResponse(array("success" => true"content" => $sendData));
  3772.         }
  3773.         return new JsonResponse(array("success" => false));
  3774.     }
  3775.     public function GetItemListForSalesReturnAction(Request $request)
  3776.     {
  3777.         if ($request->isMethod('POST')) {
  3778.             $em $this->getDoctrine();
  3779.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3780.             );
  3781.             $Content = [];
  3782.             $Transport_data = [];
  3783.             $Lul_data = [];
  3784.             if ($request->request->get('drId') != '')
  3785.                 $find_array['deliveryReceiptId'] = $request->request->get('drId');
  3786. //            if($request->request->get('warehouseId')!='')
  3787. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3788.             $QD $this->getDoctrine()
  3789.                 ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3790.                 ->findBy(
  3791.                     $find_array,
  3792.                     array()
  3793.                 );
  3794. //            if($request->request->get('wareHouseId')!='')
  3795.             $DR $this->getDoctrine()
  3796.                 ->getRepository('ApplicationBundle:DeliveryReceipt')
  3797.                 ->findOneBy(
  3798.                     $find_array,
  3799.                     array()
  3800.                 );
  3801.             $sendData = array(
  3802.                 'productList' => [],
  3803.             );
  3804.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3805.             $pckg_item_cross_match_data = [];
  3806.             $unitList Inventory::UnitTypeList($em);
  3807.             foreach ($QD as $product) {
  3808.                 if (($product->getQty()) <= 0)
  3809.                     continue;
  3810.                 $new_pid $product->getProductId();
  3811.                 $sales_code_range = [];
  3812.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  3813.                     $sales_code_range json_decode($product->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  3814.                 } else {
  3815.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  3816.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getSalesCodeRange());
  3817.                     $sales_code_range json_decode($json_without_bigintstrue);
  3818.                 }
  3819.                 $p_data = array(
  3820.                     'details_id' => $product->getId(),
  3821.                     'dr_id' => $product->getDeliveryReceiptId(),
  3822.                     'productId' => $new_pid,
  3823.                     'product_name' => isset($productList[$new_pid]) ? $productList[$new_pid]['name'] : '',
  3824.                     'qty' => $product->getQty(),
  3825.                     'delivered' => $product->getDelivered(),
  3826.                     'unitTypeId' => $product->getUnitTypeId(),
  3827.                     'deliverable' => $product->getDeliverable(),
  3828.                     'balance' => $product->getBalance(),
  3829.                     'salesCodeRangeStr' => $product->getSalesCodeRange(),
  3830.                     'salesCodeRange' => $sales_code_range,
  3831.                     'sales_codes' => $sales_code_range,
  3832.                     'sales_price' => $product->getPrice(),
  3833.                     'purchase_price' => $product->getCurrentPurchasePrice()
  3834. //                        'delivered'=>$product->getDelivered(),
  3835.                 );
  3836.                 $sendData['productList'][] = $p_data;
  3837.             }
  3838.             //now package data
  3839.             if ($sendData) {
  3840.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3841.             }
  3842.             return new JsonResponse(array("success" => false));
  3843.         }
  3844.         return new JsonResponse(array("success" => false));
  3845.     }
  3846.     public function GetItemListForIrrAction(Request $request)
  3847.     {
  3848.         if ($request->isMethod('POST')) {
  3849.             $em $this->getDoctrine();
  3850.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3851.             );
  3852.             $Content = [];
  3853.             $Transport_data = [];
  3854.             $Lul_data = [];
  3855.             if ($request->request->get('srId') != '')
  3856.                 $find_array['salesReturnId'] = $request->request->get('srId');
  3857. //            if($request->request->get('warehouseId')!='')
  3858. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3859.             $QD $this->getDoctrine()
  3860.                 ->getRepository('ApplicationBundle:SalesReturnItem')
  3861.                 ->findBy(
  3862.                     $find_array,
  3863.                     array()
  3864.                 );
  3865. //            if($request->request->get('wareHouseId')!='')
  3866.             $sendData = array(
  3867.                 'productList' => [],
  3868.             );
  3869.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3870.             $pckg_item_cross_match_data = [];
  3871.             $unitList Inventory::UnitTypeList($em);
  3872.             foreach ($QD as $product) {
  3873.                 if (($product->getReceivedBalance()) <= && ($product->getReplacedBalance()) <= 0)
  3874.                     continue;
  3875.                 $DR_ITEM null;
  3876.                 $DR_TAGGED_CODES = [];
  3877.                 $DR_TAGGED_CODES_FOR_SELECTIZE = [];
  3878.                 $RESTRICT_RECEIVED_CODES_FLAG 0;
  3879.                 $sales_code_range = [];
  3880.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  3881.                     $sales_code_range json_decode($product->getReceivedCodeRange(), true512JSON_BIGINT_AS_STRING);
  3882.                 } else {
  3883.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  3884.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getReceivedCodeRange());
  3885.                     $sales_code_range json_decode($json_without_bigintstrue);
  3886.                 }
  3887.                 $DR_TAGGED_CODES $sales_code_range;
  3888.                 if (!empty($DR_TAGGED_CODES)) {
  3889.                     $RESTRICT_RECEIVED_CODES_FLAG 1;
  3890.                     foreach ($DR_TAGGED_CODES as $DTC) {
  3891.                         $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  3892.                             'value' => $DTC
  3893.                         );
  3894.                     }
  3895.                 }
  3896. //                if ($product->getTaggedDetailsId() != 0 && $product->getTaggedDetailsId() != null) {
  3897. //
  3898. //                    $DR_ITEM = $this->getDoctrine()
  3899. //                        ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3900. //                        ->findOneBy(
  3901. //                            array(
  3902. //                                'id' => $product->getTaggedDetailsId()
  3903. //                            ),
  3904. //                            array()
  3905. //                        );
  3906. //                    if ($DR_ITEM) {
  3907. //                        if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  3908. //
  3909. //                            $DR_TAGGED_CODES = json_decode($DR_ITEM->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  3910. //                        } else {
  3911. //
  3912. //                            $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  3913. //                            $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $DR_ITEM->getSalesCodeRange());
  3914. //                            $DR_TAGGED_CODES = json_decode($json_without_bigints, true);
  3915. //                        }
  3916. //
  3917. //                        if ($DR_TAGGED_CODES == null)
  3918. //                            $DR_TAGGED_CODES = [];
  3919. //                        if (!empty($DR_TAGGED_CODES)) {
  3920. //                            $RESTRICT_RECEIVED_CODES_FLAG = 1;
  3921. //                            foreach ($DR_TAGGED_CODES as $DTC) {
  3922. //                                $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  3923. //                                    'value' => $DTC
  3924. //                                );
  3925. //                            }
  3926. //                        }
  3927. //                    }
  3928. //                }
  3929.                 $p_data = array(
  3930.                     'details_id' => $product->getId(),
  3931.                     'receivedDrTaggedCodes' => $DR_TAGGED_CODES,
  3932.                     'receivedDrTaggedCodesStr' => implode(','$DR_TAGGED_CODES),
  3933.                     'receivedDrTaggedCodesForSel' => $DR_TAGGED_CODES_FOR_SELECTIZE,
  3934.                     'receivedRestrictCodesFlag' => $RESTRICT_RECEIVED_CODES_FLAG,
  3935.                     'receivedProductId' => $product->getReceivedProductId(),
  3936.                     'receivedBalance' => $product->getReceivedBalance(),
  3937.                     'receivedUnitSalesPrice' => $product->getReceivedUnitSalesPrice(),
  3938.                     'receivedUnitPurchasePrice' => $product->getReceivedUnitPurchasePrice(),
  3939.                     'receivedProductName' => isset($productList[$product->getReceivedProductId()]) ? $productList[$product->getReceivedProductId()]['name'] : '',
  3940.                     'replacedProductId' => $product->getReplacedProductId(),
  3941.                     'replacedBalance' => $product->getReplacedBalance(),
  3942.                     'replacedUnitSalesPrice' => $product->getReplacedUnitSalesPrice(),
  3943.                     'replacedUnitPurchasePrice' => $product->getReplacedUnitPurchasePrice(),
  3944.                     'replacedProductName' => isset($productList[$product->getReplacedProductId()]) ? $productList[$product->getReplacedProductId()]['name'] : '',
  3945.                     'disposeBalance' => $product->getDisposeBalance(),
  3946.                     'unusedBalance' => $product->getUnusedBalance(),
  3947.                     'disposeTag' => $product->getDisposeTag(),
  3948.                     'unitTypeId' => $product->getUnitTypeId(),
  3949. //                        'delivered'=>$product->getDelivered(),
  3950.                 );
  3951.                 $sendData['productList'][] = $p_data;
  3952.             }
  3953.             //now package data
  3954.             if ($sendData) {
  3955.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3956.             }
  3957.             return new JsonResponse(array("success" => false));
  3958.         }
  3959.         return new JsonResponse(array("success" => false));
  3960.     }
  3961.     public function LabelFormatAction(Request $request$id 0)
  3962.     {
  3963.         $data = array(
  3964.             'formatId' => '',
  3965.             'formatCode' => '',
  3966.             'name' => '',
  3967.             'labelType' => 0,
  3968.             'width' => 60,
  3969.             'pageWidth' => 6,
  3970.             'height' => 39,
  3971.             'pageHeight' => 2,
  3972.             'formatData' => '',
  3973.         );
  3974.         if ($request->isMethod('POST')) {
  3975.             $post $request->request;
  3976.             $exists_already 0;
  3977.             if ($request->request->get('formatId') != '') {
  3978.                 $query_here $this->getDoctrine()
  3979.                     ->getRepository('ApplicationBundle:LabelFormat')
  3980.                     ->findOneBy(
  3981.                         array(
  3982.                             'formatId' => $request->request->get('formatId')
  3983.                         )
  3984.                     );
  3985.                 if (!empty($query_here)) {
  3986.                     $exists_already 1;
  3987.                     $new $query_here;
  3988.                 } else
  3989.                     $new = new LabelFormat();
  3990.             } else
  3991.                 $new = new LabelFormat();
  3992.             $new->setName($request->request->get('name'));
  3993.             $new->setLabelType($request->request->get('labelType'));
  3994.             $new->setWidth($request->request->get('width'));
  3995.             $new->setHeight($request->request->get('height'));
  3996.             $new->setFormatCode($request->request->get('formatCode'));
  3997.             $new->setActive(GeneralConstant::ACTIVE);
  3998.             $new->setPageHeight($request->request->get('pageHeight'));
  3999.             $new->setPageWidth($request->request->get('pageWidth'));
  4000.             $new->setFormatData($request->request->get('formatData'));
  4001.             if ($exists_already == 0)
  4002.                 $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4003.             $new->setEditLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4004.             $new->setCompanyId($request->getSession()->get(UserConstants::USER_COMPANY_ID));
  4005.             $em $this->getDoctrine()->getManager();
  4006.             $em->persist($new);
  4007.             $em->flush();
  4008.         }
  4009.         if ($id != 0) {
  4010.             $query_here $this->getDoctrine()
  4011.                 ->getRepository('ApplicationBundle:LabelFormat')
  4012.                 ->findOneBy(
  4013.                     array(
  4014.                         'formatId' => $id
  4015.                     )
  4016.                 );
  4017.             if ($query_here)
  4018.                 $data $query_here;
  4019.         } else if ($request->query->has('formatId')) {
  4020.             $query_here $this->getDoctrine()
  4021.                 ->getRepository('ApplicationBundle:LabelFormat')
  4022.                 ->findOneBy(
  4023.                     array(
  4024.                         'formatId' => $request->query->get('formatId')
  4025.                     )
  4026.                 );
  4027.             if ($query_here)
  4028.                 $data $query_here;
  4029.         }
  4030.         return $this->render(
  4031.             '@Inventory/pages/input_forms/label_format.html.twig',
  4032.             array(
  4033.                 'page_title' => 'Label Format',
  4034.                 'data' => $data,
  4035.                 'labelTypeList' => LabelConstant::$label_type_list,
  4036.                 'labelFieldsList' => LabelConstant::$label_fields_list,
  4037.                 'formatList' => $this->getDoctrine()
  4038.                     ->getRepository('ApplicationBundle:LabelFormat')
  4039.                     ->findBy(
  4040.                         array( //                            'formatId' => $request->query->get('formatId')
  4041.                         )
  4042.                     )
  4043.                 //                'incomeLedgerHeads'=>Accounts::getChildLedgerHeads($this->getDoctrine()->getManager(),AccountsConstant::INCOME)
  4044.             )
  4045.         );
  4046.     }
  4047.     public function GetServiceListForScAction(Request $request)
  4048.     {
  4049.         if ($request->isMethod('POST')) {
  4050.             $em $this->getDoctrine();
  4051.             $find_array = array(
  4052.                 'type' => 2//service
  4053.             );
  4054.             $Content = [];
  4055.             $Transport_data = [];
  4056.             $Lul_data = [];
  4057.             if ($request->request->get('soId') != '')
  4058.                 $find_array['salesOrderId'] = $request->request->get('soId');
  4059. //            if($request->request->get('warehouseId')!='')
  4060. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4061.             $QD $this->getDoctrine()
  4062.                 ->getRepository('ApplicationBundle:SalesOrderItem')
  4063.                 ->findBy(
  4064.                     $find_array,
  4065.                     array()
  4066.                 );
  4067. //            if($request->request->get('wareHouseId')!='')
  4068.             $SO $this->getDoctrine()
  4069.                 ->getRepository('ApplicationBundle:SalesOrder')
  4070.                 ->findOneBy(
  4071.                     array(
  4072.                         'salesOrderId' => $request->request->get('soId')
  4073.                     ),
  4074.                     array()
  4075.                 );
  4076.             $sendData = array(
  4077. //                'salesType'=>$SO->getSalesType(),
  4078. //                'packageData'=>[],
  4079.                 'productList' => [],
  4080. //                'productListByPackage'=>[],
  4081.             );
  4082.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager(), $SO->getCompanyId());
  4083.             $pckg_item_cross_match_data = [];
  4084.             foreach ($QD as $product) {
  4085.                 $p_data = array(
  4086.                     'details_id' => $product->getId(),
  4087.                     'service_id' => $product->getServiceId(),
  4088.                     'service_name' => $serviceList[$product->getServiceId()]['name'],
  4089.                     'available_inventory' => $product->getBalance(),
  4090. //                        'package_id'=>$product->getPackageId(),
  4091.                     'qty' => $product->getQty(),
  4092.                     'delivered' => $product->getDelivered(),
  4093. //                    'deliverable'=>$product->getDeliverable(),
  4094.                     'balance' => $product->getBalance(),
  4095. //                        'delivered'=>$product->getDelivered(),
  4096.                 );
  4097.                 $sendData['serviceList'][] = $p_data;
  4098.             }
  4099.             //now package data
  4100.             if ($sendData) {
  4101.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4102.             }
  4103.             return new JsonResponse(array("success" => false));
  4104.         }
  4105.         return new JsonResponse(array("success" => false));
  4106.     }
  4107.     public function CreateReceivedNoteAction(Request $request)
  4108.     {
  4109.         if ($request->isMethod('POST')) {
  4110.             $em $this->getDoctrine()->getManager();
  4111.             $entity_id array_flip(GeneralConstant::$Entity_list)['Grn']; //change
  4112.             $dochash $request->request->get('docHash'); //change
  4113.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4114.             $approveRole 1;  //created
  4115.             $approveHash $request->request->get('approvalHash');
  4116.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4117.                 $loginId$approveRole$approveHash)
  4118.             ) {
  4119.                 $this->addFlash(
  4120.                     'error',
  4121.                     'Sorry Couldnot insert Data.'
  4122.                 );
  4123.             } else {
  4124.                 $data $request->request;
  4125.                 $grnId Inventory::CreateGrn($this->getDoctrine()->getManager(), $data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4126.                 //now add Approval info
  4127.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4128.                 $approveRole 1;  //created
  4129.                 $options = array(
  4130.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4131.                     'notification_server' => $this->container->getParameter('notification_server'),
  4132.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4133.                     'url' => $this->generateUrl(
  4134.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['Grn']]
  4135.                         ['entity_view_route_path_name']
  4136.                     )
  4137.                 );
  4138.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4139.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  4140.                     $grnId,
  4141.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4142.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['Grn'], $grnId,
  4143.                     $loginId,
  4144.                     $approveRole,
  4145.                     $request->request->get('approvalHash'));
  4146.                 $this->addFlash(
  4147.                     'success',
  4148.                     'New GRN Added.'
  4149.                 );
  4150.                 $url $this->generateUrl(
  4151.                     'view_grn'
  4152.                 );
  4153.                 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),
  4154.                     "Good Received Note : " $dochash " Has Been Created And is Under Processing",
  4155.                     'pos',
  4156.                     System::getPositionIdsByDepartment($em, [GeneralConstant::SALES_DEPARTMENTGeneralConstant::PURCHASE_DEPARTMENTGeneralConstant::ACCOUNTS_DEPARTMENTGeneralConstant::INVENTORY_DEPARTMENT]),
  4157.                     'success',
  4158.                     $url "/" $grnId,
  4159.                     "GRN"
  4160.                 );
  4161.                 return $this->redirect($url "/" $grnId);
  4162.             }
  4163.         }
  4164.         return $this->render('@Inventory/pages/input_forms/received_note.html.twig',
  4165.             array(
  4166.                 'page_title' => 'GRN',
  4167.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  4168.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  4169.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  4170.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  4171.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  4172.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  4173.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  4174.                 'material_inward' => $this->getDoctrine()
  4175.                     ->getRepository('ApplicationBundle:MaterialInward')
  4176.                     ->findBy(
  4177.                         array(
  4178.                             'stage' => GeneralConstant::STAGE_PENDING_TAG
  4179.                         )
  4180.                     )
  4181. //                'po'=>Inventory::getPurchaseOrderList
  4182.             )
  4183.         );
  4184.     }
  4185.     public function GetQcListForGrnAction(Request $request)
  4186.     {
  4187.         if ($request->isMethod('POST')) {
  4188.             $find_array = array(
  4189.                 'stage' => GeneralConstant::STAGE_PENDING_TAG
  4190.             );
  4191.             $Content = [];
  4192.             $ContentByProductId = [];
  4193.             $Transport_data = [];
  4194.             $Lul_data = [];
  4195.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4196.             if ($request->request->get('poId') != '')
  4197.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4198.             if ($request->request->get('warehouseId') != '')
  4199.                 $find_array['warehouseId'] = $request->request->get('warehouseId');
  4200.             $QD $this->getDoctrine()
  4201.                 ->getRepository('ApplicationBundle:MaterialInward')
  4202.                 ->findBy(
  4203.                     $find_array,
  4204.                     array(
  4205.                         'inwardDate' => 'ASC',
  4206.                         'qcDate' => 'ASC'
  4207.                     )
  4208.                 );
  4209.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4210.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4211.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4212.             $lotNumArray = [];
  4213.             foreach ($QD as $entry) {
  4214. //                $inwardDate=strtotime($entry->getInwardDate());
  4215. //                $qcDate=strtotime($entry->getQcDate());
  4216.                 $inwardDate = ($entry->getInwardDate() instanceof \DateTime) ? $entry->getInwardDate()->format('m/d/Y') : '';
  4217.                 $qcDate = ($entry->getQcDate() instanceof \DateTime) ? $entry->getQcDate()->format('m/d/Y') : '';
  4218.                 if (!in_array($entry->getLotNumber(), $lotNumArray))
  4219.                     $lotNumArray[] = $entry->getLotNumber();
  4220.                 if (isset($ContentByProductId[$entry->getPurchaseOrderItemId()])) {
  4221.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['inwardDateList'][] = $inwardDate;
  4222.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcDateList'][] = $inwardDate;
  4223.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcIdList'][] = $entry->getQcId();
  4224.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['appQtyList'][] = $entry->getApprovedQty();
  4225.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['totQty'] += ($entry->getApprovedQty());
  4226.                 } else {
  4227.                     $ContentByProductId[$entry->getPurchaseOrderItemId()] = array(
  4228.                         'productName' => $productList[$entry->getProductId()]['name'],
  4229.                         'productUnitName' => $unitList[$productList[$entry->getProductId()]['unit_type']]['name'],
  4230.                         'qcHash' => $entry->getDocumentHash(),
  4231.                         'warehouseName' => $warehouse[$entry->getWarehouseId()]['name'],
  4232.                         'inwardDate' => $inwardDate,
  4233.                         'inwardDateList' => [$inwardDate],
  4234.                         'qcDateList' => [$qcDate],
  4235.                         'qcIdList' => [$entry->getQcId()],
  4236.                         'qcDate' => $qcDate,
  4237.                         'poQty' => $entry->getPoQty(),
  4238.                         'poPrevbalance' => $entry->getPoBalance(),
  4239.                         'appQty' => $entry->getApprovedQty(),
  4240.                         'appQtyList' => [$entry->getApprovedQty()],
  4241.                         'totQty' => $entry->getApprovedQty(),
  4242.                         'poBalance' => $entry->getPoBalance() - $entry->getApprovedQty(),
  4243.                         'qcId' => $entry->getQcId(),
  4244.                         'productId' => $entry->getProductId()
  4245.                     );
  4246.                 }
  4247.                 $Expense_Cost[$entry->getQcId()] = json_decode($entry->getExpenseCost());
  4248.                 $Expense_Id[$entry->getQcId()] = json_decode($entry->getExpenseId());
  4249.             }
  4250.             foreach ($ContentByProductId as $c) {
  4251.                 $Content[] = $c;
  4252.             }
  4253.             if ($QD) {
  4254.                 return new JsonResponse(array("success" => true"content" => $Content"lotNumber" => implode(', '$lotNumArray), 'Expense_Cost' => $Expense_Cost'Expense_Id' => $Expense_Id));
  4255.             }
  4256.             return new JsonResponse(array("success" => false));
  4257.         }
  4258.         return new JsonResponse(array("success" => false));
  4259.     }
  4260.     public function GetSrListForIrAction(Request $request)
  4261.     {
  4262.         if ($request->isMethod('POST')) {
  4263.             $find_array = array();
  4264.             $Content = [];
  4265.             if ($request->request->get('srId') != '')
  4266.                 $find_array['stockRequisitionId'] = $request->request->get('srId');
  4267.             $find_array['forceSkipTag'] = [0null];
  4268.             $QD $this->getDoctrine()
  4269.                 ->getRepository('ApplicationBundle:StockRequisitionItem')
  4270.                 ->findBy(
  4271.                     $find_array
  4272.                 );
  4273.             $itemList Inventory::ItemGroupList($this->getDoctrine()->getManager());
  4274.             $catgoryList Inventory::ProductCategoryList($this->getDoctrine()->getManager());
  4275.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4276.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4277.             $fdmData = array();
  4278.             $em $this->getDoctrine()->getManager();
  4279.             $matchType 'MAXIMUM';
  4280.             if ($request->request->has('matchType') != '') {
  4281.                 $matchType $request->request->get('matchType');
  4282.             }
  4283.             if ($matchType == 'MINIMUM') {
  4284.                 foreach ($QD as $entry) {
  4285.                     if ($entry->getTagPendingAmount() <= 0)
  4286.                         continue;
  4287.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4288.                     $combined_id $entry->getProductFdm();
  4289.                     if (isset($fdmData[$combined_id])) {
  4290.                         $fdmData[$combined_id]['unit'] += $entry->getTagPendingAmount();
  4291.                         $fdmData[$combined_id]['specific_unit'][] = $entry->getTagPendingAmount();
  4292.                         $fdmData[$combined_id]['detailsIds'][] = $entry->getId();
  4293.                         $fdmData[$combined_id]['docIds'][] = $entry->getStockRequisitionId();
  4294.                     } else {
  4295.                         $fdmData[$combined_id] = array(
  4296.                             'id' => 0,
  4297.                             'alias' => $entry->getNote(),
  4298.                             'unit' => $entry->getTagPendingAmount(),
  4299.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4300.                             'warranty' => 0,
  4301.                             'unitTypeId' => 0,
  4302.                             'unit_price' => 0,
  4303.                             'fdm' => $combined_id,
  4304.                             'extDetailsId' => 0,
  4305.                             'product_name' => $productData['productName'],
  4306.                             'total_price' => 0,
  4307.                             'detailsIds' => [$entry->getId()],
  4308.                             'docIds' => [$entry->getStockRequisitionId()],
  4309.                         );
  4310.                     }
  4311.                 }
  4312.             }
  4313.             if ($matchType == 'MAXIMUM') {
  4314.                 foreach ($QD as $entry) {
  4315.                     if ($entry->getTagPendingAmount() <= 0)
  4316.                         continue;
  4317.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4318.                     $combined_id $entry->getProductFdm();
  4319.                     $assigned 0;
  4320.                     foreach ($fdmData as $key_ind => $rel_val) {
  4321.                         $matchFdm Inventory::MatchFdm($key_ind$combined_id);
  4322.                         if ($matchFdm['hasMatched'] == 1) {
  4323.                             if ($matchFdm['isIdentical'] == 1) {
  4324.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4325.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4326.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4327.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4328.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4329.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4330.                                 $assigned 1;
  4331.                             } elseif ($matchFdm['SecondBelongsToFirst'] == 1) {
  4332.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4333.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4334.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4335.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4336.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4337.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4338.                                 $assigned 1;
  4339.                             } elseif ($matchFdm['FirstBelongsToSecond'] == 1) {
  4340.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4341.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4342.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4343.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4344.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4345.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4346.                                 $fdmData[$combined_id] = $fdmData[$key_ind];
  4347.                                 unset($fdmData[$key_ind]);
  4348.                                 $assigned 1;
  4349.                             }
  4350.                         } else {
  4351.                         }
  4352.                         if ($assigned == 1)
  4353.                             break;
  4354.                     }
  4355.                     if ($assigned == 0) {
  4356.                         $fdmData[$combined_id] = array(
  4357.                             'id' => 0,
  4358.                             'alias' => $entry->getNote(),
  4359.                             'unit' => $entry->getTagPendingAmount(),
  4360.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4361.                             'specific_unit_type_id' => [$entry->getUnitTypeId()],
  4362.                             'warranty' => 0,
  4363.                             'unitTypeId' => $productData['unitTypeId'],
  4364. //                            'unitTypeId' => $productData['unitTypeId'],
  4365.                             'unit_price' => 0,
  4366.                             'fdm' => $combined_id,
  4367.                             'extDetailsId' => 0,
  4368.                             'product_name' => htmlspecialchars($productData['productName']),
  4369.                             'total_price' => 0,
  4370.                             'detailsIds' => [$entry->getId()],
  4371.                             'docIds' => [$entry->getStockRequisitionId()],
  4372.                         );
  4373.                     }
  4374.                     if (isset($fdmData[$combined_id])) {
  4375.                     } else {
  4376.                     }
  4377.                 }
  4378.             }
  4379.             $QD $this->getDoctrine()
  4380.                 ->getRepository('ApplicationBundle:StockRequisition')
  4381.                 ->findBy(
  4382.                     array('stockRequisitionId' => $request->request->get('srId'))
  4383.                 );
  4384.             $contentNote "";
  4385.             foreach ($QD as $r) {
  4386.                 $contentNote .= $r->getNote();
  4387.                 $contentNote .= " , ";
  4388.             }
  4389.             foreach ($fdmData as $dt) {
  4390.                 $Content[] = $dt;
  4391.             }
  4392.             if ($Content) {
  4393.                 return new JsonResponse(array("success" => true"content" => $Content"contentNote" => $contentNote));
  4394.             }
  4395.             return new JsonResponse(array("success" => false));
  4396.         }
  4397.         return new JsonResponse(array("success" => false));
  4398.     }
  4399.     public function GetGrnListForEiAction(Request $request)
  4400.     {
  4401.         if ($request->isMethod('POST')) {
  4402.             $find_array = array(
  4403.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  4404.                 'approved' => GeneralConstant::APPROVED,
  4405.                 'invoiceTagged' => 1
  4406.             );
  4407.             $Content = [];
  4408.             $Content_obj = [];
  4409.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4410.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4411.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4412.             if ($request->request->get('poId') != '')
  4413.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4414.             if ($request->request->get('grnId') != '')
  4415.                 $find_array['grnId'] = $request->request->get('grnId');
  4416.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4417.             $QD_GRN $this->getDoctrine()
  4418.                 ->getRepository('ApplicationBundle:Grn')
  4419.                 ->findBy(
  4420.                     $find_array,
  4421.                     array(
  4422.                         'grnDate' => 'ASC'
  4423.                     )
  4424.                 );
  4425.             $poId 0;
  4426. //
  4427. //            $expense_id=$QD_GRN->getExpenseId()!=''?json_decode($QD_GRN->getExpenseId()):[];
  4428. //                $expense_list=$QD_GRN->getExpenseCost()!=''?json_decode($QD_GRN->getExpenseCost()):[];
  4429. //                $expense_tagged=$QD_GRN->getExpenseTagged()!=''?json_decode($QD_GRN->getExpenseTagged()):[];
  4430.             $partyId $request->request->get('partyId');
  4431.             $bill_details = [];
  4432.             $bill_details_data = [];
  4433.             $bill_details_for_grn = [];
  4434.             $exp_list InventoryConstant::$Expense_list_details;
  4435.             $supp_list Inventory::ProductSupplierList($this->getDoctrine()->getManager());
  4436.             $head_qry $this->getDoctrine()
  4437.                 ->getRepository('ApplicationBundle:AccAccountsHead')
  4438.                 ->findAll();
  4439.             $head_list = [];
  4440.             $head_list_by_advance = [];
  4441.             foreach ($head_qry as $data) {
  4442.                 $head_list[$data->getAccountsHeadId()] = array(
  4443.                     'id' => $data->getAccountsHeadId(),
  4444.                     'name' => $data->getName(),
  4445.                     'advanceTagged' => $data->getAdvanceTagged(),
  4446.                     'advanceOf' => $data->getAdvanceOf(),
  4447.                     'balance' => $data->getCurrentBalance()
  4448.                 );
  4449.                 if ($data->getAdvanceOf() != null && $data->getAdvanceOf() != && $data->getAdvanceOf() != '')
  4450.                     $head_list_by_advance[$data->getAdvanceOf()] = array(
  4451.                         'id' => $data->getAccountsHeadId(),
  4452.                         'name' => $data->getName(),
  4453.                         'advanceTagged' => $data->getAdvanceTagged(),
  4454.                         'advanceOf' => $data->getAdvanceOf(),
  4455.                         'balance' => $data->getCurrentBalance()
  4456.                     );
  4457.             }
  4458.             $exp_def_head = [];
  4459.             foreach ($exp_list as $key => $item) {
  4460.                 $def_settings $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  4461.                     'name' => $item['name'] . '_onsite_head'
  4462.                 ));
  4463.                 if ($def_settings)
  4464.                     $exp_def_head[$item['id']] = $def_settings->getData();
  4465.                 else
  4466.                     $exp_def_head[$item['id']] = '';
  4467.             }
  4468.             $bill_details_by_party = [];
  4469. //            System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($QD_GRN),'debug_data');
  4470. //            System::log_it($this->container->getParameter('kernel.root_dir'),$partyId,'debug_data');
  4471. //            System::log_it($this->container->getParameter('kernel.root_dir'),"\nexp list here".json_encode($exp_list),'debug_data');
  4472. //
  4473.             foreach ($QD_GRN as $key => $value) {
  4474.                 $expense_id $value->getExpenseId() != '' json_decode($value->getExpenseId(), true) : [];
  4475.                 $expense_list $value->getExpenseCost() != '' json_decode($value->getExpenseCost(), true) : [];
  4476.                 $expense_tagged $value->getExpenseTagged() != '' json_decode($value->getExpenseTagged(), true) : [];
  4477. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_id),'debug_data');
  4478. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_list),'debug_data');
  4479.                 foreach ($exp_list as $chabi => $entry) {
  4480. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nChabi ".$chabi,'debug_data');
  4481. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nkeys are ".array_keys($expense_id),'debug_data');
  4482.                     if (array_key_exists($chabi$expense_id)) {
  4483. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nFOUND KEY!! ",'debug_data');
  4484.                         if ($partyId == ''//all
  4485.                         {
  4486.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  4487.                                 $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  4488.                                 $advance_balance 0;
  4489.                                 if ($partyHeadId != 0) {
  4490.                                     $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  4491.                                     $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  4492.                                     $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  4493.                                 }
  4494.                                 $bill_details_by_party[$my_val][] = array(
  4495.                                     'partyId' => $my_val,
  4496.                                     'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  4497.                                     'partyHeadId' => $partyHeadId,
  4498.                                     'expTypeId' => $chabi,
  4499.                                     'expTypeName' => $exp_list[$chabi]['name'],
  4500.                                     'expTypeAlias' => $exp_list[$chabi]['alias'],
  4501.                                     'expAmount' => $expense_list[$chabi][$index],
  4502.                                     'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  4503.                                     'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  4504.                                     'AdvanceBalance' => $advance_balance,
  4505.                                     'grnId' => $value->getGrnId(),
  4506.                                     'grnName' => $value->getDocumentHash(),
  4507.                                 );
  4508.                             }
  4509.                         } else {
  4510.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  4511.                                 if (in_array($my_val$partyId)) {
  4512.                                     $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  4513.                                     $advance_balance 0;
  4514.                                     if ($partyHeadId != 0) {
  4515.                                         $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  4516.                                         $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  4517.                                         $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  4518.                                     }
  4519.                                     $bill_details_by_party[$my_val][] = array(
  4520.                                         'partyId' => $my_val,
  4521.                                         'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  4522.                                         'partyHeadId' => $partyHeadId,
  4523.                                         'expTypeId' => $chabi,
  4524.                                         'expTypeName' => $exp_list[$chabi]['name'],
  4525.                                         'expTypeAlias' => $exp_list[$chabi]['alias'],
  4526.                                         'expAmount' => $expense_list[$chabi][$index],
  4527.                                         'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  4528.                                         'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  4529.                                         'AdvanceBalance' => $advance_balance,
  4530.                                         'grnId' => $value->getGrnId(),
  4531.                                         'grnName' => $value->getDocumentHash(),
  4532.                                     );
  4533.                                 }
  4534.                             }
  4535.                         }
  4536.                     }
  4537.                 }
  4538.             }
  4539. //            $Content_obj=
  4540. //
  4541. //            foreach($Content_obj as $item)
  4542. //            {
  4543. //                $Content[]=$item;
  4544. //
  4545. //            }
  4546.             $list_of_keys array_keys($bill_details_by_party);
  4547.             if ($bill_details_by_party) {
  4548.                 return new JsonResponse(array("success" => true"content" => $bill_details_by_party'index' => $list_of_keys'h_l_b_a' => $head_list_by_advance));
  4549.             }
  4550.             return new JsonResponse(array("success" => false));
  4551.         }
  4552.         return new JsonResponse(array("success" => false));
  4553.     }
  4554.     public function GetServiceListForPiAction(Request $request)
  4555.     {
  4556.         if ($request->isMethod('POST')) {
  4557. //            $find_array=array(
  4558. //                'stage' =>  GeneralConstant::STAGE_PENDING_TAG,
  4559. //                'approved'=>GeneralConstant::APPROVED
  4560. //            );
  4561.             $Content = [];
  4562.             $Content_obj = [];
  4563.             $ContentService = [];
  4564.             $Content_service_obj = [];
  4565. //            $warehouse=Inventory::WarehouseList($this->getDoctrine()->getManager());
  4566. //            $poList=Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4567. //            $productList=Inventory::ProductList($this->getDoctrine()->getManager());
  4568.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  4569.             if ($request->request->get('poId') != '')
  4570.                 $poId $request->request->get('poId');
  4571.             if ($request->request->get('grnId') != '')
  4572.                 $find_array['grnId'] = $request->request->get('grnId');
  4573.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4574.             //adding service data temporarily
  4575.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(
  4576.                 array('purchaseOrderId' => $poId));
  4577.             $multiply_type $po->getCurrencyMultiply();
  4578.             $multiply_rate $po->getCurrencyMultiplyRate();
  4579.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  4580.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  4581.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4582.                 array('purchaseOrderId' => $poId));
  4583.             foreach ($po_items as $item) {
  4584. //                $po_item_list[$item->getProductId()]=$item;
  4585.                 //temporary service add
  4586.                 if ($item->getType() == 2)
  4587.                     $Content_service_obj[$item->getId()] = array(
  4588.                         'serviceId' => $item->getServiceId(),
  4589.                         'poItemId' => $item->getId(),
  4590.                         'colorId' => 0,
  4591.                         'sizeId' => 0,
  4592.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  4593.                         'qty' => $item->getQty(),
  4594.                         'balance' => $item->getBalance(),
  4595.                         'unit_name' => '',
  4596.                         'unit_price' => $item->getPrice() * $multiplier,
  4597.                         'grn_id' => 0,
  4598.                     );
  4599.                 //temprary service add end
  4600.             }
  4601.             //temporary service data adding done
  4602.             $po_data = [];
  4603.             $po_data = array(
  4604.                 'docHash' => $po->getDocumentHash(),
  4605.                 'docDate' => $po->getPurchaseOrderDate(),
  4606.                 'supplierId' => $po->getSupplierId(),
  4607.                 'supplierName' => $po->getSupplierId(),
  4608.                 'vatRate' => $po->getVatRate(),
  4609.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  4610.                 'aitRate' => $po->getAitRate(),
  4611.                 'aitAmount' => $po->getAitAmount(),
  4612.                 'tdsRate' => $po->getTdsRate(),
  4613.                 'tdsAmount' => $po->getTdsAmount(),
  4614.                 'vdsRate' => $po->getVdsRate(),
  4615.                 'vdsAmount' => $po->getVdsAmount(),
  4616.                 'discountRate' => $po->getDiscountRate(),
  4617.                 'discountAmount' => $po->getVatAmount(),
  4618.             );
  4619.             foreach ($Content_obj as $item) {
  4620.                 $Content[] = $item;
  4621.             }
  4622.             foreach ($Content_service_obj as $item) {
  4623.                 $ContentService[] = $item;
  4624.             }
  4625.             if ($Content || $ContentService) {
  4626.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  4627.             }
  4628.             return new JsonResponse(array("success" => false));
  4629.         }
  4630.         return new JsonResponse(array("success" => false));
  4631.     }
  4632.     public function GetGrnListForPiAction(Request $request)
  4633.     {
  4634.         if ($request->isMethod('POST')) {
  4635.             $find_array = array(
  4636.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  4637.                 'approved' => GeneralConstant::APPROVED
  4638.             );
  4639.             $Content = [];
  4640.             $Content_obj = [];
  4641.             $ContentService = [];
  4642.             $Content_service_obj = [];
  4643.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4644.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4645.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4646.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  4647.             if ($request->request->get('poId') != '')
  4648.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4649.             if ($request->request->get('grnId') != '')
  4650.                 $find_array['grnId'] = $request->request->get('grnId');
  4651.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4652.             $QD_GRN $this->getDoctrine()
  4653.                 ->getRepository('ApplicationBundle:Grn')
  4654.                 ->findBy(
  4655.                     $find_array,
  4656.                     array(
  4657.                         'grnDate' => 'ASC'
  4658.                     )
  4659.                 );
  4660.             $poId 0;
  4661.             foreach ($QD_GRN as $value) {
  4662.                 $grn_items $this->getDoctrine()->getRepository('ApplicationBundle:GrnItem')->findBy(
  4663.                     array('grnId' => $value->getGrnId()));
  4664.                 $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4665.                     array('purchaseOrderId' => $value->getPurchaseOrderId()));
  4666.                 $poId $value->getPurchaseOrderId();
  4667.                 $po_item_list = [];
  4668.                 foreach ($po_items as $item) {
  4669.                     $po_item_list[$item->getProductId()] = $item;
  4670.                 }
  4671.                 foreach ($grn_items as $entry) {
  4672.                     //adding transaction
  4673. //                    System::log_it($this->container->getParameter('kernel.root_dir'),$entry->getProductId(),'debug_data');
  4674.                     $Content_obj[$entry->getId()] = array(
  4675.                         'productId' => $entry->getProductId(),
  4676.                         'poItemId' => $entry->getPurchaseOrderItemId(),
  4677.                         'productName' => $productList[$entry->getProductId()]['name'],
  4678.                         'colorId' => $entry->getColorId(),
  4679.                         'sizeId' => $entry->getSizeId(),
  4680.                         'qty' => isset($Content_obj[$entry->getId()]) ? $Content_obj[$entry->getId()]['qty'] + $entry->getQty() : $entry->getQty(),
  4681.                         'unit_name' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  4682. //                            'unit_price'=>$po_item_list[$entry->getProductId()]->getPrice(),
  4683.                         'unit_price' => $entry->getPrice(),
  4684.                         'grn_id' => $entry->getId(),
  4685.                     );
  4686.                 }
  4687. //            for
  4688.             }
  4689.             //adding service data temporarily
  4690.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(
  4691.                 array('purchaseOrderId' => $poId));
  4692.             $multiply_type $po->getCurrencyMultiply();
  4693.             $multiply_rate $po->getCurrencyMultiplyRate();
  4694.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  4695.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  4696.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4697.                 array('purchaseOrderId' => $poId));
  4698.             foreach ($po_items as $item) {
  4699. //                $po_item_list[$item->getProductId()]=$item;
  4700.                 //temporary service add
  4701.                 if ($item->getType() == 2)
  4702.                     $Content_service_obj[$item->getId()] = array(
  4703.                         'serviceId' => $item->getServiceId(),
  4704.                         'poItemId' => $item->getId(),
  4705.                         'colorId' => 0,
  4706.                         'sizeId' => 0,
  4707.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  4708.                         'qty' => $item->getQty(),
  4709.                         'balance' => $item->getBalance(),
  4710.                         'unit_name' => '',
  4711.                         'unit_price' => $item->getPrice() * $multiplier,
  4712.                         'grn_id' => 0,
  4713.                     );
  4714.                 //temprary service add end
  4715.             }
  4716.             //temporary service data adding done
  4717.             $po_data = [];
  4718.             $vatAmount 1*$po->getVatAmount();
  4719.             $priceAfterDiscount $po->getSupplierPayableAmount() - $po->getVatAmount();
  4720.             $vatRate = ($vatAmount/$priceAfterDiscount)*100;
  4721.             $po_data = array(
  4722.                 'docHash' => $po->getDocumentHash(),
  4723.                 'docDate' => $po->getPurchaseOrderDate(),
  4724.                 'supplierId' => $po->getSupplierId(),
  4725.                 'supplierName' => $po->getSupplierId(),
  4726.                 'vatRate' => $vatRate,
  4727.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  4728.                 'aitRate' => $po->getAitRate(),
  4729.                 'aitAmount' => $po->getAitAmount(),
  4730.                 'tdsRate' => $po->getTdsRate(),
  4731.                 'tdsAmount' => $po->getTdsAmount(),
  4732.                 'vdsRate' => $po->getVdsRate(),
  4733.                 'vdsAmount' => $po->getVdsAmount(),
  4734.                 'discountRate' => $po->getDiscountRate(),
  4735. //                'discountAmount' => $po->getVatAmount(),
  4736.                 'vatAmount' => $vatAmount,
  4737.                 'discountAmount' => $po->getDiscountAmount(),
  4738.                 'supplierPayableAmount'=> $po->getSupplierPayableAmount(),
  4739.                 'priceAfterDiscount' =>  $priceAfterDiscount
  4740.             );
  4741.             foreach ($Content_obj as $item) {
  4742.                 $Content[] = $item;
  4743.             }
  4744.             foreach ($Content_service_obj as $item) {
  4745.                 $ContentService[] = $item;
  4746.             }
  4747.             if ($Content) {
  4748.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  4749.             }
  4750.             return new JsonResponse(array("success" => false));
  4751.         }
  4752.         return new JsonResponse(array("success" => false));
  4753.     }
  4754.     public function GetPoDetailsForPiAction(Request $request$poId)
  4755.     {
  4756.     }
  4757.     public function GetPoDetailsAction(Request $request$poId)
  4758.     {
  4759.         if ($request->isMethod('POST')) {
  4760.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findBy(
  4761.                 array('purchaseOrderId' => $poId));
  4762.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4763.                 array('purchaseOrderId' => $poId));
  4764.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4765.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4766.             $Content = [];
  4767.             $po_items_list = [];
  4768.             foreach ($po_items as $entry) {
  4769.                 $po_items_list[] = array(
  4770.                     'productId' => $entry->getProductId(),
  4771.                     'productName' => $productList[$entry->getProductId()]['name'],
  4772.                     'price' => $entry->getPrice(),
  4773.                     'unit' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  4774.                     'received' => $entry->getReceived(),
  4775.                     'qty' => $entry->getQty(),
  4776.                     'balance' => $entry->getBalance()
  4777.                 );
  4778.             }
  4779.             $po_data = [];
  4780.             $po_data = array(
  4781.                 'docHash' => $po->getDocumentHash(),
  4782.                 'docDate' => $po->getPurchaseOrderDate(),
  4783.                 'supplierId' => $po->getSupplierId(),
  4784.                 'supplierName' => $po->getSupplierId(),
  4785.             );
  4786.             if ($po_data) {
  4787.                 return new JsonResponse(array("success" => true"content" => $po_data));
  4788.             }
  4789.             return new JsonResponse(array("success" => false));
  4790.         }
  4791.         return new JsonResponse(array("success" => false));
  4792.     }
  4793.     public function CreateSalesReplacementAction(Request $request)
  4794.     {
  4795.         $em $this->getDoctrine()->getManager();
  4796.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4797.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4798.         if ($request->isMethod('POST')) {
  4799.             $em $this->getDoctrine()->getManager();
  4800.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesReplacement']; //change
  4801.             $dochash $request->request->get('voucherNumber'); //change
  4802.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4803.             $approveRole $request->request->get('approvalRole');
  4804.             $approveHash $request->request->get('approvalHash');
  4805.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4806.                 $loginId$approveRole$approveHash)
  4807.             ) {
  4808.                 $this->addFlash(
  4809.                     'error',
  4810.                     'Sorry Couldnot insert Data.'
  4811.                 );
  4812.             } else {
  4813.                 if ($request->request->has('check_allowed'))
  4814.                     $check_allowed 1;
  4815.                 $StID Inventory::CreateNewSalesReplacement(
  4816.                     $this->getDoctrine()->getManager(),
  4817.                     $request->request,
  4818.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  4819.                     $this->getLoggedUserCompanyId($request)
  4820.                 );
  4821.                 //now add Approval info
  4822.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4823.                 $approveRole 1;  //created
  4824.                 $options = array(
  4825.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4826.                     'notification_server' => $this->container->getParameter('notification_server'),
  4827.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4828.                     'url' => $this->generateUrl(
  4829.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesReplacement']]
  4830.                         ['entity_view_route_path_name']
  4831.                     )
  4832.                 );
  4833.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4834.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4835.                     $StID,
  4836.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  4837.                 );
  4838.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesReplacement'], $StID,
  4839.                     $loginId,
  4840.                     $approveRole,
  4841.                     $request->request->get('approvalHash'));
  4842.                 $this->addFlash(
  4843.                     'success',
  4844.                     'Stock Transfer Added.'
  4845.                 );
  4846.                 $url $this->generateUrl(
  4847.                     'view_st'
  4848.                 );
  4849.                 return $this->redirect($url "/" $StID);
  4850.             }
  4851.         }
  4852.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  4853.             array(
  4854.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  4855.             )
  4856.         );
  4857.         $INVLIST = [];
  4858.         foreach ($slotList as $slot) {
  4859.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  4860.         }
  4861.         return $this->render('@Inventory/pages/input_forms/sales_replacement.html.twig',
  4862.             array(
  4863.                 'page_title' => 'Sales Replacement Note',
  4864.                 'warehouseList' => Inventory::WarehouseList($em),
  4865.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  4866.                 'warehouseActionList' => $warehouse_action_list,
  4867.                 'warehouseActionListArray' => $warehouse_action_list_array,
  4868.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  4869.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  4870.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  4871.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  4872.                 'prefix_list' => array(
  4873.                     [
  4874.                         'id' => 1,
  4875.                         'value' => 'GN',
  4876.                         'text' => 'GN'
  4877.                     ]
  4878.                 ),
  4879.                 'assoc_list' => array(
  4880.                     [
  4881.                         'id' => 1,
  4882.                         'value' => 1,
  4883.                         'text' => 'GN'
  4884.                     ]
  4885.                 ),
  4886.                 'INVLIST' => $INVLIST
  4887.             )
  4888.         );
  4889.     }
  4890.     public function SalesReplacementListAction(Request $request)
  4891.     {
  4892.         $q $this->getDoctrine()
  4893.             ->getRepository('ApplicationBundle:SalesReplacement')
  4894.             ->findBy(
  4895.                 array(
  4896.                     'status' => GeneralConstant::ACTIVE,
  4897.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  4898. //                    'approved' =>  GeneralConstant::APPROVED,
  4899.                 )
  4900.             );
  4901.         $stage_list = array(
  4902.             => 'Pending',
  4903.             => 'Pending',
  4904.             => 'Complete',
  4905.             => 'Partial',
  4906.         );
  4907.         $data = [];
  4908.         foreach ($q as $entry) {
  4909.             $data[] = array(
  4910.                 'doc_date' => $entry->getSalesReplacementDate(),
  4911.                 'id' => $entry->getSalesReplacementId(),
  4912.                 'doc_hash' => $entry->getDocumentHash(),
  4913.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  4914.                 'stage' => $stage_list[$entry->getStage()]
  4915.             );
  4916.         }
  4917.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  4918.             array(
  4919.                 'page_title' => 'Stock Transfer List',
  4920.                 'data' => $data
  4921.             )
  4922.         );
  4923.     }
  4924.     public function ViewSalesReplacementAction(Request $request$id)
  4925.     {
  4926.         $em $this->getDoctrine()->getManager();
  4927.         $dt Inventory::GetSalesReplacementDetails($em$id);
  4928.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  4929.             array(
  4930.                 'page_title' => 'Stock Transfer',
  4931.                 'data' => $dt,
  4932.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4933.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  4934.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  4935.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4936.                     $id,
  4937.                     $dt['created_by'],
  4938.                     $dt['edited_by'])
  4939.             )
  4940.         );
  4941.     }
  4942.     public function PrintSalesReplacementAction(Request $request$id)
  4943.     {
  4944.         $em $this->getDoctrine()->getManager();
  4945.         $dt Inventory::GetSalesReplacementDetails($em$id);
  4946.         $company_data Company::getCompanyData($em1);
  4947.         $document_mark = array(
  4948.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4949.             'copy' => ''
  4950.         );
  4951.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  4952.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  4953.                 array(
  4954.                     //full array here
  4955.                     'pdf' => true,
  4956.                     'page_title' => 'Stock Transfer',
  4957.                     'export' => 'pdf,print',
  4958.                     'data' => $dt,
  4959.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4960.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  4961.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  4962.                         array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4963.                         $id,
  4964.                         $dt['created_by'],
  4965.                         $dt['edited_by']),
  4966.                     'document_mark_image' => $document_mark['original'],
  4967.                     'company_name' => $company_data->getName(),
  4968.                     'company_data' => $company_data,
  4969.                     'company_address' => $company_data->getAddress(),
  4970.                     'company_image' => $company_data->getImage(),
  4971.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  4972.                     'red' => 0
  4973.                 )
  4974.             );
  4975.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  4976. //                'orientation' => 'landscape',
  4977. //                'enable-javascript' => true,
  4978. //                'javascript-delay' => 1000,
  4979.                 'no-stop-slow-scripts' => false,
  4980.                 'no-background' => false,
  4981.                 'lowquality' => false,
  4982.                 'encoding' => 'utf-8',
  4983. //            'images' => true,
  4984. //            'cookie' => array(),
  4985.                 'dpi' => 300,
  4986.                 'image-dpi' => 300,
  4987. //                'enable-external-links' => true,
  4988. //                'enable-internal-links' => true
  4989.             ));
  4990.             return new Response(
  4991.                 $pdf_response,
  4992.                 200,
  4993.                 array(
  4994.                     'Content-Type' => 'application/pdf',
  4995.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  4996.                 )
  4997.             );
  4998.         }
  4999.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5000.             array(
  5001.                 'page_title' => 'Stock Transfer',
  5002.                 'export' => 'pdf,print',
  5003.                 'data' => $dt,
  5004.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5005.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5006.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5007.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5008.                     $id,
  5009.                     $dt['created_by'],
  5010.                     $dt['edited_by']),
  5011.                 'document_mark_image' => $document_mark['original'],
  5012.                 'company_name' => $company_data->getName(),
  5013.                 'company_data' => $company_data,
  5014.                 'company_address' => $company_data->getAddress(),
  5015.                 'company_image' => $company_data->getImage(),
  5016.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5017.                 'red' => 0
  5018.             )
  5019.         );
  5020.     }
  5021.     public function CreateStockTransferAction(Request $request)
  5022.     {
  5023.         $em $this->getDoctrine()->getManager();
  5024.         $companyId $this->getLoggedUserCompanyId($request);
  5025.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5026.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5027.         if ($request->isMethod('POST')) {
  5028.             $em $this->getDoctrine()->getManager();
  5029.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  5030.             $dochash $request->request->get('docHash'); //change
  5031.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5032.             $approveRole $request->request->get('approvalRole');
  5033.             $approveHash $request->request->get('approvalHash');
  5034.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5035.                 $loginId$approveRole$approveHash)
  5036.             ) {
  5037.                 $this->addFlash(
  5038.                     'error',
  5039.                     'Sorry Could Not insert Data.'
  5040.                 );
  5041.             } else {
  5042.                 if ($request->request->has('check_allowed'))
  5043.                     $check_allowed 1;
  5044.                 $StID Inventory::CreateNewStockTransfer(
  5045.                     $this->getDoctrine()->getManager(),
  5046.                     $request->request,
  5047.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5048.                     $this->getLoggedUserCompanyId($request)
  5049.                 );
  5050.                 //now add Approval info
  5051.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5052.                 $approveRole 1;  //created
  5053.                 $options = array(
  5054.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5055.                     'notification_server' => $this->container->getParameter('notification_server'),
  5056.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5057.                     'url' => $this->generateUrl(
  5058.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  5059.                         ['entity_view_route_path_name']
  5060.                     )
  5061.                 );
  5062.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5063.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5064.                     $StID,
  5065.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  5066.                 );
  5067.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  5068.                     $loginId,
  5069.                     $approveRole,
  5070.                     $request->request->get('approvalHash'));
  5071.                 $this->addFlash(
  5072.                     'success',
  5073.                     'Stock Transfer Added.'
  5074.                 );
  5075.                 $url $this->generateUrl(
  5076.                     'view_st'
  5077.                 );
  5078.                 return $this->redirect($url "/" $StID);
  5079.             }
  5080.         }
  5081.         $INVLIST = [];
  5082.         return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  5083.             array(
  5084.                 'page_title' => 'Stock Transfer Note',
  5085.                 'warehouseList' => Inventory::WarehouseList($em),
  5086.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5087.                 'colorList' => Inventory::GetColorList($em),
  5088.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  5089.                 'srList' => [],
  5090.                 'warehouseActionList' => $warehouse_action_list,
  5091.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5092.                 'item_list' => Inventory::ItemGroupList($em),
  5093.                 'item_list_array' => Inventory::ItemGroupListArray($em),
  5094.                 'category_list_array' => Inventory::ProductCategoryListArray($em),
  5095.                 'product_list_array' => Inventory::ProductListDetailedArray($em),
  5096. //                'product_list_array' => [],
  5097.                 'product_list' => Inventory::ProductList($em$companyId),
  5098. //                'product_list' => [],
  5099.                 'prefix_list' => array(
  5100.                     [
  5101.                         'id' => 1,
  5102.                         'value' => 'GN',
  5103.                         'text' => 'GN'
  5104.                     ]
  5105.                 ),
  5106.                 'assoc_list' => array(
  5107.                     [
  5108.                         'id' => 1,
  5109.                         'value' => 1,
  5110.                         'text' => 'GN'
  5111.                     ]
  5112.                 ),
  5113.                 'INVLIST' => $INVLIST
  5114.             )
  5115.         );
  5116.     }
  5117.     public function GetSrItemForTransferAction(Request $request)
  5118.     {
  5119.         $em $this->getDoctrine()->getManager();
  5120.         $search_query = [];
  5121.         $res_data_by_so_item_id = [];
  5122.         $Content = [];
  5123.         $productionProcessSettings = array(
  5124.             'id' => 0
  5125.         );
  5126.         if ($request->query->has('srId'))
  5127.             $search_query['stockRequisitionId'] = $request->query->get('srId');
  5128.         $DT $this->getDoctrine()
  5129.             ->getRepository('ApplicationBundle:StockRequisitionItem')
  5130.             ->findBy(
  5131.                 $search_query
  5132.             );
  5133.         $Content = array(
  5134.             'requisitioned_product_item_id' => [],
  5135.             'requisitioned_products' => [],
  5136.             'requisitioned_product_fdm' => [],
  5137.             'requisitioned_product_name' => [],
  5138.             'requisitioned_product_units' => [],
  5139.             'requisitioned_product_unit_type' => [],
  5140.             'requisitioned_product_balance' => [],
  5141.         );
  5142.         foreach ($DT as $dt) {
  5143. //            $data=json_decode($DT->getData(),true);
  5144.             $Content['requisitioned_products'][] = $dt->getProductId();
  5145.             $Content['requisitioned_product_item_id'][] = $dt->getId();
  5146.             $Content['requisitioned_product_fdm'][] = $dt->getProductFdm();
  5147.             $Content['requisitioned_product_name'][] = $dt->getProductNameFdm();
  5148.             $Content['requisitioned_product_units'][] = $dt->getQty();
  5149.             $Content['requisitioned_product_balance'][] = $dt->getAlottmentPendingAmount();
  5150.         }
  5151.         $INVLIST = [];
  5152.         if (!empty($Content)) {
  5153.             return new JsonResponse(array("success" => true"content" => $Content"INVLIST" => $INVLIST));
  5154.         } else {
  5155.             return new JsonResponse(array("success" => false"content" => $Content"INVLIST" => $INVLIST));
  5156.         }
  5157.     }
  5158.     public function StockTransferListAction(Request $request)
  5159.     {
  5160.         $q $this->getDoctrine()
  5161.             ->getRepository('ApplicationBundle:StockTransfer')
  5162.             ->findBy(
  5163.                 array(
  5164.                     'status' => GeneralConstant::ACTIVE,
  5165.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5166. //                    'approved' =>  GeneralConstant::APPROVED,
  5167.                 )
  5168.             );
  5169.         $stage_list = array(
  5170.             => 'Pending',
  5171.             => 'Pending',
  5172.             => 'Complete',
  5173.             => 'Partial',
  5174.         );
  5175.         $data = [];
  5176.         foreach ($q as $entry) {
  5177.             $data[] = array(
  5178.                 'doc_date' => $entry->getStockTransferDate(),
  5179.                 'id' => $entry->getStockTransferId(),
  5180.                 'doc_hash' => $entry->getDocumentHash(),
  5181.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5182.                 'stage' => $stage_list[$entry->getStage()]
  5183.             );
  5184.         }
  5185.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5186.             array(
  5187.                 'page_title' => 'Stock Transfer List',
  5188.                 'data' => $data
  5189.             )
  5190.         );
  5191.     }
  5192.     public function ViewStockTransferAction(Request $request$id)
  5193.     {
  5194.         $em $this->getDoctrine()->getManager();
  5195.         $dt Inventory::GetStockTransferDetails($em$id);
  5196.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  5197.             array(
  5198.                 'page_title' => 'Stock Transfer',
  5199.                 'data' => $dt,
  5200.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5201.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5202.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5203.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5204.                     $id,
  5205.                     $dt['created_by'],
  5206.                     $dt['edited_by'])
  5207.             )
  5208.         );
  5209.     }
  5210.     public function PrintStockTransferAction(Request $request$id)
  5211.     {
  5212.         $em $this->getDoctrine()->getManager();
  5213.         $dt Inventory::GetStockTransferDetails($em$id);
  5214.         $company_data Company::getCompanyData($em1);
  5215.         $document_mark = array(
  5216.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5217.             'copy' => ''
  5218.         );
  5219.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5220.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5221.                 array(
  5222.                     //full array here
  5223.                     'pdf' => true,
  5224.                     'page_title' => 'Stock Transfer',
  5225.                     'export' => 'pdf,print',
  5226.                     'data' => $dt,
  5227.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5228.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5229.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5230.                         array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5231.                         $id,
  5232.                         $dt['created_by'],
  5233.                         $dt['edited_by']),
  5234.                     'document_mark_image' => $document_mark['original'],
  5235.                     'company_name' => $company_data->getName(),
  5236.                     'company_data' => $company_data,
  5237.                     'company_address' => $company_data->getAddress(),
  5238.                     'company_image' => $company_data->getImage(),
  5239.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5240.                     'red' => 0
  5241.                 )
  5242.             );
  5243.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5244. //                'orientation' => 'landscape',
  5245. //                'enable-javascript' => true,
  5246. //                'javascript-delay' => 1000,
  5247.                 'no-stop-slow-scripts' => false,
  5248.                 'no-background' => false,
  5249.                 'lowquality' => false,
  5250.                 'encoding' => 'utf-8',
  5251. //            'images' => true,
  5252. //            'cookie' => array(),
  5253.                 'dpi' => 300,
  5254.                 'image-dpi' => 300,
  5255. //                'enable-external-links' => true,
  5256. //                'enable-internal-links' => true
  5257.             ));
  5258.             return new Response(
  5259.                 $pdf_response,
  5260.                 200,
  5261.                 array(
  5262.                     'Content-Type' => 'application/pdf',
  5263.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5264.                 )
  5265.             );
  5266.         }
  5267.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5268.             array(
  5269.                 'page_title' => 'Stock Transfer',
  5270.                 'export' => 'pdf,print',
  5271.                 'data' => $dt,
  5272.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5273.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5274.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5275.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5276.                     $id,
  5277.                     $dt['created_by'],
  5278.                     $dt['edited_by']),
  5279.                 'document_mark_image' => $document_mark['original'],
  5280.                 'company_name' => $company_data->getName(),
  5281.                 'company_data' => $company_data,
  5282.                 'company_address' => $company_data->getAddress(),
  5283.                 'company_image' => $company_data->getImage(),
  5284.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5285.                 'red' => 0
  5286.             )
  5287.         );
  5288.     }
  5289.     public function CreateStockConsumptionNoteAction(Request $request)
  5290.     {
  5291.         $em $this->getDoctrine()->getManager();
  5292.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5293.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5294.         if ($request->isMethod('POST')) {
  5295.             $em $this->getDoctrine()->getManager();
  5296.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']; //change
  5297.             $dochash $request->request->get('voucherNumber'); //change
  5298.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5299.             $approveRole $request->request->get('approvalRole');
  5300.             $approveHash $request->request->get('approvalHash');
  5301.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5302.                 $loginId$approveRole$approveHash)
  5303.             ) {
  5304.                 $this->addFlash(
  5305.                     'error',
  5306.                     'Sorry Could not insert Data.'
  5307.                 );
  5308.             } else {
  5309.                 if ($request->request->has('check_allowed'))
  5310.                     $check_allowed 1;
  5311.                 $StID Inventory::CreateNewStockConsumptionNote(
  5312.                     $this->getDoctrine()->getManager(),
  5313.                     $request->request,
  5314.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5315.                     $this->getLoggedUserCompanyId($request)
  5316.                 );
  5317.                 //now add Approval info
  5318.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5319.                 $approveRole 1;  //created
  5320.                 $options = array(
  5321.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5322.                     'notification_server' => $this->container->getParameter('notification_server'),
  5323.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5324.                     'url' => $this->generateUrl(
  5325.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']]
  5326.                         ['entity_view_route_path_name']
  5327.                     )
  5328.                 );
  5329.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5330.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5331.                     $StID,
  5332.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5333.                 );
  5334.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'], $StID,
  5335.                     $loginId,
  5336.                     $approveRole,
  5337.                     $request->request->get('approvalHash'));
  5338.                 $this->addFlash(
  5339.                     'success',
  5340.                     'Stock Consumption Added.'
  5341.                 );
  5342.                 $url $this->generateUrl(
  5343.                     'view_stock_consumption_note'
  5344.                 );
  5345.                 return $this->redirect($url "/" $StID);
  5346.             }
  5347.         }
  5348.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5349.             array(
  5350.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5351.             )
  5352.         );
  5353.         $INVLIST = [];
  5354.         foreach ($slotList as $slot) {
  5355.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5356.         }
  5357.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5358.             array(
  5359.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5360.             )
  5361.         );
  5362.         $consumptionTypeList = [];
  5363.         $consumptionTypeListArray = [];
  5364.         foreach ($consumptionTypeQry as $entry) {
  5365.             $p = array(
  5366.                 'name' => $entry->getName(),
  5367.                 'id' => $entry->getConsumptionTypeId(),
  5368.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5369.                 'cost_center_id' => $entry->getCostCenterId(),
  5370.             );
  5371.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5372.             $consumptionTypeListArray[] = $p;
  5373.         }
  5374.         //add bill list
  5375.         $service_purchase_bill_query $this->getDoctrine()
  5376.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5377.             ->findBy(
  5378.                 array(
  5379.                     'typeHash' => 'SPB',
  5380.                     'approved' => GeneralConstant::APPROVED
  5381.                 )
  5382.             );
  5383.         $service_purchase_bill_list = [];
  5384.         $service_purchase_bill_list_array = [];
  5385.         $bill = array(
  5386.             'id' => 0,
  5387.             'type' => 'SPB',
  5388.             'name' => 'New Expense',
  5389.             'text' => 'New Expense',
  5390.             'amount' => 0,
  5391.         );
  5392.         $service_purchase_bill_list[0] = $bill;
  5393.         $service_purchase_bill_list_array[] = $bill;
  5394.         foreach ($service_purchase_bill_query as $d) {
  5395.             $bill = array(
  5396.                 'id' => $d->getPurchaseInvoiceId(),
  5397.                 'type' => 'SPB',
  5398.                 'name' => $d->getDocumentHash(),
  5399.                 'text' => $d->getDocumentHash(),
  5400.                 'amount' => $d->getInvoiceAmount(),
  5401.             );
  5402.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5403.             $service_purchase_bill_list_array[] = $bill;
  5404.         }
  5405.         return $this->render('@Inventory/pages/input_forms/stock_consumption_note.html.twig',
  5406.             array(
  5407.                 'page_title' => 'Stock Consumption Note',
  5408.                 'warehouseList' => Inventory::WarehouseList($em),
  5409.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5410.                 'consumptionTypeList' => $consumptionTypeList,
  5411.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5412.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5413.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5414.                 'warehouseActionList' => $warehouse_action_list,
  5415.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5416.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5417.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5418.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5419.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5420.                 'product_list' => Inventory::ProductListDetailed($this->getDoctrine()->getManager()),
  5421.                 'prefix_list' => array(
  5422.                     [
  5423.                         'id' => 1,
  5424.                         'value' => 'GN',
  5425.                         'text' => 'GN'
  5426.                     ]
  5427.                 ),
  5428.                 'assoc_list' => array(
  5429.                     [
  5430.                         'id' => 1,
  5431.                         'value' => 1,
  5432.                         'text' => 'GN'
  5433.                     ]
  5434.                 ),
  5435.                 'INVLIST' => $INVLIST
  5436.             )
  5437.         );
  5438.     }
  5439.     public function StockConsumptionNoteListAction(Request $request)
  5440.     {
  5441.         $q $this->getDoctrine()
  5442.             ->getRepository('ApplicationBundle:StockConsumptionNote')
  5443.             ->findBy(
  5444.                 array(
  5445.                     'status' => GeneralConstant::ACTIVE,
  5446.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5447. //                    'approved' =>  GeneralConstant::APPROVED,
  5448.                 )
  5449.             );
  5450.         $stage_list = array(
  5451.             => 'Pending',
  5452.             => 'Pending',
  5453.             => 'Complete',
  5454.             => 'Partial',
  5455.         );
  5456.         $data = [];
  5457.         foreach ($q as $entry) {
  5458.             $data[] = array(
  5459.                 'doc_date' => $entry->getStockConsumptionNoteDate(),
  5460.                 'id' => $entry->getStockConsumptionNoteId(),
  5461.                 'doc_hash' => $entry->getDocumentHash(),
  5462.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5463.                 'stage' => $stage_list[$entry->getStage()]
  5464.             );
  5465.         }
  5466.         return $this->render('@Inventory/pages/views/stock_consumption_note_list.html.twig',
  5467.             array(
  5468.                 'page_title' => 'Stock Consumption Note List',
  5469.                 'data' => $data
  5470.             )
  5471.         );
  5472.     }
  5473.     public function ViewStockConsumptionNoteAction(Request $request$id)
  5474.     {
  5475.         $em $this->getDoctrine()->getManager();
  5476.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5477.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5478.             array(
  5479.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5480.             )
  5481.         );
  5482.         $consumptionTypeList = [];
  5483.         $consumptionTypeListArray = [];
  5484.         foreach ($consumptionTypeQry as $entry) {
  5485.             $p = array(
  5486.                 'name' => $entry->getName(),
  5487.                 'id' => $entry->getConsumptionTypeId(),
  5488.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5489.                 'cost_center_id' => $entry->getCostCenterId(),
  5490.             );
  5491.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5492.             $consumptionTypeListArray[] = $p;
  5493.         }
  5494.         //add bill list
  5495.         $service_purchase_bill_query $this->getDoctrine()
  5496.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5497.             ->findBy(
  5498.                 array(
  5499.                     'typeHash' => 'SPB',
  5500.                     'approved' => GeneralConstant::APPROVED
  5501.                 )
  5502.             );
  5503.         $service_purchase_bill_list = [];
  5504.         $service_purchase_bill_list_array = [];
  5505.         $bill = array(
  5506.             'id' => 0,
  5507.             'type' => 'SPB',
  5508.             'name' => 'New Expense',
  5509.             'text' => 'New Expense',
  5510.             'amount' => 0,
  5511.         );
  5512.         $service_purchase_bill_list[0] = $bill;
  5513.         $service_purchase_bill_list_array[] = $bill;
  5514.         foreach ($service_purchase_bill_query as $d) {
  5515.             $bill = array(
  5516.                 'id' => $d->getPurchaseInvoiceId(),
  5517.                 'type' => 'SPB',
  5518.                 'name' => $d->getDocumentHash(),
  5519.                 'text' => $d->getDocumentHash(),
  5520.                 'amount' => $d->getInvoiceAmount(),
  5521.             );
  5522.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5523.             $service_purchase_bill_list_array[] = $bill;
  5524.         }
  5525.         return $this->render('@Inventory/pages/views/view_stock_consumption_note.html.twig',
  5526.             array(
  5527.                 'page_title' => 'Stock Transfer',
  5528.                 'data' => $dt,
  5529.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5530.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5531.                 'consumptionTypeList' => $consumptionTypeList,
  5532.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5533.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5534.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5535.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5536.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5537.                     $id,
  5538.                     $dt['created_by'],
  5539.                     $dt['edited_by'])
  5540.             )
  5541.         );
  5542.     }
  5543.     public function PrintStockConsumptionNoteAction(Request $request$id)
  5544.     {
  5545.         $em $this->getDoctrine()->getManager();
  5546.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5547.         $company_data Company::getCompanyData($em1);
  5548.         $document_mark = array(
  5549.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5550.             'copy' => ''
  5551.         );
  5552.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5553.             array(
  5554.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5555.             )
  5556.         );
  5557.         $consumptionTypeList = [];
  5558.         $consumptionTypeListArray = [];
  5559.         foreach ($consumptionTypeQry as $entry) {
  5560.             $p = array(
  5561.                 'name' => $entry->getName(),
  5562.                 'id' => $entry->getConsumptionTypeId(),
  5563.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5564.                 'cost_center_id' => $entry->getCostCenterId(),
  5565.             );
  5566.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5567.             $consumptionTypeListArray[] = $p;
  5568.         }
  5569.         //add bill list
  5570.         $service_purchase_bill_query $this->getDoctrine()
  5571.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5572.             ->findBy(
  5573.                 array(
  5574.                     'typeHash' => 'SPB',
  5575.                     'approved' => GeneralConstant::APPROVED
  5576.                 )
  5577.             );
  5578.         $service_purchase_bill_list = [];
  5579.         $service_purchase_bill_list_array = [];
  5580.         $bill = array(
  5581.             'id' => 0,
  5582.             'type' => 'SPB',
  5583.             'name' => 'New Expense',
  5584.             'text' => 'New Expense',
  5585.             'amount' => 0,
  5586.         );
  5587.         $service_purchase_bill_list[0] = $bill;
  5588.         $service_purchase_bill_list_array[] = $bill;
  5589.         foreach ($service_purchase_bill_query as $d) {
  5590.             $bill = array(
  5591.                 'id' => $d->getPurchaseInvoiceId(),
  5592.                 'type' => 'SPB',
  5593.                 'name' => $d->getDocumentHash(),
  5594.                 'text' => $d->getDocumentHash(),
  5595.                 'amount' => $d->getInvoiceAmount(),
  5596.             );
  5597.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5598.             $service_purchase_bill_list_array[] = $bill;
  5599.         }
  5600.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5601.             $html $this->renderView('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  5602.                 array(
  5603.                     //full array here
  5604.                     'pdf' => true,
  5605.                     'page_title' => 'Stock Consumption',
  5606.                     'export' => 'pdf,print',
  5607.                     'data' => $dt,
  5608.                     'service_purchase_bill_list' => $service_purchase_bill_list,
  5609.                     'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5610.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5611.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5612.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5613.                         array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5614.                         $id,
  5615.                         $dt['created_by'],
  5616.                         $dt['edited_by']),
  5617.                     'document_mark_image' => $document_mark['original'],
  5618.                     'consumptionTypeList' => $consumptionTypeList,
  5619.                     'consumptionTypeListArray' => $consumptionTypeListArray,
  5620.                     'company_name' => $company_data->getName(),
  5621.                     'company_data' => $company_data,
  5622.                     'company_address' => $company_data->getAddress(),
  5623.                     'company_image' => $company_data->getImage(),
  5624.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5625.                     'red' => 0
  5626.                 )
  5627.             );
  5628.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5629. //                'orientation' => 'landscape',
  5630. //                'enable-javascript' => true,
  5631. //                'javascript-delay' => 1000,
  5632.                 'no-stop-slow-scripts' => false,
  5633.                 'no-background' => false,
  5634.                 'lowquality' => false,
  5635.                 'encoding' => 'utf-8',
  5636. //            'images' => true,
  5637. //            'cookie' => array(),
  5638.                 'dpi' => 300,
  5639.                 'image-dpi' => 300,
  5640. //                'enable-external-links' => true,
  5641. //                'enable-internal-links' => true
  5642.             ));
  5643.             return new Response(
  5644.                 $pdf_response,
  5645.                 200,
  5646.                 array(
  5647.                     'Content-Type' => 'application/pdf',
  5648.                     'Content-Disposition' => 'attachment; filename="stock_consumption_note_' $id '.pdf"'
  5649.                 )
  5650.             );
  5651.         }
  5652.         return $this->render('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  5653.             array(
  5654.                 'page_title' => 'Stock Consumption',
  5655.                 'export' => 'pdf,print',
  5656.                 'data' => $dt,
  5657.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5658.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5659.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5660.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5661.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5662.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5663.                     $id,
  5664.                     $dt['created_by'],
  5665.                     $dt['edited_by']),
  5666.                 'document_mark_image' => $document_mark['original'],
  5667.                 'consumptionTypeList' => $consumptionTypeList,
  5668.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5669.                 'company_name' => $company_data->getName(),
  5670.                 'company_data' => $company_data,
  5671.                 'company_address' => $company_data->getAddress(),
  5672.                 'company_image' => $company_data->getImage(),
  5673.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5674.                 'red' => 0
  5675.             )
  5676.         );
  5677.     }
  5678.     public function CreateStockReceivedNoteAction(Request $request$id 0)
  5679.     {
  5680.         $em $this->getDoctrine()->getManager();
  5681.         $companyId $this->getLoggedUserCompanyId($request);
  5682.         $extDocData = [];
  5683.         $userId $request->getSession()->get(UserConstants::USER_ID);
  5684.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  5685.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  5686.         $userBranchIdList $request->getSession()->get('branchIdList');
  5687.         if ($userBranchIdList == null$userBranchIdList = [];
  5688.         $userBranchId $request->getSession()->get('branchId');
  5689.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  5690.             $em $this->getDoctrine()->getManager();
  5691.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'];
  5692.             $dochash $request->request->get('docHash');
  5693.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5694.             $approveRole $request->request->get('approvalRole');
  5695.             $approveHash $request->request->get('approvalHash');
  5696.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5697.                 $loginId$approveRole$approveHash$id)
  5698.             ) {
  5699.                 if ($request->request->has('returnJson')) {
  5700.                     return new JsonResponse(array(
  5701.                         'success' => false,
  5702.                         'documentHash' => 0,
  5703.                         'documentId' => 0,
  5704.                         'billIds' => [],
  5705.                         'drIds' => [],
  5706.                         'pmntTransIds' => [],
  5707.                         'viewUrl' => '',
  5708.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  5709.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  5710.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  5711.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  5712.                     ));
  5713.                 } else
  5714.                     $this->addFlash(
  5715.                         'error',
  5716.                         'Sorry Could not insert Data.'
  5717.                     );
  5718.             } else {
  5719.                 if ($request->request->has('check_allowed'))
  5720.                     $check_allowed 1;
  5721.                 $StID Inventory::CreateNewStockReceivedNote(
  5722.                     $this->getDoctrine()->getManager(),
  5723.                     $request->request,
  5724.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5725.                     $this->getLoggedUserCompanyId($request)
  5726.                 );
  5727.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5728.                 $approveRole 1;
  5729.                 $options = array(
  5730.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5731.                     'notification_server' => $this->container->getParameter('notification_server'),
  5732.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5733.                     'url' => $this->generateUrl(
  5734.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  5735.                         ['entity_view_route_path_name']
  5736.                     )
  5737.                 );
  5738.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5739.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5740.                     $StID,
  5741.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5742.                 );
  5743.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  5744.                     $loginId,
  5745.                     $approveRole,
  5746.                     $request->request->get('approvalHash'));
  5747.                 $url $this->generateUrl(
  5748.                     'view_srcv'
  5749.                 );
  5750.                 if ($request->request->has('returnJson')) {
  5751.                     return new JsonResponse(array(
  5752.                         'success' => true,
  5753.                         'documentHash' => $dochash,
  5754.                         'documentId' => $StID,
  5755.                         'viewUrl' => $url "/" $StID,
  5756.                     ));
  5757.                 } else {
  5758.                     $this->addFlash(
  5759.                         'success',
  5760.                         'Stock Received Note Added.'
  5761.                     );
  5762.                     return $this->redirect($url "/" $StID);
  5763.                 }
  5764.             }
  5765.         }
  5766.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5767.             array(
  5768.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5769.             )
  5770.         );
  5771.         if ($id == 0) {
  5772.         } else {
  5773.             $extDoc $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  5774.                 array(
  5775.                     'salesOrderId' => $id,
  5776.                 )
  5777.             );
  5778.             if ($extDoc) {
  5779.                 if ($extDoc->getEditFlag() != 1) {
  5780.                     $url $this->generateUrl(
  5781.                         'view_srcv'
  5782.                     );
  5783.                     return $this->redirect($url "/" $id);
  5784.                 } else {
  5785.                     $extDocData $extDoc;
  5786.                     $extDocDataDetails $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findOneBy(
  5787.                         array(
  5788.                             'stockReceivedNoteId' => $id,
  5789.                         )
  5790.                     );
  5791.                 }
  5792.             } else {
  5793.             }
  5794.         }
  5795.         $INVLIST = [];
  5796.         foreach ($slotList as $slot) {
  5797.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5798.         }
  5799.         $dataArray = array(
  5800.             'page_title' => 'Stock Received Note',
  5801. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  5802.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  5803.             'users' => Users::getUserListById($em),
  5804.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  5805.             'warehouseList' => Inventory::WarehouseList($em),
  5806.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  5807.             'warehouseActionList' => $warehouse_action_list,
  5808.             'warehouseActionListArray' => $warehouse_action_list_array,
  5809.             'extDocData' => $extDocData,
  5810.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  5811.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5812.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5813.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5814. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5815. //            'product_list' => Inventory::ProductList($em, $companyId),
  5816.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  5817.             'prefix_list' => array(
  5818.                 [
  5819.                     'id' => 1,
  5820.                     'value' => 'GN',
  5821.                     'text' => 'GN'
  5822.                 ]
  5823.             ),
  5824.             'assoc_list' => array(
  5825.                 [
  5826.                     'id' => 1,
  5827.                     'value' => 1,
  5828.                     'text' => 'GN'
  5829.                 ]
  5830.             ),
  5831.             'INVLIST' => $INVLIST,
  5832.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  5833.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  5834.             'userBranchIdList' => $userBranchIdList,
  5835.             'userBranchId' => $userBranchId,
  5836. //            'headList' => Accounts::HeadList($em),
  5837.         );
  5838.         //json
  5839.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  5840.         {
  5841.             $dataArray['success'] = true;
  5842.             return new JsonResponse(
  5843.                 $dataArray
  5844.             );
  5845.         }
  5846.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  5847.             $dataArray
  5848.         );
  5849.     }
  5850.     public function GetItemListForStockReceivedAction(Request $request)
  5851.     {
  5852.         if ($request->isMethod('POST')) {
  5853.             $em $this->getDoctrine();
  5854.             $receiveType 1;//transfer
  5855.             if ($request->request->has('receiveType'))
  5856.                 $receiveType $request->request->get('receiveType');
  5857.             $QD = [];
  5858.             if ($receiveType == 1)
  5859.                 $QD $this->getDoctrine()
  5860.                     ->getRepository('ApplicationBundle:StockTransferItem')
  5861.                     ->findBy(
  5862.                         array(
  5863. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  5864.                             'stockTransferId' => $request->request->get('stId')
  5865.                         ),
  5866.                         array()
  5867.                     );
  5868.             if ($receiveType == 2)
  5869.                 $QD $this->getDoctrine()
  5870.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  5871.                     ->findBy(
  5872.                         array(
  5873. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  5874.                             'salesOrderId' => $request->request->get('soId')
  5875.                         ),
  5876.                         array()
  5877.                     );
  5878. //            if($request->request->get('wareHouseId')!='')
  5879. //
  5880. //            $DO=$this->getDoctrine()
  5881. //                ->getRepository('ApplicationBundle:DeliveryOrder')
  5882. //                ->findOneBy(
  5883. //                    $find_array,
  5884. //                    array(
  5885. //
  5886. //                    )
  5887. //                );
  5888.             $sendData = array(
  5889. //                'salesType'=>$SO->getSalesType(),
  5890. //                'packageData'=>[],
  5891.                 'productList' => [],
  5892. //                'productListByPackage'=>[],
  5893.             );
  5894.             $productList Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request));
  5895.             $pckg_item_cross_match_data = [];
  5896.             foreach ($QD as $product) {
  5897. //                $b_code=json_decode($product->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  5898.                 $b_code = [];
  5899.                 $newProductId $product->getProductId();
  5900.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  5901.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  5902.                     if ($to_analyze_codes_str != null)
  5903.                         $b_code json_decode($to_analyze_codes_strtrue512JSON_BIGINT_AS_STRING);
  5904.                     else
  5905.                         $b_code = [];
  5906.                 } else {
  5907.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  5908.                     if ($to_analyze_codes_str != null) {
  5909.                         $max_int_length strlen((string)PHP_INT_MAX) - 1;
  5910.                         $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$to_analyze_codes_str);
  5911.                         $b_code json_decode($json_without_bigintstrue);
  5912.                     } else {
  5913.                         $b_code = [];
  5914.                     }
  5915.                 }
  5916.                 $b_code_data = [];
  5917.                 foreach ($b_code as $d) {
  5918.                     $b_code_data[] = array(
  5919.                         'id' => $d,
  5920.                         'name' => str_pad($d13'0'STR_PAD_LEFT),
  5921.                     );
  5922.                 }
  5923.                 $p_data = array(
  5924.                     'details_id' => $product->getId(),
  5925.                     'productId' => $product->getProductId(),
  5926.                     'product_name' => isset($productList[$product->getProductId()]) ? $productList[$product->getProductId()]['name'] : 'Unknown Product',
  5927.                     'product_barcodes' => $b_code_data,
  5928. //                    'available_inventory'=>$inventory_by_warehouse?$inventory_by_warehouse->getQty():0,
  5929. //                        'package_id'=>$product->getPackageId(),
  5930.                     'qty' => $receiveType == $product->getQty() : $product->getToBeReceived(),
  5931.                     'unit_price' => $receiveType == $product->getPrice() : $productList[$product->getProductId()]['purchase_price'],
  5932.                     'balance' => $receiveType == $product->getBalance() : ($product->getToBeReceived() - $product->getReceived()),
  5933. //                        'delivered'=>$product->getDelivered(),
  5934.                 );
  5935.                 $sendData['productList'][] = $p_data;
  5936.             }
  5937.             //now package data
  5938.             if ($sendData) {
  5939.                 return new JsonResponse(array("success" => true"content" => $sendData));
  5940.             }
  5941.             return new JsonResponse(array("success" => false));
  5942.         }
  5943.         return new JsonResponse(array("success" => false));
  5944.     }
  5945.     public function StockReceivedNoteListAction(Request $request)
  5946.     {
  5947.         $q $this->getDoctrine()
  5948.             ->getRepository('ApplicationBundle:StockReceivedNote')
  5949.             ->findBy(
  5950.                 array(
  5951.                     'status' => GeneralConstant::ACTIVE,
  5952.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5953. //                    'approved' =>  GeneralConstant::APPROVED,
  5954.                 )
  5955.             );
  5956.         $stage_list = array(
  5957.             => 'Pending',
  5958.             => 'Pending',
  5959.             => 'Complete',
  5960.             => 'Partial',
  5961.         );
  5962.         $data = [];
  5963.         foreach ($q as $entry) {
  5964.             $data[] = array(
  5965.                 'doc_date' => $entry->getStockReceivedNoteDate(),
  5966.                 'id' => $entry->getStockReceivedNoteId(),
  5967.                 'doc_hash' => $entry->getDocumentHash(),
  5968.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5969.                 'stage' => $stage_list[$entry->getStage()]
  5970.             );
  5971.         }
  5972.         return $this->render('@Inventory/pages/views/stock_received_note_list.html.twig',
  5973.             array(
  5974.                 'page_title' => 'Stock Received List',
  5975.                 'data' => $data
  5976.             )
  5977.         );
  5978.     }
  5979.     public function ViewStockReceivedNoteAction(Request $request$id)
  5980.     {
  5981.         $em $this->getDoctrine()->getManager();
  5982.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  5983.         return $this->render('@Inventory/pages/views/view_stock_received_note.html.twig',
  5984.             array(
  5985.                 'page_title' => 'Stock Received Note',
  5986.                 'data' => $dt,
  5987.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  5988.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5989.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5990.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5991.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5992.                     $id,
  5993.                     $dt['created_by'],
  5994.                     $dt['edited_by'])
  5995.             )
  5996.         );
  5997.     }
  5998.     public function PrintStockReceivedNoteAction(Request $request$id)
  5999.     {
  6000.         $em $this->getDoctrine()->getManager();
  6001.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6002.         $company_data Company::getCompanyData($em1);
  6003.         $document_mark = array(
  6004.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6005.             'copy' => ''
  6006.         );
  6007.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6008.             $html $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
  6009.                 array(
  6010.                     //full array here
  6011.                     'pdf' => true,
  6012.                     'page_title' => 'Stock Received Note',
  6013.                     'export' => 'pdf,print',
  6014.                     'data' => $dt,
  6015.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6016.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6017.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6018.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6019.                         $id,
  6020.                         $dt['created_by'],
  6021.                         $dt['edited_by']),
  6022.                     'document_mark_image' => $document_mark['original'],
  6023.                     'company_name' => $company_data->getName(),
  6024.                     'company_data' => $company_data,
  6025.                     'company_address' => $company_data->getAddress(),
  6026.                     'company_image' => $company_data->getImage(),
  6027.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6028.                     'red' => 0
  6029.                 )
  6030.             );
  6031.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6032. //                'orientation' => 'landscape',
  6033. //                'enable-javascript' => true,
  6034. //                'javascript-delay' => 1000,
  6035.                 'no-stop-slow-scripts' => false,
  6036.                 'no-background' => false,
  6037.                 'lowquality' => false,
  6038.                 'encoding' => 'utf-8',
  6039. //            'images' => true,
  6040. //            'cookie' => array(),
  6041.                 'dpi' => 300,
  6042.                 'image-dpi' => 300,
  6043. //                'enable-external-links' => true,
  6044. //                'enable-internal-links' => true
  6045.             ));
  6046.             return new Response(
  6047.                 $pdf_response,
  6048.                 200,
  6049.                 array(
  6050.                     'Content-Type' => 'application/pdf',
  6051.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  6052.                 )
  6053.             );
  6054.         }
  6055.         return $this->render('@Inventory/pages/print/print_stock_received_note.html.twig',
  6056.             array(
  6057.                 'page_title' => 'Stock Received Note',
  6058.                 'export' => 'pdf,print',
  6059.                 'data' => $dt,
  6060.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6061.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6062.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6063.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6064.                     $id,
  6065.                     $dt['created_by'],
  6066.                     $dt['edited_by']),
  6067.                 'document_mark_image' => $document_mark['original'],
  6068.                 'company_name' => $company_data->getName(),
  6069.                 'company_data' => $company_data,
  6070.                 'company_address' => $company_data->getAddress(),
  6071.                 'company_image' => $company_data->getImage(),
  6072.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6073.                 'red' => 0
  6074.             )
  6075.         );
  6076.     }
  6077.     public function CreateStoreRequisitionSlipAction(Request $request$id 0)
  6078.     {
  6079.         $em $this->getDoctrine()->getManager();
  6080. //        $id;
  6081.         if ($request->isMethod('POST')) {
  6082.             $em $this->getDoctrine()->getManager();
  6083.             $entity_id array_flip(GeneralConstant::$Entity_list)['StoreRequisition']; //change
  6084.             $dochash $request->request->get('voucherNumber'); //change
  6085.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6086.             $approveRole $request->request->get('approvalRole');
  6087.             $approveHash $request->request->get('approvalHash');
  6088.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6089.                 $loginId$approveRole$approveHash$id)
  6090.             ) {
  6091.                 $this->addFlash(
  6092.                     'error',
  6093.                     'Sorry, could not insert Data.'
  6094.                 );
  6095.             } else {
  6096.                 if ($request->request->has('check_allowed'))
  6097.                     $check_allowed 1;
  6098.                 $IrID Inventory::CreateNewStoreRequisition($id,
  6099.                     $this->getDoctrine()->getManager(),
  6100.                     $request->request,
  6101.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6102.                     $this->getLoggedUserCompanyId($request)
  6103.                 );
  6104.                 //now add Approval info
  6105.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6106.                 $approveRole $request->request->get('approvalRole');
  6107.                 $options = array(
  6108.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6109.                     'notification_server' => $this->container->getParameter('notification_server'),
  6110.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6111.                     'url' => $this->generateUrl(
  6112.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StoreRequisition']]
  6113.                         ['entity_view_route_path_name']
  6114.                     )
  6115.                 );
  6116.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6117.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  6118.                     $IrID,
  6119.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6120.                 );
  6121.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StoreRequisition'], $IrID,
  6122.                     $loginId,
  6123.                     $approveRole,
  6124.                     $request->request->get('approvalHash'));
  6125.                 $this->addFlash(
  6126.                     'success',
  6127.                     'New Indent Added.'
  6128.                 );
  6129.                 $url $this->generateUrl(
  6130.                     'view_ir'
  6131.                 );
  6132.                 return $this->redirect($url "/" $IrID);
  6133.             }
  6134.         }
  6135.         $extDocData = [];
  6136.         $extDocDetailsData = [];
  6137.         if ($id == 0) {
  6138.         } else {
  6139.             $extDoc $em->getRepository('ApplicationBundle:StoreRequisition')->findOneBy(
  6140.                 array(
  6141.                     'storeRequisitionId' => $id///material
  6142.                 )
  6143.             );
  6144.             //now if its not editable, redirect to view
  6145.             if ($extDoc) {
  6146.                 if ($extDoc->getEditFlag() != 1) {
  6147.                     $url $this->generateUrl(
  6148.                         'view_ir'
  6149.                     );
  6150.                     return $this->redirect($url "/" $id);
  6151.                 } else {
  6152.                     $extDocData $extDoc;
  6153.                     $extDocDetailsData $em->getRepository('ApplicationBundle:StoreRequisitionItem')->findBy(
  6154.                         array(
  6155.                             'storeRequisitionId' => $id///material
  6156.                         )
  6157.                     );;
  6158.                 }
  6159.             } else {
  6160.             }
  6161.         }
  6162.         $companyId $this->getLoggedUserCompanyId($request);
  6163.         $productListArray = [];
  6164.         $subCategoryListArray = [];
  6165.         $categoryListArray = [];
  6166.         $igListArray = [];
  6167.         $unitListArray = [];
  6168.         $brandListArray = [];
  6169.         $productList Inventory::ProductList($em$companyId);
  6170.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6171.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6172.         $igList Inventory::ItemGroupList($em$companyId);
  6173.         $unitList Inventory::UnitTypeList($em);
  6174.         $brandList Inventory::GetBrandList($em$companyId);
  6175.         foreach ($productList as $product$productListArray[] = $product;
  6176.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6177.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6178.         foreach ($igList as $product$igListArray[] = $product;
  6179.         foreach ($unitList as $product$unitListArray[] = $product;
  6180.         foreach ($brandList as $product$brandListArray[] = $product;
  6181.         $sr_list = [];
  6182.         $QD $this->getDoctrine()
  6183.             ->getRepository('ApplicationBundle:StockRequisition')
  6184.             ->findBy(
  6185.                 array(
  6186.                     'indentTagged' => 0,
  6187.                     'approved' => 1
  6188.                 )
  6189.             );
  6190.         foreach ($QD as $dt) {
  6191.             $sr_list[$dt->getStockRequisitionId()] = array(
  6192.                 'id' => $dt->getStockRequisitionId(),
  6193.                 'name' => $dt->getDocumentHash(),
  6194.                 'text' => $dt->getDocumentHash(),
  6195.             );
  6196.         }
  6197.         return $this->render('@Inventory/pages/input_forms/store_requisition.html.twig',
  6198.             array(
  6199.                 'page_title' => 'Indent Requisition Slip',
  6200.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6201.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6202.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6203.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6204.                 'sr_list' => $sr_list,
  6205.                 'productList' => $productList,
  6206.                 'subCategoryList' => $subCategoryList,
  6207.                 'categoryList' => $categoryList,
  6208.                 'igList' => $igList,
  6209.                 'extId' => $id,
  6210.                 'extDocDetailsData' => $extDocDetailsData,
  6211.                 'extDocData' => $extDocData,
  6212.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6213.                 'unitList' => $unitList,
  6214.                 'brandList' => $brandList,
  6215.                 'brandListArray' => $brandListArray,
  6216.                 'productListArray' => $productListArray,
  6217.                 'subCategoryListArray' => $subCategoryListArray,
  6218.                 'categoryListArray' => $categoryListArray,
  6219.                 'igListArray' => $igListArray,
  6220.                 'unitListArray' => $unitListArray,
  6221.                 'prefix_list' => array(
  6222.                     [
  6223.                         'id' => 1,
  6224.                         'value' => 'GN',
  6225.                         'text' => 'General'
  6226.                     ],
  6227.                     [
  6228.                         'id' => 1,
  6229.                         'value' => 'SD',
  6230.                         'text' => 'For Sales Demand'
  6231.                     ]
  6232.                 ),
  6233.                 'assoc_list' => array(
  6234.                     [
  6235.                         'id' => 1,
  6236.                         'value' => 1,
  6237.                         'text' => 'GN'
  6238.                     ]
  6239.                 )
  6240.             )
  6241.         );
  6242.     }
  6243.     public function CreateStockRequisitionSlipAction(Request $request$id 0)
  6244.     {
  6245.         $em $this->getDoctrine()->getManager();
  6246.         if ($request->isMethod('POST')) {
  6247.             $em $this->getDoctrine()->getManager();
  6248.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockRequisition']; //change
  6249.             $dochash $request->request->get('voucherNumber'); //change
  6250.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6251.             $approveRole $request->request->get('approvalRole');
  6252.             $approveHash $request->request->get('approvalHash');
  6253.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6254.                 $loginId$approveRole$approveHash$id)
  6255.             ) {
  6256.                 $this->addFlash(
  6257.                     'error',
  6258.                     'Sorry, could not insert Data.'
  6259.                 );
  6260.             } else {
  6261.                 if ($request->request->has('check_allowed'))
  6262.                     $check_allowed 1;
  6263.                 $SrID Inventory::CreateNewStockRequisition($id,
  6264.                     $this->getDoctrine()->getManager(),
  6265.                     $request->request,
  6266.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6267.                     $this->getLoggedUserCompanyId($request)
  6268.                 );
  6269.                 //now add Approval info
  6270.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6271.                 $approveRole $request->request->get('approvalRole');
  6272.                 $options = array(
  6273.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6274.                     'notification_server' => $this->container->getParameter('notification_server'),
  6275.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6276.                     'url' => $this->generateUrl(
  6277.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockRequisition']]
  6278.                         ['entity_view_route_path_name']
  6279.                     )
  6280.                 );
  6281.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6282.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  6283.                     $SrID,
  6284.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6285.                 );
  6286.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockRequisition'], $SrID,
  6287.                     $loginId,
  6288.                     $approveRole,
  6289.                     $request->request->get('approvalHash'));
  6290.                 $this->addFlash(
  6291.                     'success',
  6292.                     'New Requisition Added.'
  6293.                 );
  6294.                 $url $this->generateUrl(
  6295.                     'view_sr'
  6296.                 );
  6297. //                return $this->redirect($url . "/" . $SrID);
  6298.             }
  6299.         }
  6300.         $extDocData = [];
  6301.         $extDocDetailsData = [];
  6302.         if ($id == 0) {
  6303.         } else {
  6304.             $extDoc $em->getRepository('ApplicationBundle:StockRequisition')->findOneBy(
  6305.                 array(
  6306.                     'stockRequisitionId' => $id///material
  6307.                 )
  6308.             );
  6309.             //now if its not editable, redirect to view
  6310.             if ($extDoc) {
  6311.                 if ($extDoc->getEditFlag() != 1) {
  6312.                     $url $this->generateUrl(
  6313.                         'view_sr'
  6314.                     );
  6315.                     return $this->redirect($url "/" $id);
  6316.                 } else {
  6317.                     $extDocData $extDoc;
  6318.                     $extDocDetailsData $em->getRepository('ApplicationBundle:StockRequisitionItem')->findBy(
  6319.                         array(
  6320.                             'stockRequisitionId' => $id///material
  6321.                         )
  6322.                     );;
  6323.                 }
  6324.             } else {
  6325.             }
  6326.         }
  6327.         $companyId $this->getLoggedUserCompanyId($request);
  6328.         $productListArray = [];
  6329.         $subCategoryListArray = [];
  6330.         $categoryListArray = [];
  6331.         $igListArray = [];
  6332.         $unitListArray = [];
  6333.         $brandListArray = [];
  6334.         $productList Inventory::ProductList($em$companyId);
  6335.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6336.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6337.         $igList Inventory::ItemGroupList($em$companyId);
  6338.         $unitList Inventory::UnitTypeList($em);
  6339.         $brandList Inventory::GetBrandList($em$companyId);
  6340.         foreach ($productList as $product$productListArray[] = $product;
  6341.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6342.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6343.         foreach ($igList as $product$igListArray[] = $product;
  6344.         foreach ($unitList as $product$unitListArray[] = $product;
  6345.         foreach ($brandList as $product$brandListArray[] = $product;
  6346.         return $this->render('@Inventory/pages/input_forms/stock_requisition_slip.html.twig',
  6347.             array(
  6348.                 'page_title' => 'Stock Requisition Slip',
  6349.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6350.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6351.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6352.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6353.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  6354.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6355.                 'productList' => $productList,
  6356.                 'extId' => $id,
  6357.                 'extDocDetailsData' => $extDocDetailsData,
  6358.                 'extDocData' => $extDocData,
  6359.                 'subCategoryList' => $subCategoryList,
  6360.                 'categoryList' => $categoryList,
  6361.                 'igList' => $igList,
  6362.                 'unitList' => $unitList,
  6363.                 'brandList' => $brandList,
  6364.                 'brandListArray' => $brandListArray,
  6365.                 'productListArray' => $productListArray,
  6366.                 'subCategoryListArray' => $subCategoryListArray,
  6367.                 'categoryListArray' => $categoryListArray,
  6368.                 'igListArray' => $igListArray,
  6369.                 'unitListArray' => $unitListArray,
  6370.                 'productionBomList' => ProductionM::ProductionBomList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6371.                 'productionScheduleList' => ProductionM::ProductionScheduleList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6372.                 'prefix_list' => array(
  6373.                     [
  6374.                         'id' => 1,
  6375.                         'value' => 'GN',
  6376.                         'text' => 'General'
  6377.                     ],
  6378.                     [
  6379.                         'id' => 1,
  6380.                         'value' => 'SD',
  6381.                         'text' => 'For Sales Demand'
  6382.                     ]
  6383.                 ),
  6384.                 'projectList' => $em->getRepository('ApplicationBundle:Project')->findBy(
  6385.                     array(
  6386.                         'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  6387.                     ), array('projectDate' => 'desc')
  6388.                 ),
  6389.                 'salesOrderList' => SalesOrderM::SalesOrderListPendingDelivery($em),
  6390.                 'assoc_list' => array(
  6391.                     [
  6392.                         'id' => 1,
  6393.                         'value' => 'GN',
  6394.                         'text' => 'General'
  6395.                     ]
  6396.                 )
  6397.             )
  6398.         );
  6399.     }
  6400.     public function CreateStockReturnAction(Request $request)
  6401.     {
  6402.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  6403.             array(
  6404.                 'page_title' => 'Stock Return',
  6405. //                'dataList'=>$dta_list
  6406.             )
  6407.         );
  6408.     }
  6409.     public function MaterialInwardAction(Request $request)
  6410.     {
  6411.         $data = [];
  6412.         if ($request->isMethod('POST')) {
  6413.             //first of all resolve the transport costs
  6414.             $total_price_value 0;
  6415.             $data_list $dt $this->getDoctrine()
  6416.                 ->getRepository('ApplicationBundle:PurchaseOrderItem')
  6417.                 ->findBy(
  6418.                     array(
  6419.                         'purchaseOrderId' => $request->request->get('poId'),
  6420.                         'productId' => $request->request->get('products')
  6421.                     )
  6422.                 );
  6423.             $purchase_items = [];
  6424.             foreach ($data_list as $key => $value) {
  6425.                 $purchase_items[$value->getProductId()] = $value;
  6426.             }
  6427.             foreach ($request->request->get('products') as $key => $entry) {
  6428.                 $total_price_value $total_price_value + ($request->request->get('receivedQty')[$key]) * ($purchase_items[$entry]->getPrice());
  6429.             }
  6430.             $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$request->request->get('poId')];
  6431.             $supplier_id $po_data['supplier_id'];
  6432.             $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6433.             foreach ($request->request->get('products') as $key => $entry) {
  6434.                 if ($request->request->get('receivedQty')[$key] > 0)
  6435.                     Inventory::NewMaterialInward($this->getDoctrine()->getManager(),
  6436.                         $request->request,
  6437.                         $key,
  6438.                         $request->request->get('poId'),
  6439.                         $request->request->get('purchaseOrderItemId'),
  6440.                         $supplier_id,
  6441.                         $request->request->get('warehouseId'),
  6442.                         $request->request->get('lotNumber'),
  6443.                         $request->request->get('type_hash'),
  6444.                         $request->request->get('prefix_hash'),
  6445.                         $request->request->get('assoc_hash'),
  6446.                         $request->request->get('number_hash'),
  6447.                         $request->request->get('docHash'),
  6448.                         $request->request->get('docDate'),
  6449.                         $purchase_items[$entry],
  6450.                         $total_price_value,
  6451.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6452.             }
  6453.             $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$request->request->get('warehouseId')]['name'];
  6454. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6455.             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),
  6456.                 "A stack of material Has Arrived at The " $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6457.                 'all',
  6458.                 "",
  6459.                 'information',
  6460.                 "",
  6461.                 "Inbound Material"
  6462.             );
  6463. //                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);
  6464.         }
  6465.         return $this->render('@Inventory/pages/input_forms/material_inward.html.twig',
  6466.             array(
  6467.                 'page_title' => 'Material Inward',
  6468.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6469.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  6470.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  6471.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  6472.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  6473.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  6474.                 "unitList" => Inventory::UnitTypeList($this->getDoctrine()->getManager())
  6475. //                'po'=>Inventory::getPurchaseOrderList
  6476.             )
  6477.         );
  6478.     }
  6479.     public function QualityControlAction(Request $request)
  6480.     {
  6481.         $checked_qc_list_flag 0;
  6482.         if ($request->query->has('checked_qc_list_flag'))
  6483.             $checked_qc_list_flag $request->query->has('checked_qc_list_flag');
  6484.         if ($request->isMethod('POST')) {
  6485.             foreach ($request->request->get('qc_checked', []) as $key => $entry) {
  6486.                 $em $this->getDoctrine()->getManager();
  6487.                 $data $this->getDoctrine()
  6488.                     ->getRepository('ApplicationBundle:MaterialInward')
  6489.                     ->findOneBy(
  6490.                         array(
  6491.                             'qcId' => $entry
  6492.                         )
  6493.                     );
  6494.                 if ($request->request->get('approvedQty')[$entry] <= 0) {
  6495.                     $em->remove($data);
  6496.                     $em->flush();
  6497.                 } else {
  6498.                     $data->setApprovedQty($request->request->get('approvedQty')[$entry]);
  6499.                     $data->setRejectedQty($data->getInwardQty() - $request->request->get('approvedQty')[$entry]);
  6500.                     $data->setQcDate(new \DateTime($request->request->get('qcDate')));
  6501.                     $data->setStage(GeneralConstant::STAGE_PENDING_TAG);
  6502.                     $em->flush();
  6503.                 }
  6504.                 //notification
  6505.                 $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$data->getPurchaseOrderId()];
  6506.                 $supplier_id $po_data['supplier_id'];
  6507.                 $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6508.                 $product_name Inventory::ProductList($this->getDoctrine()->getManager())[$data->getProductId()]['name'];
  6509.                 $qty $request->request->get('approvedQty')[$entry];
  6510.                 $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$data->getWarehouseId()]['name'];
  6511. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6512.                 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),
  6513.                     $qty " among " $data->getInwardQty() . " units of " $product_name " has passed the Quality Control in " .
  6514.                     $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6515.                     'all',
  6516.                     "",
  6517.                     'success',
  6518.                     "",
  6519.                     "Quality Control"
  6520.                 );
  6521.             }
  6522.         }
  6523.         return $this->render('@Inventory/pages/input_forms/qc.html.twig',
  6524.             array(
  6525.                 'page_title' => 'Quality Control',
  6526.                 'checked_qc_list_flag' => $checked_qc_list_flag,
  6527.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6528.                 'warehouse_indexed' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6529.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  6530.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  6531.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  6532.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  6533.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6534.                 'material_inward' => $this->getDoctrine()
  6535.                     ->getRepository('ApplicationBundle:MaterialInward')
  6536.                     ->findBy(
  6537.                         array(
  6538.                             'stage' => $checked_qc_list_flag == GeneralConstant::STAGE_PENDING GeneralConstant::STAGE_PENDING_TAG
  6539.                         )
  6540.                     )
  6541. //                'po'=>Inventory::getPurchaseOrderList
  6542.             )
  6543.         );
  6544.     }
  6545.     public function InventoryTransactionViewAction(Request $request)
  6546.     {
  6547.         $em $this->getDoctrine()->getManager();
  6548.         $qry_data = array(
  6549.             'warehouseId' => [0],
  6550.             'igId' => [0],
  6551.             'brandId' => [0],
  6552.             'categoryId' => [0],
  6553.             'actionTagId' => [0],
  6554.         );
  6555.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6556.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6557.         $data_searched = [];
  6558.         $em $this->getDoctrine()->getManager();
  6559.         $companyId $this->getLoggedUserCompanyId($request);
  6560.         $company_data Company::getCompanyData($em$companyId);
  6561.         $data = [];
  6562.         $print_title "Inventory Report";
  6563.         $document_mark = array(
  6564.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6565.             'copy' => ''
  6566.         );
  6567.         if ($request->isMethod('POST'))
  6568.             $method 'POST';
  6569.         else
  6570.             $method 'GET';
  6571.         {
  6572.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  6573.                 $request->request$method,
  6574.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6575.                 $companyId);
  6576.             if ($request->query->has('returnJson') || $request->request->has('returnJson')) {
  6577.                 return new JsonResponse(
  6578.                     array(
  6579.                         'success' => true,
  6580. //                    'page_title' => 'Product Details',
  6581. //                    'company_data' => $company_data,
  6582.                         'page_title' => 'Inventory Transactions',
  6583.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6584.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6585.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6586.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6587.                         'data_products' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6588.                         'action_tag' => $warehouse_action_list,
  6589.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6590.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6591.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6592.                         'data_searched' => $data_searched
  6593.                     )
  6594.                 );
  6595.             } else if ($request->request->get('print_data_enabled') == 1) {
  6596.                 $print_sub_title "";
  6597.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  6598.                     array(
  6599.                         'page_title' => 'Inventory Report',
  6600.                         'page_header' => 'Report',
  6601.                         'print_title' => $print_title,
  6602.                         'document_type' => 'Journal voucher',
  6603.                         'document_mark_image' => $document_mark['original'],
  6604.                         'page_header_sub' => 'Add',
  6605.                         'item_data' => [],
  6606.                         'received' => 2,
  6607.                         'return' => 1,
  6608.                         'total_w_vat' => 1,
  6609.                         'total_vat' => 1,
  6610.                         'total_wo_vat' => 1,
  6611.                         'invoice_id' => 'abcd1234',
  6612.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6613.                         'created_by' => 'created by',
  6614.                         'created_at' => '',
  6615.                         'red' => 0,
  6616.                         'company_name' => $company_data->getName(),
  6617.                         'company_data' => $company_data,
  6618.                         'company_address' => $company_data->getAddress(),
  6619.                         'company_image' => $company_data->getImage(),
  6620.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6621.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6622.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6623.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6624.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6625.                         'action_tag' => $warehouse_action_list,
  6626.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6627.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6628.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6629.                         'data_searched' => $data_searched
  6630.                     )
  6631.                 );
  6632.             }
  6633.         }
  6634.         return $this->render('@Inventory/pages/report/inventory_transaction_view.html.twig',
  6635.             array(
  6636.                 'page_title' => 'Inventory Transactions',
  6637.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6638.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6639.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6640.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6641.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6642.                 'action_tag' => $warehouse_action_list,
  6643.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6644.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6645.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6646.                 'data_searched' => $data_searched
  6647.             )
  6648.         );
  6649.     }
  6650.     public function StockConsumptionViewAction(Request $request)
  6651.     {
  6652.         $em $this->getDoctrine()->getManager();
  6653.         $start_date $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
  6654.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : new \DateTime();
  6655.         $qry_data = array(
  6656.             'warehouseId' => [0],
  6657.             'igId' => [0],
  6658.             'brandId' => [0],
  6659.             'categoryId' => [0],
  6660.             'actionTagId' => [0],
  6661.         );
  6662.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6663.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6664.         $data_searched = [];
  6665.         $em $this->getDoctrine()->getManager();
  6666.         $company_data Company::getCompanyData($em1);
  6667.         $data = [];
  6668.         $print_title "Inventory Report";
  6669.         $document_mark = array(
  6670.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6671.             'copy' => ''
  6672.         );
  6673.         if ($request->isMethod('POST'))
  6674.             $method 'POST';
  6675.         else
  6676.             $method 'GET';
  6677.         $post_data $method == 'POST' $request->request $request->query;
  6678.         $data_searched Inventory::GetStockConsumptionData($this->getDoctrine()->getManager(),
  6679.             $post_data,
  6680.             $method,
  6681.             $start_date,
  6682.             $end_date,
  6683.             $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6684.         if ($post_data->get('print_data_enabled') == 1) {
  6685.             $print_sub_title "";
  6686.             if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6687.                 $html $this->renderView('@Inventory/pages/print/print_stock_consumption.html.twig',
  6688.                     array(
  6689.                         'pdf' => 'true',
  6690.                         'page_title' => 'Inventory Report',
  6691.                         'page_header' => 'Report',
  6692.                         'print_title' => $print_title,
  6693.                         'document_type' => 'Journal voucher',
  6694.                         'document_mark_image' => $document_mark['original'],
  6695.                         'page_header_sub' => 'Add',
  6696.                         'item_data' => [],
  6697.                         'received' => 2,
  6698.                         'return' => 1,
  6699.                         'total_w_vat' => 1,
  6700.                         'total_vat' => 1,
  6701.                         'total_wo_vat' => 1,
  6702.                         'invoice_id' => 'abcd1234',
  6703.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6704.                         'created_by' => 'created by',
  6705.                         'created_at' => '',
  6706.                         'red' => 0,
  6707.                         'start_date' => $start_date,
  6708.                         'end_date' => $end_date,
  6709.                         'openFilter' => empty($post_data->keys()) ? 0,
  6710.                         'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6711.                         'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6712.                         'company_name' => $company_data->getName(),
  6713.                         'company_data' => $company_data,
  6714.                         'company_address' => $company_data->getAddress(),
  6715.                         'company_image' => $company_data->getImage(),
  6716.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6717.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6718.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6719.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6720.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6721.                         'action_tag' => $warehouse_action_list,
  6722.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6723.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6724.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6725.                         'data_searched' => $data_searched,
  6726.                         'export' => 'all'
  6727.                     )
  6728.                 );
  6729.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6730.                     'orientation' => count($data_searched['query_columns_filter']) > 'landscape' 'portrait',
  6731.                     'no-stop-slow-scripts' => true,
  6732.                     'no-background' => false,
  6733.                     'lowquality' => false,
  6734.                     'encoding' => 'utf-8',
  6735.                     'dpi' => 300,
  6736.                     'image-dpi' => 300,
  6737.                 ));
  6738.                 return new Response(
  6739.                     $pdf_response,
  6740.                     200,
  6741.                     array(
  6742.                         'Content-Type' => 'application/pdf',
  6743.                         'Content-Disposition' => 'attachment; filename="Stock_Consumption.pdf"'
  6744.                     )
  6745.                 );
  6746.             }
  6747.             return $this->render('@Inventory/pages/print/print_stock_consumption.html.twig',
  6748.                 array(
  6749.                     'page_title' => 'Inventory Report',
  6750.                     'page_header' => 'Report',
  6751.                     'print_title' => $print_title,
  6752.                     'document_type' => 'Journal voucher',
  6753.                     'document_mark_image' => $document_mark['original'],
  6754.                     'page_header_sub' => 'Add',
  6755.                     'item_data' => [],
  6756.                     'received' => 2,
  6757.                     'return' => 1,
  6758.                     'total_w_vat' => 1,
  6759.                     'total_vat' => 1,
  6760.                     'total_wo_vat' => 1,
  6761.                     'invoice_id' => 'abcd1234',
  6762.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6763.                     'created_by' => 'created by',
  6764.                     'created_at' => '',
  6765.                     'red' => 0,
  6766.                     'start_date' => $start_date,
  6767.                     'end_date' => $end_date,
  6768.                     'openFilter' => empty($post_data->keys()) ? 0,
  6769.                     'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6770.                     'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6771.                     'company_name' => $company_data->getName(),
  6772.                     'company_data' => $company_data,
  6773.                     'company_address' => $company_data->getAddress(),
  6774.                     'company_image' => $company_data->getImage(),
  6775.                     'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6776.                     'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6777.                     'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6778.                     'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6779.                     'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6780.                     'action_tag' => $warehouse_action_list,
  6781.                     'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6782.                     'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6783.                     'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6784.                     'data_searched' => $data_searched,
  6785.                     'export' => 'all'
  6786.                 )
  6787.             );
  6788.         }
  6789.         return $this->render('@Inventory/pages/report/stock_consumption.html.twig',
  6790.             array(
  6791.                 'page_title' => 'Stock Consumption',
  6792.                 'start_date' => $start_date,
  6793.                 'end_date' => $end_date,
  6794.                 'openFilter' => empty($post_data->keys()) ? 0,
  6795.                 'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6796.                 'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6797.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6798.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6799.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6800.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6801.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6802.                 'action_tag' => $warehouse_action_list,
  6803.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6804.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6805.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6806.                 'data_searched' => $data_searched
  6807.             )
  6808.         );
  6809.     }
  6810.     public function ItemViewAction(Request $request)
  6811.     {
  6812.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  6813.             array(
  6814.                 'page_title' => 'Stock Return'
  6815.             )
  6816.         );
  6817.     }
  6818.     public function ProductViewAction(Request $request$id 0)
  6819.     {
  6820.         $em $this->getDoctrine()->getManager();
  6821.         $companyId $this->getLoggedUserCompanyId($request);
  6822.         $company_data Company::getCompanyData($em$companyId);
  6823.         $data = [];
  6824.         $productData $em->getRepository('ApplicationBundle:InvProducts')
  6825.             ->findOneBy(
  6826.                 array(
  6827.                     'id' => $id
  6828.                 )
  6829.             );
  6830.         $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  6831.             ->findBy(
  6832.                 array(
  6833.                     'productId' => $id
  6834.                 )
  6835.             );
  6836.         $trans_history $em->getRepository('ApplicationBundle:InvItemTransaction')
  6837.             ->findBy(
  6838.                 array(
  6839.                     'productId' => $id
  6840.                 ), array(
  6841.                     'transactionDate' => 'ASC',
  6842.                     'id' => 'ASC'
  6843.                 )
  6844.             );
  6845.         $productDataObj = array();
  6846.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  6847.             $getters array_filter(get_class_methods($productData), function ($method) {
  6848.                 return 'get' === substr($method03);
  6849.             });
  6850.             foreach ($getters as $getter) {
  6851.                 if ($getter == 'getGlobalId')
  6852.                     continue;
  6853.         //                    if ($getter == 'getId')
  6854.         //                        continue;
  6855.                 $Fieldname str_replace('get'''$getter);
  6856.                 $productDataObj[$Fieldname] = $productData->{$getter}(); // `foo!`
  6857.             }
  6858.             if ($request->request->has('genInfoOnly') && $request->request->get('genInfoOnly') == 1) {
  6859.                 $dataArray = array(
  6860.                     'success' => true,
  6861.                     'page_title' => 'Product Details',
  6862.                     'company_data' => $company_data,
  6863.                     'productData' => $productData,
  6864.                     'productDataObj' => $productDataObj,
  6865.                     'defaultImageAppendUrl' => '/uploads/Products/',
  6866.                 );
  6867.             } else {
  6868.                 $dataArray = array(
  6869.                     'success' => true,
  6870.                     'page_title' => 'Product Details',
  6871.                     'company_data' => $company_data,
  6872.                     'productData' => $productData,
  6873.                     'productDataObj' => $productDataObj,
  6874.                     'currInvList' => $currInvList,
  6875.                     'trans_history' => $trans_history,
  6876.                     'entityList' => GeneralConstant::$Entity_list_details,
  6877.         //                    'productList' => Inventory::ProductList($em, $companyId),
  6878.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  6879.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  6880.                     'igList' => Inventory::ItemGroupList($em$companyId),
  6881.                     'unitList' => Inventory::UnitTypeList($em),
  6882.                     'brandList' => Inventory::GetBrandList($em$companyId),
  6883.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  6884.                     'warehouseList' => Inventory::WarehouseList($em),
  6885.                     'defaultImageAppendUrl' => '/uploads/Products/',
  6886.                 );
  6887.             }
  6888.             return new JsonResponse(
  6889.                 $dataArray
  6890.             );
  6891.         }
  6892.         $dataArray = array(
  6893.             'page_title' => 'Product Details',
  6894.             'company_data' => $company_data,
  6895.             'productData' => $productData,
  6896.             'currInvList' => $currInvList,
  6897.             'trans_history' => $trans_history,
  6898.             'entityList' => GeneralConstant::$Entity_list_details,
  6899.         //            'productList' => Inventory::ProductList($em, $companyId),
  6900.             'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  6901.             'categoryList' => Inventory::ProductCategoryList($em$companyId),
  6902.             'igList' => Inventory::ItemGroupList($em$companyId),
  6903.             'unitList' => Inventory::UnitTypeList($em),
  6904.             'brandList' => Inventory::GetBrandList($em$companyId),
  6905.             'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  6906.             'warehouseList' => Inventory::WarehouseList($em),
  6907.         );
  6908.         return $this->render('@Inventory/pages/views/product_view.html.twig'$dataArray
  6909.         );
  6910.     }
  6911.     public function CheckForProductInWarehouseAction(Request $request$queryStr '')
  6912.     {
  6913.         $em $this->getDoctrine()->getManager();
  6914.         $companyId $this->getLoggedUserCompanyId($request);
  6915.         $data = [
  6916.             'availableQty' => 0,
  6917.             'productByCodesArray' => [],
  6918.             'indRowId' => 0
  6919.         ];
  6920.         $html '';
  6921.         $productByCodeData = [];
  6922.         if ($request->isMethod('POST')) {
  6923.             $warehouseId $request->request->get('warehouseId'0);
  6924.             $warehouseActionId $request->request->get('warehouseActionId'0);
  6925.             $productId $request->request->get('productId'0);
  6926.             $indRowId $request->request->get('indRowId'0);
  6927.             $data['indRowId'] = $indRowId;
  6928.             $inStorage $em->getRepository('ApplicationBundle:InventoryStorage')
  6929.                 ->findBy(
  6930.                     array(
  6931.                         'productId' => $productId,
  6932.                         'warehouseId' => $warehouseId,
  6933.                         'actionTagId' => $warehouseActionId,
  6934.                         'CompanyId' => $companyId,
  6935.                     )
  6936.                 );
  6937.             foreach ($inStorage as $strg) {
  6938.                 $data['availableQty'] += $strg->getQty();
  6939.             }
  6940.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  6941.                 ->findBy(
  6942.                     array(
  6943.                         'productId' => $productId,
  6944.                         'warehouseId' => $warehouseId,
  6945.                         'warehouseActionId' => $warehouseActionId,
  6946.                         'CompanyId' => $companyId,
  6947.                     )
  6948.                 );
  6949.             foreach ($productByCodeData as $pbc) {
  6950.                 $data['productByCodesArray'][] = array(
  6951.                     'id' => $pbc->getProductByCodeId(),
  6952.                     'productId' => $pbc->getProductId(),
  6953.                     'warehouseId' => $pbc->getWarehouseId(),
  6954.                     'warehouseActionId' => $pbc->getWarehouseActionId(),
  6955. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  6956.                     'sales_code' => str_pad($pbc->getSalesCode(), 13'0'STR_PAD_LEFT),
  6957. //                'sales_code'=>$d['sales_code'],
  6958.                 );
  6959.             }
  6960.             return new JsonResponse(array(
  6961.                     'success' => true,
  6962.                     'data' => $data,
  6963.                 )
  6964.             );
  6965.         }
  6966.         return new JsonResponse(
  6967.             array(
  6968.                 'success' => false,
  6969.                 'data' => $data,
  6970.             )
  6971.         );
  6972.     }
  6973.     public function ProductByCodeListAjaxAction(Request $request$queryStr '')
  6974.     {
  6975.         $em $this->getDoctrine()->getManager();
  6976.         $companyId $this->getLoggedUserCompanyId($request);
  6977.         $company_data Company::getCompanyData($em$companyId);
  6978.         $data = [];
  6979.         $html '';
  6980.         $productByCodeData = [];
  6981.         if ($request->request->has('query') && $queryStr == '')
  6982.             $queryStr $request->request->get('queryStr');
  6983.         $get_kids_sql "select product_by_code_id id, product_id, warehouse_id, warehouse_action_id,
  6984.                             sales_code ,
  6985.                             serial_no,
  6986.                             imei1,
  6987.                             imei2,
  6988.                             imei3,
  6989.                             imei4
  6990.                             from product_by_code
  6991.                             where ( CONVERT(sales_code,char)  like '%" $queryStr "%'
  6992.                                     or  CONVERT(serial_no,char)  like '%" $queryStr "%'
  6993.                                     or  CONVERT(imei1,char)  like '%" $queryStr "%'
  6994.                                     or  CONVERT(imei2,char)  like '%" $queryStr "%'
  6995.                                     or  CONVERT(imei3,char)  like '%" $queryStr "%'
  6996.                                     or  CONVERT(imei4,char)  like '%" $queryStr "%'
  6997.                                     ) ";
  6998.         if ($request->query->has('warehouseId'))
  6999.             $get_kids_sql .= " and warehouse_id=" $request->query->get('warehouseId') . " ";
  7000.         if ($request->query->has('position'))
  7001.             $get_kids_sql .= " and position=" $request->query->get('position') . " ";
  7002.         if ($request->query->has('deliveryReceiptId'))
  7003.             $get_kids_sql .= " and deliveryReceiptId=" $request->query->get('deliveryReceiptId') . " ";
  7004.         if ($request->query->has('warehouseActionId'))
  7005.             $get_kids_sql .= " and warehouse_action_id=" $request->query->get('warehouseActionId') . " ";
  7006.         if ($request->query->has('productId'))
  7007.             $get_kids_sql .= " and product_id=" $request->query->get('productId') . " ";
  7008.         $get_kids_sql .= " and company_id=" $companyId " limit 25";
  7009.         $stmt $em->getConnection()->prepare($get_kids_sql);
  7010.         $stmt->execute();
  7011.         $get_kids $stmt->fetchAll();
  7012.         if (!empty($get_kids)) {
  7013.             foreach ($get_kids as $d) {
  7014.                 $dt = array(
  7015.                     'id' => $d['id'],
  7016.                     'productId' => $d['product_id'],
  7017.                     'warehouseId' => $d['warehouse_id'],
  7018.                     'warehouseActionId' => $d['warehouse_action_id'],
  7019. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7020.                     'sales_code' => str_pad($d['sales_code'], 13'0'STR_PAD_LEFT),
  7021.                     'serial_no' => str_pad($d['serial_no'], 13'0'STR_PAD_LEFT),
  7022.                     'imei1' => str_pad($d['imei1'], 13'0'STR_PAD_LEFT),
  7023.                     'imei2' => str_pad($d['imei2'], 13'0'STR_PAD_LEFT),
  7024.                     'imei3' => str_pad($d['imei3'], 13'0'STR_PAD_LEFT),
  7025.                     'imei4' => str_pad($d['imei4'], 13'0'STR_PAD_LEFT),
  7026. //                'sales_code'=>$d['sales_code'],
  7027.                 );
  7028.                 $data[] = $dt;
  7029.             }
  7030.         }
  7031. //        if($request->query->has('returnJson'))
  7032.         {
  7033.             return new JsonResponse(
  7034.                 array(
  7035.                     'success' => true,
  7036. //                    'page_title' => 'Product Details',
  7037. //                    'company_data' => $company_data,
  7038.                     'data' => $data,
  7039. //                    'exId'=>$id,
  7040. //                'productByCodeData' => $productByCodeData,
  7041. //                'productData' => $productData,
  7042. //                'currInvList' => $currInvList,
  7043. //                'productList' => Inventory::ProductList($em, $companyId),
  7044. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  7045. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  7046. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  7047. //                'unitList' => Inventory::UnitTypeList($em),
  7048. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  7049. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  7050. //                'warehouseList' => Inventory::WarehouseList($em),
  7051.                 )
  7052.             );
  7053.         }
  7054.     }
  7055.     public function selectDataAjaxAction(Request $request$queryStr '',
  7056.                                                  $version 'latest',
  7057.                                                  $identifier '_default_',
  7058.                                                  $apiKey '_ignore_'
  7059.     )
  7060.     {
  7061.         $em $this->getDoctrine()->getManager();
  7062.         $em_goc $this->getDoctrine()->getManager('company_group');
  7063.         $companyId 0;
  7064.         $skipCurrentUserIdRestriction $request->get('skipCurrentUserIdRestriction'0);
  7065.         $dataOnly $request->get('dataOnly'0);
  7066.         $skipCurrentEmployeeIdRestriction $request->get('skipCurrentEmployeeIdRestriction'0);
  7067.         $skipCurrentUserLoginIdRestriction $request->get('skipCurrentUserLoginIdRestriction'0);
  7068.         $currentUserId $request->getSession()->get(UserConstants::USER_ID0);
  7069.         $currentEmployeeId $request->getSession()->get(UserConstants::USER_EMPLOYEE_ID0);
  7070.         $currentUserLoginIds = [];
  7071.         if ($request->request->get('entity_group'0)) {
  7072.             $companyId 0;
  7073.             $em $this->getDoctrine()->getManager('company_group');
  7074.         } else {
  7075.             if ($request->request->get('appId'0) != 0) {
  7076.                 $gocEnabled 0;
  7077.                 if ($this->container->hasParameter('entity_group_enabled'))
  7078.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7079.                 else
  7080.                     $gocEnabled 1;
  7081.                 if ($gocEnabled == 1) {
  7082.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7083.                         $this->getDoctrine()->getManager('company_group'),
  7084.                         $gocEnabled,
  7085.                         $request->request->get('appId'0)
  7086.                     );
  7087.                     if (!empty($dataToConnect)) {
  7088.                         $connector $this->container->get('application_connector');
  7089.                         $connector->resetConnection(
  7090.                             'default',
  7091.                             $dataToConnect['dbName'],
  7092.                             $dataToConnect['dbUser'],
  7093.                             $dataToConnect['dbPass'],
  7094.                             $dataToConnect['dbHost'],
  7095.                             $reset true
  7096.                         );
  7097.                         $em $this->getDoctrine()->getManager();
  7098.                     }
  7099.                 }
  7100.             } else if ($request->getSession()->get(UserConstants::USER_APP_ID) != && $request->getSession()->get(UserConstants::USER_APP_ID) != null) {
  7101.                 $gocEnabled 0;
  7102.                 if ($this->container->hasParameter('entity_group_enabled'))
  7103.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7104.                 else
  7105.                     $gocEnabled 1;
  7106.                 if ($gocEnabled == 1) {
  7107.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7108.                         $this->getDoctrine()->getManager('company_group'),
  7109.                         $gocEnabled,
  7110.                         $request->getSession()->get(UserConstants::USER_APP_ID)
  7111.                     );
  7112.                     if (!empty($dataToConnect)) {
  7113.                         $connector $this->container->get('application_connector');
  7114.                         $connector->resetConnection(
  7115.                             'default',
  7116.                             $dataToConnect['dbName'],
  7117.                             $dataToConnect['dbUser'],
  7118.                             $dataToConnect['dbPass'],
  7119.                             $dataToConnect['dbHost'],
  7120.                             $reset true
  7121.                         );
  7122.                         $em $this->getDoctrine()->getManager();
  7123.                     }
  7124.                 }
  7125.             }
  7126.             $companyId $this->getLoggedUserCompanyId($request);
  7127.         }
  7128.         $configData = [];
  7129.         $isSingleDataset 1;
  7130.         $dataSet $request->request->has('dataset') ? $request->request->get('dataset') : [];
  7131.         if (is_string($dataSet)) $dataSet json_decode($dataSettrue);
  7132.         $valuePairs $request->get('valuePairs', []);
  7133.         if (is_string($valuePairs)) $valuePairs json_decode($valuePairstrue);
  7134.         $allResult = [];
  7135.         $datasetFromConfig = [];
  7136.         if ($identifier != '_default_') {
  7137.             $config_file $this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' $identifier 'Config.json';
  7138.             if (!file_exists($config_file)) {
  7139.             } else {
  7140.                 $fileText file_get_contents($config_file);
  7141.                 //now replace any value pairs
  7142.                 foreach ($valuePairs as $kkeeyy => $vvaalluuee) {
  7143.                     if (is_array($vvaalluuee)) {
  7144.                         if (isset($vvaalluuee['value']) && isset($vvaalluuee['type'])) {
  7145.                             if ($vvaalluuee['type'] == 'array'$fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee['value']), $fileText);
  7146.                             if ($vvaalluuee['type'] == 'value'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7147.                             if ($vvaalluuee['type'] == 'text'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7148.                         } else {
  7149.                             $fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee), $fileText);
  7150.                         }
  7151.                     }
  7152.                     $fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee$fileText);
  7153.                 }
  7154.                 $fileText str_ireplace('_query_'$request->get('query'$queryStr), $fileText);
  7155.                 $fileText str_ireplace('_itemLimit_'$request->get('itemLimit''_all_'), $fileText);
  7156.                 $fileText str_ireplace('_offset_'$request->get('offset', ($request->get('itemLimit'10))*($request->get('page'1)-1)), $fileText);
  7157.                 if (!(strpos($fileText'_CURRENT_USER_LOGIN_IDS_') === false) && $skipCurrentUserLoginIdRestriction == 0) {
  7158.                     $userInfo = [];
  7159.                     if ($request->getSession()->get(UserConstants::USER_TYPE0) == UserConstants::USER_TYPE_APPLICANT) {
  7160.                         $userInfo $em_goc->getRepository('CompanyGroupBundle:EntityLoginLog')->findBy(
  7161.                             array('userId' => $currentUserId)
  7162.                         );
  7163.                     } else {
  7164.                         $userInfo $em->getRepository('ApplicationBundle:SysLoginLog')->findBy(
  7165.                             array('userId' => $currentUserId)
  7166.                         );
  7167.                     }
  7168.                     foreach ($userInfo as $uLogininfo) {
  7169.                         $currentUserLoginIds[] = $uLogininfo->getLoginId();
  7170.                     }
  7171.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_'json_encode($currentUserLoginIds), $fileText);
  7172.                 } else {
  7173.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_''_EMPTY_'$fileText);
  7174.                 }
  7175.                 if (!(strpos($fileText'_CURRENT_USER_ID_') === false) && $skipCurrentUserIdRestriction == 0) {
  7176.                     $fileText str_ireplace('_CURRENT_USER_ID_'$currentUserId$fileText);
  7177.                 } else {
  7178.                     $fileText str_ireplace('_CURRENT_USER_ID_''_EMPTY_'$fileText);
  7179.                 }
  7180.                 if (!(strpos($fileText'_CURRENT_USER_EMPLOYEE_ID_') === false) && $skipCurrentEmployeeIdRestriction == 0) {
  7181.                     if ((strpos($fileText'skipCurrentEmployeeIdRestriction') === false)) {
  7182.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_'$currentEmployeeId$fileText);
  7183.                     } else {
  7184.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  7185.                     }
  7186.                 } else {
  7187.                     $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  7188.                 }
  7189.                 if ($fileText)
  7190.                     $datasetFromConfig json_decode($fileTexttrue);
  7191.                 $skipCurrentUserIdRestriction = isset($datasetFromConfig['skipCurrentUserIdRestriction']) ? $datasetFromConfig['skipCurrentUserIdRestriction'] : $skipCurrentUserIdRestriction;
  7192.                 $skipCurrentEmployeeIdRestriction = isset($datasetFromConfig['skipCurrentEmployeeIdRestriction']) ? $datasetFromConfig['skipCurrentEmployeeIdRestriction'] : $skipCurrentEmployeeIdRestriction;
  7193.                 $skipCurrentUserLoginIdRestriction = isset($datasetFromConfig['skipCurrentUserLoginIdRestriction']) ? $datasetFromConfig['skipCurrentUserLoginIdRestriction'] : $skipCurrentUserLoginIdRestriction;
  7194.             }
  7195.         }
  7196.         if ($dataSet == null$dataSet = [];
  7197. //        return new JsonResponse(array(
  7198. //            'queryStr'=>$queryStr
  7199. //        ));
  7200.         if (!empty($datasetFromConfig)) {
  7201.             if (isset($datasetFromConfig['tableName'])) {
  7202.                 $isSingleDataset 1;
  7203.                 $dataSet[] = $datasetFromConfig;
  7204.             } else {
  7205.                 if (count($datasetFromConfig) == 1)
  7206.                     $isSingleDataset 1;
  7207.                 $dataSet $datasetFromConfig;
  7208.             }
  7209.         }
  7210.         if (empty($dataSet)) {
  7211.             $isSingleDataset 1;
  7212.             $singleDataSet = array(
  7213.                 "valueField" => $request->request->has('valueField') ? $request->request->get('valueField') : 'id',
  7214.                 "query" => $request->get('query'$queryStr),
  7215.                 "headMarkers" => $request->get('headMarkers'''),
  7216.                 "headMarkersStrictMatch" => $request->get('headMarkersStrictMatch'0),
  7217.                 "itemLimit" => $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25,
  7218.                 "selectorId" => $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_',
  7219.                 "textField" => $request->request->has('textField') ? $request->request->get('textField') : 'name',
  7220.                 "tableName" => $request->request->has('tableName') ? $request->request->get('tableName') : '',
  7221.                 "isMultiple" => $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0,
  7222.                 "orConditions" => $request->request->has('orConditions') ? $request->request->get('orConditions') : [],
  7223.                 "andConditions" => $request->request->has('andConditions') ? $request->request->get('andConditions') : [],
  7224.                 "andOrConditions" => $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [],
  7225.                 "mustConditions" => $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [],
  7226.                 "joinTableData" => $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [],
  7227.                 "renderTextFormat" => $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '',
  7228.                 "setDataForSingle" => $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0,
  7229.                 "dataId" => $request->request->has('dataId') ? $request->request->get('dataId') : 0,
  7230.                 "lastChildrenOnly" => $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0,
  7231.                 "parentOnly" => $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0,
  7232.                 "parentIdField" => $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id',
  7233.                 "skipDefaultCompanyId" => $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1,
  7234.                 "offset" => $request->request->has('offset') ? $request->request->get('offset') : 0,
  7235.                 "returnTotalMatchedEntriesFlag" => $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0,
  7236.                 "nextOffset" => 0,
  7237.                 "totalMatchedEntries" => 0,
  7238.                 "convertToObject" => $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [],
  7239.                 "convertDateToStringFieldList" => $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [],
  7240.                 "orderByConditions" => $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [],
  7241.                 "convertToUrl" => $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [],
  7242.                 "fullPathList" => $request->request->has('fullPathList') ? $request->request->get('fullPathList') : [],
  7243.                 "ret_data" => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  7244.             );
  7245.             $dataSet[] = $singleDataSet;
  7246.         }
  7247. //        $lastResult = [
  7248. //            'identifier' => $identifier,
  7249. //            'dataSet' => $dataSet,
  7250. //        ];
  7251. //        return new JsonResponse($lastResult);
  7252.         $userId $request->getSession()->get(UserConstants::USER_ID);
  7253. //        public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [],$userId=0)
  7254.         foreach ($dataSet as $dsIndex => $dataConfig) {
  7255.             $companyId 0;
  7256.             $queryStringIndividual $queryStr;
  7257.             $data = [];
  7258.             $data_by_id = [];
  7259.             $setValueArray = [];
  7260.             $silentChangeSelectize 0;
  7261.             $setValue 0;
  7262.             $setValueType 0;// 0 for id , 1 for query
  7263.             $selectAll 0;
  7264.             if ($queryStringIndividual == '_EMPTY_')
  7265.                 $queryStringIndividual '';
  7266.             if (isset($dataConfig['query']))
  7267.                 $queryStringIndividual $dataConfig['query'];
  7268.             if ($queryStringIndividual == '_EMPTY_')
  7269.                 $queryStringIndividual '';
  7270.             $queryStringIndividual str_replace('_FSLASH_''/'$queryStringIndividual);
  7271.             if ($queryStringIndividual === '#setValue:') {
  7272.                 $queryStringIndividual '';
  7273.             }
  7274.             if (!(strpos($queryStringIndividual'_silent_change_') === false)) {
  7275.                 $silentChangeSelectize 1;
  7276.                 $queryStringIndividual str_ireplace('_silent_change_'''$queryStringIndividual);
  7277.             }
  7278.             if (!(strpos($queryStringIndividual'#setValue:') === false)) {
  7279.                 $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStringIndividual));
  7280.                 foreach ($setValueArrayBeforeFilter as $svf) {
  7281.                     if ($svf == '_ALL_') {
  7282.                         $selectAll 1;
  7283.                         $setValueArray = [];
  7284.                         continue;
  7285.                     }
  7286.                     if (is_numeric($svf)) {
  7287.                         $setValueArray[] = ($svf 1);
  7288.                         $setValue $svf 1;
  7289.                     }
  7290.                 }
  7291.                 $queryStringIndividual '';
  7292.             }
  7293.             $valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
  7294.             $headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''//Special Field
  7295.             $headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0//Special Field
  7296.             $itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
  7297.             $selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
  7298.             $textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
  7299.             $table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
  7300.             $isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
  7301.             $orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
  7302.             $andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
  7303.             $andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
  7304.             $mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
  7305.             $joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
  7306.             $renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
  7307.             $setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
  7308.             $dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
  7309.             $lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
  7310.             $parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
  7311.             $parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
  7312.             $skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
  7313.             $offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
  7314.             $returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
  7315.             $nextOffset 0;
  7316.             $totalMatchedEntries 0;
  7317.             $convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
  7318.             $convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
  7319.             $orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
  7320.             $convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
  7321.             $fullPathList = isset($dataConfig['fullPathList']) ? $dataConfig['fullPathList'] : [];
  7322.             if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  7323.             if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  7324.             if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  7325.             if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  7326.             if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  7327.             if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  7328.             if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  7329.             if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  7330.             if (is_string($fullPathList)) $fullPathList json_decode($fullPathListtrue);
  7331. //            return new JsonResponse(array(
  7332. //                'dataSet'=>$dataSet,
  7333. //                'dataConfig'=>$dataConfig,
  7334. //                'hi'=>$this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json',
  7335. //                'hiD'=>file_get_contents($this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json')
  7336. //            ));
  7337.             if ($table == '') {
  7338.                 $lastResult = array(
  7339.                     'success' => false,
  7340.                     'currentTs' => (new \Datetime())->format('U'),
  7341.                     'isMultiple' => $isMultiple,
  7342.                     'setValueArray' => $setValueArray,
  7343.                     'setValue' => $setValue,
  7344.                     'data' => $data,
  7345.                     'dataId' => $dataId,
  7346.                     'selectorId' => $selectorId,
  7347.                     'dataById' => $data_by_id,
  7348.                     'selectedId' => 0,
  7349.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  7350.                 );
  7351.             } else {
  7352.                 $restrictionData = array(
  7353. //            'table'=>'relevantField in restriction'
  7354.                     'warehouse_action' => 'warehouseActionIds',
  7355.                     'branch' => 'branchIds',
  7356.                     'warehouse' => 'warehouseIds',
  7357.                     'production_process_settings' => 'productionProcessIds',
  7358.                 );
  7359.                 $restrictionIdList = [];
  7360.                 $filterQryForCriteria "select ";
  7361.                 $selectQry "";
  7362. //        $selectQry=" `$table`.* ";
  7363.                 $selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
  7364.                 $selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
  7365.                 if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  7366.                 foreach ($selectFieldList as $selField) {
  7367.                     if ($selectQry != '')
  7368.                         $selectQry .= ", ";
  7369.                     if ($selField == '*')
  7370.                         $selectQry .= " `$table`.$selField ";
  7371.                     else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7372.                         if ($selectPrefix == '')
  7373.                             $selectQry .= " count(*)  ";
  7374.                         else
  7375.                             $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  7376.                     } else {
  7377.                         if ($selectPrefix == '')
  7378.                             $selectQry .= " `$table`.`$selField` ";
  7379.                         else
  7380.                             $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  7381.                     }
  7382.                 }
  7383.                 $joinQry " from $table ";
  7384. //        $filterQryForCriteria = "select * from $table ";
  7385.                 foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  7386. //            $conditionStr.=' 1=1 ';
  7387.                     $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  7388.                     $joinTableAlias $joinTableName '_' $joinIndex;
  7389.                     $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  7390.                     $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  7391.                     $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  7392.                     $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  7393.                     $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  7394.                     $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  7395.                     $joinMustConditions = isset($joinTableDatum['joinMustConditions']) ? $joinTableDatum['joinMustConditions'] : [];
  7396.                     $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  7397.                     $joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
  7398.                     $joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
  7399.                     if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  7400.                     if (is_string($joinMustConditions)) $joinMustConditions json_decode($joinMustConditionstrue);
  7401.                     if (is_string($joinAndOrConditions)) $joinAndOrConditions json_decode($joinAndOrConditionstrue);
  7402.                     if (is_string($joinOrConditions)) $joinOrConditions json_decode($joinOrConditionstrue);
  7403.                     foreach ($selectFieldList as $selField) {
  7404.                         if ($selField == '*')
  7405.                             $selectQry .= ", `$joinTableAlias`.$selField ";
  7406.                         else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7407.                             if ($selectPrefix == '')
  7408.                                 $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  7409.                             else
  7410.                                 $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  7411.                         } else {
  7412.                             if ($selectPrefix == '')
  7413.                                 $selectQry .= ", `$joinTableAlias`.`$selField`  ";
  7414.                             else
  7415.                                 $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  7416.                         }
  7417.                     }
  7418.                     $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  7419. //            if($joinTablePrimaryField!='')
  7420. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7421. //            $joinAndString = '';
  7422.                     $joinMustString '';
  7423.                     if ($joinTablePrimaryField != '')
  7424.                         $joinQry .= "  `$joinTableAlias`.`$joinTableOnField$fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7425.                     foreach ($joinMustConditions as $mustCondition) {
  7426. //            $conditionStr.=' 1=1 ';
  7427.                         $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  7428.                         $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  7429.                         $aliasInCondition $table;
  7430.                         if (!(strpos($cfield'.') === false)) {
  7431.                             $fullCfieldArray explode('.'$cfield);
  7432.                             $aliasInCondition $fullCfieldArray[0];
  7433.                             $cfield $fullCfieldArray[1];
  7434.                         }
  7435.                         $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  7436.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7437.                             if ($joinMustString != '')
  7438.                                 $joinMustString .= " and ";
  7439.                             if ($ctype == 'like') {
  7440.                                 $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7441.                                 $wordsBySpaces explode(' '$cvalue);
  7442.                                 foreach ($wordsBySpaces as $word) {
  7443.                                     if ($joinMustString != '')
  7444.                                         $joinMustString .= " and ";
  7445.                                     $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7446.                                 }
  7447.                             } else if ($ctype == 'not like') {
  7448.                                 $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7449.                                 $wordsBySpaces explode(' '$cvalue);
  7450.                                 foreach ($wordsBySpaces as $word) {
  7451.                                     if ($joinMustString != '')
  7452.                                         $joinMustString .= " and ";
  7453.                                     $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7454.                                 }
  7455.                             } else if ($ctype == 'not_in') {
  7456.                                 $joinMustString .= " ( ";
  7457.                                 if (in_array('null'$cvalue)) {
  7458.                                     $joinMustString .= " `$joinTableAlias`.$cfield is not null";
  7459.                                     $cvalue array_diff($cvalue, ['null']);
  7460.                                     if (!empty($cvalue))
  7461.                                         $joinMustString .= " and ";
  7462.                                 }
  7463.                                 if (in_array(''$cvalue)) {
  7464.                                     $joinMustString .= "`$joinTableAlias`.$cfield != '' ";
  7465.                                     $cvalue array_diff($cvalue, ['']);
  7466.                                     if (!empty($cvalue))
  7467.                                         $joinMustString .= " and ";
  7468.                                 }
  7469.                                 $joinMustString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7470.                             } else if ($ctype == 'in') {
  7471.                                 if (in_array('null'$cvalue)) {
  7472.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null";
  7473.                                     $cvalue array_diff($cvalue, ['null']);
  7474.                                     if (!empty($cvalue))
  7475.                                         $joinMustString .= " and ";
  7476.                                 }
  7477.                                 if (in_array(''$cvalue)) {
  7478.                                     $joinMustString .= "`$joinTableAlias`.$cfield = '' ";
  7479.                                     $cvalue array_diff($cvalue, ['']);
  7480.                                     if (!empty($cvalue))
  7481.                                         $joinMustString .= " and ";
  7482.                                 }
  7483.                                 $joinMustString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7484.                             } else if ($ctype == '=') {
  7485. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7486. //                            $fullCfieldArray = explode('.', $cfield);
  7487. //                            $aliasInCondition = $fullCfieldArray[0];
  7488. //                            $cfield = $fullCfieldArray[1];
  7489. //                        }
  7490.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7491.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null ";
  7492.                                 else
  7493.                                     $joinMustString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7494.                             } else if ($ctype == '!=') {
  7495.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7496.                                     $joinMustString .= "`$joinTableAlias`.$cfield is not null ";
  7497.                                 else
  7498.                                     $joinMustString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7499.                             } else {
  7500.                                 if (is_string($cvalue))
  7501.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7502.                                 else
  7503.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7504.                             }
  7505.                         }
  7506.                     }
  7507. //            if ($joinMustString != '') {
  7508. //                if ($conditionStr != '')
  7509. //                    $conditionStr .= (" and (" . $joinMustString . ") ");
  7510. //                else
  7511. //                    $conditionStr .= ("  (" . $joinMustString . ") ");
  7512. //            }
  7513.                     if ($joinMustString != '') {
  7514.                         $joinQry .= (' and ' $joinMustString);
  7515. //                        $joinQry.=' and (';
  7516.                     }
  7517.                     $mustBracketDone 0;
  7518.                     $joinAndString '';
  7519. //                    if ($joinTablePrimaryField != '')
  7520. //                        $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7521.                     foreach ($joinAndConditions as $andCondition) {
  7522. //            $conditionStr.=' 1=1 ';
  7523.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  7524.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  7525.                         $aliasInCondition $table;
  7526.                         if (!(strpos($cfield'.') === false)) {
  7527.                             $fullCfieldArray explode('.'$cfield);
  7528.                             $aliasInCondition $fullCfieldArray[0];
  7529.                             $cfield $fullCfieldArray[1];
  7530.                         }
  7531.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  7532.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7533.                             if ($joinAndString != '')
  7534.                                 $joinAndString .= " and ";
  7535.                             if ($ctype == 'like') {
  7536.                                 $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7537.                                 $wordsBySpaces explode(' '$cvalue);
  7538.                                 foreach ($wordsBySpaces as $word) {
  7539.                                     if ($joinAndString != '')
  7540.                                         $joinAndString .= " and ";
  7541.                                     $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7542.                                 }
  7543.                             } else if ($ctype == 'not like') {
  7544.                                 $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7545.                                 $wordsBySpaces explode(' '$cvalue);
  7546.                                 foreach ($wordsBySpaces as $word) {
  7547.                                     if ($joinAndString != '')
  7548.                                         $joinAndString .= " and ";
  7549.                                     $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7550.                                 }
  7551.                             } else if ($ctype == 'not_in') {
  7552.                                 $joinAndString .= " ( ";
  7553.                                 if (in_array('null'$cvalue)) {
  7554.                                     $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  7555.                                     $cvalue array_diff($cvalue, ['null']);
  7556.                                     if (!empty($cvalue))
  7557.                                         $joinAndString .= " and ";
  7558.                                 }
  7559.                                 if (in_array(''$cvalue)) {
  7560.                                     $joinAndString .= "`$joinTableAlias`.$cfield != '' ";
  7561.                                     $cvalue array_diff($cvalue, ['']);
  7562.                                     if (!empty($cvalue))
  7563.                                         $joinAndString .= " and ";
  7564.                                 }
  7565.                                 $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7566.                             } else if ($ctype == 'in') {
  7567.                                 if (in_array('null'$cvalue)) {
  7568.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null";
  7569.                                     $cvalue array_diff($cvalue, ['null']);
  7570.                                     if (!empty($cvalue))
  7571.                                         $joinAndString .= " and ";
  7572.                                 }
  7573.                                 if (in_array(''$cvalue)) {
  7574.                                     $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  7575.                                     $cvalue array_diff($cvalue, ['']);
  7576.                                     if (!empty($cvalue))
  7577.                                         $joinAndString .= " and ";
  7578.                                 }
  7579.                                 $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7580.                             } else if ($ctype == '=') {
  7581. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7582. //                            $fullCfieldArray = explode('.', $cfield);
  7583. //                            $aliasInCondition = $fullCfieldArray[0];
  7584. //                            $cfield = $fullCfieldArray[1];
  7585. //                        }
  7586.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7587.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  7588.                                 else
  7589.                                     $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7590.                             } else if ($ctype == '!=') {
  7591.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7592.                                     $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  7593.                                 else
  7594.                                     $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7595.                             } else {
  7596.                                 if (is_string($cvalue))
  7597.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7598.                                 else
  7599.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7600.                             }
  7601.                         }
  7602.                     }
  7603. //            if ($joinAndString != '') {
  7604. //                if ($conditionStr != '')
  7605. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  7606. //                else
  7607. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  7608. //            }
  7609.                     if ($joinAndString != '') {
  7610.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7611.                             $joinQry .= ' and (';
  7612.                             $mustBracketDone 1;
  7613.                         }
  7614.                         if ($joinQry != '')
  7615.                             $joinQry .= (" and (" $joinAndString ") ");
  7616.                         else
  7617.                             $joinQry .= ("  (" $joinAndString ") ");
  7618.                     }
  7619.                     $joinAndOrString "";
  7620.                     foreach ($joinAndOrConditions as $andOrCondition) {
  7621. //            $conditionStr.=' 1=1 ';
  7622.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  7623.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  7624.                         $aliasInCondition $table;
  7625.                         if (!(strpos($cfield'.') === false)) {
  7626.                             $fullCfieldArray explode('.'$cfield);
  7627.                             $aliasInCondition $fullCfieldArray[0];
  7628.                             $cfield $fullCfieldArray[1];
  7629.                         }
  7630.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  7631.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7632.                             if ($joinAndOrString != '')
  7633.                                 $joinAndOrString .= " or ";
  7634.                             if ($ctype == 'like') {
  7635.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7636.                                 $wordsBySpaces explode(' '$cvalue);
  7637.                                 foreach ($wordsBySpaces as $word) {
  7638.                                     if ($joinAndOrString != '')
  7639.                                         $joinAndOrString .= " or ";
  7640.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7641.                                 }
  7642.                             } else if ($ctype == 'not like') {
  7643.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7644.                                 $wordsBySpaces explode(' '$cvalue);
  7645.                                 foreach ($wordsBySpaces as $word) {
  7646.                                     if ($joinAndOrString != '')
  7647.                                         $joinAndOrString .= " or ";
  7648.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7649.                                 }
  7650.                             } else if ($ctype == 'not_in') {
  7651.                                 $joinAndOrString .= " ( ";
  7652.                                 if (in_array('null'$cvalue)) {
  7653.                                     $joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
  7654.                                     $cvalue array_diff($cvalue, ['null']);
  7655.                                     if (!empty($cvalue))
  7656.                                         $joinAndOrString .= " or ";
  7657.                                 }
  7658.                                 if (in_array(''$cvalue)) {
  7659.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != '' ";
  7660.                                     $cvalue array_diff($cvalue, ['']);
  7661.                                     if (!empty($cvalue))
  7662.                                         $joinAndOrString .= " or ";
  7663.                                 }
  7664.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7665.                             } else if ($ctype == 'in') {
  7666.                                 if (in_array('null'$cvalue)) {
  7667.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null";
  7668.                                     $cvalue array_diff($cvalue, ['null']);
  7669.                                     if (!empty($cvalue))
  7670.                                         $joinAndOrString .= " or ";
  7671.                                 }
  7672.                                 if (in_array(''$cvalue)) {
  7673.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  7674.                                     $cvalue array_diff($cvalue, ['']);
  7675.                                     if (!empty($cvalue))
  7676.                                         $joinAndOrString .= " or ";
  7677.                                 }
  7678.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7679.                             } else if ($ctype == '=') {
  7680. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7681. //                            $fullCfieldArray = explode('.', $cfield);
  7682. //                            $aliasInCondition = $fullCfieldArray[0];
  7683. //                            $cfield = $fullCfieldArray[1];
  7684. //                        }
  7685.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7686.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
  7687.                                 else
  7688.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7689.                             } else if ($ctype == '!=') {
  7690.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7691.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
  7692.                                 else
  7693.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7694.                             } else {
  7695.                                 if (is_string($cvalue))
  7696.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7697.                                 else
  7698.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7699.                             }
  7700.                         }
  7701.                     }
  7702. //            if ($joinAndOrString != '')
  7703. //                $joinQry .= $joinAndOrString;
  7704.                     if ($joinAndOrString != '') {
  7705.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7706.                             $joinQry .= ' and (';
  7707.                             $mustBracketDone 1;
  7708.                         }
  7709.                         if ($joinQry != '')
  7710.                             $joinQry .= (" and (" $joinAndOrString ") ");
  7711.                         else
  7712.                             $joinQry .= ("  (" $joinAndOrString ") ");
  7713.                     }
  7714.                     //pika
  7715.                     $joinOrString "";
  7716.                     foreach ($joinOrConditions as $orCondition) {
  7717. //            $conditionStr.=' 1=1 ';
  7718.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  7719.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  7720.                         $aliasInCondition $table;
  7721.                         if (!(strpos($cfield'.') === false)) {
  7722.                             $fullCfieldArray explode('.'$cfield);
  7723.                             $aliasInCondition $fullCfieldArray[0];
  7724.                             $cfield $fullCfieldArray[1];
  7725.                         }
  7726.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  7727.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7728.                             if ($joinOrString != '' || $joinAndString != '' || $joinMustString != '')
  7729.                                 $joinOrString .= " or ";
  7730.                             if ($ctype == 'like') {
  7731.                                 $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7732.                                 $wordsBySpaces explode(' '$cvalue);
  7733.                                 foreach ($wordsBySpaces as $word) {
  7734.                                     if ($joinOrString != '')
  7735.                                         $joinOrString .= " or ";
  7736.                                     $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7737.                                 }
  7738.                             } else if ($ctype == 'not like') {
  7739.                                 $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7740.                                 $wordsBySpaces explode(' '$cvalue);
  7741.                                 foreach ($wordsBySpaces as $word) {
  7742.                                     if ($joinOrString != '')
  7743.                                         $joinOrString .= " or ";
  7744.                                     $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7745.                                 }
  7746.                             } else if ($ctype == 'not_in') {
  7747.                                 $joinOrString .= " ( ";
  7748.                                 if (in_array('null'$cvalue)) {
  7749.                                     $joinOrString .= " `$joinTableAlias`.$cfield is not null";
  7750.                                     $cvalue array_diff($cvalue, ['null']);
  7751.                                     if (!empty($cvalue))
  7752.                                         $joinOrString .= " or ";
  7753.                                 }
  7754.                                 if (in_array(''$cvalue)) {
  7755.                                     $joinOrString .= "`$joinTableAlias`.$cfield != '' ";
  7756.                                     $cvalue array_diff($cvalue, ['']);
  7757.                                     if (!empty($cvalue))
  7758.                                         $joinOrString .= " or ";
  7759.                                 }
  7760.                                 $joinOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7761.                             } else if ($ctype == 'in') {
  7762.                                 if (in_array('null'$cvalue)) {
  7763.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null";
  7764.                                     $cvalue array_diff($cvalue, ['null']);
  7765.                                     if (!empty($cvalue))
  7766.                                         $joinOrString .= " or ";
  7767.                                 }
  7768.                                 if (in_array(''$cvalue)) {
  7769.                                     $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  7770.                                     $cvalue array_diff($cvalue, ['']);
  7771.                                     if (!empty($cvalue))
  7772.                                         $joinOrString .= " or ";
  7773.                                 }
  7774.                                 $joinOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7775.                             } else if ($ctype == '=') {
  7776. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7777. //                            $fullCfieldArray = explode('.', $cfield);
  7778. //                            $aliasInCondition = $fullCfieldArray[0];
  7779. //                            $cfield = $fullCfieldArray[1];
  7780. //                        }
  7781.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7782.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null ";
  7783.                                 else
  7784.                                     $joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7785.                             } else if ($ctype == '!=') {
  7786.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7787.                                     $joinOrString .= "`$joinTableAlias`.$cfield is not null ";
  7788.                                 else
  7789.                                     $joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7790.                             } else {
  7791.                                 if (is_string($cvalue))
  7792.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7793.                                 else
  7794.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7795.                             }
  7796.                         }
  7797.                     }
  7798. //            if ($joinOrString != '')
  7799. //                $joinQry .= $joinOrString;
  7800.                     if ($joinOrString != '') {
  7801.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7802.                             $joinQry .= ' and (';
  7803.                             $mustBracketDone 1;
  7804.                         }
  7805.                         if ($joinQry != '')
  7806.                             $joinQry .= (" or (" $joinOrString ") ");
  7807.                         else
  7808.                             $joinQry .= ("  (" $joinOrString ") ");
  7809.                     }
  7810.                     if ($joinMustString != '' && $mustBracketDone == 1) {
  7811.                         $joinQry .= ' ) ';
  7812.                     }
  7813. //
  7814. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7815.                 }
  7816.                 $filterQryForCriteria .= $selectQry;
  7817.                 $filterQryForCriteria .= $joinQry;
  7818.                 if ($skipDefaultCompanyId == && $companyId != && !isset($dataConfig['entity_group']))
  7819.                     $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  7820.                 else
  7821.                     $filterQryForCriteria .= " where 1=1 ";
  7822.                 $conditionStr "";
  7823.                 $aliasInCondition $table;
  7824.                 if ($headMarkers != '' && $table == 'acc_accounts_head') {
  7825.                     $markerList explode(','$headMarkers);
  7826.                     $spMarkerQry "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
  7827.                     $markerPassedHeads = [];
  7828.                     foreach ($markerList as $mrkr) {
  7829.                         $spMarkerQry .= " and marker_hash like '%" $mrkr "%'";
  7830.                     }
  7831.                     $spStmt $em->getConnection()->prepare($spMarkerQry);
  7832.                     $spStmt->execute();
  7833.                     $spStmtResults $spStmt->fetchAll();
  7834.                     foreach ($spStmtResults as $ggres) {
  7835.                         $markerPassedHeads[] = $ggres['accounts_head_id'];
  7836.                     }
  7837.                     if (!empty($markerPassedHeads)) {
  7838.                         if ($conditionStr != '')
  7839.                             $conditionStr .= " and (";
  7840.                         else
  7841.                             $conditionStr .= " (";
  7842.                         if ($headMarkersStrictMatch != 1) {
  7843.                             foreach ($markerPassedHeads as $mh) {
  7844.                                 $conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" $mh "/%' or ";
  7845.                             }
  7846.                         }
  7847.                         $conditionStr .= "  `$aliasInCondition`.`accounts_head_id` in (" implode(','$markerPassedHeads) . ") ";
  7848.                         $conditionStr .= " )";
  7849.                     }
  7850.                 }
  7851.                 if (isset($restrictionData[$table])) {
  7852.                     $userRestrictionData Users::getUserApplicationAccessSettings($em$userId)['options'];
  7853.                     if (isset($userRestrictionData[$restrictionData[$table]])) {
  7854.                         $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  7855.                         if ($restrictionIdList == null)
  7856.                             $restrictionIdList = [];
  7857.                     }
  7858.                     if (!empty($restrictionIdList)) {
  7859.                         if ($conditionStr != '')
  7860.                             $conditionStr .= " and ";
  7861.                         $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  7862.                     }
  7863.                 }
  7864. //        $aliasInCondition = $table;
  7865.                 if (!empty($setValueArray) || $selectAll == 1) {
  7866.                     if (!empty($setValueArray)) {
  7867.                         if ($conditionStr != '')
  7868.                             $conditionStr .= " and ";
  7869.                         $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  7870.                     }
  7871.                 } else {
  7872.                     $andString '';
  7873.                     foreach ($andConditions as $andCondition) {
  7874. //            $conditionStr.=' 1=1 ';
  7875.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  7876.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  7877.                         $aliasInCondition $table;
  7878.                         if (!(strpos($cfield'.') === false)) {
  7879.                             $fullCfieldArray explode('.'$cfield);
  7880.                             $aliasInCondition $fullCfieldArray[0];
  7881.                             $cfield $fullCfieldArray[1];
  7882.                         }
  7883.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  7884.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7885.                             if ($andString != '')
  7886.                                 $andString .= " and ";
  7887.                             if ($ctype == 'like') {
  7888.                                 $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7889.                                 $wordsBySpaces explode(' '$cvalue);
  7890.                                 foreach ($wordsBySpaces as $word) {
  7891.                                     if ($andString != '')
  7892.                                         $andString .= " and ";
  7893.                                     $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7894.                                 }
  7895.                             } else if ($ctype == 'not like') {
  7896.                                 $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7897.                                 $wordsBySpaces explode(' '$cvalue);
  7898.                                 foreach ($wordsBySpaces as $word) {
  7899.                                     if ($andString != '')
  7900.                                         $andString .= " and ";
  7901.                                     $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7902.                                 }
  7903.                             } else if ($ctype == 'not_in') {
  7904.                                 $andString .= " ( ";
  7905.                                 if (in_array('null'$cvalue)) {
  7906.                                     $andString .= " `$aliasInCondition`.$cfield is not null";
  7907.                                     $cvalue array_diff($cvalue, ['null']);
  7908.                                     if (!empty($cvalue))
  7909.                                         $andString .= " and ";
  7910.                                 }
  7911.                                 if (in_array(''$cvalue)) {
  7912.                                     $andString .= "`$aliasInCondition`.$cfield != '' ";
  7913.                                     $cvalue array_diff($cvalue, ['']);
  7914.                                     if (!empty($cvalue))
  7915.                                         $andString .= " and ";
  7916.                                 }
  7917.                                 $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7918.                             } else if ($ctype == 'in') {
  7919.                                 if (in_array('null'$cvalue)) {
  7920.                                     $andString .= "`$aliasInCondition`.$cfield is null";
  7921.                                     $cvalue array_diff($cvalue, ['null']);
  7922.                                     if (!empty($cvalue))
  7923.                                         $andString .= " and ";
  7924.                                 }
  7925.                                 if (in_array(''$cvalue)) {
  7926.                                     $andString .= "`$aliasInCondition`.$cfield = '' ";
  7927.                                     $cvalue array_diff($cvalue, ['']);
  7928.                                     if (!empty($cvalue))
  7929.                                         $andString .= " and ";
  7930.                                 }
  7931.                                 $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  7932.                             } else if ($ctype == '=') {
  7933.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7934.                                     $andString .= "`$aliasInCondition`.$cfield is null ";
  7935.                                 else
  7936.                                     $andString .= "`$aliasInCondition`.$cfield = $cvalue ";
  7937.                             } else if ($ctype == '!=') {
  7938.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7939.                                     $andString .= "`$aliasInCondition`.$cfield is not null ";
  7940.                                 else
  7941.                                     $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  7942.                             } else {
  7943.                                 if (is_string($cvalue))
  7944.                                     $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  7945.                                 else
  7946.                                     $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  7947.                             }
  7948.                         }
  7949.                     }
  7950.                     if ($andString != '') {
  7951.                         if ($conditionStr != '')
  7952.                             $conditionStr .= (" and (" $andString ") ");
  7953.                         else
  7954.                             $conditionStr .= ("  (" $andString ") ");
  7955.                     }
  7956.                     $orString '';
  7957.                     foreach ($orConditions as $orCondition) {
  7958.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  7959.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  7960.                         $aliasInCondition $table;
  7961.                         if (!(strpos($cfield'.') === false)) {
  7962.                             $fullCfieldArray explode('.'$cfield);
  7963.                             $aliasInCondition $fullCfieldArray[0];
  7964.                             $cfield $fullCfieldArray[1];
  7965.                         }
  7966.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  7967.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7968.                             if ($orString != '')
  7969.                                 $orString .= " or ";
  7970.                             if ($ctype == 'like') {
  7971.                                 $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7972.                                 $wordsBySpaces explode(' '$cvalue);
  7973.                                 foreach ($wordsBySpaces as $word) {
  7974.                                     if ($orString != '')
  7975.                                         $orString .= " or ";
  7976.                                     $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7977.                                 }
  7978.                             } else if ($ctype == 'not like') {
  7979.                                 $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7980.                                 $wordsBySpaces explode(' '$cvalue);
  7981.                                 foreach ($wordsBySpaces as $word) {
  7982.                                     if ($orString != '')
  7983.                                         $orString .= " or ";
  7984.                                     $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7985.                                 }
  7986.                             } else if ($ctype == 'not_in') {
  7987.                                 $orString .= " ( ";
  7988.                                 if (in_array('null'$cvalue)) {
  7989.                                     $orString .= " `$aliasInCondition`.$cfield is not null";
  7990.                                     $cvalue array_diff($cvalue, ['null']);
  7991.                                     if (!empty($cvalue))
  7992.                                         $orString .= " or ";
  7993.                                 }
  7994.                                 if (in_array(''$cvalue)) {
  7995.                                     $orString .= "`$aliasInCondition`.$cfield != '' ";
  7996.                                     $cvalue array_diff($cvalue, ['']);
  7997.                                     if (!empty($cvalue))
  7998.                                         $orString .= " or ";
  7999.                                 }
  8000.                                 $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8001.                             } else if ($ctype == 'in') {
  8002.                                 $orString .= " ( ";
  8003.                                 if (in_array('null'$cvalue)) {
  8004.                                     $orString .= " `$aliasInCondition`.$cfield is null";
  8005.                                     $cvalue array_diff($cvalue, ['null']);
  8006.                                     if (!empty($cvalue))
  8007.                                         $orString .= " or ";
  8008.                                 }
  8009.                                 if (in_array(''$cvalue)) {
  8010.                                     $orString .= "`$aliasInCondition`.$cfield = '' ";
  8011.                                     $cvalue array_diff($cvalue, ['']);
  8012.                                     if (!empty($cvalue))
  8013.                                         $orString .= " or ";
  8014.                                 }
  8015.                                 $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8016.                             } else if ($ctype == '=') {
  8017.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8018.                                     $orString .= "`$aliasInCondition`.$cfield is null ";
  8019.                                 else
  8020.                                     $orString .= "`$aliasInCondition`.$cfield = $cvalue ";
  8021.                             } else if ($ctype == '!=') {
  8022.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8023.                                     $orString .= "`$aliasInCondition`.$cfield is not null ";
  8024.                                 else
  8025.                                     $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8026.                             } else {
  8027.                                 if (is_string($cvalue))
  8028.                                     $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8029.                                 else
  8030.                                     $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8031.                             }
  8032.                         }
  8033.                     }
  8034.                     if ($orString != '') {
  8035.                         if ($conditionStr != '')
  8036.                             $conditionStr .= (" or (" $orString ") ");
  8037.                         else
  8038.                             $conditionStr .= ("  (" $orString ") ");
  8039.                     }
  8040.                     $andOrString '';
  8041.                     foreach ($andOrConditions as $andOrCondition) {
  8042.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  8043.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  8044.                         $aliasInCondition $table;
  8045.                         if (!(strpos($cfield'.') === false)) {
  8046.                             $fullCfieldArray explode('.'$cfield);
  8047.                             $aliasInCondition $fullCfieldArray[0];
  8048.                             $cfield $fullCfieldArray[1];
  8049.                         }
  8050.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  8051.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8052.                             if ($andOrString != '')
  8053.                                 $andOrString .= " or ";
  8054.                             if ($ctype == 'like') {
  8055.                                 $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8056.                                 $wordsBySpaces explode(' '$cvalue);
  8057.                                 foreach ($wordsBySpaces as $word) {
  8058.                                     if ($andOrString != '')
  8059.                                         $andOrString .= " or ";
  8060.                                     $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8061.                                 }
  8062.                             } else if ($ctype == 'not like') {
  8063.                                 $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8064.                                 $wordsBySpaces explode(' '$cvalue);
  8065.                                 foreach ($wordsBySpaces as $word) {
  8066.                                     if ($andOrString != '')
  8067.                                         $andOrString .= " or ";
  8068.                                     $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8069.                                 }
  8070.                             } else if ($ctype == 'in') {
  8071.                                 $andOrString .= " ( ";
  8072.                                 if (in_array('null'$cvalue)) {
  8073.                                     $andOrString .= " `$aliasInCondition`.$cfield is null";
  8074.                                     $cvalue array_diff($cvalue, ['null']);
  8075.                                     if (!empty($cvalue))
  8076.                                         $andOrString .= " or ";
  8077.                                 }
  8078.                                 if (in_array(''$cvalue)) {
  8079.                                     $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  8080.                                     $cvalue array_diff($cvalue, ['']);
  8081.                                     if (!empty($cvalue))
  8082.                                         $andOrString .= " or ";
  8083.                                 }
  8084.                                 if (!empty($cvalue))
  8085.                                     $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8086.                                 else
  8087.                                     $andOrString .= "  ) ";
  8088.                             } else if ($ctype == 'not_in') {
  8089.                                 $andOrString .= " ( ";
  8090.                                 if (in_array('null'$cvalue)) {
  8091.                                     $andOrString .= " `$aliasInCondition`.$cfield is not null";
  8092.                                     $cvalue array_diff($cvalue, ['null']);
  8093.                                     if (!empty($cvalue))
  8094.                                         $andOrString .= " or ";
  8095.                                 }
  8096.                                 if (in_array(''$cvalue)) {
  8097.                                     $andOrString .= "`$aliasInCondition`.$cfield != '' ";
  8098.                                     $cvalue array_diff($cvalue, ['']);
  8099.                                     if (!empty($cvalue))
  8100.                                         $andOrString .= " or ";
  8101.                                 }
  8102.                                 if (!empty($cvalue))
  8103.                                     $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8104.                                 else
  8105.                                     $andOrString .= "  ) ";
  8106.                             } else if ($ctype == '=') {
  8107.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8108.                                     $andOrString .= "`$aliasInCondition`.$cfield is null ";
  8109.                                 else
  8110.                                     $andOrString .= "`$aliasInCondition`.$cfield = $cvalue ";
  8111.                             } else if ($ctype == '!=') {
  8112.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8113.                                     $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  8114.                                 else
  8115.                                     $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8116.                             } else {
  8117.                                 if (is_string($cvalue))
  8118.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8119.                                 else
  8120.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8121.                             }
  8122.                         }
  8123.                     }
  8124.                     if ($andOrString != '') {
  8125.                         if ($conditionStr != '')
  8126.                             $conditionStr .= (" and (" $andOrString ") ");
  8127.                         else
  8128.                             $conditionStr .= ("  (" $andOrString ") ");
  8129.                     }
  8130.                 }
  8131.                 $mustStr '';
  8132. ///now must conditions
  8133.                 foreach ($mustConditions as $mustCondition) {
  8134. //            $conditionStr.=' 1=1 ';
  8135.                     $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  8136.                     $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  8137.                     $aliasInCondition $table;
  8138.                     if (!(strpos($cfield'.') === false)) {
  8139.                         $fullCfieldArray explode('.'$cfield);
  8140.                         $aliasInCondition $fullCfieldArray[0];
  8141.                         $cfield $fullCfieldArray[1];
  8142.                     }
  8143.                     $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  8144.                     if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8145.                         if ($mustStr != '')
  8146.                             $mustStr .= " and ";
  8147.                         if ($ctype == 'like') {
  8148.                             $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8149.                             $wordsBySpaces explode(' '$cvalue);
  8150.                             foreach ($wordsBySpaces as $word) {
  8151.                                 if ($mustStr != '')
  8152.                                     $mustStr .= " or ";
  8153.                                 $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8154.                             }
  8155.                             $mustStr .= " )";
  8156.                         } else if ($ctype == 'not like') {
  8157.                             $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8158.                             $wordsBySpaces explode(' '$cvalue);
  8159.                             foreach ($wordsBySpaces as $word) {
  8160.                                 if ($mustStr != '')
  8161.                                     $mustStr .= " and ";
  8162.                                 $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8163.                             }
  8164.                         } else if ($ctype == 'in') {
  8165.                             $mustStr .= " ( ";
  8166.                             if (in_array('null'$cvalue)) {
  8167.                                 $mustStr .= " `$aliasInCondition`.$cfield is null";
  8168.                                 $cvalue array_diff($cvalue, ['null']);
  8169.                                 if (!empty($cvalue))
  8170.                                     $mustStr .= " or ";
  8171.                             }
  8172.                             if (in_array(''$cvalue)) {
  8173.                                 $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  8174.                                 $cvalue array_diff($cvalue, ['']);
  8175.                                 if (!empty($cvalue))
  8176.                                     $mustStr .= " or ";
  8177.                             }
  8178.                             $mustStr .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8179.                         } else if ($ctype == 'not_in') {
  8180.                             $mustStr .= " ( ";
  8181.                             if (in_array('null'$cvalue)) {
  8182.                                 $mustStr .= " `$aliasInCondition`.$cfield is not null";
  8183.                                 $cvalue array_diff($cvalue, ['null']);
  8184.                                 if (!empty($cvalue))
  8185.                                     $mustStr .= " and ";
  8186.                             }
  8187.                             if (in_array(''$cvalue)) {
  8188.                                 $mustStr .= "`$aliasInCondition`.$cfield != '' ";
  8189.                                 $cvalue array_diff($cvalue, ['']);
  8190.                                 if (!empty($cvalue))
  8191.                                     $mustStr .= " and ";
  8192.                             }
  8193.                             $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8194.                         } else if ($ctype == '=') {
  8195.                             if ($cvalue == 'null' || $cvalue == 'Null')
  8196.                                 $mustStr .= "`$aliasInCondition`.$cfield is null ";
  8197.                             else
  8198.                                 $mustStr .= "`$aliasInCondition`.$cfield = $cvalue ";
  8199.                         } else if ($ctype == '!=') {
  8200.                             if ($cvalue == 'null' || $cvalue == 'Null')
  8201.                                 $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  8202.                             else
  8203.                                 $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  8204.                         } else {
  8205.                             if (is_string($cvalue))
  8206.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8207.                             else
  8208.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8209.                         }
  8210.                     }
  8211.                 }
  8212.                 if ($mustStr != '') {
  8213.                     if ($conditionStr != '')
  8214.                         $conditionStr .= (" and (" $mustStr ") ");
  8215.                     else
  8216.                         $conditionStr .= ("  (" $mustStr ") ");
  8217.                 }
  8218.                 if ($conditionStr != '')
  8219.                     $filterQryForCriteria .= (" and (" $conditionStr ") ");
  8220.                 if ($lastChildrenOnly == 1) {
  8221.                     if ($filterQryForCriteria != '')
  8222.                         $filterQryForCriteria .= ' and';
  8223.                     $filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  8224.                 } else if ($parentOnly == 1) {
  8225.                     if ($filterQryForCriteria != '')
  8226.                         $filterQryForCriteria .= ' and';
  8227.                     $filterQryForCriteria .= "`$table`.`$valueField`  in ( select distinct $parentIdField from  $table)";
  8228.                 }
  8229.                 if (!empty($orderByConditions)) {
  8230.                     $filterQryForCriteria .= "  order by ";
  8231.                     $fone 1;
  8232.                     foreach ($orderByConditions as $orderByCondition) {
  8233.                         if ($fone != 1) {
  8234.                             $filterQryForCriteria .= " , ";
  8235.                         }
  8236.                         if (isset($orderByCondition['valueList'])) {
  8237.                             if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  8238.                             if ($orderByCondition['valueList'] == null)
  8239.                                 $orderByCondition['valueList'] = [];
  8240.                             $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  8241.                         } else
  8242.                             $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  8243.                         $fone 0;
  8244.                     }
  8245.                 }
  8246.                 if ($returnTotalMatchedEntriesFlag == 1) {
  8247. //            $stmt = $em->getConnection()->prepare($get_kids_sql);
  8248. //            $stmt->execute();
  8249. //            $get_kids = $stmt->fetchAll();
  8250.                 }
  8251.                 if ($filterQryForCriteria != '')
  8252.                     if (!empty($setValueArray) || $selectAll == 1) {
  8253.                     } else {
  8254.                         if ($itemLimit != '_ALL_')
  8255.                             $filterQryForCriteria .= "  limit $offset$itemLimit ";
  8256.                         else
  8257.                             $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  8258.                     }
  8259.                 $get_kids_sql $filterQryForCriteria;
  8260.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  8261.                 $stmt->execute();
  8262.                 $get_kids $stmt->fetchAll();
  8263.                 $selectedId 0;
  8264.                 if ($table == 'warehouse_action') {
  8265.                     if (empty($get_kids)) {
  8266.                         $get_kids_sql_2 "select * from warehouse_action";
  8267.                         $stmt $em->getConnection()->prepare($get_kids_sql_2);
  8268.                         $stmt->execute();
  8269.                         $get_kids2 $stmt->fetchAll();
  8270.                         if (empty($get_kids2))
  8271.                             $get_kids GeneralConstant::$warehouse_action_list;
  8272.                     }
  8273.                 }
  8274.                 if (!empty($get_kids)) {
  8275.                     $nextOffset $offset count($get_kids);
  8276.                     $nextOffset++;
  8277.                     foreach ($get_kids as $pa) {
  8278.                         if (!empty($setValueArray) && $selectAll == 0) {
  8279.                             if (!in_array($pa[$valueField], $setValueArray))
  8280.                                 continue;
  8281.                         }
  8282.                         if (!empty($restrictionIdList)) {
  8283.                             if (!in_array($pa[$valueField], $restrictionIdList))
  8284.                                 continue;
  8285.                         }
  8286.                         if ($selectAll == 1) {
  8287.                             $setValueArray[] = $pa[$valueField];
  8288.                             $setValue $pa[$valueField];
  8289.                         } else if (count($get_kids) == && $setDataForSingle == 1) {
  8290.                             $setValueArray[] = $pa[$valueField];
  8291.                             $setValue $pa[$valueField];
  8292.                         }
  8293.                         if ($valueField != '')
  8294.                             $pa['value'] = $pa[$valueField];
  8295.                         $renderedText $renderTextFormat;
  8296.                         $compare_array = [];
  8297.                         if ($renderTextFormat != '') {
  8298.                             $renderedText $renderTextFormat;
  8299.                             $compare_arrayFull = [];
  8300.                             $compare_array = [];
  8301.                             $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  8302.                             );
  8303.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  8304.                             if (isset($compare_arrayFull[0]))
  8305.                                 $compare_array $compare_arrayFull[0];
  8306. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  8307.                             foreach ($compare_array as $cmpdt) {
  8308.                                 $tbr str_replace("__"""$cmpdt);
  8309.                                 if ($tbr != '') {
  8310.                                     if (isset($pa[$tbr])) {
  8311.                                         if ($pa[$tbr] == null)
  8312.                                             $renderedText str_replace($cmpdt''$renderedText);
  8313.                                         else
  8314.                                             $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  8315.                                     } else {
  8316.                                         $renderedText str_replace($cmpdt''$renderedText);
  8317.                                     }
  8318.                                 }
  8319.                             }
  8320.                         }
  8321.                         $pa['rendered_text'] = $renderedText;
  8322.                         $pa['text'] = ($textField != '' $pa[$textField] : '');
  8323. //                $pa['compare_array'] = $compare_array;
  8324.                         foreach ($convertToObjectFieldList as $convField) {
  8325.                             if (isset($pa[$convField])) {
  8326.                                 $taA json_decode($pa[$convField], true);
  8327.                                 if ($taA == null$taA = [];
  8328.                                 $pa[$convField] = $taA;
  8329.                             } else {
  8330.                                 $pa[$convField] = [];
  8331.                             }
  8332.                         }
  8333.                         foreach ($convertDateToStringFieldList as $convField) {
  8334.                             if (is_array($convField)) {
  8335.                                 $fld $convField['field'];
  8336.                                 $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  8337.                             } else {
  8338.                                 $fld $convField;
  8339.                                 $frmt 'Y-m-d H:i:s';
  8340.                             }
  8341.                             if (isset($pa[$fld])) {
  8342.                                 $taA = new \DateTime($pa[$fld]);
  8343.                                 $pa[$fld] = $taA->format($frmt);
  8344.                             }
  8345.                         }
  8346.                         foreach ($convertToUrl as $convField) {
  8347. //
  8348. //                            $fld = $convField;
  8349. //
  8350. //
  8351. //                            if (isset($pa[$fld])) {
  8352. //
  8353. //
  8354. //                                $pa[$fld] =
  8355. //                                    $this->generateUrl(
  8356. //                                        'dashboard', [
  8357. //
  8358. //                                    ], UrlGenerator::ABSOLUTE_URL
  8359. //                                    ).'/'.$pa[$fld];
  8360. //
  8361. //                            }
  8362.                         }
  8363.                         foreach ($fullPathList as $pathField) {
  8364.                             $fld $pathField;
  8365.                             if (isset($pa[$fld])) {
  8366.                                 if ($pa[$fld] !='' && $pa[$fld] !=null) {
  8367.                                     $pa[$fld]=($this->generateUrl(
  8368.                                             'dashboard', [
  8369.                                         ], UrlGenerator::ABSOLUTE_URL
  8370.                                         ).$pa[$fld]);
  8371.                                 }
  8372.                             }
  8373.                         }
  8374.                         $pa['currentTs'] = (new \Datetime())->format('U');
  8375.                         $data[] = $pa;
  8376.                         if ($valueField != '') {
  8377.                             $data_by_id[$pa[$valueField]] = $pa;
  8378.                             $selectedId $pa[$valueField];
  8379.                         }
  8380.                     }
  8381.                 }
  8382.                 if ($dataOnly == 1)
  8383.                     $lastResult = array(
  8384.                         'success' => true,
  8385.                         'data' => $data,
  8386.                         'currentTs' => (new \Datetime())->format('U'),
  8387.                         'restrictionIdList' => $restrictionIdList,
  8388.                         'nextOffset' => $nextOffset,
  8389.                         'totalMatchedEntries' => $totalMatchedEntries,
  8390.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8391.                     );
  8392.                 else
  8393.                     $lastResult = array(
  8394.                         'success' => true,
  8395.                         'data' => $data,
  8396.                         'tableName' => $table,
  8397.                         'setValue' => $setValue,
  8398.                         'currentTs' => (new \Datetime())->format('U'),
  8399.                         'restrictionIdList' => $restrictionIdList,
  8400.                         'andConditions' => $andConditions,
  8401.                         'queryStr' => $queryStringIndividual,
  8402.                         'isMultiple' => $isMultiple,
  8403.                         'nextOffset' => $nextOffset,
  8404.                         'totalMatchedEntries' => $totalMatchedEntries,
  8405.                         'selectorId' => $selectorId,
  8406.                         'setValueArray' => $setValueArray,
  8407.                         'silentChangeSelectize' => $silentChangeSelectize,
  8408.                         'convertToObjectFieldList' => $convertToObjectFieldList,
  8409.                         'conditionStr' => $conditionStr,
  8410. //                    'andStr' => $andString,
  8411. //                    'andOrStr' => $andOrString,
  8412.                         'dataById' => $data_by_id,
  8413.                         'selectedId' => $selectedId,
  8414.                         'dataId' => $dataId,
  8415.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8416.                     );
  8417.             }
  8418.             $allResult[] = $lastResult;
  8419.         }
  8420.         if ($isSingleDataset == 1)
  8421.             return new JsonResponse($lastResult);
  8422.         else
  8423.             return new JsonResponse($allResult);
  8424.     }
  8425.     public function updatePlanningItemSequenceAction(Request $request$queryStr '')
  8426.     {
  8427.         $em $this->getDoctrine()->getManager();
  8428.         $stmt $em->getConnection()->prepare("select  `id` , parent_id, sequence from planning_item where sequence is null 
  8429.             ORDER BY parent_id ASC, id ASC
  8430.                         ");
  8431.         $stmt->execute();
  8432.         $query_output $stmt->fetchAll();
  8433.         foreach ($query_output as $dupe) {
  8434.             System::updatePlanningItemSequence($em$dupe["id"]);
  8435.         }
  8436.         System::updatePlanningItemSequence(
  8437.             $em,
  8438.             $request->request->get('planningItemId'0),
  8439.             $request->request->get('assignType''_ASSIGN_')   ///can be _MOVE_UP_ or _MOVE_DOWN_
  8440.         );
  8441. //        if($request->query->has('returnJson'))
  8442.         return new JsonResponse(
  8443.             array(
  8444.                 'success' => true,
  8445.                 'data' => [],
  8446.             )
  8447.         );
  8448.     }
  8449.     public function insertDataAjaxAction(Request $request$queryStr '')
  8450.     {
  8451.         $em $this->getDoctrine()->getManager();
  8452. //        if($request->query->has('big_data_test'))
  8453. //        {
  8454. //            for($t=0;$t<$request->request->get('big_data_test',10000);$t++) {
  8455. //                $em = $this->getDoctrine()->getManager('company_group');
  8456. //                $NOTIFICATION = new EntityNotification();
  8457. //                $NOTIFICATION->setAppId(1);
  8458. //                $NOTIFICATION->setCompanyId(0);
  8459. //                $NOTIFICATION->setCompanyId(0);
  8460. //                $NOTIFICATION->setBody('Test Description'.$t);
  8461. //                $NOTIFICATION->setTitle('Test Title'.$t);
  8462. //                $NOTIFICATION->setExpireTs(0);
  8463. //                $NOTIFICATION->setIsBuddybee(0);
  8464. //                $NOTIFICATION->setType(0);
  8465. //                $em->persist($NOTIFICATION);
  8466. //                $em->flush();
  8467. //            }
  8468. //
  8469. //            return new JsonResponse(
  8470. //                array(
  8471. //                    'success' => true,
  8472. //                    'data' => [],
  8473. //
  8474. //
  8475. //                )
  8476. //            );
  8477. //
  8478. //
  8479. //        }
  8480.         if ($request->request->get('entity_group'0)) {
  8481.             $companyId 0;
  8482.             $em $this->getDoctrine()->getManager('company_group');
  8483.         } else
  8484.             $companyId $this->getLoggedUserCompanyId($request);
  8485.         if ($companyId) {
  8486.             $company_data = [];
  8487. //            $company_data = Company::getCompanyData($em, $companyId);
  8488.         } else {
  8489.             $companyId 0;
  8490.             $company_data = [];
  8491.         }
  8492. //        $theEntity= new EntityNotification();
  8493. //        $entityName = 'EntityNotification';
  8494. //
  8495. //        $className='\\CompanyGroupBundle\\Entity\\'.$entityName;
  8496. //
  8497. //
  8498. //            $theEntity= new $className();
  8499.         $dataToAdd $request->request->has('dataToAdd') ? $request->request->get('dataToAdd') : [];
  8500.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8501.         if ($dataToAdd == null$dataToAdd = [];
  8502.         $dataToRemove $request->request->has('dataToRemove') ? $request->request->get('dataToRemove') : [];
  8503.         if (is_string($dataToRemove)) $dataToAdd json_decode($dataToRemovetrue);
  8504.         if ($dataToRemove == null$dataToRemove = [];
  8505.         $relData = [];
  8506.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8507.         $updatedDataList = [];
  8508.         foreach ($dataToAdd as $dataInd => $dat) {
  8509.             $entityName $dat['entityName'];
  8510.             $idField $dat['idField'];
  8511.             $findByField = isset($dat['findByField']) ? $dat['findByField'] : '';
  8512.             $findByValue = isset($dat['findByValue']) ? $dat['findByValue'] : '';
  8513.             $returnRefIndex $dat['returnRefIndex'];
  8514.             $findById $dat['findId'];
  8515.             $dataFields = isset($dat['dataFields']) ? $dat['dataFields'] : [];
  8516.             $noCreation = isset($dat['noCreation']) ? $dat['noCreation'] : 0;
  8517.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  8518.             $preAdditionalSql = isset($dat['preAdditionalSql']) ? $dat['preAdditionalSql'] : '';
  8519.             if ($preAdditionalSql != '') {
  8520. //            if ($entityName == 'PlanningItem') {
  8521. //
  8522. //                $stmt='select disctinct parent_id from planning_item;';
  8523. //                $stmt->execute();
  8524. //                $get_kids = $stmt->fetchAll();
  8525. //                $p_ids=[];
  8526. //                foreach($get_kids as $g)
  8527. //                {
  8528. //                    $p_ids[]=$g['parent_id'];
  8529. //                }
  8530. //
  8531. //
  8532. //
  8533.                 $stmt $em->getConnection()->prepare($preAdditionalSql);
  8534.                 $stmt->execute();
  8535.                 $stmt->closeCursor();
  8536. //
  8537. //
  8538.             }
  8539.             if ($entityName == 'PlanningItem') {
  8540.                 $stmt $em->getConnection()->prepare("select  `id` , parent_id, sequence from planning_item where sequence is null
  8541.             ORDER BY parent_id ASC, id ASC
  8542.                         ");
  8543.                 $stmt->execute();
  8544.                 $query_output $stmt->fetchAll();
  8545.                 foreach ($query_output as $dupe) {
  8546.                     System::updatePlanningItemSequence($em$dupe["id"]);
  8547.                 }
  8548.             }
  8549.             $className = ($request->request->get('entity_group'0) ? '\\CompanyGroupBundle\\Entity\\' '\\ApplicationBundle\\Entity\\') . $entityName;
  8550.             if (
  8551.                 ($findById == || $findById == '_NA_') && $findByField == '' && $noCreation == 0
  8552.             ) {
  8553.                 $theEntity = new $className();
  8554. //                $theEntity= new EntityNotification();
  8555.             } else {
  8556.                 if ($findByField != '') {
  8557.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findOneBy(
  8558.                         array
  8559.                         (
  8560.                             $findByField => $findByValue,
  8561.                         )
  8562.                     );
  8563.                 } else {
  8564.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findOneBy(
  8565.                         array
  8566.                         (
  8567.                             $idField => $findById,
  8568.                         )
  8569.                     );
  8570.                 }
  8571.             }
  8572.             if (!$theEntity && $noCreation == 0)
  8573.                 $theEntity = new $className();
  8574.             foreach ($dataFields as $dt) {
  8575.                 $setMethod 'set' ucfirst($dt['field']);
  8576.                 $getMethod 'get' ucfirst($dt['field']);
  8577.                 $type = isset($dt['type']) ? $dt['type'] : '_VALUE_';
  8578.                 $action = isset($dt['action']) ? $dt['action'] : '_REPLACE_';
  8579.                 if (method_exists($theEntity$setMethod)) {
  8580.                     $oldValue $theEntity->{$getMethod}();
  8581.                     $newValue $oldValue;
  8582.                     if ($type == '_VALUE_') {
  8583.                         $newValue $dt['value'];
  8584.                     }
  8585.                     if ($type == '_DECIMAL_') {
  8586.                         $newValue $dt['value'];
  8587.                     }
  8588.                     if ($type == '_DATE_') {
  8589.                         $newValue = new \DateTime($dt['value']);
  8590.                     }
  8591.                     if ($type == '_ARRAY_') {
  8592.                         $oldValue json_decode($oldValue);
  8593.                         if ($oldValue == null$oldValue = [];
  8594.                         if ($action == '_REPLACE_') {
  8595.                             $newValue json_encode($dt['value']);
  8596.                         }
  8597.                         if ($action == '_APPEND_') {
  8598.                             $newValue array_merge($oldValuearray_values(array_diff([$dt['value']], $oldValue)));
  8599.                         }
  8600.                         if ($action == '_MERGE_') {
  8601.                             $newValue array_merge($oldValuearray_values(array_diff($dt['value'], $oldValue)));
  8602.                         }
  8603.                         if ($action == '_EXCLUDE_') {
  8604.                             $newValue array_values(array_diff($oldValue, [$dt['value']]));
  8605.                         }
  8606.                         if ($action == '_EXCLUDE_ARRAY_') {
  8607.                             $newValue array_values(array_diff($oldValue$dt['value']));
  8608.                         }
  8609.                         $newValue json_encode($newValue);
  8610.                     }
  8611.                     $theEntity->{$setMethod}($newValue); // `foo!`
  8612. //                    $theEntity->setCompletionPercentage(78); // `foo!`
  8613.                 }
  8614.             }
  8615.             if ($additionalSql != '') {
  8616. //            if ($entityName == 'PlanningItem') {
  8617. //
  8618. //                $stmt='select disctinct parent_id from planning_item;';
  8619. //                $stmt->execute();
  8620. //                $get_kids = $stmt->fetchAll();
  8621. //                $p_ids=[];
  8622. //                foreach($get_kids as $g)
  8623. //                {
  8624. //                    $p_ids[]=$g['parent_id'];
  8625. //                }
  8626. //
  8627. //
  8628. //
  8629.                 $stmt $em->getConnection()->prepare($additionalSql);
  8630.                 $stmt->execute();
  8631.                 $stmt->closeCursor();
  8632. //
  8633. //
  8634.             }
  8635.             if (($findById == || $findById == '_NA_') && $noCreation == 0) {
  8636.                 $em->persist($theEntity);
  8637.                 $em->flush();
  8638.                 $getMethod 'get' ucfirst($idField);
  8639.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8640.             } else if ($theEntity) {
  8641.                 $em->flush();
  8642.                 $getMethod 'get' ucfirst($idField);
  8643.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8644.             }
  8645.             if ($entityName == 'PlanningItem') {
  8646.                 $stmt $em->getConnection()->prepare('select distinct parent_id from planning_item;');
  8647.                 $stmt->execute();
  8648.                 $get_kids $stmt->fetchAll();
  8649.                 $p_ids = [];
  8650.                 foreach ($get_kids as $g) {
  8651.                     $p_ids[] = $g['parent_id'];
  8652.                 }
  8653.                 $stmt $em->getConnection()->prepare('UPDATE planning_item d SET d.`has_child` =0 WHERE d.id NOT IN (' implode(','$p_ids) . '); 
  8654.                           UPDATE planning_item d SET d.`has_child` =1 WHERE d.id  IN (' implode(','$p_ids) . ')');
  8655.                 $stmt->execute();
  8656.                 $stmt->closeCursor();
  8657.                 $updatedData System::updatePlanningItemSequence($em$theEntity->getId());
  8658.                 $theEntity $updatedData['primaryOne'];
  8659.                 $theEntityUpdated $theEntity;
  8660.                 if ($theEntityUpdated->getEntryType() == 4)///cashflow
  8661.                 {
  8662.                     MiscActions::AddCashFlowProjection($em0, [
  8663.                         'planningItemId' => $theEntityUpdated->getId(),
  8664.                         'fundRequisitionId' => 0,
  8665.                         'concernedPersonId' => 0,
  8666.                         'type' => 1//exp
  8667.                         'subType' => 1//1== khoroch hobe 2: ashbe
  8668.                         'cashFlowType' => 1//2== RCV /in  1: Payment/out
  8669.                         'creationType' => 1//auto
  8670.                         'amountType' => 1//fund
  8671.                         'cashFlowAmount' => 0,
  8672.                         'expAstAmount' => 0,
  8673.                         'accumulatedCashFlowAmount' => 0,
  8674.                         'accumulatedCashFlowBalance' => 0,
  8675.                         'accumulatedExpAstAmount' => 0,
  8676.                         'relevantExpAstHeadId' => 0,
  8677.                         'balancingHeadId' => 0,
  8678.                         'cashFlowHeadId' => 0,
  8679.                         'cashFlowHeadType' => 1,
  8680.                         'relevantProductIds' => [],
  8681.                         'reminderDateTs' => 0,
  8682.                         'cashFlowDateTs' => 0,
  8683.                         'expAstRealizationDateTs' => 0,
  8684.                     ]);
  8685.                 }
  8686.             } else if ($entityName == 'TaskLog') {
  8687.                 $session $request->getSession();
  8688.                 if ($theEntity) {
  8689.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  8690.                     $currTime = new \DateTime();
  8691.                     $options = array(
  8692.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8693.                         'notification_server' => $this->container->getParameter('notification_server'),
  8694.                     );
  8695.                     $positionsArray = [
  8696.                         array(
  8697.                             'employeeId' => $empId,
  8698.                             'userId' => $session->get(UserConstants::USER_ID0),
  8699.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  8700.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  8701.                             'lat' => 23.8623834,
  8702.                             'lng' => 90.3979294,
  8703.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING,
  8704. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  8705.                         )
  8706.                     ];
  8707.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  8708.                     if ($positionsArray == null$positionsArray = [];
  8709.                     $dataByAttId = [];
  8710.                     $workPlaceType '_UNSET_';
  8711.                     foreach ($positionsArray as $findex => $d) {
  8712.                         $sysUserId 0;
  8713.                         $userId 0;
  8714.                         $empId 0;
  8715.                         $dtTs 0;
  8716.                         $timeZoneStr '+0000';
  8717.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  8718.                         if (isset($d['userId'])) $userId $d['userId'];
  8719.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  8720.                         if (isset($d['tsMilSec'])) {
  8721.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  8722.                         }
  8723.                         if ($dtTs == 0) {
  8724.                             $currTsTime = new \DateTime();
  8725.                             $dtTs $currTsTime->format('U');
  8726.                         } else {
  8727.                             $currTsTime = new \DateTime('@' $dtTs);
  8728.                         }
  8729.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  8730.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  8731.                         $EmployeeAttendance $this->getDoctrine()
  8732.                             ->getRepository(EmployeeAttendance::class)
  8733.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  8734.                         if (!$EmployeeAttendance) {
  8735.                             $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8736.                             $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8737.                             $EmployeeAttendance = new EmployeeAttendance;
  8738.                         } else {
  8739.                             if ($EmployeeAttendance->getCurrentLocation() == 'out') {
  8740.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8741.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8742.                             } else {
  8743.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8744.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8745.                             }
  8746.                         }
  8747.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  8748.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  8749.                             $workPlaceType '_STATIC_';
  8750.                         }
  8751.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  8752.                             $dataByAttId[$attendanceInfo->getId()] = array(
  8753.                                 'attendanceInfo' => $attendanceInfo,
  8754.                                 'empId' => $empId,
  8755.                                 'lat' => 0,
  8756.                                 'lng' => 0,
  8757.                                 'address' => 0,
  8758.                                 'sysUserId' => $sysUserId,
  8759.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8760.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8761.                                 'positionArray' => []
  8762.                             );
  8763.                         $posData = array(
  8764.                             'ts' => $dtTs,
  8765.                             'lat' => $d['lat'],
  8766.                             'lng' => $d['lng'],
  8767.                             'marker' => $d['markerId'],
  8768.                             'src' => 2,
  8769.                         );
  8770.                         $posDataArray = array(
  8771.                             $dtTs,
  8772.                             $d['lat'],
  8773.                             $d['lng'],
  8774.                             $d['markerId'],
  8775.                             2
  8776.                         );
  8777.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  8778.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  8779.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  8780.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  8781.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  8782.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  8783.                         if (isset($d['address']))
  8784.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  8785. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  8786.                     }
  8787.                     $response = array(
  8788.                         'success' => true,
  8789.                     );
  8790.                     foreach ($dataByAttId as $attInfoId => $d) {
  8791.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  8792.                             $d['empId'],
  8793.                             $d['sysUserId'],
  8794.                             $d['companyId'],
  8795.                             $d['appId'],
  8796.                             $request,
  8797.                             $d['attendanceInfo'],
  8798.                             $options,
  8799.                             $d['positionArray'],
  8800.                             $d['lat'],
  8801.                             $d['lng'],
  8802.                             $d['address'],
  8803.                             $d['markerId']
  8804.                         );
  8805.                     }
  8806.                     $session->set(UserConstants::USER_CURRENT_TASK_ID$theEntity->getId());
  8807.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$theEntity->getPlanningItemId());
  8808.                 } else {
  8809.                     $session->set(UserConstants::USER_CURRENT_TASK_ID0);
  8810.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID0);
  8811.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  8812.                     $currTime = new \DateTime();
  8813.                     $options = array(
  8814.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8815.                         'notification_server' => $this->container->getParameter('notification_server'),
  8816.                     );
  8817.                     $positionsArray = [
  8818.                         array(
  8819.                             'employeeId' => $empId,
  8820.                             'userId' => $session->get(UserConstants::USER_ID0),
  8821.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  8822.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  8823.                             'lat' => 23.8623834,
  8824.                             'lng' => 90.3979294,
  8825.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT,
  8826. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  8827.                         )
  8828.                     ];
  8829.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  8830.                     if ($positionsArray == null$positionsArray = [];
  8831.                     $dataByAttId = [];
  8832.                     $workPlaceType '_UNSET_';
  8833.                     foreach ($positionsArray as $findex => $d) {
  8834.                         $sysUserId 0;
  8835.                         $userId 0;
  8836.                         $empId 0;
  8837.                         $dtTs 0;
  8838.                         $timeZoneStr '+0000';
  8839.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  8840.                         if (isset($d['userId'])) $userId $d['userId'];
  8841.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  8842.                         if (isset($d['tsMilSec'])) {
  8843.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  8844.                         }
  8845.                         if ($dtTs == 0) {
  8846.                             $currTsTime = new \DateTime();
  8847.                             $dtTs $currTsTime->format('U');
  8848.                         } else {
  8849.                             $currTsTime = new \DateTime('@' $dtTs);
  8850.                         }
  8851.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  8852.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  8853.                         $EmployeeAttendance $this->getDoctrine()
  8854.                             ->getRepository(EmployeeAttendance::class)
  8855.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  8856.                         if (!$EmployeeAttendance) {
  8857.                             continue;
  8858.                         } else {
  8859.                         }
  8860.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  8861.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT) {
  8862.                             $workPlaceType '_STATIC_';
  8863.                         }
  8864.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  8865.                             $dataByAttId[$attendanceInfo->getId()] = array(
  8866.                                 'attendanceInfo' => $attendanceInfo,
  8867.                                 'empId' => $empId,
  8868.                                 'lat' => 0,
  8869.                                 'lng' => 0,
  8870.                                 'address' => 0,
  8871.                                 'sysUserId' => $sysUserId,
  8872.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8873.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8874.                                 'positionArray' => []
  8875.                             );
  8876.                         $posData = array(
  8877.                             'ts' => $dtTs,
  8878.                             'lat' => $d['lat'],
  8879.                             'lng' => $d['lng'],
  8880.                             'marker' => $d['markerId'],
  8881.                             'src' => 2,
  8882.                         );
  8883.                         $posDataArray = array(
  8884.                             $dtTs,
  8885.                             $d['lat'],
  8886.                             $d['lng'],
  8887.                             $d['markerId'],
  8888.                             2
  8889.                         );
  8890.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  8891.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  8892.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  8893.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  8894.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  8895.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  8896.                         if (isset($d['address']))
  8897.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  8898. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  8899.                     }
  8900.                     $response = array(
  8901.                         'success' => true,
  8902.                     );
  8903.                     foreach ($dataByAttId as $attInfoId => $d) {
  8904.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  8905.                             $d['empId'],
  8906.                             $d['sysUserId'],
  8907.                             $d['companyId'],
  8908.                             $d['appId'],
  8909.                             $request,
  8910.                             $d['attendanceInfo'],
  8911.                             $options,
  8912.                             $d['positionArray'],
  8913.                             $d['lat'],
  8914.                             $d['lng'],
  8915.                             $d['address'],
  8916.                             $d['markerId']
  8917.                         );
  8918.                     }
  8919.                 }
  8920.                 $theEntityUpdated $theEntity;
  8921.             } else
  8922.                 $theEntityUpdated $theEntity;
  8923. //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  8924.             $getters = [];
  8925.             if ($theEntityUpdated)
  8926.                 $getters array_filter(get_class_methods($theEntityUpdated), function ($method) {
  8927.                     return 'get' === substr($method03);
  8928.                 });
  8929.             $updatedData = [];
  8930.             foreach ($getters as $getter) {
  8931.                 $indForThis str_replace('get'''$getter);
  8932.                 $indForThis lcfirst($indForThis);
  8933.                 $updatedData[$indForThis] = $theEntityUpdated->{$getter}();
  8934.             }
  8935.             $updatedDataList[$dataInd] = $updatedData;
  8936.         }
  8937.         foreach ($dataToRemove as $dataInd => $dat) {
  8938.             $entityName $dat['entityName'];
  8939.             $idField $dat['idField'];
  8940.             $findById $dat['findId'];
  8941.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  8942.             $theEntityList $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findBy(
  8943.                 array
  8944.                 (
  8945.                     $idField => $findById,
  8946.                 )
  8947.             );
  8948.             foreach ($theEntityList as $dt) {
  8949.                 $em->remove($dt);
  8950.                 $em->flush();
  8951.             }
  8952.             if ($additionalSql != '') {
  8953. //            if ($entityName == 'PlanningItem') {
  8954. //
  8955. //                $stmt='select disctinct parent_id from planning_item;';
  8956. //                $stmt->execute();
  8957. //                $get_kids = $stmt->fetchAll();
  8958. //                $p_ids=[];
  8959. //                foreach($get_kids as $g)
  8960. //                {
  8961. //                    $p_ids[]=$g['parent_id'];
  8962. //                }
  8963. //
  8964. //
  8965. //
  8966.                 $stmt $em->getConnection()->prepare($additionalSql);
  8967.                 $stmt->execute();
  8968.                 $stmt->closeCursor();
  8969. //
  8970. //
  8971.             }
  8972.             $updatedDataList[$dataInd] = [];
  8973.         }
  8974. //        if ($table == '') {
  8975. //            return new JsonResponse(
  8976. //                array(
  8977. //                    'success' => false,
  8978. ////                    'page_title' => 'Product Details',
  8979. ////                    'company_data' => $company_data,
  8980. //                    'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8981. //
  8982. //                )
  8983. //            );
  8984. //        }
  8985. //        if($request->query->has('returnJson'))
  8986.         return new JsonResponse(
  8987.             array(
  8988.                 'success' => true,
  8989.                 'data' => $relData,
  8990.                 'updatedDataList' => $updatedDataList,
  8991.             )
  8992.         );
  8993.     }
  8994.     public function GetAvailableQtyAction(Request $request$id 0)
  8995.     {
  8996.         $em $this->getDoctrine()->getManager();
  8997.         $productId $request->request->has('productId') ? $request->request->get('productId') : 0;
  8998.         $colorId $request->request->has('colorId') ? $request->request->get('colorId') : 0;
  8999.         $dataId $request->request->has('dataId') ? $request->request->get('dataId') : 0;
  9000.         $allowedWarehouseIds $request->request->has('warehouseId') ? [$request->request->get('warehouseId')] : [];
  9001.         $allowedWarehouseActionIds $request->request->has('warehouseActionId') ? [$request->request->get('warehouseActionId')] : [];
  9002.         $qty Inventory::getProductQty($em$productId$allowedWarehouseIds$allowedWarehouseActionIds$colorId);
  9003.         return new JsonResponse(array("success" => true,
  9004.             "qty" => $qty,
  9005.             "dataId" => $dataId,
  9006.         ));
  9007.     }
  9008.     public
  9009.     function labelFormatSelectAjaxAction(Request $request$queryStr '')
  9010.     {
  9011.         $em $this->getDoctrine()->getManager();
  9012.         $companyId $this->getLoggedUserCompanyId($request);
  9013.         $company_data Company::getCompanyData($em$companyId);
  9014.         $data = [];
  9015.         $data_by_id = [];
  9016.         $html '';
  9017.         $productByCodeData = [];
  9018.         if ($queryStr == '_EMPTY_')
  9019.             $queryStr '';
  9020.         if ($request->request->has('query') && $queryStr == '')
  9021.             $queryStr $request->request->get('queryStr');
  9022.         if ($queryStr == '_EMPTY_')
  9023.             $queryStr '';
  9024.         $filterQryForCriteria "select * from label_format where company_id=" $companyId " ";
  9025.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  9026.             $filterQryForCriteria .= " and label_type=" $request->request->get('dataType');
  9027.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  9028.             $filterQryForCriteria .= " and format_id=" $request->request->get('formatId');
  9029.         else if ($queryStr != '')
  9030.             $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' or `format_code` like '%" $queryStr "%') ";
  9031.         if ($filterQryForCriteria != '')
  9032.             $filterQryForCriteria .= "  limit 25";
  9033.         $get_kids_sql $filterQryForCriteria;
  9034. //        if ($request->request->has('productIds'))
  9035. //
  9036. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9037. //        else if ($request->request->has('productCode'))
  9038. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9039. //        else if ($filterQryForCriteria!='')
  9040. //            $get_kids_sql = $filterQryForCriteria;
  9041. //
  9042. //        else
  9043. //               $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";
  9044.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9045.         $stmt->execute();
  9046.         $get_kids $stmt->fetchAll();
  9047.         $productId 0;
  9048.         if (!empty($get_kids)) {
  9049.             foreach ($get_kids as $product) {
  9050.                 $pa = array();
  9051.                 $pa['id'] = $product['format_id'];
  9052.                 $pa['name'] = $product['name'];
  9053.                 $pa['format_code'] = $product['format_code'] . '. ' $product['name'];
  9054.                 $pa['id_code_name'] = $product['format_id'] . '. ' $product['format_code'] . ' - ' $product['name'] . ' ';
  9055.                 $pa['text'] = $product['name'];
  9056.                 $pa['value'] = $product['format_id'];
  9057.                 $data[] = $pa;
  9058.                 $data_by_id[$product['format_id']] = $pa;
  9059.                 $productId $product['format_id'];
  9060.             }
  9061.         }
  9062. //        if($request->query->has('returnJson'))
  9063.         {
  9064.             return new JsonResponse(
  9065.                 array(
  9066.                     'success' => true,
  9067. //                    'page_title' => 'Product Details',
  9068. //                    'company_data' => $company_data,
  9069.                     'data' => $data,
  9070.                     'dataById' => $data_by_id,
  9071.                     'productId' => $productId,
  9072.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9073. //                    'exId'=>$id,
  9074. //                'productByCodeData' => $productByCodeData,
  9075. //                'productData' => $productData,
  9076. //                'currInvList' => $currInvList,
  9077. //                'productList' => Inventory::ProductList($em, $companyId),
  9078. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9079. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9080. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9081. //                'unitList' => Inventory::UnitTypeList($em),
  9082. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9083. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9084. //                'warehouseList' => Inventory::WarehouseList($em),
  9085.                 )
  9086.             );
  9087.         }
  9088.     }
  9089.     public
  9090.     function CategoryListSelectAjaxAction(Request $request$queryStr '')
  9091.     {
  9092.         $em $this->getDoctrine()->getManager();
  9093.         $companyId $this->getLoggedUserCompanyId($request);
  9094.         $company_data Company::getCompanyData($em$companyId);
  9095.         $data = [];
  9096.         $data_by_id = [];
  9097.         $html '';
  9098.         $productByCodeData = [];
  9099.         if ($queryStr == '_EMPTY_')
  9100.             $queryStr '';
  9101.         if ($request->request->has('query') && $queryStr == '')
  9102.             $queryStr $request->request->get('queryStr');
  9103.         if ($queryStr == '_EMPTY_')
  9104.             $queryStr '';
  9105.         $filterQryForCriteria "select * from inv_product_categories where company_id=" $companyId " ";
  9106.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  9107.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  9108.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  9109.         if ($filterQryForCriteria != '')
  9110.             $filterQryForCriteria .= "  limit 25";
  9111.         $get_kids_sql $filterQryForCriteria;
  9112. //        if ($request->request->has('productIds'))
  9113. //
  9114. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9115. //        else if ($request->request->has('productCode'))
  9116. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9117. //        else if ($filterQryForCriteria!='')
  9118. //            $get_kids_sql = $filterQryForCriteria;
  9119. //
  9120. //        else
  9121. //               $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";
  9122.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9123.         $stmt->execute();
  9124.         $get_kids $stmt->fetchAll();
  9125.         $productId 0;
  9126.         if (!empty($get_kids)) {
  9127.             foreach ($get_kids as $product) {
  9128.                 $pa = array();
  9129.                 $pa['id'] = $product['id'];
  9130.                 $pa['name'] = $product['name'];
  9131.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  9132.                 $pa['globalId'] = $product['global_id'];
  9133.                 $pa['text'] = $product['name'];
  9134.                 $pa['value'] = $product['id'];
  9135.                 $pa['igId'] = $product['ig_id'];
  9136. //                $pa['categoryId'] = $product['category_id'];
  9137. //                $pa['subCategoryId'] = $product['sub_category_id'];
  9138.                 $data[] = $pa;
  9139.                 $data_by_id[$product['id']] = $pa;
  9140.                 $productId $product['id'];
  9141.             }
  9142.         }
  9143. //        if($request->query->has('returnJson'))
  9144.         {
  9145.             return new JsonResponse(
  9146.                 array(
  9147.                     'success' => true,
  9148. //                    'page_title' => 'Product Details',
  9149. //                    'company_data' => $company_data,
  9150.                     'data' => $data,
  9151.                     'dataById' => $data_by_id,
  9152.                     'productId' => $productId,
  9153.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9154. //                    'exId'=>$id,
  9155. //                'productByCodeData' => $productByCodeData,
  9156. //                'productData' => $productData,
  9157. //                'currInvList' => $currInvList,
  9158. //                'productList' => Inventory::ProductList($em, $companyId),
  9159. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9160. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9161. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9162. //                'unitList' => Inventory::UnitTypeList($em),
  9163. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9164. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9165. //                'warehouseList' => Inventory::WarehouseList($em),
  9166.                 )
  9167.             );
  9168.         }
  9169.     }
  9170.     public
  9171.     function SubCategoryListSelectAjaxAction(Request $request$queryStr '')
  9172.     {
  9173.         $em $this->getDoctrine()->getManager();
  9174.         $companyId $this->getLoggedUserCompanyId($request);
  9175.         $company_data Company::getCompanyData($em$companyId);
  9176.         $data = [];
  9177.         $data_by_id = [];
  9178.         $html '';
  9179.         $productByCodeData = [];
  9180.         if ($queryStr == '_EMPTY_')
  9181.             $queryStr '';
  9182.         if ($request->request->has('query') && $queryStr == '')
  9183.             $queryStr $request->request->get('queryStr');
  9184.         if ($queryStr == '_EMPTY_')
  9185.             $queryStr '';
  9186.         $filterQryForCriteria "select * from inv_product_sub_categories where company_id=" $companyId " ";
  9187.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9188.             $filterQryForCriteria .= " and sub_category_id=" $request->request->get('subCategoryId');
  9189.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  9190.             $filterQryForCriteria .= " and category_id=" $request->request->get('categoryId');
  9191.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  9192.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  9193.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  9194.             if ($request->request->get('parentId') != 0)
  9195.                 $filterQryForCriteria .= " and  parent_id=" $request->request->get('parentId');
  9196.             else
  9197.                 $filterQryForCriteria .= " and ( parent_id =0 or parent_id is null ) ";
  9198.         if ($request->request->has('level') && $request->request->get('level') != '')
  9199.             if ($request->request->get('level') != 0)
  9200.                 $filterQryForCriteria .= " and level=" $request->request->get('level');
  9201.             else
  9202.                 $filterQryForCriteria .= " and ( level =0 or level is null) ";
  9203.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  9204.         if ($filterQryForCriteria != '')
  9205.             $filterQryForCriteria .= "  limit 25";
  9206.         $get_kids_sql $filterQryForCriteria;
  9207. //        if ($request->request->has('productIds'))
  9208. //
  9209. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9210. //        else if ($request->request->has('productCode'))
  9211. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9212. //        else if ($filterQryForCriteria!='')
  9213. //            $get_kids_sql = $filterQryForCriteria;
  9214. //
  9215. //        else
  9216. //               $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";
  9217.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9218.         $stmt->execute();
  9219.         $get_kids $stmt->fetchAll();
  9220.         $productId 0;
  9221.         if (!empty($get_kids)) {
  9222.             foreach ($get_kids as $product) {
  9223.                 $pa = array();
  9224.                 $pa['id'] = $product['id'];
  9225.                 $pa['name'] = $product['name'];
  9226.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  9227.                 $pa['globalId'] = $product['global_id'];
  9228.                 $pa['parentId'] = $product['parent_id'];
  9229.                 $pa['text'] = $product['name'];
  9230.                 $pa['value'] = $product['id'];
  9231.                 $pa['igId'] = $product['ig_id'];
  9232.                 $pa['categoryId'] = $product['category_id'];
  9233. //                $pa['subCategoryId'] = $product['sub_category_id'];
  9234.                 $data[] = $pa;
  9235.                 $data_by_id[$product['id']] = $pa;
  9236.                 $productId $product['id'];
  9237.             }
  9238.         }
  9239. //        if($request->query->has('returnJson'))
  9240.         {
  9241.             return new JsonResponse(
  9242.                 array(
  9243.                     'success' => true,
  9244. //                    'page_title' => 'Product Details',
  9245. //                    'company_data' => $company_data,
  9246.                     'data' => $data,
  9247.                     'dataById' => $data_by_id,
  9248.                     'productId' => $productId,
  9249.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9250. //                    'exId'=>$id,
  9251. //                'productByCodeData' => $productByCodeData,
  9252. //                'productData' => $productData,
  9253. //                'currInvList' => $currInvList,
  9254. //                'productList' => Inventory::ProductList($em, $companyId),
  9255. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9256. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9257. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9258. //                'unitList' => Inventory::UnitTypeList($em),
  9259. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9260. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9261. //                'warehouseList' => Inventory::WarehouseList($em),
  9262.                 )
  9263.             );
  9264.         }
  9265.     }
  9266.     public
  9267.     function ProductByCodeViewAction(Request $request$id 0)
  9268.     {
  9269.         $em $this->getDoctrine()->getManager();
  9270.         $companyId $this->getLoggedUserCompanyId($request);
  9271.         $company_data Company::getCompanyData($em$companyId);
  9272.         $data = [];
  9273.         $html '';
  9274.         $productByCodeData = [];
  9275.         if ($id != 0) {
  9276.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9277.                 ->findOneBy(
  9278.                     array(
  9279.                         'productByCodeId' => $id
  9280.                     )
  9281.                 );
  9282.         } else {
  9283.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9284.                 ->findOneBy(
  9285.                     array(
  9286. //                        'productByCodeId' => $id,
  9287.                         'CompanyId' => $companyId
  9288.                     ), array(
  9289.                         'productByCodeId' => 'DESC'
  9290.                     )
  9291.                 );
  9292.             if ($productByCodeData)
  9293.                 $id $productByCodeData->getProductByCodeId();
  9294.         }
  9295.         if ($id != 0) {
  9296.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9297.                 ->findOneBy(
  9298.                     array(
  9299.                         'id' => $productByCodeData->getProductId()
  9300.                     )
  9301.                 );
  9302.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9303.                 ->findBy(
  9304.                     array(
  9305.                         'productId' => $id
  9306.                     )
  9307.                 );
  9308.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  9309.                 array(
  9310.                     'page_title' => 'Product Details',
  9311.                     'company_data' => $company_data,
  9312.                     'productByCodeData' => $productByCodeData,
  9313.                     'productData' => $productData,
  9314.                     'currInvList' => $currInvList,
  9315.                     'exId' => $id,
  9316.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9317.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9318.                     'productList' => Inventory::ProductList($em$companyId),
  9319.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9320.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9321.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9322.                     'unitList' => Inventory::UnitTypeList($em),
  9323.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9324.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9325.                     'warehouseList' => Inventory::WarehouseList($em),
  9326.                 )
  9327.             );
  9328.         } else {
  9329.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  9330.                 array(
  9331.                     'exId' => $id,
  9332.                 )
  9333.             );
  9334.         }
  9335.         if ($request->query->has('returnJson')) {
  9336.             return new JsonResponse(
  9337.                 array(
  9338.                     'success' => true,
  9339.                     'page_title' => 'Product Details',
  9340.                     'company_data' => $company_data,
  9341.                     'renderedHtml' => $html,
  9342.                     'exId' => $id,
  9343. //                'productByCodeData' => $productByCodeData,
  9344. //                'productData' => $productData,
  9345. //                'currInvList' => $currInvList,
  9346. //                'productList' => Inventory::ProductList($em, $companyId),
  9347. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9348. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9349. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9350. //                'unitList' => Inventory::UnitTypeList($em),
  9351. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9352. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9353. //                'warehouseList' => Inventory::WarehouseList($em),
  9354.                 )
  9355.             );
  9356.         } else {
  9357. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9358. //                ->findBy(
  9359. //                    array(
  9360. ////                        'productByCodeId' => $id,
  9361. //                    'CompanyId'=>$companyId
  9362. //                    )
  9363. //                );
  9364.             $productByCodeList = []; //called by ajax
  9365.             return $this->render('@Inventory/pages/views/product_by_code_view.html.twig',
  9366.                 array(
  9367.                     'page_title' => 'Product Details',
  9368.                     'company_data' => $company_data,
  9369.                     'renderedHtml' => $html,
  9370.                     'exId' => $id,
  9371.                     'productByCodeList' => $productByCodeList,
  9372. //                'productByCodeData' => $productByCodeData,
  9373. //                'productData' => $productData,
  9374. //                'currInvList' => $currInvList,
  9375. //                'productList' => Inventory::ProductList($em, $companyId),
  9376. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9377. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9378. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9379. //                'unitList' => Inventory::UnitTypeList($em),
  9380. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9381. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9382. //                'warehouseList' => Inventory::WarehouseList($em),
  9383.                 )
  9384.             );
  9385.         }
  9386.     }
  9387.     public
  9388.     function ConsumptionSettingsAction(Request $request$id)
  9389.     {
  9390.         $cc_id '';
  9391.         $cc_name '';
  9392.         $em $this->getDoctrine()->getManager();
  9393.         $companyId $this->getLoggedUserCompanyId($request);
  9394.         $consumptionTypeId 0;
  9395.         if ($request->isMethod('POST')) {
  9396.             $new_cc = [];
  9397.             if ($request->request->get('consumptionTypeId') != '' && $request->request->get('consumptionTypeId') != 0) {
  9398.                 $em $this->getDoctrine()->getManager();
  9399.                 $new_cc $this->getDoctrine()
  9400.                     ->getRepository('ApplicationBundle:ConsumptionType')
  9401.                     ->findOneBy(
  9402.                         array(
  9403.                             'consumptionTypeId' => $request->request->get('consumptionTypeId'),
  9404.                         )
  9405.                     );
  9406.                 $new_cc->setName($request->request->get('name'));
  9407.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9408.                 $new_cc->setCompanyId($companyId);
  9409.                 $em->flush();
  9410.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9411.                 $this->addFlash(
  9412.                     'success',
  9413.                     'Consumption Information Updated'
  9414.                 );
  9415.             } else {
  9416.                 $new_cc = new ConsumptionType();
  9417.                 $new_cc->setName($request->request->get('name'));
  9418.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9419.                 $new_cc->setCompanyId($companyId);
  9420.                 $em->persist($new_cc);
  9421.                 $em->flush();
  9422.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9423.                 $em->flush();
  9424.                 $this->addFlash(
  9425.                     'success',
  9426.                     'New Consumption Type Added'
  9427.                 );
  9428.             }
  9429.         }
  9430.         $extData = [];
  9431.         if ($id != 0) {
  9432.             $extData $this->getDoctrine()
  9433.                 ->getRepository('ApplicationBundle:ConsumptionType')
  9434.                 ->findOneBy(
  9435.                     array(
  9436.                         'consumptionTypeId' => $id
  9437.                     )
  9438.                 );
  9439. //            $cc_data_list = [];
  9440. //            foreach ($cc_data as $value) {
  9441. //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  9442. //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  9443. //
  9444. //                if ($value->getSupplierCategoryId() == $id) {
  9445. //                    $cc_id = $value->getSupplierCategoryId();
  9446. //                    $cc_name = $value->getName();
  9447. //                }
  9448. //            }
  9449.         }
  9450.         return $this->render('@Inventory/pages/input_forms/consumption_settings.html.twig',
  9451.             array(
  9452.                 'page_title' => 'Consumption Settings',
  9453.                 'consumptionTypeList' => $this->getDoctrine()
  9454.                     ->getRepository('ApplicationBundle:ConsumptionType')
  9455.                     ->findBy(
  9456.                         array(
  9457.                             'CompanyId' => $companyId
  9458.                         )
  9459.                     ),
  9460.                 'extData' => $extData,
  9461.                 'headList' => Accounts::getParentLedgerHeads($em),
  9462. //                'countryList'=>SalesOrderM::Co
  9463.             )
  9464.         );
  9465.     }
  9466.     public
  9467.     function ProductByCodeCheckAssignPrintAction(Request $request$id 0)
  9468.     {
  9469.         $em $this->getDoctrine()->getManager();
  9470.         $companyId $this->getLoggedUserCompanyId($request);
  9471.         $company_data Company::getCompanyData($em$companyId);
  9472.         $data = [];
  9473.         $html '';
  9474.         $productByCodeData = [];
  9475.         $productDataWeightPackageGm '';
  9476.         $productDataWeightVarianceValue 0;
  9477.         $productDataWeightVarianceType 0;
  9478.         $productByCodeDataObj = [];
  9479.         $dr_id 0;//for dr_id
  9480.         $skipRenderData 0;
  9481.         if ($request->query->has('skipRenderData'))
  9482.             $skipRenderData $request->query->get('skipRenderData');
  9483.         if ($id != 0) {
  9484.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9485.                 ->findOneBy(
  9486.                     array(
  9487.                         'productByCodeId' => $id
  9488.                     )
  9489.                 );
  9490.         } else {
  9491.             if ($request->query->has('scanCode')) {
  9492.                 $query $em->getRepository('ApplicationBundle:ProductByCode')
  9493.                     ->createQueryBuilder('p');
  9494.                 if ($request->query->has('assigned')) {
  9495.                     $query->where('p.assigned > :av')
  9496.                         ->setParameter('av'$request->query->get('assigned'));
  9497.                 } else
  9498.                     $query->where("1=0");
  9499.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  9500.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  9501.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  9502.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  9503.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  9504.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  9505.                 $query->setMaxResults(1);
  9506.                 $results $query->getQuery()->getResult();
  9507.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  9508.             } else
  9509.                 $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9510.                     ->findOneBy(
  9511.                         array(
  9512. //                        'productByCodeId' => $id,
  9513.                             'CompanyId' => $companyId
  9514.                         ), array(
  9515.                             'productByCodeId' => 'DESC'
  9516.                         )
  9517.                     );
  9518.             if ($productByCodeData)
  9519.                 $id $productByCodeData->getProductByCodeId();
  9520.         }
  9521.         if ($id != 0) {
  9522.             $productByCodeDataObj = array(
  9523.                 'salesCode' => $productByCodeData->getSalesCode(),
  9524.                 'sales_code' => $productByCodeData->getSalesCode(),
  9525.                 'sn' => $productByCodeData->getSerialNo(),
  9526.                 'serialNo' => $productByCodeData->getSerialNo(),
  9527.                 'imei1' => $productByCodeData->getImei1(),
  9528.                 'imei2' => $productByCodeData->getImei2(),
  9529.                 'soId' => $productByCodeData->getSalesOrderId(),
  9530.                 'poId' => $productByCodeData->getPurchaseOrderId(),
  9531.                 'irrId' => $productByCodeData->getIrrId(),
  9532.                 'productId' => $productByCodeData->getProductId(),
  9533.                 'productByCodeId' => $productByCodeData->getProductByCodeId(),
  9534.                 'warehouseId' => $productByCodeData->getWarehouseId(),
  9535.                 'warehouseActionId' => $productByCodeData->getWarehouseActionId(),
  9536.                 'stId' => $productByCodeData->getStockTransferId(),
  9537.                 'srId' => $productByCodeData->getStockReceivedNoteId(),
  9538.                 'scmpId' => $productByCodeData->getStockConsumptionNoteId(),
  9539.                 'clientId' => $productByCodeData->getClientId(),
  9540.                 'supplierId' => $productByCodeData->getSupplierId(),
  9541.                 'drId' => $productByCodeData->getDeliveryReceiptId(),
  9542.                 'consumerName' => $productByCodeData->getConsumerName(),
  9543.                 'drItemData' => [],
  9544. //                'salesCodes' => $productByCodeData->getDeliveryReceiptId(),
  9545.             );
  9546.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9547.                 ->findOneBy(
  9548.                     array(
  9549.                         'id' => $productByCodeData->getProductId()
  9550.                     )
  9551.                 );
  9552.             if ($productByCodeData->getProductionId() != null) {
  9553.                 $productionDataHere $em->getRepository('ApplicationBundle:Production')
  9554.                     ->findOneBy(
  9555.                         array(
  9556.                             'productionId' => $productByCodeData->getProductionId()
  9557.                         )
  9558.                     );
  9559.                 if ($productionDataHere) {
  9560.                     $productDataWeightPackageGm $productionDataHere->getPackageWeight();
  9561.                     $productDataWeightVarianceValue $productionDataHere->getPackageWeightVarianceValue();
  9562.                     $productDataWeightVarianceType $productionDataHere->getPackageWeightVarianceType();
  9563.                 }
  9564.             } else {
  9565.                 if ($productData) {
  9566.                     $productDataWeightPackageGm $productData->getWeight();
  9567.                     $productDataWeightVarianceValue $productData->getWeightVarianceValue();
  9568.                     $productDataWeightVarianceType $productData->getWeightVarianceType();
  9569.                 }
  9570.             }
  9571.             if ($productData) {
  9572.                 $productByCodeDataObj['unitTypeId'] = $productData->getUnitTypeId();
  9573.                 $productByCodeDataObj['purchasePrice'] = $productData->getPurchasePrice();
  9574.                 $productByCodeDataObj['productFdm'] = $productData->getProductFdm();
  9575.                 $productByCodeDataObj['productName'] = $productData->getName();
  9576.                 if ($request->request->has('forSalesReturn') || $request->query->has('forSalesReturn')) {
  9577.                     $QD $this->getDoctrine()
  9578.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  9579.                         ->findOneBy(
  9580.                             array(
  9581.                                 'deliveryReceiptId' => $productByCodeData->getDeliveryReceiptId(),
  9582.                                 'productId' => $productByCodeData->getProductId(),
  9583.                             )
  9584.                         );
  9585. //            if($request->request->get('wareHouseId')!='')
  9586.                     if ($QD) {
  9587.                         $new_pid $QD->getProductId();
  9588.                         $sales_code_range = [];
  9589.                         if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  9590.                             $sales_code_range json_decode($QD->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  9591.                         } else {
  9592.                             $max_int_length strlen((string)PHP_INT_MAX) - 1;
  9593.                             $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$QD->getSalesCodeRange());
  9594.                             $sales_code_range json_decode($json_without_bigintstrue);
  9595.                         }
  9596.                         $p_data = array(
  9597.                             'details_id' => $QD->getId(),
  9598.                             'productId' => $new_pid,
  9599.                             'dr_id' => $productByCodeData->getDeliveryReceiptId(),
  9600.                             'product_name' => $productData->getName(),
  9601.                             'qty' => $QD->getQty(),
  9602.                             'delivered' => $QD->getDelivered(),
  9603.                             'unitTypeId' => $QD->getUnitTypeId(),
  9604.                             'deliverable' => $QD->getDeliverable(),
  9605.                             'balance' => $QD->getBalance(),
  9606.                             'salesCodeRangeStr' => $QD->getSalesCodeRange(),
  9607.                             'salesCodeRange' => $sales_code_range,
  9608.                             'sales_codes' => $sales_code_range,
  9609.                             'sales_price' => $QD->getPrice(),
  9610.                             'purchase_price' => $QD->getCurrentPurchasePrice()
  9611. //                        'delivered'=>$product->getDelivered(),
  9612.                         );
  9613.                         $productByCodeDataObj['drItemData'][] = $p_data;
  9614.                     }
  9615.                 }
  9616.             }
  9617.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9618.                 ->findBy(
  9619.                     array(
  9620.                         'productId' => $id
  9621.                     )
  9622.                 );
  9623.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  9624.                 array(
  9625.                     'page_title' => 'Details',
  9626.                     'company_data' => $company_data,
  9627.                     'productByCodeData' => $productByCodeData,
  9628.                     'productByCodeDataObj' => $productByCodeDataObj,
  9629.                     'productData' => $productData,
  9630.                     'currInvList' => $currInvList,
  9631.                     'productDataWeightPackageGm' => $productDataWeightPackageGm,
  9632.                     'productDataWeightVarianceValue' => $productDataWeightVarianceValue,
  9633.                     'productDataWeightVarianceType' => $productDataWeightVarianceType,
  9634.                     'exId' => $id,
  9635.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9636.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9637.                     'productList' => Inventory::ProductList($em$companyId),
  9638.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9639.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9640.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9641.                     'unitList' => Inventory::UnitTypeList($em),
  9642.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9643.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9644.                     'warehouseList' => Inventory::WarehouseList($em),
  9645.                 )
  9646.             ));
  9647.         } else {
  9648.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  9649.                 array(
  9650.                     'exId' => $id,
  9651.                 )
  9652.             ));
  9653.         }
  9654.         if ($request->query->has('returnJson')) {
  9655.             return new JsonResponse(
  9656.                 array(
  9657.                     'success' => true,
  9658.                     'page_title' => 'Product Details',
  9659.                     'company_data' => $company_data,
  9660.                     'renderedHtml' => $html,
  9661.                     'exId' => $id,
  9662.                     'productByCodeDataObj' => $productByCodeDataObj,
  9663. //                'productData' => $productData,
  9664. //                'currInvList' => $currInvList,
  9665. //                'productList' => Inventory::ProductList($em, $companyId),
  9666. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9667. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9668. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9669. //                'unitList' => Inventory::UnitTypeList($em),
  9670. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9671. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9672. //                'warehouseList' => Inventory::WarehouseList($em),
  9673.                 )
  9674.             );
  9675.         } else {
  9676. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9677. //                ->findBy(
  9678. //                    array(
  9679. ////                        'productByCodeId' => $id,
  9680. //                    'CompanyId'=>$companyId
  9681. //                    )
  9682. //                );
  9683.             $productByCodeList = []; //called by ajax
  9684.             return $this->render('@Inventory/pages/views/product_by_code_assign_check_print.html.twig',
  9685.                 array(
  9686.                     'page_title' => 'Serial Manager',
  9687.                     'company_data' => $company_data,
  9688.                     'renderedHtml' => $html,
  9689.                     'exId' => $id,
  9690.                     'productByCodeList' => $productByCodeList,
  9691.                     'productByCodeDataObj' => $productByCodeDataObj,
  9692. //                'productByCodeData' => $productByCodeData,
  9693. //                'productData' => $productData,
  9694. //                'currInvList' => $currInvList,
  9695. //                'productList' => Inventory::ProductList($em, $companyId),
  9696. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9697. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9698. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9699. //                'unitList' => Inventory::UnitTypeList($em),
  9700. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9701. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9702. //                'warehouseList' => Inventory::WarehouseList($em),
  9703.                 )
  9704.             );
  9705.         }
  9706.     }
  9707.     public
  9708.     function TestProductByCodeCheckAssignPrintAction(Request $request$id 0)
  9709.     {
  9710.         $em $this->getDoctrine()->getManager();
  9711.         $companyId $this->getLoggedUserCompanyId($request);
  9712.         $company_data Company::getCompanyData($em$companyId);
  9713.         $data = [];
  9714.         $html '';
  9715.         $productByCodeData = [];
  9716.         $productByCodeDataObj = [];
  9717.         if ($id != 0) {
  9718.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9719.                 ->findOneBy(
  9720.                     array(
  9721.                         'productByCodeId' => $id
  9722.                     )
  9723.                 );
  9724.         } else {
  9725.             if ($request->query->has('scanCode')) {
  9726.                 $query $em->getRepository('ApplicationBundle:ProductByCode')
  9727.                     ->createQueryBuilder('p');
  9728.                 if ($request->query->has('assigned')) {
  9729.                     $query->where('p.assigned > :av')
  9730.                         ->setParameter('av'$request->query->get('assigned'));
  9731.                 } else
  9732.                     $query->where("1=0");
  9733.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  9734.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  9735.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  9736.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  9737.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  9738.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  9739.                 $query->setMaxResults(1);
  9740.                 $results $query->getQuery()->getResult();
  9741.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  9742.             } else
  9743.                 $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9744.                     ->findOneBy(
  9745.                         array(
  9746. //                        'productByCodeId' => $id,
  9747.                             'CompanyId' => $companyId
  9748.                         ), array(
  9749.                             'productByCodeId' => 'DESC'
  9750.                         )
  9751.                     );
  9752.             if ($productByCodeData)
  9753.                 $id $productByCodeData->getProductByCodeId();
  9754.         }
  9755.         if ($id != 0) {
  9756.             $productByCodeDataObj = array(
  9757.                 'sn' => $productByCodeData->getSalesCode(),
  9758.                 'imei1' => $productByCodeData->getImei1(),
  9759.                 'imei2' => $productByCodeData->getImei2(),
  9760.                 'colorId' => $productByCodeData->getColorId(),
  9761.             );
  9762.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9763.                 ->findOneBy(
  9764.                     array(
  9765.                         'id' => $productByCodeData->getProductId()
  9766.                     )
  9767.                 );
  9768.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9769.                 ->findBy(
  9770.                     array(
  9771.                         'productId' => $id
  9772.                     )
  9773.                 );
  9774.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  9775.                 array(
  9776.                     'page_title' => 'Details',
  9777.                     'company_data' => $company_data,
  9778.                     'productByCodeData' => $productByCodeData,
  9779.                     'productData' => $productData,
  9780.                     'currInvList' => $currInvList,
  9781.                     'exId' => $id,
  9782.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9783.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9784.                     'productList' => Inventory::ProductList($em$companyId),
  9785.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9786.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9787.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9788.                     'unitList' => Inventory::UnitTypeList($em),
  9789.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9790.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9791.                     'warehouseList' => Inventory::WarehouseList($em),
  9792.                 )
  9793.             );
  9794.         } else {
  9795.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  9796.                 array(
  9797.                     'exId' => $id,
  9798.                 )
  9799.             );
  9800.         }
  9801.         if ($request->query->has('returnJson')) {
  9802.             return new JsonResponse(
  9803.                 array(
  9804.                     'success' => true,
  9805.                     'page_title' => 'Product Details',
  9806.                     'company_data' => $company_data,
  9807.                     'renderedHtml' => $html,
  9808.                     'exId' => $id,
  9809.                     'productByCodeDataObj' => $productByCodeDataObj,
  9810. //                'productData' => $productData,
  9811. //                'currInvList' => $currInvList,
  9812. //                'productList' => Inventory::ProductList($em, $companyId),
  9813. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9814. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9815. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9816. //                'unitList' => Inventory::UnitTypeList($em),
  9817. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9818. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9819. //                'warehouseList' => Inventory::WarehouseList($em),
  9820.                 )
  9821.             );
  9822.         } else {
  9823. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9824. //                ->findBy(
  9825. //                    array(
  9826. ////                        'productByCodeId' => $id,
  9827. //                    'CompanyId'=>$companyId
  9828. //                    )
  9829. //                );
  9830.             $productByCodeList = []; //called by ajax
  9831.             return $this->render('@Inventory/pages/views/test_product_by_code_assign_check_print.html.twig',
  9832.                 array(
  9833.                     'page_title' => ' Test Serial Manager',
  9834.                     'company_data' => $company_data,
  9835.                     'renderedHtml' => $html,
  9836.                     'exId' => $id,
  9837.                     'productByCodeList' => $productByCodeList,
  9838.                     'productByCodeDataObj' => $productByCodeDataObj,
  9839. //                'productByCodeData' => $productByCodeData,
  9840. //                'productData' => $productData,
  9841. //                'currInvList' => $currInvList,
  9842. //                'productList' => Inventory::ProductList($em, $companyId),
  9843. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9844. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9845. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9846. //                'unitList' => Inventory::UnitTypeList($em),
  9847. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9848. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9849. //                'warehouseList' => Inventory::WarehouseList($em),
  9850.                 )
  9851.             );
  9852.         }
  9853.     }
  9854.     public
  9855.     function DeleteProductAction(Request $request$id '')
  9856.     {
  9857.         $em $this->getDoctrine()->getManager();
  9858.         $idListArray = [];
  9859.         if ($request->isMethod('POST')) {
  9860.             if ($id == 0)
  9861.                 $id $request->request->get('productId');
  9862.             //now check the product closing , if nothing then we cna remove it
  9863.             $query_here $this->getDoctrine()
  9864.                 ->getRepository('ApplicationBundle:InvClosingBalance')
  9865.                 ->findBy(
  9866.                     array(
  9867.                         'productId' => $request->request->get('productId')
  9868.                     )
  9869.                 );
  9870.             if (!empty($query_here)) {
  9871.                 return new JsonResponse(
  9872.                     array(
  9873.                         'success' => false,
  9874.                     )
  9875.                 );
  9876.             } else {
  9877.                 $qry $em->getRepository('ApplicationBundle:ProductByCode')->findBy(array(
  9878.                     'productId' => $id
  9879.                 ));
  9880.                 foreach ($qry as $det) {
  9881.                     //remove any barcoded products
  9882.                     $em->remove($det);
  9883.                     $em->flush();
  9884.                 }
  9885.                 $qry $em->getRepository('ApplicationBundle:InvProducts')->findBy(array(
  9886.                     'id' => $id
  9887.                 ));
  9888.                 foreach ($qry as $det) {
  9889.                     //remove any barcoded products
  9890.                     $em->remove($det);
  9891.                     $em->flush();
  9892.                 }
  9893.                 $qry $em->getRepository('ApplicationBundle:InvItemTransaction')->findBy(array(
  9894.                     'productId' => $id
  9895.                 ));
  9896.                 foreach ($qry as $det) {
  9897.                     //remove any barcoded products
  9898.                     $em->remove($det);
  9899.                     $em->flush();
  9900.                 }
  9901.                 return new JsonResponse(
  9902.                     array(
  9903.                         'success' => true,
  9904.                     )
  9905.                 );
  9906.             }
  9907.         }
  9908.         return new JsonResponse(
  9909.             array(
  9910.                 'success' => false,
  9911.             )
  9912.         );
  9913.     }
  9914.     public
  9915.     function RegisterProductAction(Request $request$idListStr '')
  9916.     {
  9917.         $em $this->getDoctrine()->getManager();
  9918.         $companyId $this->getLoggedUserCompanyId($request);
  9919.         $company_data Company::getCompanyData($em$companyId);
  9920.         $session $request->getSession();
  9921. //        System::setSessionForUser($session );
  9922.         $idListArray = [];
  9923.         if ($idListStr != '')
  9924.             $idListArray explode(','$idListStr);
  9925.         $data = [];
  9926. //        if ($request->isMethod('POST')) {
  9927. //            $post = $request->request;
  9928. //            if ($request->request->get('formatId') != '') {
  9929. //                $query_here = $this->getDoctrine()
  9930. //                    ->getRepository('ApplicationBundle:CheckFormat')
  9931. //                    ->findOneBy(
  9932. //                        array(
  9933. //                            'formatId' => $request->request->get('formatId')
  9934. //                        )
  9935. //                    );
  9936. //                if (!empty($query_here))
  9937. //                    $new = $query_here;
  9938. //            } else
  9939. //                $new = new CheckFormat();
  9940. //            $new->setName($request->request->get('name'));
  9941. //            $new->setWidth($request->request->get('width'));
  9942. //            $new->setHeight($request->request->get('height'));
  9943. //            $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
  9944. //            $new->setCheckPayToTop($request->request->get('checkPayToTop'));
  9945. //            $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
  9946. //            $new->setCheckAmountTop($request->request->get('checkAmountTop'));
  9947. //            $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
  9948. //            $new->setCheckAiWTop($request->request->get('checkAiWTop'));
  9949. //            $new->setCheckDateLeft($request->request->get('checkDateLeft'));
  9950. //            $new->setCheckDateTop($request->request->get('checkDateTop'));
  9951. //            $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
  9952. //            $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
  9953. //            $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
  9954. //            $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
  9955. //            $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
  9956. //            $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
  9957. //            $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
  9958. //            $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
  9959. //            $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
  9960. //            $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
  9961. //            $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 1 : 0);
  9962. //            $new->setCheckImage($request->request->get('checkImage'));
  9963. //
  9964. //            $em = $this->getDoctrine()->getManager();
  9965. //            $em->persist($new);
  9966. //            $em->flush();
  9967. //
  9968. //        }
  9969. //        if (!empty($idListArray)) {
  9970. //            $query_here = $this->getDoctrine()
  9971. //                ->getRepository('ApplicationBundle:ProductByCode')
  9972. //                ->findBy(
  9973. //                    array(
  9974. //                        'productByCodeId' => $idListArray
  9975. //                    )
  9976. //                );
  9977. //            if (!empty($query_here))
  9978. //                $data = $query_here;
  9979. //
  9980. //        }
  9981. //        else if ($request->query->has('formatId')) {
  9982. //            $query_here = $this->getDoctrine()
  9983. //                ->getRepository('ApplicationBundle:CheckFormat')
  9984. //                ->findOneBy(
  9985. //                    array(
  9986. //                        'formatId' => $request->query->get('formatId')
  9987. //                    )
  9988. //                );
  9989. //            if (!empty($query_here))
  9990. //                $data = $query_here;
  9991. //        }
  9992.         $data = [];
  9993.         $html '';
  9994.         $productByCodeData = [];
  9995.         if ($request->query->has('returnJson')) {
  9996.             return new JsonResponse(
  9997.                 array(
  9998.                     'success' => true,
  9999.                     'page_title' => 'Product Details',
  10000.                     'company_data' => $company_data,
  10001.                     'renderedHtml' => $html,
  10002.                     'data' => $data,
  10003.                     'idListArray' => $idListArray,
  10004. //                    'exId'=>$id,
  10005. //                'productByCodeData' => $productByCodeData,
  10006. //                'productData' => $productData,
  10007. //                'currInvList' => $currInvList,
  10008. //                'productList' => Inventory::ProductList($em, $companyId),
  10009. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10010. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10011. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10012. //                'unitList' => Inventory::UnitTypeList($em),
  10013. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10014. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10015. //                'warehouseList' => Inventory::WarehouseList($em),
  10016.                 )
  10017.             );
  10018.         } else {
  10019.             return $this->render('@Inventory/pages/input_forms/register_product.html.twig',
  10020.                 array(
  10021.                     'page_title' => 'Register Product',
  10022.                     'company_data' => $company_data,
  10023.                     'renderedHtml' => $html,
  10024. //                    'exIdList'=>$i,
  10025.                     'idListArray' => $idListArray,
  10026.                     'data' => $data,
  10027.                     'productByCodeList' => [],
  10028.                     'productByCodeData' => [],
  10029.                     'productList' => Inventory::ProductList($em$companyId),
  10030.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10031.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10032.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10033.                     'unitList' => Inventory::UnitTypeList($em),
  10034.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10035.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10036.                     'warehouseList' => Inventory::WarehouseList($em),
  10037.                 )
  10038.             );
  10039.         }
  10040.     }
  10041.     public
  10042.     function BrandViewAction(Request $request)
  10043.     {
  10044.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  10045.             array(
  10046.                 'page_title' => 'Stock Return'
  10047.             )
  10048.         );
  10049.     }
  10050.     public
  10051.     function PrintTableDataAction(Request $request)
  10052.     {
  10053.         $em $this->getDoctrine()->getManager();
  10054.         $company_data Company::getCompanyData($em1);
  10055.         $data = [];
  10056.         $print_title "test";
  10057.         $document_mark = array(
  10058.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10059.             'copy' => ''
  10060.         );
  10061.         $mis_data = [];
  10062.         $p 1;
  10063.         return $this->render('@Inventory/pages/print/print_table_data.html.twig',
  10064.             array(
  10065.                 'page_title' => 'Data Report',
  10066.                 'data' => $data,
  10067.                 'page_header' => 'Report',
  10068.                 'print_title' => $print_title,
  10069.                 'document_type' => 'Journal voucher',
  10070.                 'document_mark_image' => $document_mark['original'],
  10071.                 'page_header_sub' => 'Add',
  10072. //                'type_list'=>$type_list,
  10073.                 'mis_data' => $mis_data,
  10074.                 'item_data' => [],
  10075.                 'received' => 2,
  10076.                 'return' => 1,
  10077.                 'total_w_vat' => 1,
  10078.                 'total_vat' => 1,
  10079.                 'total_wo_vat' => 1,
  10080.                 'invoice_id' => 'abcd1234',
  10081.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10082.                 'created_by' => 'created by',
  10083.                 'created_at' => '',
  10084.                 'red' => 0,
  10085.                 'company_name' => $company_data->getName(),
  10086.                 'company_data' => $company_data,
  10087.                 'company_address' => $company_data->getAddress(),
  10088.                 'company_image' => $company_data->getImage(),
  10089.                 'p' => $p
  10090.             )
  10091.         );
  10092.     }
  10093.     public
  10094.     function ReplacementReportAction(Request $request)
  10095.     {
  10096.         $qry_data = array(
  10097.             'warehouseId' => [0],
  10098.             'igId' => [0],
  10099.             'brandId' => [0],
  10100.             'categoryId' => [0],
  10101.             'actionTagId' => [0],
  10102.         );
  10103.         $em $this->getDoctrine()->getManager();
  10104.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  10105.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  10106.         $data_searched = [];
  10107.         $companyId $this->getLoggedUserCompanyId($request);
  10108.         $company_data Company::getCompanyData($em$companyId);
  10109.         $data = [];
  10110.         $print_title "Inventory Report";
  10111.         $document_mark = array(
  10112.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10113.             'copy' => ''
  10114.         );
  10115.         $post_data $request->request;
  10116.         $start_date $post_data->has('start_date') ? $post_data->get('start_date') : '';
  10117.         $end_date $post_data->has('end_date') ? $post_data->get('end_date') : '';
  10118.         if ($request->isMethod('POST'))
  10119.             $method 'POST';
  10120.         else
  10121.             $method 'GET';
  10122.         {
  10123. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  10124.             $data_searched Inventory::GetReplacementReportData($this->getDoctrine()->getManager(),
  10125.                 $request->request$method,
  10126.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  10127.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  10128.                 return new JsonResponse(
  10129.                     array(
  10130.                         'page_title' => 'Inventory ',
  10131.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10132.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10133.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10134.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10135.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10136.                         'action_tag' => $warehouse_action_list,
  10137.                         'start_date' => $start_date,
  10138.                         'end_date' => $end_date,
  10139.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10140.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10141.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10142.                         'data_searched' => $data_searched,
  10143.                         'success' => empty($data_searched['query_result']) ? false true
  10144.                     )
  10145.                 );
  10146.             }
  10147.             if ($request->request->get('print_data_enabled') == 1) {
  10148.                 $print_sub_title "";
  10149.                 return $this->render('@Inventory/pages/print/print_replacement_report.html.twig',
  10150.                     array(
  10151.                         'page_title' => 'Replacement Report',
  10152.                         'page_header' => 'Report',
  10153.                         'print_title' => $print_title,
  10154.                         'document_type' => 'Journal voucher',
  10155.                         'document_mark_image' => $document_mark['original'],
  10156.                         'page_header_sub' => 'Add',
  10157.                         'item_data' => [],
  10158.                         'received' => 2,
  10159.                         'return' => 1,
  10160.                         'total_w_vat' => 1,
  10161.                         'total_vat' => 1,
  10162.                         'total_wo_vat' => 1,
  10163.                         'invoice_id' => 'abcd1234',
  10164.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  10165.                         'created_by' => 'created by',
  10166.                         'created_at' => '',
  10167.                         'red' => 0,
  10168.                         'company_name' => $company_data->getName(),
  10169.                         'company_data' => $company_data,
  10170.                         'company_address' => $company_data->getAddress(),
  10171.                         'company_image' => $company_data->getImage(),
  10172.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10173.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10174.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10175.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10176.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10177.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10178.                         'action_tag' => $warehouse_action_list,
  10179.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10180.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10181.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10182.                         'start_date' => $start_date,
  10183.                         'end_date' => $end_date,
  10184.                         'data_searched' => $data_searched
  10185.                     )
  10186.                 );
  10187.             }
  10188.         }
  10189.         return $this->render('@Inventory/pages/report/replacement_report.html.twig',
  10190.             array(
  10191.                 'page_title' => 'Replacement Report',
  10192.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10193.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10194.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10195.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10196.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10197. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10198.                 'action_tag' => $warehouse_action_list,
  10199.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10200.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10201.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10202.                 'start_date' => $start_date,
  10203.                 'end_date' => $end_date,
  10204.                 'data_searched' => $data_searched,
  10205.                 'success' => empty($data_searched['query_result']) ? false true
  10206.             )
  10207.         );
  10208.     }
  10209.     public
  10210.     function InventoryViewAction(Request $request)
  10211.     {
  10212.         $qry_data = array(
  10213.             'warehouseId' => [0],
  10214.             'igId' => [0],
  10215.             'brandId' => [0],
  10216.             'categoryId' => [0],
  10217.             'actionTagId' => [0],
  10218.         );
  10219.         $em $this->getDoctrine()->getManager();
  10220.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  10221.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  10222.         $data_searched = [];
  10223.         $companyId $this->getLoggedUserCompanyId($request);
  10224.         $company_data Company::getCompanyData($em$companyId);
  10225.         $data = [];
  10226.         $print_title "Inventory Report";
  10227.         $document_mark = array(
  10228.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10229.             'copy' => ''
  10230.         );
  10231.         if ($request->isMethod('POST'))
  10232.             $method 'POST';
  10233.         else
  10234.             $method 'GET';
  10235.         {
  10236. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  10237.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  10238.                 $request->request$method,
  10239.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  10240.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  10241.                 return new JsonResponse(
  10242.                     array(
  10243.                         'page_title' => 'Inventory ',
  10244.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10245.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10246.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10247.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10248.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10249.                         'action_tag' => $warehouse_action_list,
  10250.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10251.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10252.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10253.                         'data_searched' => $data_searched,
  10254.                         'success' => empty($data_searched['query_result']) ? false true
  10255.                     )
  10256.                 );
  10257.             }
  10258.             if ($request->request->get('print_data_enabled') == 1) {
  10259.                 $print_sub_title "";
  10260.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  10261.                     array(
  10262.                         'page_title' => 'Inventory Report',
  10263.                         'page_header' => 'Report',
  10264.                         'print_title' => $print_title,
  10265.                         'document_type' => 'Journal voucher',
  10266.                         'document_mark_image' => $document_mark['original'],
  10267.                         'page_header_sub' => 'Add',
  10268.                         'item_data' => [],
  10269.                         'received' => 2,
  10270.                         'return' => 1,
  10271.                         'total_w_vat' => 1,
  10272.                         'total_vat' => 1,
  10273.                         'total_wo_vat' => 1,
  10274.                         'invoice_id' => 'abcd1234',
  10275.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  10276.                         'created_by' => 'created by',
  10277.                         'created_at' => '',
  10278.                         'red' => 0,
  10279.                         'company_name' => $company_data->getName(),
  10280.                         'company_data' => $company_data,
  10281.                         'company_address' => $company_data->getAddress(),
  10282.                         'company_image' => $company_data->getImage(),
  10283.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10284.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10285.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10286.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10287.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10288.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10289.                         'action_tag' => $warehouse_action_list,
  10290.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10291.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10292.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10293.                         'data_searched' => $data_searched
  10294.                     )
  10295.                 );
  10296.             }
  10297.         }
  10298.         return $this->render('@Inventory/pages/report/inventory_view.html.twig',
  10299.             array(
  10300.                 'page_title' => 'Inventory',
  10301.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10302.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10303.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10304.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10305.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10306. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10307.                 'action_tag' => $warehouse_action_list,
  10308.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10309.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10310.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10311.                 'data_searched' => $data_searched
  10312.             )
  10313.         );
  10314.     }
  10315.     public
  10316.     function GrnListAction(Request $request)
  10317.     {
  10318.         $q $this->getDoctrine()
  10319.             ->getRepository('ApplicationBundle:Grn')
  10320.             ->findBy(
  10321.                 array(
  10322.                     'status' => GeneralConstant::ACTIVE,
  10323. //                    'approved' =>  GeneralConstant::APPROVED,
  10324.                 )
  10325.             );
  10326.         $stage_list = array(
  10327.             => 'Pending',
  10328.             => 'Pending',
  10329.             => 'Complete',
  10330.             => 'Partial',
  10331.         );
  10332.         $data = [];
  10333.         foreach ($q as $entry) {
  10334.             $data[] = array(
  10335.                 'doc_date' => $entry->getGrnDate(),
  10336.                 'id' => $entry->getGrnId(),
  10337.                 'doc_hash' => $entry->getDocumentHash(),
  10338.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  10339.                 'stage' => $stage_list[$entry->getStage()]
  10340.             );
  10341.         }
  10342.         return $this->render('@Inventory/pages/views/grn_list.html.twig',
  10343.             array(
  10344.                 'page_title' => 'Grn List',
  10345.                 'data' => $data
  10346.             )
  10347.         );
  10348.     }
  10349.     public
  10350.     function ViewGrnAction(Request $request$id)
  10351.     {
  10352.         $em $this->getDoctrine()->getManager();
  10353.         $dt Inventory::GetGrnDetails($em$id);
  10354.         return $this->render('@Inventory/pages/views/view_grn.html.twig',
  10355.             array(
  10356.                 'page_title' => 'View',
  10357.                 'data' => $dt,
  10358.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  10359.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10360.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10361.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10362.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10363.                     $id,
  10364.                     $dt['created_by'],
  10365.                     $dt['edited_by'])
  10366.             )
  10367.         );
  10368.     }
  10369.     public
  10370.     function PrintGrnAction(Request $request$id)
  10371.     {
  10372.         $em $this->getDoctrine()->getManager();
  10373.         $dt Inventory::GetGrnDetails($em$id);
  10374.         $company_data Company::getCompanyData($em1);
  10375.         $document_mark = array(
  10376.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10377.             'copy' => ''
  10378.         );
  10379.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10380.             $html $this->renderView('@Inventory/pages/print/print_received_note.html.twig',
  10381.                 array(
  10382.                     //full array here
  10383.                     'pdf' => true,
  10384.                     'page_title' => 'Grn',
  10385.                     'export' => 'pdf,print',
  10386.                     'data' => $dt,
  10387.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10388.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10389.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10390.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10391.                         $id,
  10392.                         $dt['created_by'],
  10393.                         $dt['edited_by']),
  10394.                     'document_mark_image' => $document_mark['original'],
  10395.                     'company_name' => $company_data->getName(),
  10396.                     'company_data' => $company_data,
  10397.                     'company_address' => $company_data->getAddress(),
  10398.                     'company_image' => $company_data->getImage(),
  10399.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10400.                     'red' => 0
  10401.                 )
  10402.             );
  10403.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10404. //                'orientation' => 'landscape',
  10405. //                'enable-javascript' => true,
  10406. //                'javascript-delay' => 1000,
  10407.                 'no-stop-slow-scripts' => false,
  10408.                 'no-background' => false,
  10409.                 'lowquality' => false,
  10410.                 'encoding' => 'utf-8',
  10411. //            'images' => true,
  10412. //            'cookie' => array(),
  10413.                 'dpi' => 300,
  10414.                 'image-dpi' => 300,
  10415. //                'enable-external-links' => true,
  10416. //                'enable-internal-links' => true
  10417.             ));
  10418.             return new Response(
  10419.                 $pdf_response,
  10420.                 200,
  10421.                 array(
  10422.                     'Content-Type' => 'application/pdf',
  10423.                     'Content-Disposition' => 'attachment; filename="grn.pdf"'
  10424.                 )
  10425.             );
  10426.         }
  10427.         return $this->render('@Inventory/pages/print/print_received_note.html.twig',
  10428.             array(
  10429.                 'page_title' => 'Grn',
  10430.                 'export' => 'pdf,print',
  10431.                 'data' => $dt,
  10432.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10433.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10434.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10435.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10436.                     $id,
  10437.                     $dt['created_by'],
  10438.                     $dt['edited_by']),
  10439.                 'document_mark_image' => $document_mark['original'],
  10440.                 'company_name' => $company_data->getName(),
  10441.                 'company_data' => $company_data,
  10442.                 'company_address' => $company_data->getAddress(),
  10443.                 'company_image' => $company_data->getImage(),
  10444.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10445.                 'red' => 0
  10446.             )
  10447.         );
  10448.     }
  10449.     public
  10450.     function PrintGrnBarcodeAction(Request $request$id)
  10451.     {
  10452.         $em $this->getDoctrine()->getManager();
  10453.         $dt Inventory::GetGrnDetails($em$id);
  10454.         $company_data Company::getCompanyData($em1);
  10455.         $repeatCount 1;
  10456.         if ($request->query->has('repeatCount'))
  10457.             $repeatCount $request->query->get('repeatCount');
  10458.         $document_mark = array(
  10459.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10460.             'copy' => ''
  10461.         );
  10462.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10463.             $html $this->renderView('@Inventory/pages/print/print_grn_barcodes.html.twig',
  10464.                 array(
  10465.                     //full array here
  10466.                     'pdf' => true,
  10467.                     'page_title' => 'Grn Barcodes',
  10468.                     'export' => 'print',
  10469.                     'data' => $dt,
  10470.                     'repeatCount' => $repeatCount,
  10471.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10472.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10473.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10474.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10475.                         $id,
  10476.                         $dt['created_by'],
  10477.                         $dt['edited_by']),
  10478.                     'document_mark_image' => $document_mark['original'],
  10479.                     'company_name' => $company_data->getName(),
  10480.                     'company_data' => $company_data,
  10481.                     'company_address' => $company_data->getAddress(),
  10482.                     'company_image' => $company_data->getImage(),
  10483.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10484.                     'red' => 0
  10485.                 )
  10486.             );
  10487.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10488. //                'orientation' => 'landscape',
  10489.                 'enable-javascript' => true,
  10490. //                'javascript-delay' => 1000,
  10491.                 'no-stop-slow-scripts' => false,
  10492.                 'no-background' => false,
  10493.                 'lowquality' => false,
  10494.                 'encoding' => 'utf-8',
  10495. //            'images' => true,
  10496. //            'cookie' => array(),
  10497.                 'dpi' => 300,
  10498.                 'image-dpi' => 300,
  10499. //                'enable-external-links' => true,
  10500. //                'enable-internal-links' => true
  10501.             ));
  10502.             return new Response(
  10503.                 $pdf_response,
  10504.                 200,
  10505.                 array(
  10506.                     'Content-Type' => 'application/pdf',
  10507.                     'Content-Disposition' => 'attachment; filename="grn_barcodes.pdf"'
  10508.                 )
  10509.             );
  10510.         }
  10511.         return $this->render('@Inventory/pages/print/print_grn_barcodes.html.twig',
  10512.             array(
  10513.                 'page_title' => 'Grn barcodes',
  10514. //                'export'=>'pdf,print',
  10515.                 'data' => $dt,
  10516.                 'repeatCount' => $repeatCount,
  10517.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10518.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10519.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10520.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10521.                     $id,
  10522.                     $dt['created_by'],
  10523.                     $dt['edited_by']),
  10524.                 'document_mark_image' => $document_mark['original'],
  10525.                 'company_name' => $company_data->getName(),
  10526.                 'company_data' => $company_data,
  10527.                 'company_address' => $company_data->getAddress(),
  10528.                 'company_image' => $company_data->getImage(),
  10529.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10530.                 'red' => 0
  10531.             )
  10532.         );
  10533.     }
  10534.     public
  10535.     function GenerateBarcodeAction(Request $request$type$id$item_id)
  10536.     {
  10537.         $em $this->getDoctrine()->getManager();
  10538.         $repeatCount 1;
  10539.         $spec_item_id 0;
  10540.         $skip_ids = [];
  10541.         $clearUnnecessaryOnly 0;
  10542.         if ($request->query->has('skipIds'))
  10543.             $skip_ids $request->query->get('skipIds');
  10544.         if ($request->query->has('clearUnnecessaryOnly'))
  10545.             $clearUnnecessaryOnly $request->query->get('clearUnnecessaryOnly');
  10546.         if ($type == 'srcv') {
  10547.             $doc_data $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  10548.                 array(
  10549.                     'stockReceivedNoteId' => $id
  10550.                 )
  10551.             );
  10552.             if ($item_id == '_single_') {
  10553.                 $doc_item_data $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
  10554.                     array(
  10555.                         'stockReceivedNoteId' => $id,
  10556. //                        'id' => $item_id
  10557.                     )
  10558.                 );
  10559.             } else {
  10560.                 $doc_item_data $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
  10561.                     array(
  10562.                         'stockReceivedNoteId' => $id,
  10563.                         'id' => $item_id
  10564.                     )
  10565.                 );
  10566.             }
  10567.             $inv_acc_data = [
  10568.                 'fa_amount' => 0,
  10569.                 'tg_amount' => 0,
  10570.             ];
  10571.             $inv_acc_data_by_head = [
  10572.             ];
  10573.             $new_non_delivered_sales_code_range = [];
  10574.             foreach ($doc_item_data as $entry) {
  10575.                 //adding transaction
  10576.                 $sales_code_range_ser = [];
  10577.                 if (in_array($entry->getId(), $skip_ids))
  10578.                     continue;
  10579.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10580.                     ->findOneBy(
  10581.                         array(
  10582.                             'id' => $entry->getProductId()
  10583.                         )
  10584.                     );
  10585.                 $stitem $em->getRepository('ApplicationBundle:StockTransferItem')
  10586.                     ->findOneBy(
  10587.                         array(
  10588.                             'id' => $entry->getStockTransferItemId(),
  10589.                             'productId' => $entry->getProductId()
  10590.                         )
  10591.                     );
  10592.                 if ($product) {
  10593.                     if ($product->getHasSerial() == 1) {
  10594.                         //clear if exists
  10595.                         if ($clearUnnecessaryOnly == 1) {
  10596.                             $get_kids_sql "DELETE FROM product_by_code
  10597.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10598. //                $get_kids_sql .=' ORDER BY name ASC';
  10599.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  10600.                             $stmt->execute();
  10601.                             $em->flush();
  10602.                         } else {
  10603.                             $get_kids_sql "DELETE FROM product_by_code
  10604.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10605. //                $get_kids_sql .=' ORDER BY name ASC';
  10606.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  10607.                             $stmt->execute();
  10608.                             $em->flush();
  10609.                         }
  10610. //                        $check_here = $stmt->fetchAll();
  10611.                         //now addng product by code
  10612.                         $sales_code_range = [];
  10613.                         if ($doc_data->getType() == || $doc_data->getType() == 4) {
  10614. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10615. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10616.                             $product_action_tag_id $entry->getWarehouseActionId();
  10617.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getQty(),
  10618.                                 $doc_data->getStockReceivedNoteDate(), $entry->getWarrantyMon(), 0$doc_data->getCompanyId(), $entry->getWarehouseId(),
  10619.                                 $entry->getWarehouseActionId(), $entry->getPurchaseCodeRange(), nullnullnullnull$doc_data->getStockReceivedNoteId()
  10620.                             );
  10621.                             $sales_code_range $barcodeData['sales_code_range'];
  10622.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  10623.                             $em->flush();
  10624.                         }
  10625. //                        else {
  10626. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10627. //
  10628. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10629. //                            } else {
  10630. //
  10631. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10632. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10633. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10634. //                            }
  10635. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10636. //
  10637. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10638. //                            } else {
  10639. //
  10640. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10641. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10642. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10643. //                            }
  10644. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10645. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10646. //                            $new_non_delivered_sales_code_range = [];
  10647. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10648. //                                if (!(in_array($ndsc, $sales_code_range)))
  10649. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10650. //                            }
  10651. //                            if ($sales_code_range != null) {
  10652. //                                foreach ($sales_code_range as $ind => $dt) {
  10653. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  10654. //                                        ->findOneBy(
  10655. //                                            array(
  10656. //                                                'salesCode' => [$dt],
  10657. //                                                'productId' => $entry->getProductId()
  10658. //                                            )
  10659. //                                        );
  10660. //
  10661. //                                    if ($np) {
  10662. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10663. //                                        $np->setProductId($entry->getProductId());
  10664. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10665. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10666. //                                        $np->setPosition(1);//in warehouse
  10667. //                                        $np->setStockReceivedNoteId($id);
  10668. //
  10669. //
  10670. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10671. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10672. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10673. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10674. //                                            'direction' => 'in',
  10675. //                                            'warehouseId' => $entry->getWarehouseId(),
  10676. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10677. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10678. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10679. //                                        );
  10680. //                                        $np->setTransactionHistory(json_encode(
  10681. //                                            $trans_history
  10682. //                                        ));
  10683. //
  10684. //
  10685. //                                        $em->persist($np);
  10686. //                                        $em->flush();
  10687. //                                    }
  10688. //                                }
  10689. //                            }
  10690. //                        }
  10691.                     }
  10692.                 }
  10693.                 //adding transaction
  10694.                 if ($stitem) {
  10695.                     $stitem->setNonDeliveredSalesCodeRange(json_encode($new_non_delivered_sales_code_range));
  10696.                 }
  10697.                 $spec_item_id $entry->getId();
  10698.                 if ($item_id == '_single_') {
  10699.                     break;
  10700.                 }
  10701.             }
  10702.         }
  10703.         if ($type == 'irr') {
  10704.             $doc_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacement')->findOneBy(
  10705.                 array(
  10706.                     'itemReceivedAndReplacementId' => $id
  10707.                 )
  10708.             );
  10709.             if ($item_id == '_single_') {
  10710.                 $doc_item_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
  10711.                     array(
  10712.                         'itemReceivedAndReplacementId' => $id,
  10713. //                        'id' => $item_id
  10714.                     )
  10715.                 );
  10716.             } else {
  10717.                 $doc_item_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
  10718.                     array(
  10719.                         'itemReceivedAndReplacementId' => $id,
  10720.                         'id' => $item_id
  10721.                     )
  10722.                 );
  10723.             }
  10724.             $inv_acc_data = [
  10725.                 'fa_amount' => 0,
  10726.                 'tg_amount' => 0,
  10727.             ];
  10728.             $inv_acc_data_by_head = [
  10729.             ];
  10730.             $new_non_delivered_sales_code_range = [];
  10731.             foreach ($doc_item_data as $entry) {
  10732.                 //adding transaction
  10733.                 $sales_code_range_ser = [];
  10734.                 if (in_array($entry->getId(), $skip_ids))
  10735.                     continue;
  10736.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10737.                     ->findOneBy(
  10738.                         array(
  10739.                             'id' => $entry->getReceivedProductId()
  10740.                         )
  10741.                     );
  10742.                 if ($product) {
  10743.                     if ($product->getHasSerial() == 1) {
  10744.                         //clear if exists
  10745. //                        if($clearUnnecessaryOnly==1) {
  10746. //                            $get_kids_sql = "DELETE FROM product_by_code
  10747. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10748. ////                $get_kids_sql .=' ORDER BY name ASC';
  10749. //
  10750. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10751. //                            $stmt->execute();
  10752. //                            $em->flush();
  10753. //                        }
  10754. //                        else{
  10755. //                            $get_kids_sql = "DELETE FROM product_by_code
  10756. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10757. ////                $get_kids_sql .=' ORDER BY name ASC';
  10758. //
  10759. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10760. //                            $stmt->execute();
  10761. //                            $em->flush();
  10762. //                        }
  10763. //                        $check_here = $stmt->fetchAll();
  10764.                         //now addng product by code
  10765.                         $sales_code_range = [];
  10766.                         if ($entry->getReceivedQty() > 0) {
  10767. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10768. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10769. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  10770.                             $barcodeData Inventory::GenerateBarcode($em$entry->getReceivedProductId(), $entry->getReceivedQty(),
  10771.                                 $doc_data->getItemReceivedAndReplacementDate(), 00$doc_data->getCompanyId(), $entry->getReceivedWarehouseId(),
  10772.                                 $entry->getReceivedWarehouseActionId(), nullnullnullnullnullnullnullnull$doc_data->getItemReceivedAndReplacementId()
  10773.                             );
  10774.                             $sales_code_range $barcodeData['sales_code_range'];
  10775.                             $entry->setReceivedCodeRange(json_encode($sales_code_range));
  10776.                             $em->flush();
  10777.                         }
  10778. //                        else {
  10779. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10780. //
  10781. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10782. //                            } else {
  10783. //
  10784. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10785. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10786. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10787. //                            }
  10788. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10789. //
  10790. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10791. //                            } else {
  10792. //
  10793. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10794. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10795. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10796. //                            }
  10797. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10798. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10799. //                            $new_non_delivered_sales_code_range = [];
  10800. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10801. //                                if (!(in_array($ndsc, $sales_code_range)))
  10802. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10803. //                            }
  10804. //                            if ($sales_code_range != null) {
  10805. //                                foreach ($sales_code_range as $ind => $dt) {
  10806. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  10807. //                                        ->findOneBy(
  10808. //                                            array(
  10809. //                                                'salesCode' => [$dt],
  10810. //                                                'productId' => $entry->getProductId()
  10811. //                                            )
  10812. //                                        );
  10813. //
  10814. //                                    if ($np) {
  10815. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10816. //                                        $np->setProductId($entry->getProductId());
  10817. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10818. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10819. //                                        $np->setPosition(1);//in warehouse
  10820. //                                        $np->setStockReceivedNoteId($id);
  10821. //
  10822. //
  10823. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10824. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10825. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10826. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10827. //                                            'direction' => 'in',
  10828. //                                            'warehouseId' => $entry->getWarehouseId(),
  10829. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10830. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10831. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10832. //                                        );
  10833. //                                        $np->setTransactionHistory(json_encode(
  10834. //                                            $trans_history
  10835. //                                        ));
  10836. //
  10837. //
  10838. //                                        $em->persist($np);
  10839. //                                        $em->flush();
  10840. //                                    }
  10841. //                                }
  10842. //                            }
  10843. //                        }
  10844.                     }
  10845.                 }
  10846.                 //adding transaction
  10847.                 $spec_item_id $entry->getId();
  10848.                 if ($item_id == '_single_') {
  10849.                     break;
  10850.                 }
  10851.             }
  10852.         }
  10853.         if ($type == 'prdcn') {
  10854.             $doc_data $em->getRepository('ApplicationBundle:Production')->findOneBy(
  10855.                 array(
  10856.                     'productionId' => $id
  10857.                 )
  10858.             );
  10859.             if ($item_id == '_single_') {
  10860.                 $doc_item_data $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
  10861.                     array(
  10862.                         'productionId' => $id,
  10863. //                        'id' => $item_id
  10864.                     )
  10865.                 );
  10866.             } else {
  10867.                 $doc_item_data $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
  10868.                     array(
  10869.                         'productionId' => $id,
  10870.                         'id' => $item_id
  10871.                     )
  10872.                 );
  10873.             }
  10874.             $inv_acc_data = [
  10875.                 'fa_amount' => 0,
  10876.                 'tg_amount' => 0,
  10877.             ];
  10878.             $inv_acc_data_by_head = [
  10879.             ];
  10880.             $new_non_delivered_sales_code_range = [];
  10881.             foreach ($doc_item_data as $entry) {
  10882.                 //adding transaction
  10883.                 $sales_code_range_ser = [];
  10884.                 if (in_array($entry->getId(), $skip_ids))
  10885.                     continue;
  10886.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10887.                     ->findOneBy(
  10888.                         array(
  10889.                             'id' => $entry->getProductId()
  10890.                         )
  10891.                     );
  10892.                 if ($product) {
  10893.                     if ($product->getHasSerial() == 1) {
  10894.                         //clear if exists
  10895. //                        if($clearUnnecessaryOnly==1) {
  10896. //                            $get_kids_sql = "DELETE FROM product_by_code
  10897. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10898. ////                $get_kids_sql .=' ORDER BY name ASC';
  10899. //
  10900. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10901. //                            $stmt->execute();
  10902. //                            $em->flush();
  10903. //                        }
  10904. //                        else{
  10905. //                            $get_kids_sql = "DELETE FROM product_by_code
  10906. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10907. ////                $get_kids_sql .=' ORDER BY name ASC';
  10908. //
  10909. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10910. //                            $stmt->execute();
  10911. //                            $em->flush();
  10912. //                        }
  10913. //                        $check_here = $stmt->fetchAll();
  10914.                         //now addng product by code
  10915.                         $sales_code_range = [];
  10916.                         if ($entry->getProducedQty() > 0) {
  10917. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10918. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10919. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  10920.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getProducedQty(),
  10921.                                 $doc_data->getProductionDate(), 00$doc_data->getCompanyId(), $entry->getWarehouseId(),
  10922.                                 $entry->getProducedItemActionTagId(), nullnullnullnullnullnullnull$doc_data->getProductionId(), null
  10923.                             );
  10924.                             $sales_code_range $barcodeData['sales_code_range'];
  10925.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  10926.                             $em->flush();
  10927.                         }
  10928. //                        else {
  10929. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10930. //
  10931. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10932. //                            } else {
  10933. //
  10934. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10935. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10936. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10937. //                            }
  10938. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10939. //
  10940. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10941. //                            } else {
  10942. //
  10943. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10944. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10945. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10946. //                            }
  10947. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10948. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10949. //                            $new_non_delivered_sales_code_range = [];
  10950. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10951. //                                if (!(in_array($ndsc, $sales_code_range)))
  10952. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10953. //                            }
  10954. //                            if ($sales_code_range != null) {
  10955. //                                foreach ($sales_code_range as $ind => $dt) {
  10956. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  10957. //                                        ->findOneBy(
  10958. //                                            array(
  10959. //                                                'salesCode' => [$dt],
  10960. //                                                'productId' => $entry->getProductId()
  10961. //                                            )
  10962. //                                        );
  10963. //
  10964. //                                    if ($np) {
  10965. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10966. //                                        $np->setProductId($entry->getProductId());
  10967. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10968. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10969. //                                        $np->setPosition(1);//in warehouse
  10970. //                                        $np->setStockReceivedNoteId($id);
  10971. //
  10972. //
  10973. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10974. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10975. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10976. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10977. //                                            'direction' => 'in',
  10978. //                                            'warehouseId' => $entry->getWarehouseId(),
  10979. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10980. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10981. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10982. //                                        );
  10983. //                                        $np->setTransactionHistory(json_encode(
  10984. //                                            $trans_history
  10985. //                                        ));
  10986. //
  10987. //
  10988. //                                        $em->persist($np);
  10989. //                                        $em->flush();
  10990. //                                    }
  10991. //                                }
  10992. //                            }
  10993. //                        }
  10994.                     }
  10995.                 }
  10996.                 //adding transaction
  10997.                 $spec_item_id $entry->getId();
  10998.                 if ($item_id == '_single_') {
  10999.                     break;
  11000.                 }
  11001.             }
  11002.         }
  11003.         return new JsonResponse(array(
  11004.             'success' => $spec_item_id != true false,
  11005.             'skipIds' => [],
  11006.             'spec_item_id' => $spec_item_id
  11007.         ));
  11008. //        return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  11009. //            array(
  11010. //                'page_title' => 'Srcv barcodes',
  11011. ////                'export'=>'pdf,print',
  11012. //                'data' => $dt,
  11013. //                'repeatCount' => $repeatCount,
  11014. //                'item_id' => $item_id,
  11015. //                'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11016. //                    $id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11017. //                'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11018. //                    array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11019. //                    $id,
  11020. //                    $dt['created_by'],
  11021. //                    $dt['edited_by']),
  11022. //                'document_mark_image' => $document_mark['original'],
  11023. //                                    'company_name' => $company_data->getName(),
  11024. //                    'company_data'=>$company_data,
  11025. //                'company_address' => $company_data->getAddress(),
  11026. //                'company_image' => $company_data->getImage(),
  11027. //                'invoice_footer' => $company_data->getInvoiceFooter(),
  11028. //                'red' => 0
  11029. //
  11030. //            )
  11031. //        );
  11032.     }
  11033.     public
  11034.     function PrintLabelAction(Request $request$id)
  11035.     {
  11036.         $em $this->getDoctrine()->getManager();
  11037. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11038.         $repeatCount 1;
  11039.         $assignProductId '';
  11040.         $productByCodeIds = [];
  11041.         $print_selection_type 1;
  11042.         $print_selection_string 1;
  11043.         $assignLabelFormatId 0;
  11044.         $assignColorId 0;
  11045.         $assignProductionScheduleId 0;
  11046.         $warehouseId '';
  11047.         $warehouseActionId '';
  11048.         $toAssignPosition '';
  11049.         $printFlag $request->request->has('printFlag') ? $request->request->get('printFlag') : 1;
  11050.         $returnJson $request->request->has('returnJson') ? $request->request->get('returnJson') : 0;
  11051.         if ($returnJson == 1)
  11052.             $printFlag 0;
  11053.         $companyId $this->getLoggedUserCompanyId($request);
  11054.         if ($request->query->has('repeatCount'))
  11055.             $repeatCount $request->query->get('repeatCount');
  11056.         if ($request->request->has('print_selection_type'))
  11057.             $print_selection_type $request->request->get('print_selection_type');
  11058.         if ($request->request->has('print_selection_string'))
  11059.             $print_selection_string $request->request->get('print_selection_string');
  11060.         if ($request->request->has('productByCodeIds'))
  11061.             $productByCodeIds json_decode($request->request->get('productByCodeIds'), true);
  11062.         if ($request->request->has('formatId'))
  11063.             $assignLabelFormatId $request->request->get('formatId');
  11064.         if ($printFlag == 0) {
  11065.             if ($request->request->has('productSelector'))
  11066.                 $assignProductId $request->request->get('productSelector');
  11067.             if ($request->request->has('colorId'))
  11068.                 $assignColorId $request->request->get('colorId');
  11069.             if ($request->request->has('productionScheduleId'))
  11070.                 $assignProductionScheduleId $request->request->get('productionScheduleId');
  11071.             if ($request->request->has('warehouseId'))
  11072.                 $warehouseId $request->request->get('warehouseId');
  11073.             if ($request->request->has('warehouseActionId'))
  11074.                 $warehouseActionId $request->request->get('warehouseActionId');
  11075.             if ($request->request->has('position'))
  11076.                 $toAssignPosition $request->request->get('position');
  11077.             if ($assignColorId == '')
  11078.                 $assignColorId 0;
  11079.         }
  11080.         if ($productByCodeIds == null)
  11081.             $productByCodeIds = [];
  11082.         $productByCodeData = [];
  11083.         $productList = [];
  11084.         $productIds = [];
  11085.         if ($print_selection_type == 2) {
  11086.             //range
  11087.             $productByCodeIds Inventory::getIdsFromIdSelectionStr($print_selection_string);
  11088.         }
  11089.         $labelData = [
  11090.             'formatId' => 0
  11091.         ];
  11092.         $formatId 0;
  11093.         if (!empty($productByCodeIds)) {
  11094.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11095.                 ->findBy(
  11096.                     array(
  11097.                         'productByCodeId' => $productByCodeIds
  11098.                     )
  11099.                 );
  11100.             foreach ($productByCodeData as $d) {
  11101.                 if ($d->getStage() < 10$d->setStage(11);
  11102.                 if ($assignProductId != '') {
  11103.                     $d->setProductId($assignProductId);
  11104.                 }
  11105.                 if ($assignColorId != 0) {
  11106.                     $d->setColorId($assignColorId);
  11107.                 } else {
  11108.                     $productData $em->getRepository('ApplicationBundle:InvProducts')
  11109.                         ->findOneBy(
  11110.                             array(
  11111.                                 'id' => $assignProductId
  11112.                             )
  11113.                         );
  11114.                     if ($productData) {
  11115.                         $d->setColorId($productData->getDefaultColorId());
  11116.                     }
  11117.                 }
  11118.                 if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  11119.                     $d->setDefaultLabelFormatId($assignLabelFormatId);
  11120.                     $d->setDeviceLabelFormatId($assignLabelFormatId);
  11121.                 }
  11122.                 $toAssignPosition != '' $d->setPosition($toAssignPosition) : '';
  11123.                 $warehouseId != '' $d->setWarehouseId($warehouseId) : '';
  11124.                 $warehouseActionId != '' $d->setWarehouseActionId($warehouseActionId) : '';
  11125.                 if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  11126.                     $d->setProductionScheduleId($assignProductionScheduleId);
  11127.                     $productionSchedule $em->getRepository('ApplicationBundle:ProductionSchedule')
  11128.                         ->findOneBy(
  11129.                             array(
  11130.                                 'productionScheduleId' => $assignProductionScheduleId
  11131.                             )
  11132.                         );
  11133.                     if ($productionSchedule) {
  11134.                         if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  11135.                             //becuase it will assigned at previous lines
  11136.                         } else {
  11137.                             $d->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  11138.                             $d->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  11139.                         }
  11140.                         $d->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  11141.                         $d->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  11142.                     }
  11143.                 }
  11144.                 $em->flush();
  11145.                 if ($d->getProductId() != '' || $d->getProductId() != null)
  11146.                     $productIds[] = $d->getProductId();
  11147.                 $formatId $d->getDeviceLabelFormatId();
  11148.             }
  11149.         }
  11150.         $labelFormatHere $em->getRepository('ApplicationBundle:LabelFormat')
  11151.             ->findOneBy(
  11152.                 array(
  11153.                     'formatId' => $formatId,
  11154. //                        'CompanyId' => $companyId
  11155.                 )
  11156.             );
  11157.         if ($labelFormatHere) {
  11158.             $formatData json_decode($labelFormatHere->getFormatData(), true);
  11159.             if ($formatData == null$formatData = [];
  11160.             $labelData = array(
  11161.                 'id' => $labelFormatHere->getFormatId(),
  11162.                 'formatId' => $labelFormatHere->getFormatId(),
  11163.                 'labelType' => $labelFormatHere->getLabelType(),
  11164.                 'name' => $labelFormatHere->getName(),
  11165.                 'width' => $labelFormatHere->getWidth(),
  11166.                 'pageWidth' => $labelFormatHere->getPageWidth(),
  11167.                 'height' => $labelFormatHere->getheight(),
  11168.                 'pageHeight' => $labelFormatHere->getPageHeight(),
  11169.                 'formatData' => $formatData,
  11170.             );
  11171.         }
  11172.         $productList Inventory::ProductList($em$this->getLoggedUserCompanyId($request), 10''$productIds);
  11173.         $company_data Company::getCompanyData($em1);
  11174.         $document_mark = array(
  11175.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11176.             'copy' => ''
  11177.         );
  11178.         $dt $productByCodeData;
  11179.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11180.             $html $this->renderView('@Inventory/pages/print/print_label.html.twig',
  11181.                 array(
  11182.                     //full array here
  11183.                     'pdf' => true,
  11184.                     'page_title' => 'Device Labels',
  11185.                     'export' => 'print',
  11186.                     'repeatCount' => $repeatCount,
  11187.                     'labelData' => $labelData,
  11188.                     'brandList' => Inventory::GetBrandList($em$companyId),
  11189. //                    'item_id' => $item_id,
  11190.                     'data' => $dt,
  11191.                     'productList' => $productList,
  11192.                     'approval_data' => [],
  11193.                     'document_log' => [],
  11194.                     'document_mark_image' => $document_mark['original'],
  11195.                     'company_name' => $company_data->getName(),
  11196.                     'company_data' => $company_data,
  11197.                     'company_address' => $company_data->getAddress(),
  11198.                     'company_image' => $company_data->getImage(),
  11199.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11200.                     'red' => 0
  11201.                 )
  11202.             );
  11203.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11204. //                'orientation' => 'landscape',
  11205.                 'enable-javascript' => true,
  11206. //                'javascript-delay' => 1000,
  11207.                 'no-stop-slow-scripts' => false,
  11208.                 'no-background' => false,
  11209.                 'lowquality' => false,
  11210.                 'encoding' => 'utf-8',
  11211. //            'images' => true,
  11212. //            'cookie' => array(),
  11213.                 'dpi' => 300,
  11214.                 'image-dpi' => 300,
  11215. //                'enable-external-links' => true,
  11216. //                'enable-internal-links' => true
  11217.             ));
  11218.             return new Response(
  11219.                 $pdf_response,
  11220.                 200,
  11221.                 array(
  11222.                     'Content-Type' => 'application/pdf',
  11223.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11224.                 )
  11225.             );
  11226.         }
  11227.         $url $this->generateUrl(
  11228.             'print_label'
  11229.         );
  11230.         if ($returnJson == && $printFlag == 0) {
  11231. //                    $dr = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  11232. //                        array(
  11233. //                            'salesOrderId' => $orderId, ///material
  11234. //
  11235. //                        )
  11236. //                    );
  11237.             return new JsonResponse(array(
  11238.                 'success' => true,
  11239. //                        'documentHash' => $order->getDocumentHash(),
  11240. //                'documentId' => $receiptId,
  11241. //                'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
  11242. //
  11243. //                'viewUrl' => $url . "/" . $receiptId,
  11244.             ));
  11245.         } else return $this->render('@Inventory/pages/print/print_label.html.twig',
  11246.             array(
  11247.                 'page_title' => 'Product Labels',
  11248. //                'export'=>'pdf,print',
  11249.                 'data' => $dt,
  11250.                 'productList' => $productList,
  11251.                 'repeatCount' => $repeatCount,
  11252. //                'item_id' => $item_id,
  11253.                 'labelData' => $labelData,
  11254.                 'brandList' => Inventory::GetBrandList($em$companyId),
  11255.                 'approval_data' => [],
  11256.                 'document_log' => [],
  11257.                 'document_mark_image' => $document_mark['original'],
  11258.                 'company_name' => $company_data->getName(),
  11259.                 'company_data' => $company_data,
  11260.                 'company_address' => $company_data->getAddress(),
  11261.                 'company_image' => $company_data->getImage(),
  11262.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11263.                 'red' => 0
  11264.             )
  11265.         );
  11266.     }
  11267.     public
  11268.     function PrintCartonLabelAction(Request $request$id)
  11269.     {
  11270.         $em $this->getDoctrine()->getManager();
  11271. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11272.         $repeatCount 1;
  11273.         $assignProductId '';
  11274.         $productByCodeIds = [];
  11275.         $cartonId 0;
  11276.         if ($id != 0)
  11277.             $cartonId $id;
  11278.         $colorText '';
  11279.         $weightText '';
  11280.         if ($request->query->has('repeatCount'))
  11281.             $repeatCount $request->query->get('repeatCount');
  11282.         if ($request->request->has('printCartonId'))
  11283.             $cartonId $request->request->get('printCartonId');
  11284.         if ($request->request->has('printCartonColorText'))
  11285.             $colorText $request->request->get('printCartonColorText');
  11286.         if ($request->request->has('printCartonWeightText'))
  11287.             $weightText $request->request->get('printCartonWeightText');
  11288.         $labelData = [
  11289.             'formatId' => 0
  11290.         ];
  11291.         if ($productByCodeIds == null)
  11292.             $productByCodeIds = [];
  11293.         $productByCodeData = [];
  11294.         $cartonData = [];
  11295.         $product = [];
  11296.         if ($cartonId != 0) {
  11297.             $cartonData $em->getRepository('ApplicationBundle:Carton')
  11298.                 ->findOneBy(
  11299.                     array(
  11300.                         'id' => $cartonId
  11301.                     )
  11302.                 );
  11303.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11304.                 ->findBy(
  11305.                     array(
  11306.                         'cartonId' => $cartonId
  11307.                     )
  11308.                 );
  11309. //            if(!empty($productByCodeData))
  11310. //                $product = $em->getRepository('ApplicationBundle:InvProducts')
  11311. //                ->findOneBy(
  11312. //                    array(
  11313. //                        'id' => $productByCodeData[0]->getProductId()
  11314. //                    )
  11315. //                );
  11316. //            else
  11317.             $product $em->getRepository('ApplicationBundle:InvProducts')
  11318.                 ->findOneBy(
  11319.                     array(
  11320.                         'id' => $cartonData->getProductId()
  11321.                     )
  11322.                 );
  11323.             $formatId $cartonData->getCartonLabelFormatId();
  11324.             $labelFormatHere $em->getRepository('ApplicationBundle:LabelFormat')
  11325.                 ->findOneBy(
  11326.                     array(
  11327.                         'formatId' => $formatId,
  11328. //                        'CompanyId' => $companyId
  11329.                     )
  11330.                 );
  11331.             if ($labelFormatHere) {
  11332.                 $formatData json_decode($labelFormatHere->getFormatData(), true);
  11333.                 if ($formatData == null$formatData = [];
  11334.                 $labelData = array(
  11335.                     'id' => $labelFormatHere->getFormatId(),
  11336.                     'formatId' => $labelFormatHere->getFormatId(),
  11337.                     'labelType' => $labelFormatHere->getLabelType(),
  11338.                     'name' => $labelFormatHere->getName(),
  11339.                     'width' => $labelFormatHere->getWidth(),
  11340.                     'pageWidth' => $labelFormatHere->getPageWidth(),
  11341.                     'height' => $labelFormatHere->getheight(),
  11342.                     'pageHeight' => $labelFormatHere->getPageHeight(),
  11343.                     'formatData' => $formatData,
  11344.                 );
  11345.             }
  11346.         }
  11347.         $company_data Company::getCompanyData($em1);
  11348.         $document_mark = array(
  11349.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11350.             'copy' => ''
  11351.         );
  11352.         $dt $productByCodeData;
  11353.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11354.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  11355.                 array(
  11356.                     //full array here
  11357.                     'pdf' => true,
  11358.                     'page_title' => 'Carton Labels',
  11359.                     'export' => 'print',
  11360.                     'labelData' => $labelData,
  11361.                     'repeatCount' => $repeatCount,
  11362. //                    'item_id' => $item_id,
  11363.                     'data' => $dt,
  11364.                     'cartonData' => $cartonData,
  11365.                     'product' => $product,
  11366.                     'colorText' => $colorText,
  11367.                     'weightText' => $weightText,
  11368.                     'approval_data' => [],
  11369.                     'document_log' => [],
  11370.                     'document_mark_image' => $document_mark['original'],
  11371.                     'company_name' => $company_data->getName(),
  11372.                     'company_data' => $company_data,
  11373.                     'company_address' => $company_data->getAddress(),
  11374.                     'company_image' => $company_data->getImage(),
  11375.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11376.                     'red' => 0
  11377.                 )
  11378.             );
  11379.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11380. //                'orientation' => 'landscape',
  11381.                 'enable-javascript' => true,
  11382. //                'javascript-delay' => 1000,
  11383.                 'no-stop-slow-scripts' => false,
  11384.                 'no-background' => false,
  11385.                 'lowquality' => false,
  11386.                 'encoding' => 'utf-8',
  11387. //            'images' => true,
  11388. //            'cookie' => array(),
  11389.                 'dpi' => 300,
  11390.                 'image-dpi' => 300,
  11391. //                'enable-external-links' => true,
  11392. //                'enable-internal-links' => true
  11393.             ));
  11394.             return new Response(
  11395.                 $pdf_response,
  11396.                 200,
  11397.                 array(
  11398.                     'Content-Type' => 'application/pdf',
  11399.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11400.                 )
  11401.             );
  11402.         }
  11403.         if ($request->query->has('previewOnly')) {
  11404.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  11405.                 array(
  11406.                     'page_title' => 'Carton Labels',
  11407. //                'export'=>'pdf,print',
  11408.                     'data' => $dt,
  11409.                     'skip_parameters' => 1,
  11410.                     'labelData' => $labelData,
  11411.                     'cartonData' => $cartonData,
  11412.                     'product' => $product,
  11413.                     'colorText' => $colorText,
  11414.                     'weightText' => $weightText,
  11415.                     'repeatCount' => $repeatCount,
  11416. //                'item_id' => $item_id,
  11417.                     'approval_data' => [],
  11418.                     'document_log' => [],
  11419.                     'document_mark_image' => $document_mark['original'],
  11420.                     'company_name' => $company_data->getName(),
  11421.                     'company_data' => $company_data,
  11422.                     'company_address' => $company_data->getAddress(),
  11423.                     'company_image' => $company_data->getImage(),
  11424.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11425.                     'red' => 0
  11426.                 )
  11427.             );
  11428.             if ($request->query->has('returnJson')) {
  11429.                 return new JsonResponse(
  11430.                     array(
  11431.                         'success' => true,
  11432.                         'page_title' => 'Product Details',
  11433.                         'company_data' => $company_data,
  11434.                         'renderedHtml' => $html,
  11435. //                'productData' => $productData,
  11436. //                'currInvList' => $currInvList,
  11437. //                'productList' => Inventory::ProductList($em, $companyId),
  11438. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11439. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11440. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11441. //                'unitList' => Inventory::UnitTypeList($em),
  11442. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11443. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11444. //                'warehouseList' => Inventory::WarehouseList($em),
  11445.                     )
  11446.                 );
  11447.             }
  11448.         }
  11449.         return $this->render('@Inventory/pages/print/print_carton_label.html.twig',
  11450.             array(
  11451.                 'page_title' => 'Carton Labels',
  11452. //                'export'=>'pdf,print',
  11453.                 'data' => $dt,
  11454.                 'cartonData' => $cartonData,
  11455.                 'product' => $product,
  11456. //                'productByCodeData' => $productByCodeData,
  11457.                 'colorText' => $colorText,
  11458.                 'weightText' => $weightText,
  11459.                 'repeatCount' => $repeatCount,
  11460.                 'labelData' => $labelData,
  11461. //                'item_id' => $item_id,
  11462.                 'approval_data' => [],
  11463.                 'document_log' => [],
  11464.                 'document_mark_image' => $document_mark['original'],
  11465.                 'company_name' => $company_data->getName(),
  11466.                 'company_data' => $company_data,
  11467.                 'company_address' => $company_data->getAddress(),
  11468.                 'company_image' => $company_data->getImage(),
  11469.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11470.                 'red' => 0
  11471.             )
  11472.         );
  11473.     }
  11474.     public
  11475.     function AssignInfoToProductByCodeAction(Request $request$id)
  11476.     {
  11477.         $em $this->getDoctrine()->getManager();
  11478.         $companyId $this->getLoggedUserCompanyId($request);
  11479. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11480.         $cartonId '';
  11481.         $passStatus 5;
  11482.         $assignProductId '';
  11483.         $assignProductionId '';
  11484.         $assignProductionScheduleId '';
  11485.         $gbWeightGm '';
  11486.         $dvWeightGm '';
  11487.         $cartonWeightGm '';
  11488.         if ($request->request->has('cartonId'))
  11489.             $cartonId $request->request->get('cartonId');
  11490.         if ($request->request->has('passStatus'))
  11491.             $passStatus $request->request->get('passStatus');
  11492.         if ($request->request->has('productByCodeId'))
  11493.             $id $request->request->get('productByCodeId');
  11494.         if ($request->request->has('productId'))
  11495.             $assignProductId $request->request->get('productId');
  11496.         if ($request->request->has('productionId'))
  11497.             $assignProductionId $request->request->get('productionId');
  11498.         if ($request->request->has('productionScheduleId'))
  11499.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  11500.         if ($request->request->has('gbWeightGm'))
  11501.             $gbWeightGm $request->request->get('gbWeightGm');
  11502.         if ($request->request->has('dvWeightGm'))
  11503.             $dvWeightGm $request->request->get('dvWeightGm');
  11504.         if ($request->request->has('cartonWeightGm'))
  11505.             $cartonWeightGm $request->request->get('cartonWeightGm');
  11506.         $cartonAssignedAlready 0;
  11507.         $otherData = array(
  11508.             'currentCartonBalance' => 0,
  11509.             'currentCartonCapacity' => 0,
  11510.             'currentCartonAssigned' => 0,
  11511.             'currentCartonFull' => 0,
  11512.         );
  11513.         if ($id != && $id != '') {
  11514.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11515.                 ->findOneBy(
  11516.                     array(
  11517.                         'productByCodeId' => $id
  11518.                     )
  11519.                 );
  11520.             if ($assignProductId != ''$productByCodeData->setProductId($assignProductId);
  11521.             if ($productByCodeData->getCartonId() != '' || $productByCodeData->getCartonId() != null)
  11522.                 $cartonAssignedAlready 1;
  11523.             else if ($cartonId != ''$productByCodeData->setCartonId($cartonId);
  11524.             if ($dvWeightGm != ''$productByCodeData->setSingleWeightGm($dvWeightGm);
  11525.             if ($gbWeightGm != '') {
  11526.                 $productByCodeData->setPackagedWeightGm($gbWeightGm);
  11527.             }
  11528.             $colorText '_NA_';
  11529.             if ($passStatus != 5$productByCodeData->setStage($passStatus);
  11530.             $productByCodeData->setCompanyId($companyId);
  11531.             if ($assignProductionId != '') {
  11532.                 $productByCodeData->setProductionId($assignProductionId);
  11533.                 $productionData $em->getRepository('ApplicationBundle:Production')
  11534.                     ->findOneBy(
  11535.                         array(
  11536.                             'productionId' => $assignProductionId
  11537.                         )
  11538.                     );
  11539.                 if ($assignProductId != '' && $assignProductId != null && $assignProductId != 0)
  11540.                     $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11541.                         array(
  11542.                             'productionId' => $assignProductionId,
  11543.                             'productId' => $assignProductId,
  11544.                             'type' => 1,
  11545.                         )
  11546.                     );
  11547.                 else
  11548.                     $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11549.                         array(
  11550.                             'productionId' => $assignProductionId,
  11551. //                            'productId' => $assignProductId,
  11552.                             'type' => 1,
  11553.                         )
  11554.                     );
  11555.                 $assignProductionScheduleId $productionData->getProductionScheduleId();
  11556.                 if ($productionItemData) {
  11557.                     $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11558.                     $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11559.                     $productByCodeData->setPosition(1);//in inventory
  11560.                     $productByCodeData->setSerialAssigned(1);
  11561.                     $productByCodeData->setColorId($productionItemData->getColorId());
  11562.                     $productByCodeData->setColorText($productionItemData->getColorText());
  11563.                     $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11564.                     $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11565.                     if ($passStatus == 1)//passed
  11566.                     {
  11567. //                    $transDate = new \DateTime();
  11568. //                    Inventory::addItemToInventoryCompact($em,
  11569. //                        $productionItemData->getProductId(),
  11570. //                        $productionItemData->getWarehouseId(),
  11571. //                        $productionItemData->getWarehouseId(),
  11572. //                        $productionData->getProducedItemActionTagId(),
  11573. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11574. //                        $transDate,
  11575. //                        1,
  11576. //                        1,
  11577. //                        $entry['valueAdd'],
  11578. //                        $entry['valueSub'],
  11579. //                        $entry['price'],
  11580. //                        $this->getLoggedUserCompanyId($request),
  11581. //                        0,
  11582. //                        $entry['entity'],
  11583. //                        $entry['entityId'],
  11584. //                        $entry['entityDocHash']
  11585. //                    );
  11586.                     }
  11587.                     $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  11588.                     if ($transHistory == null)
  11589.                         $transHistory = [];
  11590.                     $transHistory[] = array(
  11591.                         'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  11592.                         'direction' => 'in',
  11593.                         'warehouseId' => $productionItemData->getWarehouseId(),
  11594.                         'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  11595.                         'fromWarehouseId' => 0,
  11596.                         'fromWarehouseActionId' => //stock of goods
  11597.                     );
  11598.                     $productByCodeData->setTransactionHistory(json_encode($transHistory));
  11599.                 }
  11600.             }
  11601.             if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  11602.                 $productByCodeData->setProductionScheduleId($assignProductionScheduleId);
  11603.                 $productionSchedule $em->getRepository('ApplicationBundle:ProductionSchedule')
  11604.                     ->findOneBy(
  11605.                         array(
  11606.                             'productionScheduleId' => $assignProductionScheduleId
  11607.                         )
  11608.                     );
  11609.                 if ($productionSchedule) {
  11610.                     $productByCodeData->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  11611.                     $productByCodeData->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  11612.                     $productByCodeData->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  11613.                     $productByCodeData->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  11614.                     if ($productByCodeData->getProductionId() == null || $productByCodeData->getProductionId() == '' || $productByCodeData->getProductionId() == 0) {
  11615.                         $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11616.                             array(
  11617.                                 'productionScheduleId' => $assignProductionScheduleId,
  11618.                                 'productId' => $productionSchedule->getProducedProductId(),
  11619.                                 'type' => 1,
  11620.                             )
  11621.                         );
  11622. //                        $assignProductionScheduleId=$productionData->getProductionScheduleId();
  11623.                         if ($productionItemData) {
  11624.                             $productByCodeData->setProductionId($productionItemData->getProductionId());
  11625.                             $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11626.                             $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11627.                             $productByCodeData->setPosition(1);//in inventory
  11628.                             $productByCodeData->setSerialAssigned(1);
  11629.                             $productByCodeData->setColorId($productionItemData->getColorId());
  11630.                             $productByCodeData->setColorText($productionItemData->getColorText());
  11631.                             $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11632.                             $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11633.                             if ($passStatus == 1)//passed
  11634.                             {
  11635. //                    $transDate = new \DateTime();
  11636. //                    Inventory::addItemToInventoryCompact($em,
  11637. //                        $productionItemData->getProductId(),
  11638. //                        $productionItemData->getWarehouseId(),
  11639. //                        $productionItemData->getWarehouseId(),
  11640. //                        $productionData->getProducedItemActionTagId(),
  11641. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11642. //                        $transDate,
  11643. //                        1,
  11644. //                        1,
  11645. //                        $entry['valueAdd'],
  11646. //                        $entry['valueSub'],
  11647. //                        $entry['price'],
  11648. //                        $this->getLoggedUserCompanyId($request),
  11649. //                        0,
  11650. //                        $entry['entity'],
  11651. //                        $entry['entityId'],
  11652. //                        $entry['entityDocHash']
  11653. //                    );
  11654.                             }
  11655.                             $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  11656.                             if ($transHistory == null)
  11657.                                 $transHistory = [];
  11658.                             $transHistory[] = array(
  11659.                                 'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  11660.                                 'direction' => 'in',
  11661.                                 'warehouseId' => $productionItemData->getWarehouseId(),
  11662.                                 'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  11663.                                 'fromWarehouseId' => 0,
  11664.                                 'fromWarehouseActionId' => //stock of goods
  11665.                             );
  11666.                             $productByCodeData->setTransactionHistory(json_encode($transHistory));
  11667.                         }
  11668.                     }
  11669.                 }
  11670.             }
  11671. //                $productByCodeData->setPurchaseWarrantyLastDate($new_pwld);
  11672.             $em->flush();
  11673.             //now adding carton
  11674.         }
  11675.         if ($cartonId != '') {
  11676.             $carton $em->getRepository('ApplicationBundle:Carton')
  11677.                 ->findOneBy(
  11678.                     array(
  11679.                         'id' => $cartonId
  11680.                     )
  11681.                 );
  11682.             if ($cartonWeightGm != ''$carton->setCartonWeightGm($cartonWeightGm);
  11683.             $otherData['currentCartonCapacity'] = $carton->getCartonCapacityCount();
  11684.             if ($cartonAssignedAlready == 0)
  11685.                 $carton->setCartonAssignedCount(($carton->getCartonAssignedCount()) + 1);
  11686.             $otherData['currentCartonAssigned'] = $carton->getCartonAssignedCount();
  11687.             $otherData['currentCartonBalance'] = $otherData['currentCartonCapacity'] - $otherData['currentCartonAssigned'];
  11688.             if ($otherData['currentCartonAssigned'] >= $otherData['currentCartonCapacity'])
  11689.                 $otherData['currentCartonFull'] = 1;
  11690.             $em->flush();
  11691.         }
  11692.         if ($cartonId != '') {
  11693. //                    if($cartonAssignedAlready==1)
  11694. //                    {
  11695.             $productByCodeDataListForThisCarton $em->getRepository('ApplicationBundle:ProductByCode')
  11696.                 ->findBy(
  11697.                     array(
  11698.                         'cartonId' => $cartonId
  11699.                     )
  11700.                 );
  11701.             $carton $em->getRepository('ApplicationBundle:Carton')
  11702.                 ->findOneBy(
  11703.                     array(
  11704.                         'id' => $cartonId
  11705.                     )
  11706.                 );
  11707.             $total_carton_predicted_weight 0;
  11708.             $colorTextList = [];
  11709.             $cartonProductByCodeIds = [];
  11710.             foreach ($productByCodeDataListForThisCarton as $pikamaster) {
  11711.                 if (!in_array($pikamaster->getProductByCodeId(), $cartonProductByCodeIds))
  11712.                     $cartonProductByCodeIds[] = $pikamaster->getProductByCodeId();
  11713.                 if (!in_array($pikamaster->getColorText(), $colorTextList) && $pikamaster->getColorText() != null)
  11714.                     $colorTextList[] = $pikamaster->getColorText();
  11715.                 $total_carton_predicted_weight += ($pikamaster->getPackagedWeightGm());
  11716.                 if ($passStatus != 5)
  11717.                     if ($pikamaster->getStage() < $passStatus)
  11718.                         $pikamaster->setStage($passStatus);
  11719.             }
  11720.             if ($carton)
  11721.                 $carton->setCartonCalculatedWeightGm($total_carton_predicted_weight);
  11722.             if ($passStatus != 5)
  11723.                 $carton->setStage($passStatus);
  11724.             $carton->setColors(implode(','$colorTextList));
  11725.             $carton->setCartonProductByCodeIds(json_encode($cartonProductByCodeIds));
  11726.             $em->flush();
  11727.         }
  11728.         return new JsonResponse(array(
  11729.             'success' => true,
  11730.             'otherData' => $otherData,
  11731.         ));
  11732.     }
  11733.     public
  11734.     function RefreshCartonListAction(Request $request$id)
  11735.     {
  11736.         $em $this->getDoctrine()->getManager();
  11737. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11738.         $cartonListArray = [];
  11739.         $cartonList = [];
  11740.         $assignableCartonList = [];
  11741.         $assignableCartonListArray = [];
  11742.         $assignable 0;
  11743.         $cartonId '';
  11744.         $passStatus 5;
  11745.         $assignProductId '';
  11746.         $assignProductionId '';
  11747.         $assignProductionScheduleId '';
  11748.         if ($request->request->has('productionId'))
  11749.             $assignProductionId $request->request->get('productionId');
  11750.         if ($request->request->has('productionScheduleId'))
  11751.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  11752.         if ($request->request->has('assignable'))
  11753.             $assignable $request->request->get('assignable');
  11754.         $cartonAssignedAlready 0;
  11755.         $otherData = array(
  11756.             'currentCartonBalance' => 0,
  11757.             'currentCartonCapacity' => 0,
  11758.             'currentCartonAssigned' => 0,
  11759.             'currentCartonFull' => 0,
  11760.         );
  11761.         //1st get all cartons for this production id
  11762.         $cartonList $em->getRepository('ApplicationBundle:Carton')
  11763.             ->findBy(
  11764.                 array(
  11765. //                    'productionId' => $assignProductionId,
  11766.                     'productionScheduleId' => $assignProductionScheduleId
  11767.                 )
  11768.             );
  11769.         $foundAssignable 0;
  11770.         $setId 0;
  11771.         $lastdmySer '';
  11772.         foreach ($cartonList as $carton) {
  11773.             $cartonData = array(
  11774.                 'id' => $carton->getId(),
  11775.                 'name' => $carton->getCartonNumber(),
  11776.                 'colors' => $carton->getColors(),
  11777.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  11778.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  11779.             );
  11780.             $cartonListArray[] = $cartonData;
  11781.             $cartonList[$cartonData['id']] = $cartonData;
  11782.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  11783.                 $foundAssignable 1;
  11784.                 $setId $cartonData['id'];
  11785.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  11786.                 $assignableCartonListArray[] = $cartonData;
  11787.             }
  11788.         }
  11789.         if ($assignable == && $foundAssignable == 0) {
  11790. //            $productionData = $em->getRepository('ApplicationBundle:Production')
  11791. //                ->findOneBy(
  11792. //                    array(
  11793. //                        'productionId' => $assignProductionId
  11794. //                    )
  11795. //                );
  11796.             $productionScheduleData $em->getRepository('ApplicationBundle:ProductionSchedule')
  11797.                 ->findOneBy(
  11798.                     array(
  11799.                         'productionScheduleId' => $assignProductionScheduleId
  11800.                     )
  11801.                 );
  11802.             $productId 0;
  11803.             $product = [];
  11804.             $productModel '';
  11805.             if ($productionScheduleData)
  11806.                 $productId $productionScheduleData->getProducedProductId();
  11807. //            $productionItem = $em->getRepository('ApplicationBundle:ProductionEntryItem')
  11808. //                ->findOneBy(
  11809. //                    array(
  11810. //                        'productionId' => $assignProductionId,
  11811. //                        'type' => 1
  11812. //                    )
  11813. //                );
  11814.             if ($productId != 0) {
  11815. //                    $productId = $productionItem->getProductId();
  11816.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  11817.                     ->findOneBy(
  11818.                         array(
  11819.                             'id' => $productId,
  11820.                         )
  11821.                     );
  11822.                 $productModel $product->getModelNo();
  11823.             }
  11824.             $carton = new Carton();
  11825.             $carton_capacity $productionScheduleData->getCartonCapacity();
  11826.             $carton->setProductId($productId);
  11827.             $carton->setProductionId($assignProductionId);
  11828.             $carton->setProductionScheduleId($assignProductionScheduleId);
  11829.             if ($productionScheduleData) {
  11830.                 $carton->setCartonLabelFormatId($productionScheduleData->getCartonLabelFormatId());
  11831.             }
  11832.             $carton->setCartonCapacityCount($carton_capacity == null $carton_capacity);
  11833.             $carton->setCartonAssignedCount(0);
  11834.             $carton->setCompanyId($this->getLoggedUserCompanyId($request));
  11835.             $today = new \DateTime();
  11836.             $dmy $productModel '-' . ($today->format('m')) . '-' . ($today->format('Y')) . '-' $productionScheduleData->getBatchNumber();
  11837.             $ser 0;
  11838.             $carton->setCartonNumberDmy($dmy);
  11839.             $carton->setCartonNumberLastSer(* (($today->format('h')) . '' . ($today->format('i'))));
  11840.             $carton->setCartonNumber($dmy '-' . ($today->format('h')) . '' . ($today->format('i')));
  11841.             $em->persist($carton);
  11842.             $em->flush();
  11843.             $cartonData = array(
  11844.                 'id' => $carton->getId(),
  11845.                 'name' => $carton->getCartonNumber(),
  11846.                 'colors' => $carton->getColors(),
  11847.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  11848.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  11849.             );
  11850.             $cartonListArray[] = $cartonData;
  11851.             $cartonList[$cartonData['id']] = $cartonData;
  11852.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  11853.                 $foundAssignable 1;
  11854.                 $setId $cartonData['id'];
  11855.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  11856.                 $assignableCartonListArray[] = $cartonData;
  11857.             }
  11858.         }
  11859.         return new JsonResponse(array(
  11860.             'success' => true,
  11861.             'cartonList' => $cartonList,
  11862.             'cartonListArray' => $cartonListArray,
  11863.             'assignableCartonList' => $assignableCartonList,
  11864.             'assignableCartonListArray' => $assignableCartonListArray,
  11865.             'setId' => $setId,
  11866.         ));
  11867.     }
  11868.     public
  11869.     function PrintDrBarcodeAction(Request $request$id$item_id)
  11870.     {
  11871.         $em $this->getDoctrine()->getManager();
  11872.         $dt Inventory::GetDrDetails($em$id$item_id);
  11873.         $repeatCount 1;
  11874.         if ($request->query->has('repeatCount'))
  11875.             $repeatCount $request->query->get('repeatCount');
  11876.         $company_data Company::getCompanyData($em1);
  11877.         $document_mark = array(
  11878.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11879.             'copy' => ''
  11880.         );
  11881.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11882.             $html $this->renderView('@Inventory/pages/print/print_dr_barcodes.html.twig',
  11883.                 array(
  11884.                     //full array here
  11885.                     'pdf' => true,
  11886.                     'page_title' => 'Challan Barcodes',
  11887.                     'export' => 'print',
  11888.                     'repeatCount' => $repeatCount,
  11889.                     'item_id' => $item_id,
  11890.                     'data' => $dt,
  11891.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11892.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11893.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11894.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  11895.                         $id,
  11896.                         $dt['created_by'],
  11897.                         $dt['edited_by']),
  11898.                     'document_mark_image' => $document_mark['original'],
  11899.                     'company_name' => $company_data->getName(),
  11900.                     'company_data' => $company_data,
  11901.                     'company_address' => $company_data->getAddress(),
  11902.                     'company_image' => $company_data->getImage(),
  11903.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11904.                     'red' => 0
  11905.                 )
  11906.             );
  11907.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11908. //                'orientation' => 'landscape',
  11909.                 'enable-javascript' => true,
  11910. //                'javascript-delay' => 1000,
  11911.                 'no-stop-slow-scripts' => false,
  11912.                 'no-background' => false,
  11913.                 'lowquality' => false,
  11914.                 'encoding' => 'utf-8',
  11915. //            'images' => true,
  11916. //            'cookie' => array(),
  11917.                 'dpi' => 300,
  11918.                 'image-dpi' => 300,
  11919. //                'enable-external-links' => true,
  11920. //                'enable-internal-links' => true
  11921.             ));
  11922.             return new Response(
  11923.                 $pdf_response,
  11924.                 200,
  11925.                 array(
  11926.                     'Content-Type' => 'application/pdf',
  11927.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  11928.                 )
  11929.             );
  11930.         }
  11931.         return $this->render('@Inventory/pages/print/print_dr_barcodes.html.twig',
  11932.             array(
  11933.                 'page_title' => 'Challan barcodes',
  11934. //                'export'=>'pdf,print',
  11935.                 'data' => $dt,
  11936.                 'repeatCount' => $repeatCount,
  11937.                 'item_id' => $item_id,
  11938.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11939.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11940.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11941.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  11942.                     $id,
  11943.                     $dt['created_by'],
  11944.                     $dt['edited_by']),
  11945.                 'document_mark_image' => $document_mark['original'],
  11946.                 'company_name' => $company_data->getName(),
  11947.                 'company_data' => $company_data,
  11948.                 'company_address' => $company_data->getAddress(),
  11949.                 'company_image' => $company_data->getImage(),
  11950.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11951.                 'red' => 0
  11952.             )
  11953.         );
  11954.     }
  11955.     public
  11956.     function PrintIrrBarcodeAction(Request $request$id$item_id)
  11957.     {
  11958.         $em $this->getDoctrine()->getManager();
  11959.         $dt Inventory::GetIrrDetails($em$id$item_id);
  11960.         $repeatCount 1;
  11961.         if ($request->query->has('repeatCount'))
  11962.             $repeatCount $request->query->get('repeatCount');
  11963.         $company_data Company::getCompanyData($em1);
  11964.         $document_mark = array(
  11965.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11966.             'copy' => ''
  11967.         );
  11968.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11969.             $html $this->renderView('@Inventory/pages/print/print_irr_barcodes.html.twig',
  11970.                 array(
  11971.                     //full array here
  11972.                     'pdf' => true,
  11973.                     'page_title' => 'Sales Return Barcodes',
  11974.                     'export' => 'print',
  11975.                     'repeatCount' => $repeatCount,
  11976.                     'item_id' => $item_id,
  11977.                     'data' => $dt,
  11978.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  11979.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11980.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11981.                         array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  11982.                         $id,
  11983.                         $dt['created_by'],
  11984.                         $dt['edited_by']),
  11985.                     'document_mark_image' => $document_mark['original'],
  11986.                     'company_name' => $company_data->getName(),
  11987.                     'company_data' => $company_data,
  11988.                     'company_address' => $company_data->getAddress(),
  11989.                     'company_image' => $company_data->getImage(),
  11990.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11991.                     'red' => 0
  11992.                 )
  11993.             );
  11994.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11995. //                'orientation' => 'landscape',
  11996.                 'enable-javascript' => true,
  11997. //                'javascript-delay' => 1000,
  11998.                 'no-stop-slow-scripts' => false,
  11999.                 'no-background' => false,
  12000.                 'lowquality' => false,
  12001.                 'encoding' => 'utf-8',
  12002. //            'images' => true,
  12003. //            'cookie' => array(),
  12004.                 'dpi' => 300,
  12005.                 'image-dpi' => 300,
  12006. //                'enable-external-links' => true,
  12007. //                'enable-internal-links' => true
  12008.             ));
  12009.             return new Response(
  12010.                 $pdf_response,
  12011.                 200,
  12012.                 array(
  12013.                     'Content-Type' => 'application/pdf',
  12014.                     'Content-Disposition' => 'attachment; filename="irr_barcodes.pdf"'
  12015.                 )
  12016.             );
  12017.         }
  12018.         return $this->render('@Inventory/pages/print/print_irr_barcodes.html.twig',
  12019.             array(
  12020.                 'page_title' => 'Sales Return barcodes',
  12021. //                'export'=>'pdf,print',
  12022.                 'data' => $dt,
  12023.                 'repeatCount' => $repeatCount,
  12024.                 'item_id' => $item_id,
  12025.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12026.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12027.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12028.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12029.                     $id,
  12030.                     $dt['created_by'],
  12031.                     $dt['edited_by']),
  12032.                 'document_mark_image' => $document_mark['original'],
  12033.                 'company_name' => $company_data->getName(),
  12034.                 'company_data' => $company_data,
  12035.                 'company_address' => $company_data->getAddress(),
  12036.                 'company_image' => $company_data->getImage(),
  12037.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12038.                 'red' => 0
  12039.             )
  12040.         );
  12041.     }
  12042.     public
  12043.     function PrintSrcvBarcodeAction(Request $request$id$item_id)
  12044.     {
  12045.         $em $this->getDoctrine()->getManager();
  12046.         $dt Inventory::GetSrcvDetails($em$id$item_id);
  12047.         $repeatCount 1;
  12048.         if ($request->query->has('repeatCount'))
  12049.             $repeatCount $request->query->get('repeatCount');
  12050.         $company_data Company::getCompanyData($em1);
  12051.         $document_mark = array(
  12052.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12053.             'copy' => ''
  12054.         );
  12055.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12056.             $html $this->renderView('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12057.                 array(
  12058.                     //full array here
  12059.                     'pdf' => true,
  12060.                     'page_title' => 'Grn Barcodes',
  12061.                     'export' => 'print',
  12062.                     'repeatCount' => $repeatCount,
  12063.                     'item_id' => $item_id,
  12064.                     'data' => $dt,
  12065.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12066.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12067.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12068.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12069.                         $id,
  12070.                         $dt['created_by'],
  12071.                         $dt['edited_by']),
  12072.                     'document_mark_image' => $document_mark['original'],
  12073.                     'company_name' => $company_data->getName(),
  12074.                     'company_data' => $company_data,
  12075.                     'company_address' => $company_data->getAddress(),
  12076.                     'company_image' => $company_data->getImage(),
  12077.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12078.                     'red' => 0
  12079.                 )
  12080.             );
  12081.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12082. //                'orientation' => 'landscape',
  12083.                 'enable-javascript' => true,
  12084. //                'javascript-delay' => 1000,
  12085.                 'no-stop-slow-scripts' => false,
  12086.                 'no-background' => false,
  12087.                 'lowquality' => false,
  12088.                 'encoding' => 'utf-8',
  12089. //            'images' => true,
  12090. //            'cookie' => array(),
  12091.                 'dpi' => 300,
  12092.                 'image-dpi' => 300,
  12093. //                'enable-external-links' => true,
  12094. //                'enable-internal-links' => true
  12095.             ));
  12096.             return new Response(
  12097.                 $pdf_response,
  12098.                 200,
  12099.                 array(
  12100.                     'Content-Type' => 'application/pdf',
  12101.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  12102.                 )
  12103.             );
  12104.         }
  12105.         return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12106.             array(
  12107.                 'page_title' => 'Srcv barcodes',
  12108. //                'export'=>'pdf,print',
  12109.                 'data' => $dt,
  12110.                 'repeatCount' => $repeatCount,
  12111.                 'item_id' => $item_id,
  12112.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12113.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12114.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12115.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12116.                     $id,
  12117.                     $dt['created_by'],
  12118.                     $dt['edited_by']),
  12119.                 'document_mark_image' => $document_mark['original'],
  12120.                 'company_name' => $company_data->getName(),
  12121.                 'company_data' => $company_data,
  12122.                 'company_address' => $company_data->getAddress(),
  12123.                 'company_image' => $company_data->getImage(),
  12124.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12125.                 'red' => 0
  12126.             )
  12127.         );
  12128.     }
  12129. //product by code
  12130.     public
  12131.     function ImeiListExcelUploadAction(Request $request)
  12132.     {
  12133.         $lastIndex $request->request->get('lastIndex'0);
  12134.         if ($request->isMethod('POST')) {
  12135.             $post $request->request;
  12136.             if ($request->request->has('chunkData')) {
  12137.                 //now getting the relevant checks
  12138.                 $check_list = [];
  12139.                 $csv_data $request->request->get('chunkData', []);
  12140.                 $em $this->getDoctrine()->getManager();
  12141.                 foreach ($csv_data as $ind => $data_row) {
  12142. //                    if ($ind == 1)
  12143. //                        continue;
  12144.                     $np $this->getDoctrine()
  12145.                         ->getRepository('ApplicationBundle:ProductByCode')
  12146.                         ->findOneBy(
  12147.                             array(
  12148.                                 'salesCode' => isset($data_row[4]) ? $data_row[4] : 0,
  12149. //                    'approved' =>  GeneralConstant::APPROVED,
  12150.                             )
  12151.                         );
  12152.                     if (!$np)
  12153.                         $np = new ProductByCode();
  12154. //                    $np = new ProductByCode();
  12155.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  12156.                     if (isset($data_row[1])) $np->setProductId($data_row[1]);
  12157.                     if (isset($data_row[0])) $np->setLcNumber($data_row[0]);
  12158.                     if (isset($data_row[2])) $np->setCartonNumber($data_row[2]);
  12159.                     if (isset($data_row[3])) $np->setSerialNo($data_row[3]);
  12160.                     $np->setSerialAssigned(isset($data_row[10]) ? $data_row[10] : 0);
  12161.                     if (isset($data_row[4])) $np->setImei1($data_row[4]);
  12162.                     if (isset($data_row[5])) $np->setImei2($data_row[5]);
  12163.                     if (isset($data_row[6])) $np->setImei3($data_row[6]);
  12164.                     if (isset($data_row[7])) $np->setImei4($data_row[7]);
  12165.                     if (isset($data_row[8])) $np->setBtMac($data_row[8]);
  12166.                     if (isset($data_row[9])) $np->setWlanMac($data_row[9]);
  12167.                     $np->setWarehouseId(isset($data_row[11]) ? $data_row[11] : 0);
  12168.                     $np->setWarehouseActionId(isset($data_row[12]) ? $data_row[12] : 0);
  12169.                     $np->setPosition(isset($data_row[13]) ? $data_row[13] : 0);//in inventory
  12170.                     $np->setPurchaseOrderId(0);
  12171.                     $np->setGrnId(0);
  12172.                     $np->setStage(0);
  12173.                     if (isset($data_row[3])) $np->setSalesCodeRange(json_encode([$data_row[3]]));
  12174. //                $np->setSalesCode($data_row[3]);
  12175.                     if (isset($data_row[4])) $np->setSalesCode($data_row[4]); //IMEI
  12176.                     $np->setSalesCodeSer(0);
  12177.                     $np->setSalesCodeDmy('');
  12178.                     $np->setPurchaseCodeRange("");
  12179.                     $np->setPurchaseReceiptDate(null);
  12180.                     $np->setLastInDate(null);
  12181.                     $np->setStatus(GeneralConstant::ACTIVE);
  12182.                     $np->setTransactionHistory(json_encode([
  12183.                         ]
  12184.                     ));
  12185.                     $np->setPurchaseWarrantyLastDate(null);
  12186.                     $em->persist($np);
  12187.                     $em->flush();
  12188.                 }
  12189.                 return new JsonResponse(array(
  12190.                     "success" => true,
  12191.                     "lastIndex" => $lastIndex,
  12192.                     "file_path" => '',
  12193.                     "csv_data" => $csv_data,
  12194.                     //                "debug_data"=>System::encryptSignature($r)
  12195.                 ));
  12196.             } else {
  12197.                 $path "";
  12198.                 $file_path "";
  12199.                 //            var_dump($request->files);
  12200.                 //        var_dump($request->getFile());
  12201.                 foreach ($request->files as $uploadedFile) {
  12202.                     //            if($uploadedFile->getImage())
  12203.                     //                var_dump($uploadedFile->getFile());
  12204.                     //                var_dump($uploadedFile);
  12205.                     if ($uploadedFile != null) {
  12206.                         $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  12207.                         $path $fileName;
  12208.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  12209.                         if (!file_exists($upl_dir)) {
  12210.                             mkdir($upl_dir0777true);
  12211.                         }
  12212.                         $file $uploadedFile->move($upl_dir$path);
  12213.                     }
  12214.                 }
  12215.                 //        print_r($file);
  12216.                 if ($path != "")
  12217.                     $file_path 'uploads/FileUploads/' $path;
  12218.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  12219.                 //
  12220.                 //            $img_file = file_get_contents($g_path);
  12221.                 //            $r=base64_encode($img_file);
  12222.                 $row 1;
  12223.                 $csv_data = [];
  12224.                 if (($handle fopen($g_path"r")) !== FALSE) {
  12225.                     while (($data fgetcsv($handle1000",")) !== FALSE) {
  12226.                         $num count($data);
  12227.                         $csv_data[$row] = $data;
  12228.                         //                    echo "<p> $num fields in line $row: <br /></p>\n";
  12229.                         $row++;
  12230.                         //                    for ($c=0; $c < $num; $c++) {
  12231.                         //                        echo $data[$c] . "<br />\n";
  12232.                         //                    }
  12233.                     }
  12234.                     fclose($handle);
  12235.                 }
  12236.                 //now getting the relevant checks
  12237.                 $check_list = [];
  12238.                 $em $this->getDoctrine()->getManager();
  12239.                 foreach ($csv_data as $ind => $data_row) {
  12240.                     if ($ind == 1)
  12241.                         continue;
  12242.                     $np = new ProductByCode();
  12243.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  12244.                     $np->setProductId($data_row[1]);
  12245.                     $np->setLcNumber($data_row[0]);
  12246.                     $np->setCartonNumber($data_row[2]);
  12247.                     $np->setSerialNo($data_row[3]);
  12248.                     $np->setSerialAssigned(0);
  12249.                     $np->setImei1($data_row[4]);
  12250.                     $np->setImei2($data_row[5]);
  12251.                     $np->setImei3($data_row[6]);
  12252.                     $np->setImei4($data_row[7]);
  12253.                     $np->setBtMac($data_row[8]);
  12254.                     $np->setWlanMac($data_row[9]);
  12255.                     $np->setWarehouseId(0);
  12256.                     $np->setWarehouseActionId(0);
  12257.                     $np->setPosition(0);//in inventory
  12258.                     $np->setPurchaseOrderId(0);
  12259.                     $np->setGrnId(0);
  12260.                     $np->setStage(0);
  12261.                     $np->setSalesCodeRange(json_encode([$data_row[3]]));
  12262. //                $np->setSalesCode($data_row[3]);
  12263.                     $np->setSalesCode($data_row[4]); //IMEI
  12264.                     $np->setSalesCodeSer(0);
  12265.                     $np->setSalesCodeDmy('');
  12266.                     $np->setPurchaseCodeRange("");
  12267.                     $np->setPurchaseReceiptDate(null);
  12268.                     $np->setLastInDate(null);
  12269.                     $np->setStatus(GeneralConstant::ACTIVE);
  12270.                     $np->setTransactionHistory(json_encode([
  12271.                         ]
  12272.                     ));
  12273.                     $np->setPurchaseWarrantyLastDate(null);
  12274.                     $em->persist($np);
  12275.                     $em->flush();
  12276.                 }
  12277.                 return new JsonResponse(array(
  12278.                     "success" => true,
  12279.                     "lastIndex" => $lastIndex,
  12280.                     "file_path" => $file_path,
  12281.                     "csv_data" => $csv_data,
  12282.                     //                "debug_data"=>System::encryptSignature($r)
  12283.                 ));
  12284.             }
  12285.         }
  12286.         return new JsonResponse(array(
  12287.             "success" => false,
  12288.             "file_path" => '',
  12289.             "csv_data" => [],
  12290.             "lastIndex" => $lastIndex,
  12291.         ));
  12292.     }
  12293.     public
  12294.     function ProductByCodeListAction(Request $request)
  12295.     {
  12296.         $em $this->getDoctrine()->getManager();
  12297.         $companyId $this->getLoggedUserCompanyId($request);
  12298.         $listData Inventory::GetProductListForProductByCodeListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  12299.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  12300.             if ($request->query->has('dataTableQry')) {
  12301.                 return new JsonResponse(
  12302.                     $listData
  12303.                 );
  12304.             }
  12305.         }
  12306.         $q = [];
  12307. //        $q = $this->getDoctrine()
  12308. //            ->getRepository('ApplicationBundle:ProductByCode')
  12309. //            ->findBy(
  12310. //                array(
  12311. //                    'status' => GeneralConstant::ACTIVE,
  12312. ////                    'approved' =>  GeneralConstant::APPROVED,
  12313. //                )
  12314. //
  12315. //            );
  12316.         //temp start
  12317. //        foreach($q as $np) {
  12318. //            if($np->getPosition()==1) {   /// only starting ones or in warehouse ones
  12319. //                $temp_obj = json_decode($np->getTransactionHistory());
  12320. //                if ($temp_obj != null) {
  12321. //                    $transHistory = [];
  12322. //                    $transHistory[] = $temp_obj;
  12323. //                    $np->setTransactionHistory(json_encode($transHistory));
  12324. //                }
  12325. //            }
  12326. //            $em->flush();
  12327. //        }
  12328.         ///temp end
  12329.         $stage_list = array(
  12330.             => 'Pending',
  12331.             => 'Pending',
  12332.             => 'Complete',
  12333.             => 'Partial',
  12334.         );
  12335.         $data = [];
  12336. //        foreach($q as $entry)
  12337. //        {
  12338. //            $data[]=array(
  12339. //                'doc_date'=>$entry->getStockRequisitionDate(),
  12340. //                'id'=>$entry->getStockRequisitionId(),
  12341. //                'doc_hash'=>$entry->getDocumentHash(),
  12342. //                'approval_status'=>GeneralConstant::$approvalStatus[$entry->getApproved()],
  12343. //                'stage'=>$stage_list[$entry->getStage()]
  12344. //
  12345. //            );
  12346. //        }
  12347.         return $this->render('@Inventory/pages/views/product_by_code_list.html.twig',
  12348.             array(
  12349.                 'page_title' => 'Product List',
  12350.                 'data' => $q,
  12351. //                'listData' => $listData,
  12352.                 'products' => Inventory::ProductList($em),
  12353.                 'warehouseList' => Inventory::WarehouseList($em)
  12354.             )
  12355.         );
  12356.     }
  12357. //SR
  12358.     public
  12359.     function SrListAction(Request $request)
  12360.     {
  12361.         $q $this->getDoctrine()
  12362.             ->getRepository('ApplicationBundle:StockRequisition')
  12363.             ->findBy(
  12364.                 array(
  12365.                     'status' => GeneralConstant::ACTIVE,
  12366. //                    'approved' =>  GeneralConstant::APPROVED,
  12367.                 )
  12368.                 ,
  12369.                 array(
  12370.                     'stockRequisitionDate' => 'DESC'
  12371.                 )
  12372.             );
  12373.         $stage_list = array(
  12374.             => 'Pending',
  12375.             => 'Pending',
  12376.             => 'Complete',
  12377.             => 'Partial',
  12378.         );
  12379.         $data = [];
  12380.         foreach ($q as $entry) {
  12381.             $data[] = array(
  12382.                 'doc_date' => $entry->getStockRequisitionDate(),
  12383.                 'id' => $entry->getStockRequisitionId(),
  12384.                 'doc_hash' => $entry->getDocumentHash(),
  12385.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12386.                 'stage' => $stage_list[$entry->getStage()],
  12387.                 'indentTagged' => $entry->getIndentTagged(),
  12388.                 'srIds' => $entry->getSrIds(),
  12389.                 'irIds' => $entry->getIrIds(),
  12390.                 'prIds' => $entry->getPrIds(),
  12391.                 'poIds' => $entry->getPoIds(),
  12392.             );
  12393.         }
  12394.         return $this->render('@Inventory/pages/views/sr_list.html.twig',
  12395.             array(
  12396.                 'page_title' => 'Stock Requisition List',
  12397.                 'data' => $data
  12398.             )
  12399.         );
  12400.     }
  12401.     public
  12402.     function ViewSrAction(Request $request$id)
  12403.     {
  12404.         $em $this->getDoctrine()->getManager();
  12405.         $dt Inventory::GetSrDetails($em$id);
  12406.         return $this->render('@Inventory/pages/views/view_stock_requisition.html.twig',
  12407.             array(
  12408.                 'page_title' => 'Stock requisition',
  12409.                 'data' => $dt,
  12410.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12411.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12412.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12413.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12414.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12415.                     $id,
  12416.                     $dt['created_by'],
  12417.                     $dt['edited_by'])
  12418.             )
  12419.         );
  12420.     }
  12421.     public
  12422.     function PrintSrAction(Request $request$id)
  12423.     {
  12424.         $em $this->getDoctrine()->getManager();
  12425.         $dt Inventory::GetSrDetails($em$id);
  12426.         $company_data Company::getCompanyData($em1);
  12427.         $document_mark = array(
  12428.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12429.             'copy' => ''
  12430.         );
  12431.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12432.             $html $this->renderView('@Inventory/pages/print/print_sr.html.twig',
  12433.                 array(
  12434.                     //full array here
  12435.                     'pdf' => true,
  12436.                     'page_title' => 'Stock Requisition',
  12437.                     'export' => 'pdf,print',
  12438.                     'data' => $dt,
  12439.                     'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12440.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12441.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12442.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12443.                         array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12444.                         $id,
  12445.                         $dt['created_by'],
  12446.                         $dt['edited_by']),
  12447.                     'document_mark_image' => $document_mark['original'],
  12448.                     'company_name' => $company_data->getName(),
  12449.                     'company_data' => $company_data,
  12450.                     'company_address' => $company_data->getAddress(),
  12451.                     'company_image' => $company_data->getImage(),
  12452.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12453.                     'red' => 0
  12454.                 )
  12455.             );
  12456.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12457. //                'orientation' => 'landscape',
  12458. //                'enable-javascript' => true,
  12459. //                'javascript-delay' => 1000,
  12460.                 'no-stop-slow-scripts' => false,
  12461.                 'no-background' => false,
  12462.                 'lowquality' => false,
  12463.                 'encoding' => 'utf-8',
  12464. //            'images' => true,
  12465. //            'cookie' => array(),
  12466.                 'dpi' => 300,
  12467.                 'image-dpi' => 300,
  12468. //                'enable-external-links' => true,
  12469. //                'enable-internal-links' => true
  12470.             ));
  12471.             return new Response(
  12472.                 $pdf_response,
  12473.                 200,
  12474.                 array(
  12475.                     'Content-Type' => 'application/pdf',
  12476.                     'Content-Disposition' => 'attachment; filename="stock_requisition_' $id '.pdf"'
  12477.                 )
  12478.             );
  12479.         }
  12480.         return $this->render('@Inventory/pages/print/print_sr.html.twig',
  12481.             array(
  12482.                 'page_title' => 'Stock Requisition',
  12483.                 'export' => 'pdf,print',
  12484.                 'data' => $dt,
  12485.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12486.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12487.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12488.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12489.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12490.                     $id,
  12491.                     $dt['created_by'],
  12492.                     $dt['edited_by']),
  12493.                 'document_mark_image' => $document_mark['original'],
  12494.                 'company_name' => $company_data->getName(),
  12495.                 'company_data' => $company_data,
  12496.                 'company_address' => $company_data->getAddress(),
  12497.                 'company_image' => $company_data->getImage(),
  12498.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12499.                 'red' => 0
  12500.             )
  12501.         );
  12502.     }
  12503. //IR
  12504.     public
  12505.     function IrListAction(Request $request)
  12506.     {
  12507.         $q $this->getDoctrine()
  12508.             ->getRepository('ApplicationBundle:StoreRequisition')
  12509.             ->findBy(
  12510.                 array(
  12511.                     'status' => GeneralConstant::ACTIVE,
  12512. //                    'approved' =>  GeneralConstant::APPROVED,
  12513.                 ),
  12514.                 array(
  12515.                     'storeRequisitionDate' => 'DESC'
  12516.                 )
  12517.             );
  12518.         $stage_list = array(
  12519.             => 'Pending',
  12520.             => 'Pending',
  12521.             => 'Complete',
  12522.             => 'Partial',
  12523.         );
  12524.         $data = [];
  12525.         foreach ($q as $entry) {
  12526.             $data[] = array(
  12527.                 'doc_date' => $entry->getStoreRequisitionDate(),
  12528.                 'id' => $entry->getStoreRequisitionId(),
  12529.                 'doc_hash' => $entry->getDocumentHash(),
  12530.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12531.                 'stage' => $stage_list[$entry->getStage()],
  12532.                 'prTagged' => $entry->getIndentTagged(),
  12533.                 'srIds' => $entry->getSrIds(),
  12534.                 'irIds' => $entry->getIrIds(),
  12535.                 'prIds' => $entry->getPrIds(),
  12536.                 'poIds' => $entry->getPoIds(),
  12537.             );
  12538.         }
  12539.         return $this->render('@Inventory/pages/views/ir_list.html.twig',
  12540.             array(
  12541.                 'page_title' => 'Indent Requisition List',
  12542.                 'data' => $data
  12543.             )
  12544.         );
  12545.     }
  12546.     public
  12547.     function ViewIrAction(Request $request$id)
  12548.     {
  12549.         $em $this->getDoctrine()->getManager();
  12550.         $dt Inventory::GetIrDetails($em$id);
  12551.         return $this->render('@Inventory/pages/views/view_indent_requisition.html.twig',
  12552.             array(
  12553.                 'page_title' => 'Indent',
  12554.                 'data' => $dt,
  12555.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12556.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12557.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12558.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12559.                     $id,
  12560.                     $dt['created_by'],
  12561.                     $dt['edited_by'])
  12562.             )
  12563.         );
  12564.     }
  12565.     public
  12566.     function PrintIrAction(Request $request$id)
  12567.     {
  12568.         $em $this->getDoctrine()->getManager();
  12569.         $dt Inventory::GetIrDetails($em$id);
  12570.         $company_data Company::getCompanyData($em1);
  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_ir.html.twig',
  12577.                 array(
  12578.                     //full array here
  12579.                     'pdf' => true,
  12580.                     'page_title' => 'Indent Requisition',
  12581.                     'export' => 'pdf,print',
  12582.                     'data' => $dt,
  12583.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12584.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12585.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12586.                         array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12587.                         $id,
  12588.                         $dt['created_by'],
  12589.                         $dt['edited_by']),
  12590.                     'document_mark_image' => $document_mark['original'],
  12591.                     'company_name' => $company_data->getName(),
  12592.                     'company_data' => $company_data,
  12593.                     'company_address' => $company_data->getAddress(),
  12594.                     'company_image' => $company_data->getImage(),
  12595.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12596.                     'red' => 0
  12597.                 )
  12598.             );
  12599.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12600. //                'orientation' => 'landscape',
  12601. //                'enable-javascript' => true,
  12602. //                'javascript-delay' => 1000,
  12603.                 'no-stop-slow-scripts' => false,
  12604.                 'no-background' => false,
  12605.                 'lowquality' => false,
  12606.                 'encoding' => 'utf-8',
  12607. //            'images' => true,
  12608. //            'cookie' => array(),
  12609.                 'dpi' => 300,
  12610.                 'image-dpi' => 300,
  12611. //                'enable-external-links' => true,
  12612. //                'enable-internal-links' => true
  12613.             ));
  12614.             return new Response(
  12615.                 $pdf_response,
  12616.                 200,
  12617.                 array(
  12618.                     'Content-Type' => 'application/pdf',
  12619.                     'Content-Disposition' => 'attachment; filename="indent_' $id '.pdf"'
  12620.                 )
  12621.             );
  12622.         }
  12623.         return $this->render('@Inventory/pages/print/print_ir.html.twig',
  12624.             array(
  12625.                 'page_title' => 'Indent Requisition',
  12626.                 'export' => 'pdf,print',
  12627.                 'data' => $dt,
  12628.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12629.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12630.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12631.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12632.                     $id,
  12633.                     $dt['created_by'],
  12634.                     $dt['edited_by']),
  12635.                 'document_mark_image' => $document_mark['original'],
  12636.                 'company_name' => $company_data->getName(),
  12637.                 'company_data' => $company_data,
  12638.                 'company_address' => $company_data->getAddress(),
  12639.                 'company_image' => $company_data->getImage(),
  12640.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12641.                 'red' => 0
  12642.             )
  12643.         );
  12644.     }
  12645. //PR
  12646.     public
  12647.     function PrListAction(Request $request)
  12648.     {
  12649.         $q $this->getDoctrine()
  12650.             ->getRepository('ApplicationBundle:PurchaseRequisition')
  12651.             ->findBy(
  12652.                 array(
  12653.                     'status' => GeneralConstant::ACTIVE,
  12654. //                    'approved' =>  GeneralConstant::APPROVED,
  12655.                 ),
  12656.                 array(
  12657.                     'purchaseRequisitionDate' => 'DESC'
  12658.                 )
  12659.             );
  12660.         $stage_list = array(
  12661.             => 'Pending',
  12662.             => 'Pending',
  12663.             => 'Complete',
  12664.             => 'Partial',
  12665.         );
  12666.         $data = [];
  12667.         foreach ($q as $entry) {
  12668.             $data[] = array(
  12669.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  12670.                 'id' => $entry->getPurchaseRequisitionId(),
  12671.                 'doc_hash' => $entry->getDocumentHash(),
  12672.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12673.                 'acquisition_status' => $entry->getAcquisitionStatus(),
  12674.                 'acquisition_start_date' => $entry->getAcquisitionStartDate(),
  12675.                 'acquisition_end_date' => $entry->getAcquisitionEndDate(),
  12676.                 'acquisition_method' => $entry->getquotationAcquisitionMethod(),
  12677.                 'poTagged' => $entry->getPoTagged(),
  12678.                 'typeHash' => $entry->getTypehash(),
  12679.                 'srIds' => $entry->getSrIds(),
  12680.                 'irIds' => $entry->getIrIds(),
  12681.                 'prIds' => $entry->getPrIds(),
  12682.                 'poIds' => $entry->getPoIds(),
  12683.             );
  12684.         }
  12685.         return $this->render('@Inventory/pages/views/pr_list.html.twig',
  12686.             array(
  12687.                 'page_title' => 'Purchase Requisition List',
  12688.                 'data' => $data
  12689.             )
  12690.         );
  12691.     }
  12692.     public
  12693.     function ServiceRequisitionListAction(Request $request)
  12694.     {
  12695.         $q $this->getDoctrine()
  12696.             ->getRepository('ApplicationBundle:PurchaseRequisition')
  12697.             ->findBy(
  12698.                 array(
  12699.                     'status' => GeneralConstant::ACTIVE,
  12700. //                    'approved' =>  GeneralConstant::APPROVED,
  12701.                 ),
  12702.                 array(
  12703.                     'purchaseRequisitionDate' => 'DESC'
  12704.                 )
  12705.             );
  12706.         $stage_list = array(
  12707.             => 'Pending',
  12708.             => 'Pending',
  12709.             => 'Complete',
  12710.             => 'Partial',
  12711.         );
  12712.         $data = [];
  12713.         foreach ($q as $entry) {
  12714.             $data[] = array(
  12715.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  12716.                 'id' => $entry->getPurchaseRequisitionId(),
  12717.                 'doc_hash' => $entry->getDocumentHash(),
  12718.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12719.                 'poTagged' => $entry->getPoTagged(),
  12720.                 'typeHash' => $entry->getTypehash(),
  12721.                 'srIds' => $entry->getSrIds(),
  12722.                 'irIds' => $entry->getIrIds(),
  12723.                 'prIds' => $entry->getPrIds(),
  12724.                 'poIds' => $entry->getPoIds(),
  12725.             );
  12726.         }
  12727.         return $this->render('@Inventory/pages/views/service_requisition_list.html.twig',
  12728.             array(
  12729.                 'page_title' => 'Service Requisition List',
  12730.                 'data' => $data
  12731.             )
  12732.         );
  12733.     }
  12734.     public
  12735.     function ViewPrAction(Request $request$id)
  12736.     {
  12737.         $em $this->getDoctrine()->getManager();
  12738.         $dt Inventory::GetPrDetails($em$id);
  12739.         $companyId $this->getLoggedUserCompanyId($request);
  12740.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  12741.             array(
  12742.                 'page_title' => 'Purchase Requisition',
  12743.                 'data' => $dt,
  12744.                 'branchList' => Client::BranchList($em$companyId),
  12745.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12746.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12747.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12748.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12749.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12750.                     $id,
  12751.                     $dt['created_by'],
  12752.                     $dt['edited_by'])
  12753.             )
  12754.         );
  12755.     }
  12756.     public
  12757.     function ViewServiceRequisitionAction(Request $request$id)
  12758.     {
  12759.         $em $this->getDoctrine()->getManager();
  12760.         $dt Inventory::GetPrDetails($em$id);
  12761.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  12762.             array(
  12763.                 'page_title' => 'Service Requisition',
  12764.                 'data' => $dt,
  12765.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12766.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12767.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12768.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12769.                     $id,
  12770.                     $dt['created_by'],
  12771.                     $dt['edited_by'])
  12772.             )
  12773.         );
  12774.     }
  12775.     public
  12776.     function PrintPrAction(Request $request$id)
  12777.     {
  12778.         $em $this->getDoctrine()->getManager();
  12779.         $dt Inventory::GetPrDetails($em$id);
  12780.         $companyId $this->getLoggedUserCompanyId($request);
  12781.         $company_data Company::getCompanyData($em$companyId);
  12782.         $document_mark = array(
  12783.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12784.             'copy' => ''
  12785.         );
  12786.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12787.             $html $this->renderView('@Inventory/pages/print/print_pr.html.twig',
  12788.                 array(
  12789.                     //full array here
  12790.                     'pdf' => true,
  12791.                     'page_title' => 'Purchase Requisition',
  12792.                     'export' => 'pdf,print',
  12793.                     'data' => $dt,
  12794.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12795.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12796.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12797.                         array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12798.                         $id,
  12799.                         $dt['created_by'],
  12800.                         $dt['edited_by']),
  12801.                     'document_mark_image' => $document_mark['original'],
  12802.                     'branchList' => Client::BranchList($em$companyId),
  12803.                     'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12804.                     'company_name' => $company_data->getName(),
  12805.                     'company_data' => $company_data,
  12806.                     'company_address' => $company_data->getAddress(),
  12807.                     'company_image' => $company_data->getImage(),
  12808.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12809.                     'red' => 0
  12810.                 )
  12811.             );
  12812.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12813. //                'orientation' => 'landscape',
  12814. //                'enable-javascript' => true,
  12815. //                'javascript-delay' => 1000,
  12816.                 'no-stop-slow-scripts' => false,
  12817.                 'no-background' => false,
  12818.                 'lowquality' => false,
  12819.                 'encoding' => 'utf-8',
  12820. //            'images' => true,
  12821. //            'cookie' => array(),
  12822.                 'dpi' => 300,
  12823.                 'image-dpi' => 300,
  12824. //                'enable-external-links' => true,
  12825. //                'enable-internal-links' => true
  12826.             ));
  12827.             return new Response(
  12828.                 $pdf_response,
  12829.                 200,
  12830.                 array(
  12831.                     'Content-Type' => 'application/pdf',
  12832.                     'Content-Disposition' => 'attachment; filename="purchase_requisition_' $id '.pdf"'
  12833.                 )
  12834.             );
  12835.         }
  12836.         return $this->render('@Inventory/pages/print/print_pr.html.twig',
  12837.             array(
  12838.                 'page_title' => 'Purchase Requisition',
  12839.                 'export' => 'pdf,print',
  12840.                 'data' => $dt,
  12841.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12842.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12843.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12844.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12845.                     $id,
  12846.                     $dt['created_by'],
  12847.                     $dt['edited_by']),
  12848.                 'document_mark_image' => $document_mark['original'],
  12849.                 'company_name' => $company_data->getName(),
  12850.                 'company_data' => $company_data,
  12851.                 'branchList' => Client::BranchList($em$companyId),
  12852.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12853.                 'company_address' => $company_data->getAddress(),
  12854.                 'company_image' => $company_data->getImage(),
  12855.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12856.                 'red' => 0
  12857.             )
  12858.         );
  12859.     }
  12860.     public
  12861.     function CreateSecondaryDeliveryReceiptAction(Request $request)
  12862.     {
  12863.         $em $this->getDoctrine()->getManager();
  12864.         $companyId $this->getLoggedUserCompanyId($request);
  12865.         $userBranchIdList $request->getSession()->get('branchIdList');
  12866.         if ($userBranchIdList == null$userBranchIdList = [];
  12867.         $userBranchId $request->getSession()->get('branchId');
  12868.         if ($request->isMethod('POST')) {
  12869.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  12870.             $dochash $request->request->get('docHash'); //change
  12871.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12872.             $approveRole 1;  //created
  12873.             $approveHash $request->request->get('approvalHash');
  12874.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  12875.                 $loginId$approveRole$approveHash)
  12876.             ) {
  12877.                 $this->addFlash(
  12878.                     'error',
  12879.                     'Sorry Couldnot insert Data.'
  12880.                 );
  12881.             } else {
  12882.                 $receiptId SalesOrderM::CreateNewSecondaryDeliveryReceipt($this->getDoctrine()->getManager(), $request->request,
  12883.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  12884.                     $this->getLoggedUserCompanyId($request));
  12885.                 //now add Approval info
  12886.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12887.                 $approveRole 1;  //created
  12888.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12889.                     $receiptId,
  12890.                     $loginId,
  12891.                     $approveRole,
  12892.                     $request->request->get('approvalHash'));
  12893.                 $options = array(
  12894.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  12895.                     'notification_server' => $this->container->getParameter('notification_server'),
  12896.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  12897.                     'url' => $this->generateUrl(
  12898.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  12899.                         ['entity_view_route_path_name']
  12900.                     )
  12901.                 );
  12902.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  12903.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12904.                     $receiptId,
  12905.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  12906.                 );
  12907.                 $this->addFlash(
  12908.                     'success',
  12909.                     'New Delivery Receipt Created'
  12910.                 );
  12911.                 $url $this->generateUrl(
  12912.                     'view_delivery_receipt'
  12913.                 );
  12914.                 return $this->redirect($url "/" $receiptId);
  12915.             }
  12916.         }
  12917.         $debugData = [];
  12918. //        $dr_data=$em->getRepository('ApplicationBundle:DeliveryReceipt')->findOneBy(
  12919. //            array(
  12920. //                'deliveryReceiptId'=>$dr_id
  12921. //            )
  12922. //        );
  12923.         $new_swld = new \DateTime('2017-07-09');
  12924. //        if ($entry->getWarranty() > 0)
  12925. //            $new_swld->modify('+' . $entry->getWarranty() . ' month');
  12926.         $debugData[] = $new_swld->format('Y-m-d');
  12927.         $debugData[] = $new_swld;
  12928. //        $debugData[]=$dr_data->getDeliveryReceiptDate();
  12929.         $debugData[] = '+' '1' ' month';
  12930.         $branchList Client::BranchList($em$companyId, [], $userBranchIdList);
  12931.         $warehouseIds = [];
  12932.         foreach ($branchList as $br) {
  12933.             $warehouseIds[] = $br['warehouseId'];
  12934.         }
  12935.         return $this->render('@Inventory/pages/input_forms/secondaryDeliveryReceipt.html.twig',
  12936.             array(
  12937.                 'page_title' => 'New Delivery Receipt',
  12938.                 'ExistingClients' => Accounts::getClientLedgerHeads($em),
  12939.                 'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($em),
  12940.                 'ClientList' => SalesOrderM::GetSecondaryClientList($em),
  12941.                 'warehouse' => Inventory::WarehouseList($em$companyId$warehouseIds),
  12942.                 'salesOrders' => SalesOrderM::SecondarySalesOrderListPendingDelivery($em$warehouseIds),
  12943.                 'salesOrdersArray' => SalesOrderM::SecondarySalesOrderListPendingDeliveryArray($em$warehouseIds),
  12944.                 'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
  12945.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
  12946.                 'debugData' => $debugData,
  12947.             )
  12948.         );
  12949.     }
  12950.     public
  12951.     function AddUnitTypeAction(Request $request$id 0)
  12952.     {
  12953.         $em $this->getDoctrine()->getManager();
  12954.         $companyId $this->getLoggedUserCompanyId($request);
  12955.         if ($request->isMethod('POST')) {
  12956.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12957.             $unitType = new UnitType();
  12958.             $unitType->setName($request->request->get('name'));
  12959.             $unitType->setStatus(1);
  12960.             $em->persist($unitType);
  12961.             $em->flush();
  12962.             $this->addFlash(
  12963.                 'success',
  12964.                 'Unit Type Added'
  12965.             );
  12966.         }
  12967.         $unitTypeDeatails $em->getRepository(UnitType::class)->findAll();
  12968.         return $this->render('@Inventory/pages/input_forms/addUnitType.html.twig',
  12969.             array(
  12970.                 'page_title' => 'Add Unit Type',
  12971.                 'unitTypeDeatails' => $unitTypeDeatails
  12972.             )
  12973.         );
  12974.     }
  12975.     public function AddSpecTypeAction(Request $request$id 0)
  12976.     {
  12977.         $em $this->getDoctrine()->getManager();
  12978.         $companyId $this->getLoggedUserCompanyId($request);
  12979.         if ($request->isMethod('POST')) {
  12980.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12981.             $specType = new SpecType();
  12982.             $specType->setName($request->request->get('name'));
  12983.             $specType->setStatus(1);
  12984.             $em->persist($specType);
  12985.             $em->flush();
  12986.             $this->addFlash(
  12987.                 'success',
  12988.                 'Spec Type Added'
  12989.             );
  12990.         }
  12991.         $specTypeDeatails $em->getRepository(SpecType::class)->findAll();
  12992.         return $this->render('@Inventory/pages/input_forms/addSpecType.html.twig',
  12993.             array(
  12994.                 'page_title' => 'Add Spec Type',
  12995.                 'specTypeDeatails' => $specTypeDeatails
  12996.             )
  12997.         );
  12998.     }
  12999.     public
  13000.     function SubcategoryListAction()
  13001.     {
  13002.         return $this->render('@Inventory/pages/input_forms/subCategoryList.html.twig',
  13003.             array(
  13004.                 'page_title' => 'Sub Category List',
  13005.             )
  13006.         );
  13007.     }
  13008.     public function SyncProductAction(Request $request$id)
  13009.     {
  13010.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  13011.         $em_local $this->getDoctrine()->getManager();
  13012.         if ($systemType == '_ERP_') {
  13013.             $product $em_local->getRepository('ApplicationBundle:InvProducts')->find($id);
  13014.             if (!$product) {
  13015.                 return new JsonResponse(['error' => 'Product not found'], 404);
  13016.             }
  13017.             // Get category details
  13018.             $category $em_local->getRepository('ApplicationBundle:InvProductCategories')->find($product->getCategoryId());
  13019.             $brand $em_local -> getRepository('ApplicationBundle:BrandCompany')->find($product->getBrandCompany());
  13020.             $productData = [];
  13021.             $categoryData = [];
  13022.             $brandData = [];
  13023.             // Get product fields
  13024.             $reflectionClass = new \ReflectionClass($product);
  13025.             foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  13026.                 if (strpos($method->getName(), 'get') === 0) {
  13027.                     $property lcfirst(str_replace('get'''$method->getName()));
  13028.                     $productData[$property] = $method->invoke($product);
  13029.                 }
  13030.             }
  13031.             // Get category fields
  13032.             if ($category) {
  13033.                 $categoryReflection = new \ReflectionClass($category);
  13034.                 foreach ($categoryReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  13035.                     if (strpos($method->getName(), 'get') === 0) {
  13036.                         $property lcfirst(str_replace('get'''$method->getName()));
  13037.                         $categoryData[$property] = $method->invoke($category);
  13038.                     }
  13039.                 }
  13040.             }
  13041.             // Brand data
  13042.             if ($brand) {
  13043.                 $brandReflection = new \ReflectionClass($brand);
  13044.                 foreach ($brandReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  13045.                     if (strpos($method->getName(), 'get') === 0) {
  13046.                         $property lcfirst(str_replace('get'''$method->getName()));
  13047.                         $brandData[$property] = $method->invoke($brand);
  13048.                     }
  13049.                 }
  13050.             }
  13051.             // Store product data in pending_data
  13052.             $product->setPendingData(json_encode($productData));
  13053.             $em_local->flush();
  13054.             // Send  product,brand & category to central
  13055.             $syncData = [
  13056.                 'product' => $productData,
  13057.                 'category' => $categoryData,
  13058.                 'brand' => $brandData
  13059.             ];
  13060.             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/product_sync/' $id;
  13061.             $curl curl_init();
  13062.             curl_setopt_array($curl, [
  13063.                 CURLOPT_RETURNTRANSFER => true,
  13064.                 CURLOPT_POST => true,
  13065.                 CURLOPT_URL => $urlToCall,
  13066.                 CURLOPT_CONNECTTIMEOUT => 10,
  13067.                 CURLOPT_SSL_VERIFYPEER => false,
  13068.                 CURLOPT_SSL_VERIFYHOST => false,
  13069.                 CURLOPT_HTTPHEADER => [],
  13070.                 CURLOPT_POSTFIELDS => ['syncData' => json_encode($syncData)]
  13071.             ]);
  13072.             $retData curl_exec($curl);
  13073.             $errData curl_error($curl);
  13074.             curl_close($curl);
  13075.             if ($errData) {
  13076.                 return new JsonResponse(['error' => $errData], 500);
  13077.             }
  13078.             $retDataObj json_decode($retDatatrue);
  13079.             if (isset($retDataObj['globalId'])) {
  13080.                 $product->setGlobalId($retDataObj['globalId']);
  13081.                 $em_local->flush();
  13082.             }
  13083.             return new JsonResponse(['message' => 'Product (pending) and category synced to central server!']);
  13084.         }
  13085.         // CENTRAL SYSTEM PROCESSING
  13086.         else if ($systemType == '_CENTRAL_') {
  13087.             $requestData $request->get('syncData');
  13088.             if (!$requestData) {
  13089.                 return new JsonResponse(['error' => 'Invalid data received'], 400);
  13090.             }
  13091.             $requestData json_decode($requestDatatrue);
  13092.             $productData $requestData['product'] ?? null;
  13093.             $categoryData $requestData['category'] ?? null;
  13094.             $brandData $requestData['brand'] ?? null;
  13095.             if (!$productData) {
  13096.                 return new JsonResponse(['error' => 'Product data missing'], 400);
  13097.             }
  13098.             // Process product (Store in pending_data)
  13099.             $product $em_local->getRepository('ApplicationBundle:InvProducts')->find($productData['id']) ?? new InvProducts();
  13100.             // Store in pending_data until approval
  13101.             $product->setPendingData(json_encode($productData));
  13102.             $this->ApproveProductAction($id);
  13103.             $em_local->persist($product);
  13104.             // Process category (Save directly)
  13105.             if ($categoryData) {
  13106.                 $category $em_local->getRepository('ApplicationBundle:InvProductCategories')->find($categoryData['id']) ?? new InvProductCategories();
  13107.                 foreach ($categoryData as $field => $value) {
  13108.                     if ($field === 'id') continue;
  13109.                     $setterMethod 'set' ucfirst($field);
  13110.                     if (method_exists($category$setterMethod)) {
  13111.                         $category->$setterMethod($value);
  13112.                     }
  13113.                 }
  13114.                 $em_local->persist($category);
  13115.             }
  13116.             // process brand data
  13117.             if($brandData){
  13118.                 $brand $em_local->getRepository('ApplicationBundle:BrandCompany')->find($brandData['id']) ?? new BrandCompany();
  13119.                 foreach ($brandData as $field => $value){
  13120.                     if($field === 'id') continue;
  13121.                     $setterMethod 'set'.ucfirst($field);
  13122.                     if(method_exists($brand,$setterMethod)){
  13123.                         $brand->$setterMethod($value);
  13124.                     }
  13125.                 }
  13126.                 $em_local->persist($brand);
  13127.             }
  13128.             $em_local->flush();
  13129.             return new JsonResponse(['globalId' => $product->getId()]);
  13130.         }
  13131.         return new JsonResponse("Product (pending) and category updated successfully in central!");
  13132.     }
  13133.     public function ApproveProductAction($id)
  13134.     {
  13135.         $em $this->getDoctrine()->getManager();
  13136.         $product $em->getRepository('ApplicationBundle:InvProducts')->find($id);
  13137.         if (!$product) {
  13138.             return new JsonResponse(['error' => 'Product not found'], 404);
  13139.         }
  13140.         $pendingData $product->getPendingData();
  13141.         if (!$pendingData) {
  13142.             return new JsonResponse(['error' => 'No pending data found for this product'], 400);
  13143.         }
  13144.         $data json_decode($pendingDatatrue);
  13145.         if (!$data || !is_array($data)) {
  13146.             return new JsonResponse(['error' => 'Invalid pending data format'], 400);
  13147.         }
  13148.         // Populate actual fields
  13149.         foreach ($data as $field => $value) {
  13150.             if ($field === 'id') continue; // Skip ID
  13151.             $setter 'set' ucfirst($field);
  13152.             if (method_exists($product$setter)) {
  13153.                 $product->$setter($value);
  13154.             }
  13155.         }
  13156.         $product->setPendingData(null); // Clear pending data
  13157.         $em->flush();
  13158.         return new JsonResponse(['message' => 'Product approved and data applied successfully!']);
  13159.     }
  13160. }