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 GetRefreshedItemAction(Request $request$type 0)
  149.     {
  150.         $em $this->getDoctrine()->getManager();
  151.         $companyId $this->getLoggedUserCompanyId($request);
  152.         $productListArray = [];
  153.         $subCategoryListArray = [];
  154.         $categoryListArray = [];
  155.         $igListArray = [];
  156.         $unitListArray = [];
  157.         $skipProductList $request->request->has('skipProductList') ? $request->request->get('skipProductList') : 0;
  158.         $productList = ($skipProductList == 1) ? [] : Inventory::ProductList($em$companyId$type);
  159.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  160.         $categoryList Inventory::ProductCategoryList($em$companyId);
  161.         $igList Inventory::ItemGroupList($em$companyId);
  162.         $unitList Inventory::UnitTypeList($em);
  163.         $brandList Inventory::GetBrandList($em$companyId);
  164.         foreach ($productList as $product) {
  165.             $productListArray[] = $product;
  166.         }
  167.         foreach ($categoryList as $product) {
  168.             $categoryListArray[] = $product;
  169.         }
  170.         foreach ($subCategoryList as $product) {
  171.             $subCategoryListArray[] = $product;
  172.         }
  173.         foreach ($igList as $product) {
  174.             $igListArray[] = $product;
  175.         }
  176.         foreach ($unitList as $product) {
  177.             $unitListArray[] = $product;
  178.         }
  179.         $brandListArray = [];
  180.         foreach ($brandList as $product) {
  181.             $brandListArray[] = $product;
  182.         }
  183.         $qry $em->getRepository("ApplicationBundle:AccService")->findBy(array(
  184.             "status" => GeneralConstant::ACTIVE,
  185.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  186. //            'type'=>1//trade items
  187.         ));
  188.         $sl = [];
  189.         $sl_array = [];
  190.         foreach ($qry as $product) {
  191.             $sl[$product->getServiceId()] = array(
  192.                 'text' => $product->getServiceName(),
  193.                 'value' => $product->getServiceId(),
  194.                 'name' => $product->getServiceName(),
  195.                 'id' => $product->getServiceId(),
  196.             );
  197.             $sl_array[] = array(
  198.                 'text' => $product->getServiceName(),
  199.                 'value' => $product->getServiceId(),
  200.                 'name' => $product->getServiceName(),
  201.                 'id' => $product->getServiceId(),
  202.             );
  203.         }
  204.         $hl Accounts::HeadList($em);
  205.         $hl_array Accounts::getParentLedgerHeads($em"""", [], 1$this->getLoggedUserCompanyId($request));
  206.         return new JsonResponse(
  207.             array(
  208. //                'page_title'=>'BOM',
  209. //                'clients'=>SalesOrderM::GetClientList($em),
  210. //                'clients_by_ac_head'=>SalesOrderM::GetClientListByAcHead($em),
  211.                 'productList' => $productList,
  212.                 'subCategoryList' => $subCategoryList,
  213.                 'categoryList' => $categoryList,
  214.                 'igList' => $igList,
  215.                 'unitList' => $unitList,
  216.                 'brandList' => $brandList,
  217.                 'productListArray' => $productListArray,
  218.                 'subCategoryListArray' => $subCategoryListArray,
  219.                 'categoryListArray' => $categoryListArray,
  220.                 'igListArray' => $igListArray,
  221.                 'unitListArray' => $unitListArray,
  222.                 'brandListArray' => $brandListArray,
  223.                 "success" => true,
  224.                 'users' => Users::getUserListById($em),
  225.                 'stages' => ProjectConstant::$projectStages,
  226.                 'sl' => $sl,
  227.                 'hl' => $hl,
  228.                 'hl_array' => $hl_array,
  229.                 'sl_array' => $sl_array,
  230. //                'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
  231.             )
  232.         );
  233.     }
  234.     public function GetProductListForMisAction(Request $request)
  235.     {
  236.         $em $this->getDoctrine()->getManager();
  237.         $productIds $request->query->get('productId');
  238.         $fdmList = [];
  239.         $find_array = array('id' => $productIds);
  240.         if ($request->query->get('fdmList')) {
  241.             $find_array = array();
  242.             $fdmList $productIds $request->query->get('fdmList');
  243.         }
  244. //            $find_array=array('id' =>  $productIds);
  245.         $products $this->getDoctrine()
  246.             ->getRepository('ApplicationBundle:InvProducts')
  247.             ->findBy(
  248.                 $find_array
  249.             );
  250.         $productList = [];
  251.         $productListForShow = [];
  252.         foreach ($products as $entry) {
  253.             $productList[$entry->getId()] = array(
  254.                 'id' => $entry->getId(),
  255.                 'name' => $entry->getName(),
  256.                 'fdm' => $entry->getProductFdm(),
  257.             );
  258.         }
  259.         $products_in_stock $this->getDoctrine()
  260.             ->getRepository('ApplicationBundle:InventoryStorage')
  261.             ->findBy(
  262.                 $find_array
  263.             );
  264.         $warehouseList Inventory::WarehouseList($em);
  265.         if (!empty($fdmList)) {
  266.             foreach ($products_in_stock as $dt) {
  267. //            if()
  268.                 $matched_a_product 0;
  269.                 foreach ($fdmList as $fdm) {
  270.                     $matchFdm Inventory::MatchFdm($fdm$productList[$dt->getProductId()]['fdm']);
  271.                     if ($matchFdm['hasMatched'] == 1) {
  272.                         if ($matchFdm['isIdentical'] == || $matchFdm['FirstBelongsToSecond'] == 1) {
  273.                             $matched_a_product 1;
  274.                             if (isset($productListForShow[$dt->getProductId()])) {
  275.                             } else {
  276.                                 $productListForShow[$dt->getProductId()] = array(
  277.                                     'id' => $productList[$dt->getProductId()]['id'],
  278.                                     'name' => $productList[$dt->getProductId()]['name'],
  279.                                     'fdm' => $productList[$dt->getProductId()]['fdm'],
  280.                                 );
  281.                             }
  282.                             if (isset($productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  283.                                 $productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  284.                             else {
  285.                                 $productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  286.                             }
  287.                             break;
  288.                         }
  289.                     }
  290.                 }
  291.                 if ($matched_a_product == 0) {
  292.                     continue;
  293.                 }
  294.                 if (isset($productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  295.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  296.                 else
  297.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  298.             }
  299.         } else {
  300.             foreach ($products_in_stock as $dt) {
  301. //            if()
  302.                 if (isset($productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  303.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  304.                 else
  305.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  306.             }
  307.             $productListForShow $productList;
  308.         }
  309.         $engine $this->container->get("templating");
  310. //        $SD=Supplier::GetSupplierDetailsForMis($em,$supplier_id);
  311.         if ($productList) {
  312.             $Content $engine->render('@Inventory/pages/report/selected_item_stock.html.twig', array("productList" => $productListForShow'warehouseList' => $warehouseList));
  313.             return new JsonResponse(array("success" => true"content" => $Content'productListForShow' => $productListForShow));
  314.         }
  315.         return new JsonResponse(array("success" => false));
  316.     }
  317.     public function CreateProductAction(Request $request$id 0)
  318.     {
  319.         $ex_id 0;
  320.         $prod_det = [];
  321.         $product_duplicate 0;
  322.         $group_type 1;//item
  323.         $em $this->getDoctrine()->getManager();
  324.         $companyId $this->getLoggedUserCompanyId($request);
  325.         $route $request->get('_route');
  326.         if ($route == 'create_service')
  327.             $group_type 2;//service
  328.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  329.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  330.         if ($request->isMethod('POST')) {
  331.             if ($id == 0)
  332.                 $id $request->request->has('ex_id') ? $request->request->get('ex_id') : 0;
  333.             if ($id == 0) {
  334.                 if ($group_type == 2)
  335.                     $ext_pr $this->getDoctrine()
  336.                         ->getRepository('ApplicationBundle:AccService')
  337.                         ->findOneBy(
  338.                             array(
  339.                                 'serviceName' => $request->request->get('name'),
  340.                             )
  341.                         );
  342.                 else
  343.                     $ext_pr $this->getDoctrine()
  344.                         ->getRepository('ApplicationBundle:InvProducts')
  345.                         ->findOneBy(
  346.                             array(
  347.                                 'name' => $request->request->get('name'),
  348.                             )
  349.                         );
  350.                 if ($ext_pr)
  351.                     $product_duplicate 1;
  352.             }
  353.             if ($product_duplicate == 1) {
  354.                 $this->addFlash(
  355.                     'error',
  356.                     'Duplicate Entry Found'
  357.                 );
  358.             } else {
  359.                 $image_list = [];
  360.                 $defaultImage "";
  361.                 $defaultImageUploadedFile null;
  362.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  363.                 if ($group_type == 2) {
  364.                     $ig $this->getDoctrine()
  365.                         ->getRepository('ApplicationBundle:InvItemGroup')
  366.                         ->findOneBy(
  367.                             array(
  368.                                 'id' => $request->request->get('itemgroupId')
  369.                             )
  370.                         );
  371.                     $defaultPurchaseActionTagId $request->request->get('defaultPurchaseActionTagId''');
  372.                     $ledgerHitAs $request->request->get('ledgerHitAs''');
  373.                     $defaultExpenseId $request->request->get('defaultExpenseId''');
  374.                     Inventory::CreateNewService(
  375.                         $this->getDoctrine()->getManager(),
  376.                         $request->request->get('ex_id'),
  377.                         $request->request->get('name'),
  378.                         $companyId,
  379.                         $request->request->get('typeId'),
  380.                         $request->request->get('categoryId'),
  381.                         $request->request->get('brandCompany'),
  382.                         $request->request->get('subCategoryId'),
  383.                         $request->request->get('itemgroupId'),
  384.                         $request->request->get('unitTypeId'),
  385.                         $request->request->get('note'),
  386.                         $request->request->get('alias'''),
  387.                         $request->request->get('categorization_1'''),
  388.                         $request->request->get('categorization_2'''),
  389.                         $request->request->get('categorization_3'''),
  390.                         $request->request->get('categorization_4'''),
  391.                         $request->request->get('purchasePrice'0),
  392.                         $request->request->get('salesPrice'0),
  393.                         $request->request->get('productFdm'''),
  394.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  395.                         ($ledgerHitAs != '') ? $ledgerHitAs $ig->getLedgerHitAs(),
  396.                         ($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId $ig->getDefaultPurchaseActionTagId(),
  397.                         ($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId $ig->getDefaultExpenseId()
  398.                     );
  399.                     $this->addFlash(
  400.                         'success',
  401.                         'Service Have Been Added/Updated'
  402.                     );
  403.                 } else {
  404.                     $ig $this->getDoctrine()
  405.                         ->getRepository('ApplicationBundle:InvItemGroup')
  406.                         ->findOneBy(
  407.                             array(
  408.                                 'id' => $request->request->get('itemgroupId')
  409.                             )
  410.                         );
  411.                     $defaultPurchaseActionTagId $request->request->get('defaultPurchaseActionTagId''');
  412.                     $ledgerHitAs $request->request->get('ledgerHitAs''');
  413.                     $defaultExpenseId $request->request->get('defaultExpenseId''');
  414.                     $crateData = [];
  415.                     foreach ($request->request->get('product_crate', []) as $crateIndex => $crateId) {
  416.                         $crateData[] = array(
  417.                             'id' => $crateId,
  418.                             'qty' => $request->request->get('product_qty', [])[$crateIndex],
  419.                         );
  420.                     }
  421.                     $specData = [];
  422.                     foreach ($request->request->get('spec', []) as $specIndex => $specId) {
  423.                         $specData[] = array(
  424.                             'id' => $specId,
  425.                             'value' => $request->request->get('spec_value', [])[$specIndex],
  426.                         );
  427.                     }
  428.                     $sizesData = [];
  429.                     foreach ($request->request->get('product_size', []) as $sizeIndex => $crateId) {
  430.                         $sizesData[] = array(
  431.                             'size' => $request->request->get('product_size', [])[$sizeIndex],
  432.                             'dimension' => $request->request->get('product_dimension', [])[$sizeIndex],
  433.                             'dimensionUnitType' => $request->request->get('product_dimension_unit_type', [])[$sizeIndex],
  434.                             'weight' => $request->request->get('product_weight', [])[$sizeIndex],
  435.                             'weightUnitType' => $request->request->get('product_weight_unit_type', [])[$sizeIndex],
  436.                         );
  437.                     }
  438.                     Inventory::CreateNewProduct(
  439.                         $this->getDoctrine()->getManager(),
  440.                         $request->request->get('ex_id'0),
  441.                         $request->request->get('name'''),
  442.                         $request->request->get('model_no'''),
  443.                         $this->getLoggedUserCompanyId($request),
  444.                         $request->request->get('typeId'1),
  445.                         $request->request->get('categoryId'null),
  446.                         $request->request->get('hasSerial'null),
  447.                         $ig->getDraccountsHeadId(),
  448.                         $ig->getCraccountsHeadId(),
  449.                         ($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId $ig->getDefaultPurchaseActionTagId(),
  450.                         $ig->getVatAsExpenseFlag(),
  451.                         $request->request->get('brandCompany'null),
  452.                         $request->request->get('subCategoryId'null),
  453.                         $request->request->get('yearlyDepreciation'0),
  454.                         $request->request->get('purchaseWarrantyMonths'0),
  455.                         $request->request->get('salesWarrantyMonths'0),
  456.                         $request->request->get('startingBalanceUnit'0),
  457.                         $request->request->get('reorderLevel'0),
  458.                         $request->request->get('note'''),
  459.                         $request->request->get('alias'''),
  460.                         $request->request->get('itemgroupId'null),
  461.                         $request->request->get('unitTypeId'null),
  462.                         $request->request->get('hsCode'''),
  463.                         $request->request->get('skuCode'''),
  464.                         $request->files->get('dataSheets', []),
  465.                         $request->request->get('partId'''),
  466.                         $request->request->get('productCode'''),
  467.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  468.                         $request->request->get('purchasePrice'0),
  469.                         $request->request->get('salesPrice'0),
  470.                         $request->files->get('product_default_image'null),
  471.                         $upl_dir,
  472.                         $request->files->get('product_images', []),
  473.                         $request->request->get('expiryDays'0),
  474.                         $request->request->get('dimension'''),
  475.                         $request->request->get('dimensionUnitTypeId'0),
  476.                         $request->request->get('productFdm'''),
  477.                         $request->request->get('weight'''),
  478.                         $request->request->get('weightUnitTypeId'0),
  479.                         $request->request->get('specification'null),
  480.                         $request->request->get('ingredient'null),
  481.                         $request->request->get('nutrition'null),
  482.                         $request->request->get('segregatePriceByColorsFlag'null),
  483.                         $request->request->get('segregatePriceBySizesFlag'null),
  484.                         $request->request->get('categorization_1'''),
  485.                         $request->request->get('categorization_2'''),
  486.                         $request->request->get('categorization_3'''),
  487.                         $request->request->get('categorization_4'''),
  488.                         $request->request->get('weightVarianceValue'0),
  489.                         $request->request->get('weightVarianceType'0),
  490.                         $request->request->get('singleWeight'''),
  491.                         $request->request->get('singleWeightUnitTypeId'0),
  492.                         $request->request->get('singleWeightVarianceValue'0),
  493.                         $request->request->get('singleWeightVarianceType'0),
  494.                         $request->request->get('cartonWeightVarianceValue'0),
  495.                         $request->request->get('cartonWeightVarianceType'0),
  496.                         $request->request->get('cartonCapacityCount'0),
  497.                         $request->request->get('tac'''),
  498.                         $request->request->get('sellable'0),
  499.                         $request->request->get('abstract'0),
  500.                         $request->request->get('tags'''),
  501.                         $request->request->get('markerFlags'''),
  502.                         $request->request->get('defaultColorId'0),
  503.                         $request->request->get('product_color', []),
  504.                         $request->request->get('product_size', []),
  505.                         ($ledgerHitAs != '') ? $ledgerHitAs $ig->getLedgerHitAs(),
  506.                         ($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId $ig->getDefaultExpenseId(),
  507.                         $crateData,
  508.                         $sizesData,
  509.                         $specData
  510.                     );
  511.                     $this->addFlash(
  512.                         'success',
  513.                         'Product Have Been Added/Updated'
  514.                     );
  515.                 }
  516.             }
  517.             if ($request->request->has('returnJson')) {
  518.                 return new JsonResponse(array(
  519.                     'success' => true
  520.                 ));
  521.             }
  522.             if ($group_type == 2)
  523.                 return $this->redirectToRoute("create_service");
  524.             else
  525.                 return $this->redirectToRoute("create_product");
  526.         }
  527.         if ($id != 0) {
  528.             $ex_id $id;
  529.             if ($group_type == 2)
  530.                 $prod_det $this->getDoctrine()->getRepository('ApplicationBundle:AccService')->findOneBy(array(
  531.                     'serviceId' => $id//for now for stock of goods
  532. //                    'opening_locked'=>0
  533.                 ));
  534.             else
  535.                 $prod_det $this->getDoctrine()->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
  536.                     'id' => $id//for now for stock of goods
  537. //                    'opening_locked'=>0
  538.                 ));
  539.         }
  540.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  541.             'name' => 'warehouse_action_1'//for now for stock of goods
  542.         ));
  543.         return $this->render('@Inventory/pages/input_forms/create_product.html.twig',
  544.             array(
  545.                 'page_title' => $group_type == 'Service Entry' 'Product Entry',
  546.                 'group_type' => $group_type,
  547.                 'inv_head' => $inv_head $inv_head->getData() : '',
  548. //                'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  549.                 'services' => Inventory::ServiceList($this->getDoctrine()->getManager()),
  550.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  551.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  552.                 'itemgroup' => Inventory::ItemGroupList($em$companyId$group_type),
  553.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  554.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  555.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager(), 1),
  556.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  557.                 'ex_id' => $ex_id,
  558.                 'warehouse_action_list' => $warehouse_action_list,
  559.                 'warehouse_action_list_array' => $warehouse_action_list_array,
  560.                 'markerFlags' => InventoryConstant::$SPECIAL_MARKER_ARRAY,
  561.                 'ex_prod_det' => $prod_det
  562.             )
  563.         );
  564.     }
  565.     public function ProductListAction(Request $request)
  566.     {
  567.         $em $this->getDoctrine()->getManager();
  568.         $companyId $this->getLoggedUserCompanyId($request);
  569.         $listData Inventory::GetProductListForProductListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  570.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  571.             if ($request->query->has('dataTableQry')) {
  572.                 return new JsonResponse(
  573.                     $listData
  574.                 );
  575.             }
  576.         }
  577.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  578.             'name' => 'warehouse_action_1'//for now for stock of goods
  579.         ));
  580.         return $this->render('@Inventory/pages/views/product_list.html.twig',
  581.             array(
  582.                 'page_title' => 'Product List',
  583.                 'inv_head' => $inv_head $inv_head->getData() : '',
  584. //                'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  585.                 'products' => [],
  586.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  587.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  588.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  589.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  590.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  591. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  592.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  593.             )
  594.         );
  595.     }
  596.     public function SalesVsDeliveryListAction(Request $request)
  597.     {
  598.         $em $this->getDoctrine()->getManager();
  599.         $session $request->getSession();
  600.         $userType $session->get(UserConstants::USER_TYPE);
  601.         $userId $session->get(UserConstants::USER_ID);
  602.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  603.             'approved' => GeneralConstant::APPROVED,
  604. //            'stage' => GeneralConstant::STAGE_PENDING
  605.         );
  606.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  607.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  608.         }
  609. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  610. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  611. //            $selectiveDocumentsFlag=1; //by default will show only selective
  612. //            if(isset($userRestrictions['canSeeAllSo'])) {
  613. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  614. //                    $selectiveDocumentsFlag = 0;
  615. //                }
  616. //            }
  617. //
  618. //            if($selectiveDocumentsFlag==1)
  619. //            {
  620. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  621. //            }
  622. //        }
  623.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  624.             'name' => 'warehouse_action_1'//for now for stock of goods
  625.         ));
  626.         if ($request->query->has('queryDate')) {
  627.             $date = new \DateTime($request->query->get('queryDate'));
  628.         } else {
  629.             $today = new \DateTime();
  630.             $todayStr $today->format('Y-m-d');
  631.             $date = new \DateTime($todayStr);
  632.         }
  633.         $orderQryArray['salesOrderDate'] = $date;
  634.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrder')->findBy($orderQryArray);
  635.         $so_ids = [];
  636.         $so_data = [];
  637.         $so_item_ids = [];
  638.         $so_item_data = [];
  639.         foreach ($salesOrders as $salesOrder) {
  640.             if ($salesOrder->getSalesOrderDate() > $date)
  641.                 continue;
  642.             $so_ids[] = $salesOrder->getSalesOrderId();
  643.             $so_data[$salesOrder->getSalesOrderId()] = array(
  644.                 "id" => $salesOrder->getSalesOrderId(),
  645.                 "documentHash" => $salesOrder->getDocumentHash(),
  646.                 "clientId" => $salesOrder->getClientId(),
  647.             );
  648.         }
  649.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrderItem')->findBy(array(
  650.             'salesOrderId' => $so_ids,
  651.         ));
  652.         foreach ($salesOrderItems as $salesOrderItem) {
  653.             $so_item_ids[] = $salesOrderItem->getId();
  654.             $so_item_data[$salesOrderItem->getId()] = array(
  655.                 "id" => $salesOrderItem->getId(),
  656.                 "productId" => $salesOrderItem->getProductId(),
  657.                 "productName" => $salesOrderItem->getProductNameFdm(),
  658.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  659.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  660.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  661. //                "documentHash"=>$salesOrder->getDocumentHash(),
  662.                 "qty" => $salesOrderItem->getQty(),
  663.                 "transitQty" => $salesOrderItem->getTransitQty(),
  664.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  665.             );
  666.         }
  667.         return $this->render('@Inventory/pages/views/sales_vs_delivery_status.html.twig',
  668.             array(
  669.                 'page_title' => 'Order Vs. Disperse',
  670.                 'inv_head' => $inv_head $inv_head->getData() : '',
  671.                 'so_data' => $so_data,
  672.                 'queryDate' => $date,
  673.                 'so_item_data' => $so_item_data,
  674.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  675.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  676.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  677.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  678.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  679.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  680.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  681. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  682.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  683.             )
  684.         );
  685.     }
  686.     public function DeliveryPendingOrderListAction(Request $request)
  687.     {
  688.         $em $this->getDoctrine()->getManager();
  689.         $session $request->getSession();
  690.         $userType $session->get(UserConstants::USER_TYPE);
  691.         $userId $session->get(UserConstants::USER_ID);
  692.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  693.             'approved' => GeneralConstant::APPROVED,
  694.             'stage' => GeneralConstant::STAGE_PENDING
  695.         );
  696.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  697.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  698.         }
  699. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  700. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  701. //            $selectiveDocumentsFlag=1; //by default will show only selective
  702. //            if(isset($userRestrictions['canSeeAllSo'])) {
  703. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  704. //                    $selectiveDocumentsFlag = 0;
  705. //                }
  706. //            }
  707. //
  708. //            if($selectiveDocumentsFlag==1)
  709. //            {
  710. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  711. //            }
  712. //        }
  713.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  714.             'name' => 'warehouse_action_1'//for now for stock of goods
  715.         ));
  716.         if ($request->query->has('queryDate')) {
  717.             $date = new \DateTime($request->query->get('queryDate'));
  718.         } else {
  719.             $today = new \DateTime();
  720.             $todayStr $today->format('Y-m-d');
  721.             $date = new \DateTime($todayStr);
  722.         }
  723. //        $orderQryArray['salesOrderDate'] = $date;
  724.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrder')->findBy($orderQryArray);
  725.         $so_ids = [];
  726.         $so_data = [];
  727.         $so_item_ids = [];
  728.         $so_item_data = [];
  729.         foreach ($salesOrders as $salesOrder) {
  730.             if ($salesOrder->getSalesOrderDate() > $date)
  731.                 continue;
  732.             $so_ids[] = $salesOrder->getSalesOrderId();
  733.             $so_data[$salesOrder->getSalesOrderId()] = array(
  734.                 "id" => $salesOrder->getSalesOrderId(),
  735.                 "documentHash" => $salesOrder->getDocumentHash(),
  736.                 "clientId" => $salesOrder->getClientId(),
  737.             );
  738.         }
  739.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrderItem')->findBy(array(
  740.             'salesOrderId' => $so_ids,
  741.         ));
  742.         foreach ($salesOrderItems as $salesOrderItem) {
  743.             $so_item_ids[] = $salesOrderItem->getId();
  744.             $so_item_data[$salesOrderItem->getId()] = array(
  745.                 "id" => $salesOrderItem->getId(),
  746.                 "productId" => $salesOrderItem->getProductId(),
  747.                 "productName" => $salesOrderItem->getProductNameFdm(),
  748.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  749.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  750.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  751. //                "documentHash"=>$salesOrder->getDocumentHash(),
  752.                 "qty" => $salesOrderItem->getQty(),
  753.                 "transitQty" => $salesOrderItem->getTransitQty(),
  754.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  755.             );
  756.         }
  757.         return $this->render('@Inventory/pages/views/delivery_pending_order_list.html.twig',
  758.             array(
  759.                 'page_title' => 'Pending Delivery',
  760.                 'inv_head' => $inv_head $inv_head->getData() : '',
  761.                 'so_data' => $so_data,
  762.                 'queryDate' => $date,
  763.                 'so_item_data' => $so_item_data,
  764.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  765.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  766.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  767.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  768.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  769.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  770.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  771. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  772.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  773.             )
  774.         );
  775.     }
  776.     public function ItemGroupAction(Request $request$id 0)
  777.     {
  778.         $ex_id 0;
  779.         $det = [];
  780.         $em $this->getDoctrine()->getManager();
  781.         $companyId $this->getLoggedUserCompanyId($request);
  782.         $group_type 1;//item
  783.         $route $request->get('_route');
  784.         if ($route == 'service_group')
  785.             $group_type 2;//service
  786.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  787.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  788.         if ($request->isMethod('POST')) {
  789.             Inventory::CreateItemGroup($this->getDoctrine()->getManager(),
  790.                 $request->request->get('ex_id'),
  791.                 $this->getLoggedUserCompanyId($request),
  792.                 $request->request,
  793.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  794.         }
  795.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  796.             'name' => 'warehouse_action_1'//for now for stock of goods
  797.         ));
  798.         if ($id != 0) {
  799.             $ex_id $id;
  800.             $det $this->getDoctrine()->getRepository('ApplicationBundle:InvItemGroup')->findOneBy(array(
  801.                 'id' => $id//for now for stock of goods
  802. //                    'opening_locked'=>0
  803.             ));
  804.         }
  805.         return $this->render('@Inventory/pages/input_forms/item_group.html.twig',
  806.             array(
  807.                 'page_title' => $group_type == "Item Groups" "Service Groups",
  808.                 'inv_head' => $inv_head $inv_head->getData() : '',
  809.                 'group_type' => $group_type,
  810.                 'igList' => Inventory::ItemGroupList($em$companyId$group_type),
  811.                 'warehouse_action_list' => $warehouse_action_list,
  812. //                'data'=>Inventory::ItemGroupFormRelatedData($this->getDoctrine()->getManager()),
  813.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  814.                 'ex_id' => $ex_id,
  815.                 'ex_det' => $det
  816.             )
  817.         );
  818.     }
  819.     public function addStartingOpeningInOutAction(Request $request$refreshed_opening 0)
  820.     {
  821.         //be very careful!!
  822.         $em $this->getDoctrine()->getManager();
  823. //        $last_refresh_date="";
  824.         //steps
  825.         //1. set all inventory to their opening position
  826.         $assign_list = array();
  827.         $data = array();
  828.         if ($refreshed_opening == 0) {
  829.             $new_cc $em
  830.                 ->getRepository('ApplicationBundle:AccSettings')
  831.                 ->findOneBy(
  832.                     array(
  833.                         'name' => 'accounting_year_start',
  834.                     )
  835.                 );
  836.             $date_start = new \DateTime($new_cc->getData());
  837.             $date_start_str $date_start->format('Y-m-d');
  838.             $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  839. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  840.             $stmt $em->getConnection()->prepare($closingQuery);
  841.             $stmt->execute();
  842.             $iniClosing $stmt->fetchAll();
  843. //                $stmt = $em->getConnection()->prepare($transQuery);
  844. //                $stmt->execute();
  845. //                $iniTrans = $stmt->fetchAll();
  846.             $singleClosing_byProductId = array();
  847.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  848.             foreach ($iniClosing as $item) {
  849.                 if (!isset($singleClosing_byProductId[$item['product_id']])) {
  850.                     $singleClosing_byProductId[$item['product_id']] = array(
  851.                         'date' => $item['date'],
  852.                         'qtyAdd' => $item['qty_addition'],
  853.                         'qtySub' => '0',
  854.                         'valueAdd' => $item['addition'],
  855.                         'valueSub' => '0',
  856.                         'fromWarehouse' => 0,
  857.                         'toWarehouse' => $item['warehouse_id'],
  858.                         'fromWarehouseSub' => 0,
  859.                         'toWarehouseSub' => $item['action_tag_id'],
  860.                         'price' => ($item['addition'] / $item['qty_addition'])
  861.                     );
  862.                 }
  863.             }
  864.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  865. //                foreach ($iniTrans as $item) {
  866. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  867. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  868. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  869. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  870. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  871. //                    }
  872. //                }
  873.             foreach ($singleClosing_byProductId as $key => $item) {
  874.                 if (!isset($data[$key])) {
  875.                     $data[$key][] = $item;
  876.                 }
  877.             }
  878.             //now that we go the data we can empty the closing table
  879. //                $get_kids_sql ='UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  880. //    truncate `inv_closing_balance`;
  881. //    truncate `inventory_storage`;
  882. //    truncate `inv_item_transaction`;';
  883. //                $stmt = $em->getConnection()->prepare($get_kids_sql);
  884. //                $stmt->execute();
  885. //                $stmt->closeCursor();
  886. //                $stmt->fetchAll();
  887.             $total_inv_value_in 0;
  888.             foreach ($data as $key => $item) {
  889.                 if (!empty($item)) {
  890.                     foreach ($item as $entry) {
  891.                         $transDate = new \DateTime($entry['date']);
  892.                         $new = new InvItemInOut();
  893.                         $new->setProductId($key);
  894.                         $new->setWarehouseId($entry['toWarehouse']);
  895.                         $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  896.                         $new->setActionTagId($entry['toWarehouseSub']);
  897.                         $new->setTransactionDate($transDate);
  898.                         $new->setQty($entry['qtyAdd']);
  899.                         $new->setPrice($entry['price']);
  900.                         $new->setAmount($entry['qtyAdd'] * $entry['price']);
  901.                         $new->setEntity(0);// opening =0
  902.                         $new->setEntityId(0);// opening =0
  903.                         $new->setDebitCreditHeadId(0);// opening =0
  904.                         $new->setVoucherIds(null);// opening =0
  905.                         $em->persist($new);
  906.                         $em->flush();
  907.                         $total_inv_value_in += $entry['qtyAdd'] * $entry['price'];
  908.                     }
  909.                 }
  910.             }
  911.             $refreshed_opening 1;
  912. //                $terminate=1;
  913. //                $last_refresh_date=$last_refresh_date_obj->format('Y-m-d');
  914.             return new JsonResponse(array(
  915.                 "success" => true,
  916.             ));
  917.             //now call the function which will add the 1st ever entry or opening entry
  918.         }
  919.         //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  920.         return new JsonResponse(array(
  921.             "success" => false,
  922.         ));
  923.     }
  924.     public function RefreshInventoryAction(Request $request$refreshed_opening 0)
  925.     {
  926.         //be very careful!!
  927.         $em $this->getDoctrine()->getManager();
  928.         $refreshed_opening 0;
  929.         $last_refresh_date "";
  930.         $last_refresh_date_obj "";
  931.         $terminate 0;
  932.         $companyId $this->getLoggedUserCompanyId($request);
  933.         $modifyAccTransaction $request->request->has('modify_acc_trans_flag') ? $request->request->get('modify_acc_trans_flag') : 0;
  934.         $modifyProductionPrice $request->request->has('modify_production_price') ? $request->request->get('modify_production_price') : 0;
  935. //        $last_refresh_date="";
  936.         if ($request->isMethod('POST')) {
  937.             //steps
  938.             //1. set all inventory to their opening position
  939.             $assign_list = array();
  940.             $data = array();
  941.             if ($request->request->has('inventory_refreshed'))
  942.                 $refreshed_opening $request->request->get('inventory_refreshed');
  943.             if ($request->request->has('last_refresh_date'))
  944.                 $last_refresh_date $request->request->get('last_refresh_date');
  945.             if ($refreshed_opening == 0) {
  946. //                System::log_it($this->container->getParameter('kernel.root_dir'), "",
  947. //                    'inventory_refresh_debug', 0); //last er 1 is append
  948.                 $new_cc $em
  949.                     ->getRepository('ApplicationBundle:AccSettings')
  950.                     ->findOneBy(
  951.                         array(
  952.                             'name' => 'accounting_year_start',
  953.                         )
  954.                     );
  955.                 $date_start = new \DateTime($new_cc->getData());
  956.                 $date_start_str $date_start->format('Y-m-d');
  957.                 $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  958. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  959.                 $stmt $em->getConnection()->prepare($closingQuery);
  960.                 $stmt->execute();
  961.                 $iniClosing $stmt->fetchAll();
  962. //                $stmt = $em->getConnection()->prepare($transQuery);
  963. //                $stmt->execute();
  964. //                $iniTrans = $stmt->fetchAll();
  965.                 $singleClosing_byProductId = array();
  966.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  967.                 foreach ($iniClosing as $item) {
  968.                     if (!isset($singleClosing_byProductId[$item['product_id']])) {
  969.                         $singleClosing_byProductId[$item['product_id']] = array(
  970.                             'date' => $item['date'],
  971.                             'qtyAdd' => $item['qty_addition'],
  972.                             'qtySub' => '0',
  973.                             'valueAdd' => $item['addition'],
  974.                             'valueSub' => '0',
  975.                             'fromWarehouse' => 0,
  976.                             'toWarehouse' => $item['warehouse_id'],
  977.                             'fromWarehouseSub' => 0,
  978.                             'toWarehouseSub' => $item['action_tag_id'],
  979.                             'price' => $item['qty_addition'] != ? ($item['addition'] / $item['qty_addition']) : $item['addition']
  980.                         );
  981.                     }
  982.                 }
  983.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  984. //                foreach ($iniTrans as $item) {
  985. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  986. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  987. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  988. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  989. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  990. //                    }
  991. //                }
  992.                 foreach ($singleClosing_byProductId as $key => $item) {
  993.                     if (!isset($data[$key])) {
  994.                         $data[$key][] = $item;
  995.                     }
  996.                 }
  997.                 //new one
  998.                 //chekc if ultra opening stock received note exists if not create it
  999.                 $mo $em
  1000.                     ->getRepository('ApplicationBundle:StockReceivedNote')
  1001.                     ->findOneBy(
  1002.                         array(
  1003.                             'documentHash' => '_MASTER_OPENING_',
  1004.                             'typeHash' => 'SR',
  1005.                             'prefixHash' => 4,
  1006.                             'assocHash' => '_MASTER_OPENING_',
  1007.                             'numberHash' => 1,
  1008.                         )
  1009.                     );
  1010.                 if (!$mo) {
  1011.                     //doensot exist to add :)
  1012. //                    $products = $post_data->get('products');
  1013. //                    $qty = $post_data->get('qty');
  1014. //                    $note = $post_data->get('note');
  1015.                     $new = new StockReceivedNote();
  1016.                     $new->setStockReceivedNoteDate(new \DateTime($date_start_str));
  1017.                     $new->setCompanyId($companyId);
  1018.                     $new->setDocumentHash('_MASTER_OPENING_');
  1019.                     $new->setTypeHash('SR');
  1020.                     $new->setPrefixHash(4);
  1021.                     $new->setAssocHash('_MASTER_OPENING_');
  1022.                     $new->setNumberHash(1);
  1023.                     $new->setCreditHeadId(0);
  1024.                     $new->setStockTransferId(0);
  1025.                     $new->setSalesOrderId(0);
  1026.                     $new->setType(4);
  1027.                     $new->setStatus(GeneralConstant::ACTIVE);
  1028.                     $new->setWarehouseId(0);
  1029.                     $new->setNote('');
  1030.                     $new->setAutoCreated(1);
  1031.                     $new->setApproved(GeneralConstant::APPROVED);
  1032. //        $new->setIndentTagged(0);
  1033.                     $new->setStage(GeneralConstant::STAGE_COMPLETE);
  1034.                     $new->setCreatedLoginId(0);
  1035.                     $new->setEditedLoginId(0);
  1036.                     $em->persist($new);
  1037.                     $em->flush();
  1038.                     $SRID $new->getStockReceivedNoteId();
  1039.                     $last_refresh_date_obj $new->getStockReceivedNoteDate();
  1040.                     //now add items to details
  1041.                     foreach ($data as $key => $item) {
  1042.                         if (!empty($item)) {
  1043.                             foreach ($item as $entry) {
  1044.                                 $transDate = new \DateTime($entry['date']);
  1045.                                 if ($last_refresh_date_obj == '') {
  1046.                                     $last_refresh_date_obj $transDate;
  1047.                                 } else if ($transDate $last_refresh_date_obj) {
  1048.                                     $last_refresh_date_obj $transDate;
  1049.                                 }
  1050.                                 $new = new StockReceivedNoteItem();
  1051.                                 $new->setStockReceivedNoteId($SRID);
  1052.                                 $new->setStockTransferItemId(0);
  1053.                                 $salesCodeRange = [];
  1054.                                 $salesCodeRangeStr '';
  1055.                                 $new->setSalesCodeRange("[" $salesCodeRangeStr "]");
  1056.                                 $new->setQty($entry['qtyAdd']);
  1057.                                 $new->setPrice($entry['price']);
  1058.                                 $new->setBalance($entry['qtyAdd']);
  1059.                                 $new->setProductId($key);
  1060.                                 $new->setWarrantyMon(0);
  1061.                                 $new->setWarehouseId($entry['toWarehouse']);
  1062.                                 $new->setWarehouseActionId($entry['toWarehouseSub']);
  1063.                                 $em->persist($new);
  1064.                                 $em->flush();
  1065.                             }
  1066.                         }
  1067.                     }
  1068. //                    for ($i = 0; $i < count($products); $i++) {
  1069. //
  1070. //
  1071. //                        $srItem = self::CreateNewStockReceivedNoteItem($em, $post_data, $i, $new->getStockReceivedNoteId(), $LoginID);
  1072. //                    }
  1073.                 }
  1074.                 if ($mo)
  1075.                     $last_refresh_date_obj $mo->getStockReceivedNoteDate();
  1076.                 $last_refresh_date_obj->modify('-1 day');///new so that it willstart form this day on next call
  1077.                 //new ends
  1078.                 //now that we go the data we can empty the closing table
  1079.                 $get_kids_sql "UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  1080. UPDATE `purchase_order` SET expense_amount=0, expense_pending_balance_amount=0, grn_tag_pending_expense_invoice_ids='[]' WHERE 1;
  1081.     truncate `inv_closing_balance`;
  1082.     truncate `inventory_storage`;
  1083.     truncate `inv_item_transaction`;";
  1084.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  1085.                 $stmt->execute();
  1086.                 $stmt->closeCursor();
  1087. //                $stmt->fetchAll();
  1088. //                foreach ($data as $key => $item) {
  1089. //                    if (!empty($item)) {
  1090. //                        foreach ($item as $entry) {
  1091. //                            $transDate = new \DateTime($entry['date']);
  1092. //                            Inventory::addItemToInventoryCompact($em,
  1093. //                                $key,
  1094. //                                $entry['fromWarehouse'],
  1095. //                                $entry['toWarehouse'],
  1096. //                                $entry['fromWarehouseSub'],
  1097. //                                $entry['toWarehouseSub'],
  1098. //                                $transDate,
  1099. //                                $entry['qtyAdd'],
  1100. //                                $entry['qtySub'],
  1101. //                                $entry['valueAdd'],
  1102. //                                $entry['valueSub'],
  1103. //                                $entry['price'],
  1104. //                                $this->getLoggedUserCompanyId($request));
  1105. //                            if ($last_refresh_date_obj == '') {
  1106. //                                $last_refresh_date_obj = $transDate;
  1107. //                            } else if ($transDate < $last_refresh_date_obj) {
  1108. //                                $last_refresh_date_obj = $transDate;
  1109. //                            }
  1110. //                        }
  1111. //                    }
  1112. //                }
  1113.                 $refreshed_opening 1;
  1114. //                $terminate=1;
  1115.                 if ($last_refresh_date_obj == "") {
  1116.                     $last_refresh_date $date_start_str;
  1117.                 } else {
  1118.                     $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1119.                 }
  1120.                 return new JsonResponse(array(
  1121.                     "success" => true,
  1122.                     "last_refresh_date" => $last_refresh_date,
  1123.                     "inventory_refreshed" => $refreshed_opening
  1124.                 ));
  1125.                 //now call the function which will add the 1st ever entry or opening entry
  1126.             }
  1127.             //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  1128.             if ($last_refresh_date != '')
  1129.                 $last_refresh_date_obj = new \DateTime($last_refresh_date);
  1130.             else {
  1131.                 $new_cc $em
  1132.                     ->getRepository('ApplicationBundle:AccSettings')
  1133.                     ->findOneBy(
  1134.                         array(
  1135.                             'name' => 'accounting_year_start',
  1136.                         )
  1137.                     );
  1138.                 $last_refresh_date_obj = new \DateTime($new_cc->getData());
  1139.                 $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1140.             }
  1141.             $last_refresh_date_obj->modify('+1 day');
  1142.             $today = new \DateTime();
  1143.             if ($last_refresh_date_obj $today) {
  1144.                 $terminate 1;
  1145.             }
  1146.             $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1147.             //ok now we got the date so get grn item on this date
  1148.             //GRN
  1149.             $query "SELECT grn_item.*, grn.grn_date, grn.document_hash from  grn_item
  1150.               join grn on grn.grn_id=grn_item.grn_id
  1151.             where grn.grn_date ='" $last_refresh_date " 00:00:00' and grn.approved=1";
  1152.             $stmt $em->getConnection()->prepare($query);
  1153.             $stmt->execute();
  1154.             $queryData $stmt->fetchAll();
  1155.             $grn_ids = [];
  1156.             foreach ($queryData as $item) {
  1157.                 $data[$item['product_id']][] = array(
  1158.                     'date' => $last_refresh_date,
  1159.                     'entity' => array_flip(GeneralConstant::$Entity_list)['Grn'],
  1160.                     'entityId' => $item['grn_id'],
  1161.                     'colorId' => $item['color_id'],
  1162.                     'sizeId' => $item['size_id'],
  1163.                     'entityDocHash' => $item['document_hash'],
  1164.                     'qtyAdd' => $item['qty'],
  1165.                     'qtySub' => 0,
  1166.                     'valueAdd' => ($item['qty'] * $item['price_with_expense']),
  1167.                     'valueSub' => 0,
  1168.                     'price' => $item['price_with_expense'],
  1169.                     'fromWarehouse' => 0,
  1170.                     'toWarehouse' => $item['warehouse_id'],
  1171.                     'fromWarehouseSub' => 0,
  1172. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1173.                     'toWarehouseSub' => $item['warehouse_action_id']
  1174.                 );
  1175.                 if (!in_array($item['grn_id'], $grn_ids))
  1176.                     $grn_ids[] = $item['grn_id'];
  1177.             }
  1178.             //now add grns
  1179.             foreach ($data as $key => $item) {
  1180.                 if (!empty($item)) {
  1181.                     foreach ($item as $entry) {
  1182.                         $transDate = new \DateTime($entry['date']);
  1183.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1184.                             $key,
  1185.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1186.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1187.                             $entry['fromWarehouse'],
  1188.                             $entry['toWarehouse'],
  1189.                             $entry['fromWarehouseSub'],
  1190.                             $entry['toWarehouseSub'],
  1191.                             $transDate,
  1192.                             $entry['qtyAdd'],
  1193.                             $entry['qtySub'],
  1194.                             $entry['valueAdd'],
  1195.                             $entry['valueSub'],
  1196.                             $entry['price'],
  1197.                             $this->getLoggedUserCompanyId($request),
  1198.                             0,
  1199.                             $entry['entity'],
  1200.                             $entry['entityId'],
  1201.                             $entry['entityDocHash'],
  1202.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_SUPPLER
  1203.                         );
  1204.                         if ($last_refresh_date_obj == '') {
  1205.                             $last_refresh_date_obj $transDate;
  1206.                         } else if ($transDate $last_refresh_date_obj) {
  1207.                             $last_refresh_date_obj $transDate;
  1208.                         }
  1209.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1210.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1211.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1212.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1213.                             "",
  1214.                             'inventory_refresh_debug'1); //last er 1 is append
  1215.                     }
  1216.                 }
  1217.             }
  1218.             ///adding grn vouhcer mod here too incase it wasnot in the distributed IG for heads
  1219. //            $grn=$em->getRepository('ApplicationBundle:Grn')->findBy(array(
  1220. //                'grnId'=>$grn_ids,
  1221. //                'modifyVoucherFlag'=>1 //have to add this flag
  1222. //            ));
  1223.             foreach ($grn_ids as $grn_id) {
  1224.                 if ($modifyAccTransaction == 1)
  1225.                     Inventory::ModifyGrnTransactions($em$grn_id1);
  1226.                 else
  1227.                     Inventory::ModifyGrnTransactions($em$grn_id);
  1228.             }
  1229.             //adding voucher ends
  1230.             $inv_head_list_by_wa = [];
  1231.             $inv_head_list = [];
  1232.             $cogs_head 0;
  1233.             $cogs_head 0;
  1234.             $internal_proj 0;
  1235. //            if ($project) {
  1236. //                if ($project->getProjectType() == 2) {
  1237. //                    $cogs_head = $project->getInternalProjectAssetHeadId();
  1238. //                    $internal_proj = 1;
  1239. //                } else {
  1240. //                    $cogs_head_qry = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1241. //                        'name' => 'cogs'
  1242. //                    ));
  1243. //                    $cogs_head = $cogs_head_qry->getData();
  1244. //                }
  1245. //            } else {
  1246.             $cogs_head_qry $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1247.                 'name' => 'cogs'
  1248.             ));
  1249.             $cogs_head $cogs_head_qry->getData();
  1250. //            }
  1251.             $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');
  1252.             foreach ($warehouse_action_list as $wa) {
  1253.                 $inv_head_data $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1254.                         'name' => 'warehouse_action_' $wa['id'])
  1255.                 );
  1256.                 if ($inv_head_data) {
  1257.                     $inv_head_list_by_wa[$wa['id']] = $inv_head_data->getData();
  1258.                     $inv_head_list[] = $inv_head_data->getData();
  1259.                 }
  1260.             }
  1261.             $data = [];
  1262.             //____________STOCK_RECEIVED___________________
  1263.             $docEntity "StockReceivedNote";
  1264.             $docEntityIdField "stockReceivedNoteId";
  1265.             $accTransactionDataByDocId = [];
  1266.             $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
  1267.               join stock_received_note on stock_received_note.stock_received_note_id=stock_received_note_item.stock_received_note_id
  1268.             where stock_received_note.stock_received_note_date ='" $last_refresh_date " 00:00:00' and stock_received_note.approved=1";
  1269.             $stmt $em->getConnection()->prepare($query);
  1270.             $stmt->execute();
  1271.             $queryData $stmt->fetchAll();
  1272.             $grn_ids = [];
  1273.             foreach ($queryData as $item) {
  1274.                 $data[$item['product_id']][] = array(
  1275.                     'date' => $last_refresh_date,
  1276.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  1277.                     'entityId' => $item['stock_received_note_id'],
  1278.                     'colorId' => $item['color_id'],
  1279.                     'sizeId' => $item['size_id'],
  1280.                     'type' => $item['type'],
  1281.                     'entityDocHash' => $item['document_hash'],
  1282.                     'qtyAdd' => $item['qty'],
  1283.                     'qtySub' => 0,
  1284.                     'valueAdd' => ($item['qty'] * $item['price']),
  1285.                     'valueSub' => 0,
  1286.                     'price' => $item['price'],
  1287.                     'fromWarehouse' => 0,
  1288.                     'toWarehouse' => $item['warehouse_id'],
  1289.                     'fromWarehouseSub' => 0,
  1290. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1291.                     'toWarehouseSub' => $item['warehouse_action_id']
  1292.                 );
  1293. //                if (!in_array($item['grn_id'], $grn_ids))
  1294. //                    $grn_ids[] = $item['grn_id'];
  1295.             }
  1296.             foreach ($data as $key => $item) {
  1297.                 if (!empty($item)) {
  1298.                     foreach ($item as $entry) {
  1299.                         $transDate = new \DateTime($entry['date']);
  1300.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1301.                             $key,
  1302.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1303.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1304.                             $entry['fromWarehouse'],
  1305.                             $entry['toWarehouse'],
  1306.                             $entry['fromWarehouseSub'],
  1307.                             $entry['toWarehouseSub'],
  1308.                             $transDate,
  1309.                             $entry['qtyAdd'],
  1310.                             $entry['qtySub'],
  1311.                             $entry['valueAdd'],
  1312.                             $entry['valueSub'],
  1313.                             $entry['price'],
  1314.                             $this->getLoggedUserCompanyId($request),
  1315.                             0,
  1316.                             $entry['entity'],
  1317.                             $entry['entityId'],
  1318.                             $entry['entityDocHash'],
  1319.                             $entry['type'] == ?
  1320.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_OPENING :
  1321.                                 ($entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_STOCK_IN :
  1322.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT)
  1323.                         );
  1324.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1325.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1326.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1327.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1328.                             "",
  1329.                             'inventory_refresh_debug'1); //last er 1 is append
  1330.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1331.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1332.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  1333.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  1334.                         else
  1335.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  1336.                         if ($last_refresh_date_obj == '') {
  1337.                             $last_refresh_date_obj $transDate;
  1338.                         } else if ($transDate $last_refresh_date_obj) {
  1339.                             $last_refresh_date_obj $transDate;
  1340.                         }
  1341.                     }
  1342.                 }
  1343.             }
  1344.             if ($modifyAccTransaction == 1) {
  1345.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1346.                     $docHere $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  1347.                         $docEntityIdField => $docId,
  1348.                     ));;
  1349.                     if ($docHere) {
  1350.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1351.                         if ($curr_v_ids == null)
  1352.                             $curr_v_ids = [];
  1353.                         $skipVids = [];
  1354.                         $toChangeVid 0;
  1355.                         $voucher null;
  1356.                         foreach ($curr_v_ids as $vid) {
  1357.                             if (in_array($vid$skipVids))
  1358.                                 continue;
  1359.                             $skipVids[] = $vid//to prevent duplicate query
  1360.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1361.                                 'transactionId' => $vid,
  1362.                             ));;
  1363.                             if ($voucher) {
  1364.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1365.                                     $toChangeVid $vid;
  1366.                                 } else {
  1367.                                     continue;
  1368.                                 }
  1369.                             }
  1370.                         }
  1371.                         if ($toChangeVid == 0) {
  1372.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1373.                                 $em,
  1374.                                 $docHere->getStockReceivedNoteDate()->format('Y-m-d'),
  1375.                                 0,
  1376.                                 AccountsConstant::VOUCHER_JOURNAL,
  1377.                                 'Journal For Stock Received Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  1378.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1379.                                 'JV',
  1380.                                 'GN',
  1381.                                 0,
  1382.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1383.                                 0,
  1384.                                 $docHere->getCreatedLoginId(),
  1385.                                 $docHere->getCompanyId(),
  1386.                                 '',
  1387.                                 0,
  1388.                                 1
  1389.                             );
  1390.                             $em->flush();
  1391.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1392.                                 'transactionId' => $toChangeVid,
  1393.                             ));;
  1394.                         }
  1395.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  1396.                         $tot_inv_amount 0;
  1397.                         foreach ($transData as $k => $v) {
  1398.                             $tot_inv_amount += ($v);
  1399.                             Accounts::CreateNewTransactionDetails($em,
  1400.                                 '',
  1401.                                 $toChangeVid,
  1402.                                 Generic::CurrToInt($v),
  1403.                                 $k,
  1404.                                 'Inventory Inward For - ' $docHere->getDocumentHash(),
  1405.                                 AccountsConstant::DEBIT,
  1406.                                 0,
  1407.                                 [],
  1408.                                 [],
  1409.                                 $docHere->getCreatedLoginId()
  1410.                             );
  1411.                         }
  1412.                         $stockReceivedType $docHere->getType();
  1413.                         $to_balance_head 0;
  1414.                         if (in_array($stockReceivedType, [23]))
  1415.                             $to_balance_head $docHere->getCreditHeadId();
  1416.                         else {
  1417.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1418.                                     'name' => 'inv_on_transit_head')
  1419.                             );
  1420.                             if ($inv_transit_head)
  1421.                                 $to_balance_head $inv_transit_head->getData();
  1422.                         }
  1423.                         Accounts::CreateNewTransactionDetails($em,
  1424.                             '',
  1425.                             $toChangeVid,
  1426.                             Generic::CurrToInt($tot_inv_amount),
  1427.                             $to_balance_head,
  1428.                             in_array($stockReceivedType, [23]) ? 'Balancing of Stock in Items for -' $docHere->getDocumentHash() : 'In Transit Items for -' $docHere->getDocumentHash(),
  1429.                             AccountsConstant::CREDIT,
  1430.                             0,
  1431.                             [],
  1432.                             [],
  1433.                             $docHere->getCreatedLoginId()
  1434.                         );
  1435.                         if ($voucher)
  1436.                             $voucher->setTransactionAmount($tot_inv_amount);
  1437.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1438.                         if ($curr_v_ids != null)
  1439.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1440.                         else
  1441.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1442.                         $em->flush();
  1443. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  1444.                     }
  1445.                 }
  1446.             }
  1447.             $data = [];
  1448.             $query "SELECT purchase_invoice.* from  purchase_invoice
  1449. where purchase_invoice.purchase_invoice_date ='" $last_refresh_date " 00:00:00' and purchase_invoice.approved=1
  1450.             ";
  1451.             $stmt $em->getConnection()->prepare($query);
  1452.             $stmt->execute();
  1453.             $queryData $stmt->fetchAll();
  1454.             foreach ($queryData as $pi) {
  1455.                 $transDate = new \DateTime($pi['purchase_invoice_date']);
  1456.                 if ($last_refresh_date_obj == '') {
  1457.                     $last_refresh_date_obj $transDate;
  1458.                 } else if ($transDate $last_refresh_date_obj) {
  1459.                     $last_refresh_date_obj $transDate;
  1460.                 }
  1461.                 Accounts::CalibrateProductPriceWithPi($em$pi['purchase_invoice_id'], 1);
  1462.             }
  1463.             $data = [];
  1464.             $query "SELECT expense_invoice.* from  expense_invoice
  1465. where expense_invoice.expense_invoice_date ='" $last_refresh_date " 00:00:00' and expense_invoice.approved=1 and
  1466.             expense_invoice_type_id=1";
  1467.             $stmt $em->getConnection()->prepare($query);
  1468.             $stmt->execute();
  1469.             $queryData $stmt->fetchAll();
  1470.             foreach ($queryData as $ei) {
  1471.                 $transDate = new \DateTime($ei['expense_invoice_date']);
  1472.                 if ($last_refresh_date_obj == '') {
  1473.                     $last_refresh_date_obj $transDate;
  1474.                 } else if ($transDate $last_refresh_date_obj) {
  1475.                     $last_refresh_date_obj $transDate;
  1476.                 }
  1477.                 $grn_ids json_decode($ei['grn_id_list'], true);
  1478.                 if ($grn_ids == null)
  1479.                     $grn_ids = [];
  1480. //                if (!empty($grn_ids)) {
  1481. //
  1482. //
  1483. //                        if ($ei->getExpenseInvocationStrategyOnGrn() != 2) {
  1484. //                            $grn = $em->getRepository('ApplicationBundle:Grn')->findBy(array(
  1485. //                                'purchaseOrderId' => $ei->getPurchaseOrderId()
  1486. //                            ));
  1487. //
  1488. //                        }
  1489. //                        else
  1490. //                        {
  1491. //                            $po = $em->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(array(
  1492. //                                'purchaseOrderId' => $ei['purchase_order_id']
  1493. //                            ));
  1494. //
  1495. //                            if ($po) {
  1496. //                                $po->setExpenseAmount($po->getExpenseAmount() + $ei['invoice_amount']);
  1497. //                            }
  1498. //                            continue; //grn expense will be there anyway
  1499. //                        }
  1500. //
  1501. //
  1502. //
  1503. //                }
  1504.                 Accounts::CalibrateProductPriceWithExpense($em$ei['expense_invoice_id']);
  1505. //                $po = $em->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(array(
  1506. //                    'purchaseOrderId' => $ei['purchase_order_id']
  1507. //                ));
  1508. //
  1509. //
  1510. //                //first get the total valuation
  1511. //                if ($po) {
  1512. //                    $total_product_value = 0;
  1513. //                    $total_pending_expense = 0;
  1514. //                    $po_item_data = $em->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(array(
  1515. ////                'productId' => $item->getProductId(),
  1516. //                        'purchaseOrderId' => $ei['purchase_order_id']
  1517. //                    ));
  1518. //
  1519. //
  1520. //                    foreach ($po_item_data as $it) {
  1521. ////                    $product = $em->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
  1522. ////                        'id' => $item->getProductId()
  1523. ////                    ));
  1524. //
  1525. //                        $poqty = $it->getReceived();
  1526. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);
  1527. //                        $total_product_value += (1 * $po_price);
  1528. //
  1529. //
  1530. //                    }
  1531. //
  1532. //
  1533. //                    //now we know the total grn price value. lets get the fraction increase
  1534. //                    $total_pending_expense = $ei['invoice_amount'];
  1535. //                    if ($total_product_value != 0)
  1536. //                        $fraction_increase = ($total_pending_expense) / ($total_product_value);
  1537. //                    else
  1538. //                        $fraction_increase = 0;
  1539. //
  1540. //                    foreach ($po_item_data as $it) {
  1541. //                        $item = $it;
  1542. //                        $product = $em->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
  1543. //                            'id' => $it->getProductId()
  1544. //                        ));
  1545. //                        if (!$product)
  1546. //                            continue;
  1547. //
  1548. ////                    $items_in_inventory=$em->getRepository('ApplicationBundle:InventoryStorage')->findBy(array(
  1549. ////                        'productId'=>$item->getProductId()
  1550. ////                    ));
  1551. //
  1552. //                        $poqty = $it->getReceived();
  1553. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);;
  1554. //
  1555. //                        $existing_qty = $product->getQty();;
  1556. //
  1557. //
  1558. //                        $increased_po_price = ($po_price * $fraction_increase);
  1559. //
  1560. //                        //now lets see homuch is the total price
  1561. //                        $new_purchase_price = $product->getPurchasePrice();
  1562. //
  1563. //                        if ($increased_po_price != 0) {
  1564. //                            $last_grn_item = $em->getRepository('ApplicationBundle:GrnItem')->findOneBy(array(
  1565. //                                'purchaseOrderItemId' => $item->getId()
  1566. //                            ));
  1567. //                            if ($last_grn_item) {
  1568. //
  1569. //                                $data[$last_grn_item->getProductId()][] = array(
  1570. //                                    'date' => $last_refresh_date,
  1571. //
  1572. //                                    'entity' => array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  1573. //                                    'entityId' => $ei['expense_invoice_id'],
  1574. //                                    'colorId' => $last_grn_item->getColorId(),
  1575. //                                    'sizeId' => $last_grn_item->getSizeId(),
  1576. //                                    'entityDocHash' => $ei['document_hash'],
  1577. //                                    'qtyAdd' => 0,
  1578. //                                    'qtySub' => 0,
  1579. //                                    'valueAdd' => $increased_po_price,
  1580. ////                                    'valueAdd' => $increased_po_price>=0?$increased_po_price:0,
  1581. ////                    'valueSub' => ($item['qty'] * $item['price']),
  1582. ////                                    'valueSub' => $increased_po_price<0?((-1)*$increased_po_price):0,
  1583. //                                    'valueSub' => 0,
  1584. //                                    'price' => '_UNSET_',
  1585. //                                    'fromWarehouse' => 0,
  1586. //                                    'toWarehouse' => $last_grn_item->getWarehouseId(),
  1587. //                                    'fromWarehouseSub' => 0,
  1588. ////                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1589. //                                    'toWarehouseSub' => $last_grn_item->getWarehouseActionId()
  1590. //                                );
  1591. //
  1592. ////                                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);
  1593. ////
  1594. ////                                $total_item_price = $increased_po_price + ($product->getPurchasePrice() * ($existing_qty));
  1595. ////                                if ($existing_qty != 0)
  1596. ////                                    $new_purchase_price = $total_item_price / $existing_qty;
  1597. //
  1598. //
  1599. //                                $total_pending_expense -= $increased_po_price;
  1600. //                            }
  1601. //                        }
  1602. //                    }
  1603. //
  1604. //
  1605. //
  1606. //
  1607. //
  1608. //
  1609. //                } else {
  1610. //                    continue;
  1611. //                }
  1612.             }
  1613.             $data = [];
  1614.             //____________STOCK_TRANSFER___________________
  1615.             $docEntity "StockTransfer";
  1616.             $docEntityIdField "stockTransferId";
  1617.             $accTransactionDataByDocId = [];
  1618.             $query "SELECT stock_transfer_item.*,  stock_transfer.stock_transfer_date, stock_transfer.document_hash, stock_transfer.transfer_action_type from  stock_transfer_item
  1619.               join stock_transfer on stock_transfer.stock_transfer_id=stock_transfer_item.stock_transfer_id
  1620.             where stock_transfer.stock_transfer_date ='" $last_refresh_date " 00:00:00' and stock_transfer.approved=1";
  1621.             $stmt $em->getConnection()->prepare($query);
  1622.             $stmt->execute();
  1623.             $queryData $stmt->fetchAll();
  1624.             $grn_ids = [];
  1625.             foreach ($queryData as $item) {
  1626.                 $data[$item['product_id']][] = array(
  1627.                     'date' => $last_refresh_date,
  1628.                     'transfer_action_type' => $item['transfer_action_type'],
  1629.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  1630.                     'entityId' => $item['stock_transfer_id'],
  1631.                     'colorId' => $item['color_id'],
  1632.                     'sizeId' => $item['size_id'],
  1633.                     'entityDocHash' => $item['document_hash'],
  1634.                     'qtyAdd' => $item['transfer_action_type'] == $item['qty'] : 0,
  1635.                     'qtySub' => $item['qty'],
  1636.                     'valueAdd' => 0,
  1637. //                    'valueSub' => ($item['qty'] * $item['price']),
  1638.                     'valueSub' => '_AUTO_',
  1639.                     'price' => $item['price'],
  1640.                     'fromWarehouse' => $item['warehouse_id'],
  1641.                     'toWarehouse' => $item['transfer_action_type'] == $item['to_warehouse_id'] : 0,
  1642.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  1643. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1644.                     'toWarehouseSub' => $item['transfer_action_type'] == $item['to_warehouse_action_id'] : 0
  1645.                 );
  1646. //                if (!in_array($item['grn_id'], $grn_ids))
  1647. //                    $grn_ids[] = $item['grn_id'];
  1648.             }
  1649.             //now add grns
  1650.             foreach ($data as $key => $item) {
  1651.                 if (!empty($item)) {
  1652.                     foreach ($item as $entry) {
  1653.                         $transDate = new \DateTime($entry['date']);
  1654.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1655.                             $key,
  1656.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1657.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1658.                             $entry['fromWarehouse'],
  1659.                             $entry['toWarehouse'],
  1660.                             $entry['fromWarehouseSub'],
  1661.                             $entry['toWarehouseSub'],
  1662.                             $transDate,
  1663.                             $entry['qtyAdd'],
  1664.                             $entry['qtySub'],
  1665.                             $entry['valueAdd'],
  1666.                             $entry['valueSub'],
  1667.                             $entry['price'],
  1668.                             $this->getLoggedUserCompanyId($request),
  1669.                             0,
  1670.                             $entry['entity'],
  1671.                             $entry['entityId'],
  1672.                             $entry['entityDocHash'],
  1673.                             $entry['transfer_action_type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_INTER_WAREHOUSE GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT
  1674.                         );
  1675.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1676.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1677.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1678.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1679.                             "",
  1680.                             'inventory_refresh_debug'1); //last er 1 is append
  1681.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1682.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1683.                         if ($entry['transfer_action_type'] == 4) {
  1684.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  1685.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtySub'] * $modifiedData['slot_cost_price'];
  1686.                             else
  1687.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  1688.                         }
  1689.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  1690.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  1691.                         else
  1692.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  1693.                         if ($last_refresh_date_obj == '') {
  1694.                             $last_refresh_date_obj $transDate;
  1695.                         } else if ($transDate $last_refresh_date_obj) {
  1696.                             $last_refresh_date_obj $transDate;
  1697.                         }
  1698.                     }
  1699.                 }
  1700.             }
  1701.             if ($modifyAccTransaction == 1) {
  1702.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1703.                     $docHere $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  1704.                         $docEntityIdField => $docId,
  1705.                     ));;
  1706.                     if ($docHere) {
  1707.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1708.                         if ($curr_v_ids == null)
  1709.                             $curr_v_ids = [];
  1710.                         $skipVids = [];
  1711.                         $toChangeVid 0;
  1712.                         $voucher null;
  1713.                         foreach ($curr_v_ids as $vid) {
  1714.                             if (in_array($vid$skipVids))
  1715.                                 continue;
  1716.                             $skipVids[] = $vid//to prevent duplicate query
  1717.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1718.                                 'transactionId' => $vid,
  1719.                             ));;
  1720.                             if ($voucher) {
  1721.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1722.                                     $toChangeVid $vid;
  1723.                                 } else {
  1724.                                     continue;
  1725.                                 }
  1726.                             }
  1727.                         }
  1728.                         if ($toChangeVid == 0) {
  1729.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1730.                                 $em,
  1731.                                 $docHere->getStockTransferDate()->format('Y-m-d'),
  1732.                                 0,
  1733.                                 AccountsConstant::VOUCHER_JOURNAL,
  1734.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  1735.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1736.                                 'JV',
  1737.                                 'GN',
  1738.                                 0,
  1739.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1740.                                 0,
  1741.                                 $docHere->getCreatedLoginId(),
  1742.                                 $docHere->getCompanyId(),
  1743.                                 '',
  1744.                                 0,
  1745.                                 1
  1746.                             );
  1747.                             $em->flush();
  1748.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1749.                                 'transactionId' => $toChangeVid,
  1750.                             ));;
  1751.                         }
  1752.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  1753.                         $tot_inv_amount 0;
  1754.                         foreach ($transData as $k => $v) {
  1755.                             $tot_inv_amount += ($v);
  1756.                             Accounts::CreateNewTransactionDetails($em,
  1757.                                 '',
  1758.                                 $toChangeVid,
  1759.                                 Generic::CurrToInt($v),
  1760.                                 $k,
  1761.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  1762.                                 $v >= AccountsConstant::DEBIT AccountsConstant::CREDIT,
  1763.                                 0,
  1764.                                 [],
  1765.                                 [],
  1766.                                 $docHere->getCreatedLoginId()
  1767.                             );
  1768.                         }
  1769. //                        $stockReceivedType = $docHere->getType();
  1770.                         $to_balance_head 0;
  1771.                         if ($docHere->getTransferActionType() == 4) {
  1772.                         } else {
  1773.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1774.                                     'name' => 'inv_on_transit_head')
  1775.                             );
  1776.                             if ($inv_transit_head)
  1777.                                 $to_balance_head $inv_transit_head->getData();
  1778.                         }
  1779.                         if ($to_balance_head != 0) {
  1780.                             Accounts::CreateNewTransactionDetails($em,
  1781.                                 '',
  1782.                                 $toChangeVid,
  1783.                                 Generic::CurrToInt($tot_inv_amount),
  1784.                                 $to_balance_head,
  1785.                                 'In Transit Items for -' $docHere->getDocumentHash(),
  1786.                                 $tot_inv_amount >= AccountsConstant::CREDIT AccountsConstant::DEBIT,
  1787.                                 0,
  1788.                                 [],
  1789.                                 [],
  1790.                                 $docHere->getCreatedLoginId()
  1791.                             );
  1792.                         }
  1793.                         if ($voucher)
  1794.                             $voucher->setTransactionAmount($tot_inv_amount);
  1795.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1796.                         if ($curr_v_ids != null)
  1797.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1798.                         else
  1799.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1800.                         $em->flush();
  1801. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  1802.                     }
  1803.                 }
  1804.             }
  1805.             $data = [];
  1806.             //____________IRR___________________
  1807.             $docEntity "ItemReceivedAndReplacement";
  1808.             $docEntityIdField "itemReceivedAndReplacementId";
  1809.             $accTransactionDataByDocId = [];
  1810.             $query "SELECT irr_item.*,  item_received_replacement.irr_date, item_received_replacement.document_hash from  irr_item
  1811.               join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  1812.             where item_received_replacement.irr_date ='" $last_refresh_date " 00:00:00' and item_received_replacement.approved=1";
  1813.             $stmt $em->getConnection()->prepare($query);
  1814.             $stmt->execute();
  1815.             $queryData $stmt->fetchAll();
  1816.             $irr_add_data = [];
  1817.             $irr_replace_data = [];
  1818.             $irr_dispose_data = [];
  1819.             foreach ($queryData as $item) {
  1820.                 $irr_add_data[$item['received_product_id']][] = array(
  1821.                     'date' => $last_refresh_date,
  1822.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1823.                     'entityId' => $item['irr_id'],
  1824.                     'colorId' => $item['received_product_color_id'],
  1825.                     'sizeId' => $item['received_product_color_id'],
  1826.                     'entityDocHash' => $item['document_hash'],
  1827.                     'qtyAdd' => $item['received_qty'],
  1828.                     'qtySub' => 0,
  1829.                     'valueAdd' => ($item['received_qty'] * $item['received_unit_purchase_price']),
  1830.                     'valueSub' => 0,
  1831.                     'price' => $item['received_unit_purchase_price'],
  1832.                     'fromWarehouse' => 0,
  1833.                     'toWarehouse' => $item['received_warehouse_id'],
  1834.                     'fromWarehouseSub' => 0,
  1835.                     'toWarehouseSub' => $item['received_warehouse_action_id']
  1836.                 );
  1837.                 $irr_replace_data[$item['replaced_product_id']][] = array(
  1838.                     'date' => $last_refresh_date,
  1839.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1840.                     'entityId' => $item['irr_id'],
  1841.                     'colorId' => $item['replaced_product_color_id'],
  1842.                     'sizeId' => $item['replaced_product_color_id'],
  1843.                     'entityDocHash' => $item['document_hash'],
  1844.                     'qtyAdd' => 0,
  1845.                     'qtySub' => $item['replaced_qty'],
  1846.                     'valueAdd' => 0,
  1847.                     'valueSub' => ($item['replaced_qty'] * $item['replaced_unit_purchase_price']),
  1848.                     'price' => $item['replaced_unit_purchase_price'],
  1849.                     'fromWarehouse' => $item['replaced_warehouse_id'],
  1850.                     'toWarehouse' => 0,
  1851.                     'fromWarehouseSub' => $item['replaced_warehouse_action_id'],
  1852.                     'toWarehouseSub' => 0
  1853.                 );
  1854.                 $irr_dispose_data[$item['received_product_id']][] = array(
  1855.                     'date' => $last_refresh_date,
  1856.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1857.                     'entityId' => $item['irr_id'],
  1858.                     'colorId' => $item['received_product_color_id'],
  1859.                     'sizeId' => $item['received_product_size_id'],
  1860.                     'entityDocHash' => $item['document_hash'],
  1861.                     'qtyAdd' => 0,
  1862.                     'qtySub' => $item['dispose_qty'],
  1863.                     'valueAdd' => 0,
  1864.                     'valueSub' => ($item['dispose_qty'] * $item['received_unit_purchase_price']),
  1865.                     'price' => $item['received_unit_purchase_price'],
  1866.                     'fromWarehouse' => $item['received_warehouse_id'],
  1867.                     'toWarehouse' => 0,
  1868.                     'fromWarehouseSub' => $item['received_warehouse_id'],
  1869.                     'toWarehouseSub' => 0
  1870.                 );
  1871.             }
  1872.             //now add irrs
  1873.             foreach ($irr_add_data as $key => $item) {
  1874.                 if (!empty($item)) {
  1875.                     foreach ($item as $entry) {
  1876.                         $transDate = new \DateTime($entry['date']);
  1877.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1878.                             $key,
  1879.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1880.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1881.                             $entry['fromWarehouse'],
  1882.                             $entry['toWarehouse'],
  1883.                             $entry['fromWarehouseSub'],
  1884.                             $entry['toWarehouseSub'],
  1885.                             $transDate,
  1886.                             $entry['qtyAdd'],
  1887.                             $entry['qtySub'],
  1888.                             $entry['valueAdd'],
  1889.                             $entry['valueSub'],
  1890.                             $entry['price'],
  1891.                             $this->getLoggedUserCompanyId($request),
  1892.                             0,
  1893.                             $entry['entity'],
  1894.                             $entry['entityId'],
  1895.                             $entry['entityDocHash'],
  1896.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  1897.                         );
  1898.                         if ($modifiedData)
  1899.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1900.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1901.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1902.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1903.                                 "",
  1904.                                 'inventory_refresh_debug'1); //last er 1 is append
  1905.                         if ($last_refresh_date_obj == '') {
  1906.                             $last_refresh_date_obj $transDate;
  1907.                         } else if ($transDate $last_refresh_date_obj) {
  1908.                             $last_refresh_date_obj $transDate;
  1909.                         }
  1910.                     }
  1911.                 }
  1912.             }
  1913.             foreach ($irr_replace_data as $key => $item) {
  1914.                 if (!empty($item)) {
  1915.                     foreach ($item as $entry) {
  1916.                         $transDate = new \DateTime($entry['date']);
  1917.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1918.                             $key,
  1919.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1920.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1921.                             $entry['fromWarehouse'],
  1922.                             $entry['toWarehouse'],
  1923.                             $entry['fromWarehouseSub'],
  1924.                             $entry['toWarehouseSub'],
  1925.                             $transDate,
  1926.                             $entry['qtyAdd'],
  1927.                             $entry['qtySub'],
  1928.                             $entry['valueAdd'],
  1929.                             $entry['valueSub'],
  1930.                             $entry['price'],
  1931.                             $this->getLoggedUserCompanyId($request),
  1932.                             0,
  1933.                             $entry['entity'],
  1934.                             $entry['entityId'],
  1935.                             $entry['entityDocHash']);
  1936.                         if ($modifiedData)
  1937.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1938.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1939.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1940.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1941.                                 "",
  1942.                                 'inventory_refresh_debug'1); //last er 1 is append
  1943.                         if ($last_refresh_date_obj == '') {
  1944.                             $last_refresh_date_obj $transDate;
  1945.                         } else if ($transDate $last_refresh_date_obj) {
  1946.                             $last_refresh_date_obj $transDate;
  1947.                         }
  1948.                     }
  1949.                 }
  1950.             }
  1951.             foreach ($irr_dispose_data as $key => $item) {
  1952.                 if (!empty($item)) {
  1953.                     foreach ($item as $entry) {
  1954.                         $transDate = new \DateTime($entry['date']);
  1955.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1956.                             $key,
  1957.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1958.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1959.                             $entry['fromWarehouse'],
  1960.                             $entry['toWarehouse'],
  1961.                             $entry['fromWarehouseSub'],
  1962.                             $entry['toWarehouseSub'],
  1963.                             $transDate,
  1964.                             $entry['qtyAdd'],
  1965.                             $entry['qtySub'],
  1966.                             $entry['valueAdd'],
  1967.                             $entry['valueSub'],
  1968.                             $entry['price'],
  1969.                             $this->getLoggedUserCompanyId($request),
  1970.                             0,
  1971.                             $entry['entity'],
  1972.                             $entry['entityId'],
  1973.                             $entry['entityDocHash'],
  1974.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  1975.                         );
  1976.                         if ($modifiedData)
  1977.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1978.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1979.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1980.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1981.                                 "",
  1982.                                 'inventory_refresh_debug'1); //last er 1 is append
  1983.                         if ($last_refresh_date_obj == '') {
  1984.                             $last_refresh_date_obj $transDate;
  1985.                         } else if ($transDate $last_refresh_date_obj) {
  1986.                             $last_refresh_date_obj $transDate;
  1987.                         }
  1988.                     }
  1989.                 }
  1990.             }
  1991.             $data = [];
  1992.             //____________DELIVERY_RECEIPT___________________
  1993.             $docEntity "DeliveryReceipt";
  1994.             $docEntityIdField "deliveryReceiptId";
  1995.             $accTransactionDataByDocId = [];
  1996.             $query "SELECT delivery_receipt_item.*, delivery_receipt.delivery_receipt_date, delivery_receipt.document_hash, delivery_receipt.skip_inventory_hit from  delivery_receipt_item
  1997.               join delivery_receipt on delivery_receipt.delivery_receipt_id=delivery_receipt_item.delivery_receipt_id
  1998.             where delivery_receipt.delivery_receipt_date ='" $last_refresh_date " 00:00:00' and delivery_receipt.approved=1";
  1999.             $stmt $em->getConnection()->prepare($query);
  2000.             $stmt->execute();
  2001.             $queryData $stmt->fetchAll();
  2002.             foreach ($queryData as $item) {
  2003.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  2004.                     ->findOneBy(
  2005.                         array(
  2006.                             'id' => $item['product_id']
  2007.                         )
  2008.                     );
  2009.                 $curr_purchase_price $product->getPurchasePrice();
  2010.                 if ($item['skip_inventory_hit'] != 1) {
  2011.                     $data[$item['product_id']][] = array(
  2012.                         'date' => $last_refresh_date,
  2013.                         'entity' => array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  2014.                         'entityId' => $item['delivery_receipt_id'],
  2015.                         'colorId' => $item['color_id'],
  2016.                         'sizeId' => $item['size_id'],
  2017.                         'entityDocHash' => $item['document_hash'],
  2018.                         'qtyAdd' => 0,
  2019.                         'qtySub' => ($item['qty'] * $item['unit_multiplier']),
  2020.                         'valueAdd' => 0,
  2021.                         'valueSub' => '_AUTO_',
  2022.                         'price' => $curr_purchase_price,
  2023.                         'fromWarehouse' => $item['warehouse_id'],
  2024.                         'toWarehouse' => 0,
  2025.                         'fromWarehouseSub' => $item['warehouse_action_id'] != null $item['warehouse_action_id'] : GeneralConstant::WAREHOUSE_ACTION_GOODS,
  2026.                         'toWarehouseSub' => 0
  2027.                     );
  2028.                 }
  2029.                 $get_kids_sql "UPDATE `delivery_receipt_item` SET current_purchase_price='" $curr_purchase_price "' WHERE id=" $item['id'] . ";";
  2030.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  2031.                 $stmt->execute();
  2032.             }
  2033.             foreach ($data as $key => $item) {
  2034.                 if (!empty($item)) {
  2035.                     foreach ($item as $entry) {
  2036.                         $transDate = new \DateTime($entry['date']);
  2037.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2038.                             $key,
  2039.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2040.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2041.                             $entry['fromWarehouse'],
  2042.                             $entry['toWarehouse'],
  2043.                             $entry['fromWarehouseSub'],
  2044.                             $entry['toWarehouseSub'],
  2045.                             $transDate,
  2046.                             $entry['qtyAdd'],
  2047.                             $entry['qtySub'],
  2048.                             $entry['valueAdd'],
  2049.                             $entry['valueSub'],
  2050.                             $entry['price'],
  2051.                             $this->getLoggedUserCompanyId($request),
  2052.                             0,
  2053.                             $entry['entity'],
  2054.                             $entry['entityId'],
  2055.                             $entry['entityDocHash'],
  2056.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2057.                         );
  2058.                         if ($modifiedData)
  2059.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2060.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2061.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2062.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2063.                                 "",
  2064.                                 'inventory_refresh_debug'1); //last er 1 is append
  2065.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2066.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  2067.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2068.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2069.                         else
  2070.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2071.                         if ($last_refresh_date_obj == '') {
  2072.                             $last_refresh_date_obj $transDate;
  2073.                         } else if ($transDate $last_refresh_date_obj) {
  2074.                             $last_refresh_date_obj $transDate;
  2075.                         }
  2076.                     }
  2077.                 }
  2078.             }
  2079.             if ($modifyAccTransaction == 1) {
  2080.                 //for now we are suuming there is only receipt without confirmation needed
  2081.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2082.                     $docHereDr $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  2083.                         $docEntityIdField => $docId,
  2084.                     ));;
  2085.                     $so $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
  2086.                         array(
  2087.                             'salesOrderId' => $docHereDr->getSalesOrderId()
  2088.                         )
  2089.                     );
  2090.                     $query $em->getRepository('ApplicationBundle:SalesInvoice')
  2091.                         ->createQueryBuilder('p');
  2092.                     $query->where('p.salesOrderId = :soID')
  2093.                         ->setParameter('soID'$docHereDr->getSalesOrderId());
  2094.                     $query->andWhere("p.deliveryReceiptIds LIKE '%" $docId "%' ");
  2095.                     $query->setMaxResults(1);
  2096.                     $results $query->getQuery()->getResult();
  2097.                     $docHere null;
  2098.                     if (!empty($results))
  2099.                         $docHere $results[0];
  2100.                     if ($docHere) {
  2101.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2102.                         if ($curr_v_ids == null)
  2103.                             $curr_v_ids = [];
  2104.                         $skipVids = [];
  2105.                         $toChangeVid 0;
  2106.                         $voucher null;
  2107.                         foreach ($curr_v_ids as $vid) {
  2108.                             if (in_array($vid$skipVids))
  2109.                                 continue;
  2110.                             $skipVids[] = $vid//to prevent duplicate query
  2111.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2112.                                 'transactionId' => $vid,
  2113.                             ));;
  2114.                             if ($voucher) {
  2115.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2116.                                     $toChangeVid $vid;
  2117.                                 } else {
  2118.                                     continue;
  2119.                                 }
  2120.                                 if (strpos($voucher->getDescription(), 'Inventory') !== false) {
  2121. //                                    echo "Word Found!";
  2122.                                     $toChangeVid $vid;
  2123.                                 } else {
  2124.                                     continue;
  2125.                                 }
  2126.                             }
  2127.                         }
  2128.                         if ($toChangeVid == 0) {
  2129.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2130.                                 $em,
  2131.                                 $docHere->getSalesInvoiceDate()->format('Y-m-d'),
  2132.                                 0,
  2133.                                 AccountsConstant::VOUCHER_JOURNAL,
  2134.                                 'Journal For Inventory balance for Sales Invoice ' $docHere->getDocumentHash(),
  2135.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2136.                                 'JV',
  2137.                                 'GN',
  2138.                                 0,
  2139.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2140.                                 0,
  2141.                                 $docHere->getCreatedLoginId(),
  2142.                                 $docHere->getCompanyId(),
  2143.                                 '',
  2144.                                 0,
  2145.                                 1,
  2146.                                 0''$so->getBranchId(),
  2147.                                 AccountsConstant::INVOICE_REVENUE_JOURNAL,
  2148.                                 array_flip(GeneralConstant::$Entity_list)['SalesInvoice'], $docHere->getSalesInvoiceId(), $docHere->getDocumentHash()
  2149.                             );
  2150.                             $em->flush();
  2151.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2152.                                 'transactionId' => $toChangeVid,
  2153.                             ));;
  2154.                         }
  2155. //                        DeleteDocument::AccTransactions($em, $toChangeVid, 0);
  2156.                         //now remove cogs or inventory related transactions
  2157.                         $voucherDetails $em->getRepository('ApplicationBundle:AccTransactionDetails')->findBy(array(
  2158.                             'transactionId' => $toChangeVid,
  2159.                         ));;
  2160.                         foreach ($voucherDetails as $vdtls) {
  2161.                             if (in_array($vdtls->getAccountsHeadId(), $inv_head_list)) {
  2162.                                 $em->remove($vdtls);
  2163.                                 $em->flush();
  2164.                             }
  2165.                             if ($cogs_head == $vdtls->getAccountsHeadId()) {
  2166.                                 $em->remove($vdtls);
  2167.                                 $em->flush();
  2168.                             }
  2169.                         }
  2170.                         $tot_inv_amount 0;
  2171.                         foreach ($transData as $k => $v) {
  2172.                             $tot_inv_amount += ($v);
  2173.                             Accounts::CreateNewTransactionDetails($em,
  2174.                                 '',
  2175.                                 $toChangeVid,
  2176.                                 Generic::CurrToInt($v),
  2177.                                 $k,
  2178.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2179.                                 AccountsConstant::DEBIT,
  2180.                                 0,
  2181.                                 [],
  2182.                                 [],
  2183.                                 $docHere->getCreatedLoginId()
  2184.                             );
  2185.                         }
  2186. //                        $stockReceivedType = $docHere->getType();
  2187.                         $to_balance_head 0;
  2188. //                        if ($docHere->getTransferActionType() == 4)
  2189.                         if (1) {
  2190.                         } else {
  2191.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  2192.                                     'name' => 'inv_on_transit_head')
  2193.                             );
  2194.                             if ($inv_transit_head)
  2195.                                 $to_balance_head $inv_transit_head->getData();
  2196.                         }
  2197.                         if ($to_balance_head != 0) {
  2198.                             Accounts::CreateNewTransactionDetails($em,
  2199.                                 '',
  2200.                                 $toChangeVid,
  2201.                                 Generic::CurrToInt($tot_inv_amount),
  2202.                                 $to_balance_head,
  2203.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  2204.                                 AccountsConstant::CREDIT,
  2205.                                 0,
  2206.                                 [],
  2207.                                 [],
  2208.                                 $docHere->getCreatedLoginId()
  2209.                             );
  2210.                         }
  2211.                         if ($voucher)
  2212.                             $voucher->setTransactionAmount($tot_inv_amount);
  2213.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2214.                         if ($curr_v_ids != null)
  2215.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2216.                         else
  2217.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2218.                         $em->flush();
  2219. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2220.                     }
  2221.                 }
  2222.             }
  2223.             $data = [];
  2224.             //____________STOCK_CONSUMPTION___________________
  2225.             $docEntity "StockConsumptionNote";
  2226.             $docEntityIdField "stockConsumptionNoteId";
  2227.             $accTransactionDataByDocId = [];
  2228.             $query "SELECT stock_consumption_note_item.*,  stock_consumption_note.stock_consumption_note_date, stock_consumption_note.document_hash, stock_consumption_note.data
  2229.               from  stock_consumption_note_item
  2230.               join stock_consumption_note on stock_consumption_note.stock_consumption_note_id=stock_consumption_note_item.stock_consumption_note_id
  2231.             where stock_consumption_note.stock_consumption_note_date ='" $last_refresh_date " 00:00:00' and stock_consumption_note.approved=1";
  2232.             $stmt $em->getConnection()->prepare($query);
  2233.             $stmt->execute();
  2234.             $queryData $stmt->fetchAll();
  2235.             $consumption_data = [];
  2236.             $produced_data = [];
  2237.             $checked_stcm_ids = [];
  2238.             foreach ($queryData as $item) {
  2239. //                $product=$em->getRepository('ApplicationBundle:InvProducts')
  2240. //                    ->findOneBy(
  2241. //                        array(
  2242. //                            'id'=>$item['product_id']
  2243. //                        )
  2244. //                    );
  2245. //
  2246. //                $curr_purchase_price=$product->getPurchasePrice();
  2247.                 if (!in_array($item['stock_consumption_note_id'], $checked_stcm_ids)) {
  2248.                     $conversion_data json_decode($item['data'], true);
  2249.                     if ($conversion_data == null)
  2250.                         $conversion_data = [];
  2251.                     if (isset($conversion_data['conversionData'])) {
  2252.                         if (isset($conversion_data['conversionData']['converted_products'])) {
  2253.                             $curr_spec_data $conversion_data['conversionData'];
  2254.                             foreach ($curr_spec_data['converted_products'] as $pika_key => $val) {
  2255.                                 $consumption_data[$val][] = array(
  2256.                                     'date' => $last_refresh_date,
  2257.                                     'type' => 2,
  2258.                                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2259.                                     'entityId' => $item['stock_consumption_note_id'],
  2260.                                     'colorId' => isset($curr_spec_data['converted_product_colors'][$pika_key]) ? ($curr_spec_data['converted_product_colors'][$pika_key]) : 0,
  2261.                                     'sizeId' => isset($curr_spec_data['converted_product_sizes'][$pika_key]) ? ($curr_spec_data['converted_product_sizes'][$pika_key]) : 0,
  2262.                                     'entityDocHash' => $item['document_hash'],
  2263.                                     'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_units'][$pika_key]) : 0,
  2264.                                     'qtySub' => 0,
  2265.                                     '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,
  2266.                                     'valueSub' => 0,
  2267.                                     'price' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_unit_price'][$pika_key]) : 0,
  2268.                                     'fromWarehouse' => 0,
  2269.                                     'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key]) ? ($curr_spec_data['converted_warehouseId'][$pika_key]) : 0,
  2270.                                     'fromWarehouseSub' => 0,
  2271.                                     'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key]) ? ($curr_spec_data['converted_warehouseActionId'][$pika_key]) : 0
  2272.                                 );
  2273.                             }
  2274.                         }
  2275.                     }
  2276. //                    if(isset($conversion_data['expenseCost'] ))
  2277. //                    if(isset($conversion_data['expenseCost']['expense_heads'] ))
  2278. //                    {
  2279. //                        $curr_spec_data=$conversion_data['expenseCost'];
  2280. //                        foreach($curr_spec_data['expense_heads'] as $pika_key=>$val)
  2281. //                        {
  2282. //
  2283. //                            $consumption_data[$val][] = array(
  2284. //                                'date' => $last_refresh_date,
  2285. //                                'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2286. //                                'entityId' => $item['stock_consumption_note_id'],
  2287. //                                'entityDocHash' => $item['document_hash'],
  2288. //                                'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_units'][$pika_key]):0,
  2289. //                                'qtySub' => 0,
  2290. //                                '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,
  2291. //                                'valueSub' => 0,
  2292. //                                'price' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_unit_price'][$pika_key]):0,
  2293. //                                'fromWarehouse' => 0,
  2294. //                                'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key])?(1*$curr_spec_data['converted_warehouseId'][$pika_key]):0,
  2295. //                                'fromWarehouseSub' => 0,
  2296. //                                'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key])?(1*$curr_spec_data['converted_warehouseActionId'][$pika_key]):0
  2297. //                            );
  2298. //                        }
  2299. //                    }
  2300.                     $checked_stcm_ids[] = $item['stock_consumption_note_id'];
  2301.                 }
  2302.                 $consumption_data[$item['product_id']][] = array(
  2303.                     'date' => $last_refresh_date,
  2304.                     'type' => 1,
  2305.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2306.                     'entityId' => $item['stock_consumption_note_id'],
  2307.                     'colorId' => $item['color_id'],
  2308.                     'sizeId' => $item['size_id'],
  2309.                     'entityDocHash' => $item['document_hash'],
  2310.                     'qtyAdd' => 0,
  2311.                     'qtySub' => ($item['qty'] * 1),
  2312.                     'valueAdd' => 0,
  2313.                     'valueSub' => (($item['qty']) * ($item['price'])),
  2314.                     'price' => $item['price'],
  2315.                     'fromWarehouse' => $item['warehouse_id'],
  2316.                     'toWarehouse' => 0,
  2317.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  2318.                     'toWarehouseSub' => 0
  2319.                 );
  2320. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2321. //                $stmt = $em->getConnection()->prepare($get_kids_sql);
  2322. //                $stmt->execute();
  2323.             }
  2324.             foreach ($consumption_data as $key => $item) {
  2325.                 if (!empty($item)) {
  2326.                     foreach ($item as $entry) {
  2327.                         $transDate = new \DateTime($entry['date']);
  2328.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2329.                             $key,
  2330.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2331.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2332.                             $entry['fromWarehouse'],
  2333.                             $entry['toWarehouse'],
  2334.                             $entry['fromWarehouseSub'],
  2335.                             $entry['toWarehouseSub'],
  2336.                             $transDate,
  2337.                             $entry['qtyAdd'],
  2338.                             $entry['qtySub'],
  2339.                             $entry['valueAdd'],
  2340.                             $entry['valueSub'],
  2341.                             $entry['price'],
  2342.                             $this->getLoggedUserCompanyId($request),
  2343.                             0,
  2344.                             $entry['entity'],
  2345.                             $entry['entityId'],
  2346.                             $entry['entityDocHash'],
  2347.                             $entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION
  2348.                         );
  2349.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2350.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2351.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2352.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2353.                             "",
  2354.                             'inventory_refresh_debug'1); //last er 1 is append
  2355.                         if ($last_refresh_date_obj == '') {
  2356.                             $last_refresh_date_obj $transDate;
  2357.                         } else if ($transDate $last_refresh_date_obj) {
  2358.                             $last_refresh_date_obj $transDate;
  2359.                         }
  2360.                     }
  2361.                 }
  2362.             }
  2363.             $data = [];
  2364.             //____________PRODUCTION___________________
  2365.             $docEntity "Production";
  2366.             $docEntityIdField "productionId";
  2367.             $accTransactionDataByDocId = [];
  2368.             $consumedAmountByProductionId = [];
  2369.             $query "SELECT * from production_process_settings
  2370.             where approved=1 order by production_process_settings_id asc  ";
  2371.             $stmt $em->getConnection()->prepare($query);
  2372.             $stmt->execute();
  2373.             $processList $stmt->fetchAll();
  2374. //            $processList=[];
  2375.             foreach ($processList as $process) {
  2376.                 $query "SELECT production_entry_item.*,  production.production_date, production.document_hash
  2377.               from  production_entry_item
  2378.               join production on production_entry_item.production_id=production.production_id
  2379.             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  ";
  2380.                 $stmt $em->getConnection()->prepare($query);
  2381.                 $stmt->execute();
  2382.                 $queryData $stmt->fetchAll();
  2383.                 $produced_data = [];
  2384.                 $rejected_data = [];
  2385.                 $consumed_data = [];
  2386.                 foreach ($queryData as $item) {
  2387. //                $product=$em->getRepository('ApplicationBundle:InvProducts')
  2388. //                    ->findOneBy(
  2389. //                        array(
  2390. //                            'id'=>$item['product_id']
  2391. //                        )
  2392. //                    );
  2393. //
  2394. //                $curr_purchase_price=$product->getPurchasePrice();
  2395.                     if ($item['price'] == '')
  2396.                         $item['price'] = 0;
  2397.                     if ($item['price'] < 0)
  2398.                         $item['price'] = 0;
  2399.                     $item['production_nature_id'];
  2400.                     $consumed_data[$item['product_id']][] = array(
  2401.                         'date' => $last_refresh_date,
  2402.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2403.                         'entityId' => $item['production_id'],
  2404.                         'colorId' => $item['color_id'],
  2405.                         'sizeId' => $item['size_id'],
  2406.                         'entityDocHash' => $item['document_hash'],
  2407.                         'qtyAdd' => 0,
  2408.                         'qtySub' => ($item['additional_consumed_qty'] * 1) + ($item['consumed_qty']),
  2409.                         'valueAdd' => 0,
  2410.                         'valueSub' => '_AUTO_',
  2411.                         'price' => $item['price'],
  2412.                         'fromWarehouse' => $item['warehouse_id'],
  2413.                         'toWarehouse' => 0,
  2414.                         'fromWarehouseSub' => $item['consumed_item_action_tag_id'],
  2415.                         'toWarehouseSub' => 0,
  2416.                         'production_nature_id' => $item['production_nature_id'],
  2417.                     );
  2418.                     $produced_data[$item['product_id']][] = array(
  2419.                         'date' => $last_refresh_date,
  2420.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2421.                         'entityId' => $item['production_id'],
  2422.                         'colorId' => $item['color_id'],
  2423.                         'sizeId' => $item['size_id'],
  2424.                         'entityDocHash' => $item['document_hash'],
  2425.                         'qtyAdd' => ($item['accepted_qty'] * 1),
  2426.                         'qtySub' => 0,
  2427.                         'valueAdd' => (($item['accepted_qty'] * 1) * ($item['price'])),
  2428.                         'valueSub' => 0,
  2429.                         'price' => $item['price'],
  2430.                         'fromWarehouse' => 0,
  2431.                         'toWarehouse' => $item['warehouse_id'],
  2432.                         'fromWarehouseSub' => 0,
  2433.                         'toWarehouseSub' => $item['produced_item_action_tag_id'],
  2434.                         'production_nature_id' => $item['production_nature_id'],
  2435.                     );
  2436.                     $rejected_data[$item['product_id']][] = array(
  2437.                         'date' => $last_refresh_date,
  2438.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2439.                         'entityId' => $item['production_id'],
  2440.                         'colorId' => $item['color_id'],
  2441.                         'sizeId' => $item['size_id'],
  2442.                         'entityDocHash' => $item['document_hash'],
  2443.                         'qtyAdd' => ($item['rejected_qty'] * 1),
  2444.                         'qtySub' => 0,
  2445.                         'valueAdd' => (($item['rejected_qty'] * 1) * ($item['price'])),
  2446.                         'valueSub' => 0,
  2447.                         'price' => $item['price'],
  2448.                         'fromWarehouse' => 0,
  2449.                         'toWarehouse' => $item['warehouse_id'],
  2450.                         'fromWarehouseSub' => 0,
  2451.                         'toWarehouseSub' => $item['rejected_item_action_tag_id'],
  2452.                         'production_nature_id' => $item['production_nature_id'],
  2453.                     );
  2454. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2455. //                $stmt = $em->getConnection()->prepare($get_kids_sql);
  2456. //                $stmt->execute();
  2457.                 }
  2458.                 foreach ($consumed_data as $key => $item) {
  2459.                     if (!empty($item)) {
  2460.                         foreach ($item as $entry) {
  2461.                             $transDate = new \DateTime($entry['date']);
  2462.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2463.                                 $key,
  2464.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2465.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2466.                                 $entry['fromWarehouse'],
  2467.                                 $entry['toWarehouse'],
  2468.                                 $entry['fromWarehouseSub'],
  2469.                                 $entry['toWarehouseSub'],
  2470.                                 $transDate,
  2471.                                 $entry['qtyAdd'],
  2472.                                 $entry['qtySub'],
  2473.                                 $entry['valueAdd'],
  2474.                                 $entry['valueSub'],
  2475.                                 $entry['price'],
  2476.                                 $this->getLoggedUserCompanyId($request),
  2477.                                 0,
  2478.                                 $entry['entity'],
  2479.                                 $entry['entityId'],
  2480.                                 $entry['entityDocHash'],
  2481.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION);
  2482.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2483.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2484.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2485.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2486.                                 "",
  2487.                                 'inventory_refresh_debug'1); //last er 1 is append
  2488.                             if (!isset($consumedAmountByProductionId[$entry['entityId']]))
  2489.                                 $consumedAmountByProductionId[$entry['entityId']] = ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2490.                             else
  2491.                                 $consumedAmountByProductionId[$entry['entityId']] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2492.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2493.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  2494.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2495.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2496.                             else
  2497.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2498.                             if ($last_refresh_date_obj == '') {
  2499.                                 $last_refresh_date_obj $transDate;
  2500.                             } else if ($transDate $last_refresh_date_obj) {
  2501.                                 $last_refresh_date_obj $transDate;
  2502.                             }
  2503.                         }
  2504.                     }
  2505.                 }
  2506.                 foreach ($produced_data as $key => $item) {
  2507.                     if (!empty($item)) {
  2508.                         foreach ($item as $entry) {
  2509.                             $transDate = new \DateTime($entry['date']);
  2510.                             $productionNature $entry['production_nature_id'];
  2511.                             if (in_array($productionNature, [12])) {
  2512.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2513.                                     $key,
  2514.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2515.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2516.                                     $entry['fromWarehouse'],
  2517.                                     $entry['toWarehouse'],
  2518.                                     $entry['fromWarehouseSub'],
  2519.                                     $entry['toWarehouseSub'],
  2520.                                     $transDate,
  2521.                                     $entry['qtyAdd'],
  2522.                                     $entry['qtySub'],
  2523. //                                $entry['valueAdd'],
  2524.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2525.                                     $entry['valueSub'],
  2526.                                     $entry['price'],
  2527.                                     $this->getLoggedUserCompanyId($request),
  2528.                                     0,
  2529.                                     $entry['entity'],
  2530.                                     $entry['entityId'],
  2531.                                     $entry['entityDocHash'],
  2532.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2533.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2534.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2535.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2536.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2537.                                     "",
  2538.                                     'inventory_refresh_debug'1); //last er 1 is append
  2539.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2540.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2541.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2542.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2543.                                 else
  2544.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2545. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2546. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2547. //                            else
  2548. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2549.                             } else {
  2550.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2551.                                     $key,
  2552.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2553.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2554.                                     $entry['fromWarehouse'],
  2555.                                     $entry['toWarehouse'],
  2556.                                     $entry['fromWarehouseSub'],
  2557.                                     $entry['toWarehouseSub'],
  2558.                                     $transDate,
  2559.                                     0,
  2560.                                     0,
  2561. //                                $entry['valueAdd'],
  2562.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2563.                                     0,
  2564.                                     $entry['price'],
  2565.                                     $this->getLoggedUserCompanyId($request),
  2566.                                     0,
  2567.                                     $entry['entity'],
  2568.                                     $entry['entityId'],
  2569.                                     $entry['entityDocHash'],
  2570.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2571.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2572.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2573.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2574.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2575.                                     "",
  2576.                                     'inventory_refresh_debug'1); //last er 1 is append
  2577.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2578.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2579.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2580.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2581.                                 else
  2582.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2583. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2584. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2585. //                            else
  2586. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2587.                             }
  2588.                             if ($last_refresh_date_obj == '') {
  2589.                                 $last_refresh_date_obj $transDate;
  2590.                             } else if ($transDate $last_refresh_date_obj) {
  2591.                                 $last_refresh_date_obj $transDate;
  2592.                             }
  2593.                         }
  2594.                     }
  2595.                 }
  2596.                 foreach ($rejected_data as $key => $item) {
  2597.                     if (!empty($item)) {
  2598.                         foreach ($item as $entry) {
  2599.                             $transDate = new \DateTime($entry['date']);
  2600.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2601.                                 $key,
  2602.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2603.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2604.                                 $entry['fromWarehouse'],
  2605.                                 $entry['toWarehouse'],
  2606.                                 $entry['fromWarehouseSub'],
  2607.                                 $entry['toWarehouseSub'],
  2608.                                 $transDate,
  2609.                                 $entry['qtyAdd'],
  2610.                                 $entry['qtySub'],
  2611.                                 $entry['valueAdd'],
  2612.                                 $entry['valueSub'],
  2613.                                 $entry['price'],
  2614.                                 $this->getLoggedUserCompanyId($request),
  2615.                                 0,
  2616.                                 $entry['entity'],
  2617.                                 $entry['entityId'],
  2618.                                 $entry['entityDocHash'],
  2619.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2620.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2621.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2622.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2623.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2624.                                 "",
  2625.                                 'inventory_refresh_debug'1); //last er 1 is append
  2626.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2627.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  2628.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2629.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = (-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2630.                             else
  2631.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ((-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2632.                             if ($last_refresh_date_obj == '') {
  2633.                                 $last_refresh_date_obj $transDate;
  2634.                             } else if ($transDate $last_refresh_date_obj) {
  2635.                                 $last_refresh_date_obj $transDate;
  2636.                             }
  2637.                         }
  2638.                     }
  2639.                 }
  2640.             }
  2641.             if ($modifyAccTransaction == 1) {
  2642.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2643.                     $docHere $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  2644.                         $docEntityIdField => $docId,
  2645.                     ));;
  2646.                     if ($docHere) {
  2647.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2648.                         if ($curr_v_ids == null)
  2649.                             $curr_v_ids = [];
  2650.                         $skipVids = [];
  2651.                         $toChangeVid 0;
  2652.                         $voucher null;
  2653.                         foreach ($curr_v_ids as $vid) {
  2654.                             if (in_array($vid$skipVids))
  2655.                                 continue;
  2656.                             $skipVids[] = $vid//to prevent duplicate query
  2657.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2658.                                 'transactionId' => $vid,
  2659.                             ));;
  2660.                             if ($voucher) {
  2661.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2662.                                     $toChangeVid $vid;
  2663.                                 } else {
  2664.                                     continue;
  2665.                                 }
  2666.                             }
  2667.                         }
  2668.                         if ($toChangeVid == 0) {
  2669.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2670.                                 $em,
  2671.                                 $docHere->getProductionDate()->format('Y-m-d'),
  2672.                                 0,
  2673.                                 AccountsConstant::VOUCHER_JOURNAL,
  2674.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  2675.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2676.                                 'JV',
  2677.                                 'GN',
  2678.                                 0,
  2679.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2680.                                 0,
  2681.                                 $docHere->getCreatedLoginId(),
  2682.                                 $docHere->getCompanyId(),
  2683.                                 '',
  2684.                                 0,
  2685.                                 1
  2686.                             );
  2687.                             $em->flush();
  2688.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2689.                                 'transactionId' => $toChangeVid,
  2690.                             ));;
  2691.                         }
  2692.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  2693.                         $tot_inv_amount 0;
  2694.                         foreach ($transData as $k => $v) {
  2695.                             $tot_inv_amount += ($v);
  2696.                             Accounts::CreateNewTransactionDetails($em,
  2697.                                 '',
  2698.                                 $toChangeVid,
  2699.                                 Generic::CurrToInt($v),
  2700.                                 $k,
  2701.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2702.                                 AccountsConstant::DEBIT,
  2703.                                 0,
  2704.                                 [],
  2705.                                 [],
  2706.                                 $docHere->getCreatedLoginId()
  2707.                             );
  2708.                         }
  2709. //                        $stockReceivedType = $docHere->getType();
  2710.                         $to_balance_head 0;
  2711. //                        if ($docHere->getTransferActionType() == 4)
  2712.                         if (1) {
  2713.                         } else {
  2714.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  2715.                                     'name' => 'inv_on_transit_head')
  2716.                             );
  2717.                             if ($inv_transit_head)
  2718.                                 $to_balance_head $inv_transit_head->getData();
  2719.                         }
  2720.                         if ($to_balance_head != 0) {
  2721.                             Accounts::CreateNewTransactionDetails($em,
  2722.                                 '',
  2723.                                 $toChangeVid,
  2724.                                 Generic::CurrToInt($tot_inv_amount),
  2725.                                 $to_balance_head,
  2726.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  2727.                                 AccountsConstant::CREDIT,
  2728.                                 0,
  2729.                                 [],
  2730.                                 [],
  2731.                                 $docHere->getCreatedLoginId()
  2732.                             );
  2733.                         }
  2734.                         if ($voucher)
  2735.                             $voucher->setTransactionAmount($tot_inv_amount);
  2736.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2737.                         if ($curr_v_ids != null)
  2738.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2739.                         else
  2740.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2741.                         $em->flush();
  2742. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2743.                     }
  2744.                 }
  2745.             }
  2746.             if ($terminate == 0) {
  2747.                 return new JsonResponse(array(
  2748.                     "success" => true,
  2749.                     "last_refresh_date" => $last_refresh_date,
  2750.                     "inventory_refreshed" => $refreshed_opening
  2751.                 ));
  2752.             } else {
  2753.                 return new JsonResponse(array(
  2754.                     "success" => false,
  2755.                     "last_refresh_date" => $last_refresh_date,
  2756.                     "inventory_refreshed" => $refreshed_opening
  2757.                 ));
  2758.             }
  2759.         }
  2760.         return new JsonResponse(array(
  2761.             "success" => false,
  2762.             "last_refresh_date" => $last_refresh_date,
  2763.             "inventory_refreshed" => $refreshed_opening
  2764.         ));
  2765.         //2 .now make an array with necessary data based on challan and grn for now willl need consumption later
  2766.         //broken into transactions not closing
  2767.         //structure---> $data['productId']=array(
  2768.         //'date'=>'2017-09-02 00:00:00'
  2769.         //'qtyAdd'=>'2'
  2770.         //'qtySub'=>'0'
  2771.         //'valueAdd'=>'2000'
  2772.         //'valueSub'=>'0'
  2773.         //'fromWarehouse'=>'0'
  2774.         //'toWarehouse'=>'0'
  2775.         //'fromWarehouseSub'=>'0'
  2776.         //'toWarehouseSub'=>'0'
  2777.         //)
  2778.         //
  2779.     }
  2780.     public function OpeningItemAction(Request $request)
  2781.     {
  2782.         $em $this->getDoctrine()->getManager();
  2783.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  2784.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  2785.         if ($request->isMethod('POST')) {
  2786.             $pp trim($request->request->get('purchasePrice'));
  2787. //replace comma with space
  2788.             $pp str_replace(","""$pp);
  2789.             if ($request->request->get('productId') != '') {
  2790.                 foreach ($request->request->get('warehouseId') as $key => $value) {
  2791.                     $data = array(
  2792.                         'productId' => $request->request->get('productId'),
  2793.                         'warehouseId' => $request->request->get('warehouseId')[$key],
  2794.                         'warehouseActionId' => $request->request->get('warehouseActionId')[$key],
  2795.                         'purchasePrice' => $pp,
  2796.                         'date' => new \DateTime($request->request->get('date')),
  2797.                         'qty' => $request->request->get('qty')[$key],
  2798.                     );
  2799.                     $transDate = new \DateTime($request->request->get('date'));
  2800.                     $new = new InvItemInOut();
  2801.                     $new->setProductId($request->request->get('productId'));
  2802.                     $new->setWarehouseId($request->request->get('warehouseId')[$key]);
  2803.                     $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  2804.                     $new->setActionTagId($request->request->get('warehouseActionId')[$key]);
  2805.                     $new->setTransactionDate($transDate);
  2806.                     $new->setQty($request->request->get('qty')[$key]);
  2807.                     $new->setPrice($pp);
  2808.                     $new->setAmount($request->request->get('qty')[$key] * $pp);
  2809.                     $new->setEntity(0);// opening =0
  2810.                     $new->setEntityId(0);// opening =0
  2811.                     $new->setDebitCreditHeadId(0);// opening =0
  2812.                     $new->setVoucherIds(null);// opening =0
  2813.                     $em->persist($new);
  2814.                     $em->flush();
  2815. //                    $total_inv_value_in_by_id += $request->request->get('qty')[$key] * $pp;
  2816.                     Inventory::AddOpeningInventoryStock($em$data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2817.                 }
  2818.             }
  2819.         }
  2820.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  2821.             'name' => 'warehouse_action_1'//for now for stock of goods
  2822.         ));
  2823.         return $this->render('@Inventory/pages/input_forms/opening_item_assign.html.twig',
  2824.             array(
  2825.                 'page_title' => "Opening Items",
  2826.                 'inv_head' => $inv_head $inv_head->getData() : '',
  2827.                 'products' => $this->getDoctrine()->getRepository('ApplicationBundle:InvProducts')->findBy(array(
  2828.                     'status' => GeneralConstant::ACTIVE//for now for stock of goods
  2829. //                    'opening_locked'=>0
  2830.                 )),
  2831.                 'warehouseList' => Inventory::WarehouseList($em),
  2832.                 'warehouseActionList' => $warehouse_action_list
  2833.             )
  2834.         );
  2835.     }
  2836.     public function CreateProductCategoryAction(Request $request)
  2837.     {
  2838.         if ($request->isMethod('POST')) {
  2839.             $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));
  2840.             if ($cat_data['id'] != '')
  2841.                 return new JsonResponse(array("success" => true'cat_data' => $cat_data));
  2842.         }
  2843.         return new JsonResponse(array("success" => false,));
  2844. //        return $this->redirectToRoute("create_product");
  2845.     }
  2846.     public function CreateProductSubCategoryAction(Request $request)
  2847.     {
  2848.         if ($request->isMethod('POST')) {
  2849.             $spec_data Inventory::CreateSubCategory($this->getDoctrine()->getManager(),
  2850.                 $this->getLoggedUserCompanyId($request), $request->request->get('spec_name'),
  2851.                 $request->request->get('level'0),
  2852.                 $request->request->get('parentId'0),
  2853.                 $request->request->get('itemgroupId'),
  2854.                 $request->request->get('categoryId'),
  2855.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2856.             if ($spec_data['id'] != '')
  2857.                 return new JsonResponse(array("success" => true'spec_data' => $spec_data));
  2858.         }
  2859.         return new JsonResponse(array("success" => false,));
  2860. //        return $this->redirectToRoute("create_product");
  2861.     }
  2862.     public function CreateProductBrandAction(Request $request)
  2863.     {
  2864.         if ($request->isMethod('POST')) {
  2865.             $data Inventory::CreateBrand($this->getDoctrine()->getManager(),
  2866.                 $this->getLoggedUserCompanyId($request), $request->request->get('brand_name'),
  2867.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2868.             if ($data['id'] != '')
  2869.                 return new JsonResponse(array("success" => true'data' => $data));
  2870.         }
  2871.         return new JsonResponse(array("success" => false,));
  2872. //        return $this->redirectToRoute("create_product");
  2873.     }
  2874.     public function CreateIssueNoteAction(Request $request)
  2875.     {
  2876.         return $this->render('@Inventory/pages/input_forms/issue_note.html.twig',
  2877.             array(
  2878.                 'page_title' => 'Issue Note'
  2879.             )
  2880.         );
  2881.     }
  2882.     public function ProcessDraftDeliveryReceiptAction(Request $request$id 0)
  2883.     {
  2884.         $em $this->getDoctrine()->getManager();
  2885.         $companyId $this->getLoggedUserCompanyId($request);
  2886.         $extId $id;
  2887.         $receiptId $id;
  2888.         $allowed 0;
  2889.         if ($request->isMethod('POST')) {
  2890.             $receiptId $request->request->get('deliveryReceiptId');
  2891.             $QD $this->getDoctrine()
  2892.                 ->getRepository('ApplicationBundle:DeliveryReceipt')
  2893.                 ->findOneBy(
  2894.                     array(
  2895.                         'deliveryReceiptId' => $receiptId
  2896.                     ),
  2897.                     array()
  2898.                 );
  2899.             $soId $QD->getSalesOrderId();
  2900.             $drData = [];
  2901.             $dr_item_data $em->getRepository('ApplicationBundle:DeliveryReceiptItem')->findBy(
  2902.                 array(
  2903.                     'deliveryReceiptId' => $receiptId,
  2904.                 )
  2905.             );
  2906.             foreach ($dr_item_data as $dr_item) {
  2907.                 $drData[] = array(
  2908.                     'soItemId' => $dr_item->getSalesorderItemId(),
  2909.                     'qty' => $dr_item->getQty()
  2910.                 );
  2911.             }
  2912. //            $drData=[
  2913. //                ['soItemId'=>9,'qty'=>9],
  2914. //                ['soItemId'=>9,'qty'=>9],
  2915. //                ['soItemId'=>9,'qty'=>9],
  2916. //            ];
  2917.             $toGetSoItemsId = [];
  2918.             $toGetDoItemsId = [];
  2919.             $drDataBySoItemId = [];
  2920.             $drDataByDoItemId = [];
  2921.             $so $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(array(
  2922.                 'salesOrderId' => $soId   //$id is soId
  2923.             ));
  2924.             if ($so->getDeliveryOrderSkipFlag() == 1) {
  2925.                 foreach ($drData as $pp) {
  2926.                     $toGetSoItemsId[] = $pp['soItemId'];
  2927.                     $drDataBySoItemId[$pp['soItemId']] = $pp;
  2928.                 }
  2929.             } else {
  2930.                 foreach ($drData as $pp) {
  2931.                     $toGetDoItemsId[] = $pp['soItemId'];
  2932.                     $drDataByDoItemId[$pp['soItemId']] = $pp;
  2933.                 }
  2934.                 $do_item_data $em->getRepository('ApplicationBundle:DeliveryOrderItem')->findBy(
  2935.                     array(
  2936.                         'salesorderId' => $id,
  2937.                         'id' => $toGetDoItemsId
  2938.                     )
  2939.                 );
  2940.                 foreach ($do_item_data as $dd) {
  2941.                     $toGetSoItemsId[] = $dd->getSalesorderItemId();
  2942.                     $drDataBySoItemId[$dd->getSalesorderItemId()] = $drDataByDoItemId[$dd->getId()];
  2943.                 }
  2944. //                $do_item_data = $em->getRepository('ApplicationBundle:SalesOrderItem')->findOneBy(
  2945. //                    array(
  2946. ////                'salesOrderId'=>$post_data->get('soId', null),
  2947. //                        'id' => $post_data->get('do_details_id')[$key]
  2948. //                    )
  2949. //                );
  2950.             }
  2951.             $so_item_data $em->getRepository('ApplicationBundle:SalesOrderItem')->findBy(
  2952.                 array(
  2953.                     'salesOrderId' => $soId,
  2954.                     'id' => $toGetSoItemsId
  2955.                 )
  2956.             );
  2957.             $prev_so_amount $so->getSoAmount();
  2958.             $total_discounted_amount 0;
  2959.             $total_product_amount 0;
  2960.             $total_discount 0;
  2961.             $total_special_discount $so->getSpecialDiscountAmount();
  2962.             $total_special_discount_rate $so->getSpecialDiscountRate();
  2963.             foreach ($so_item_data as $item) {
  2964.                 $qty $drDataBySoItemId[$item->getId()]['qty'];
  2965.                 $price $item->getPrice();
  2966.                 $amount $qty $price;
  2967.                 $discountAmount $amount * ($item->getDiscountRate() / 100);
  2968.                 $discountedAmount $amount $discountAmount;
  2969.                 $total_discounted_amount += $discountedAmount;
  2970.                 $total_discount += $discountAmount;
  2971.                 $total_product_amount += $amount;
  2972.             }
  2973.             $aitRate $so->getAitRate();
  2974.             $vatRate $so->getVatRate();
  2975.             if ($aitRate == '' || $aitRate == null$aitRate 0;
  2976.             if ($vatRate == '' || $vatRate == null$vatRate 0;
  2977. //        $so->setVatRate($post->get('vat_rate', null));
  2978.             $vatAmount $total_discounted_amount * ($vatRate 100);
  2979.             $aitAmount $total_discounted_amount * ($aitRate 100);
  2980.             $total_sales_amount $total_discounted_amount $vatAmount $aitAmount $total_special_discount;
  2981.             //now get client
  2982.             $client $em->getRepository('ApplicationBundle:AccClients')->findOneBy(array(
  2983.                 'clientId' => $so->getClientId(),
  2984.             ));
  2985.             if ($client->getCreditLimitEnabled() != 1) {
  2986.                 $allowed 1;
  2987.             } else {
  2988.                 $creditLimit $client->getCreditLimit();
  2989.                 $due $client->getClientDue();
  2990.                 if ($creditLimit >= ($due $total_sales_amount))
  2991.                     $allowed 1;
  2992.             }
  2993.             //now package data
  2994.             if ($allowed == 0) {
  2995.                 return new JsonResponse(array(
  2996.                     'success' => false,
  2997. //                        'documentHash' => $order->getDocumentHash(),
  2998.                     'documentId' => $receiptId,
  2999.                     'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3000.                     'viewUrl' => '',
  3001.                 ));
  3002.             }
  3003.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  3004.             $dochash $request->request->get('docHash'); //change
  3005.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3006.             $approveRole 1;  //created
  3007.             $approveHash $request->request->get('approvalHash');
  3008.             $receiptId $request->request->get('deliveryReceiptId');
  3009.             $sig DocValidation::isSignatureOk($em$loginId$approveHash);
  3010. //            $this->addFlash(
  3011. //                'success',
  3012. //                'New Transaction Added.'
  3013. //            );
  3014.             $success $sig == false true;
  3015.             if ($success == true) {
  3016.                 $QD $this->getDoctrine()
  3017.                     ->getRepository('ApplicationBundle:DeliveryReceipt')
  3018.                     ->findOneBy(
  3019.                         array(
  3020.                             'deliveryReceiptId' => $receiptId
  3021.                         ),
  3022.                         array()
  3023.                     );
  3024.                 $draftFlag $QD->getDraftFlag();
  3025.                 if ($draftFlag == 1) {
  3026.                     //now add Approval info
  3027.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3028.                     $approveRole 1;  //created
  3029.                     System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3030.                         $receiptId,
  3031.                         $loginId,
  3032.                         $approveRole,
  3033.                         $request->request->get('approvalHash'));
  3034.                     $options = array(
  3035.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3036.                         'notification_server' => $this->container->getParameter('notification_server'),
  3037.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3038.                         'url' => $this->generateUrl(
  3039.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  3040.                             ['entity_view_route_path_name']
  3041.                         )
  3042.                     );
  3043.                     System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3044.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3045.                         $receiptId,
  3046.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3047.                     );
  3048.                     $QD->setDraftFlag(0);
  3049.                     $em->flush();
  3050.                 }
  3051.                 $url $this->generateUrl(
  3052.                     'view_delivery_receipt'
  3053.                 );
  3054.                 if ($request->request->has('returnJson')) {
  3055. //                    $dr = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  3056. //                        array(
  3057. //                            'salesOrderId' => $orderId, ///material
  3058. //
  3059. //                        )
  3060. //                    );
  3061.                     return new JsonResponse(array(
  3062.                         'success' => true,
  3063. //                        'documentHash' => $order->getDocumentHash(),
  3064.                         'documentId' => $receiptId,
  3065.                         'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3066.                         'viewUrl' => $url "/" $receiptId,
  3067.                     ));
  3068.                 } else {
  3069.                     $this->addFlash(
  3070.                         'success',
  3071.                         'Action Successful'
  3072.                     );
  3073.                     return $this->redirect($url "/" $receiptId);
  3074.                 }
  3075.             }
  3076.         }
  3077.         return new JsonResponse(array(
  3078.             'success' => false,
  3079. //                        'documentHash' => $order->getDocumentHash(),
  3080.             'documentId' => $receiptId,
  3081.             'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3082.             'viewUrl' => '',
  3083.         ));
  3084.     }
  3085.     public function CreateServiceChallanAction(Request $request)
  3086.     {
  3087.         $em $this->getDoctrine()->getManager();
  3088.         if ($request->isMethod('POST')) {
  3089.             $entity_id array_flip(GeneralConstant::$Entity_list)['ServiceChallan']; //change
  3090.             $dochash $request->request->get('docHash'); //change
  3091.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3092.             $approveRole $request->request->get('approvalRole');
  3093.             $approveHash $request->request->get('approvalHash');
  3094.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  3095.                 $loginId$approveRole$approveHash)
  3096.             ) {
  3097.                 $this->addFlash(
  3098.                     'error',
  3099.                     'Sorry Could not insert Data.'
  3100.                 );
  3101.             } else {
  3102.                 $receiptId SalesOrderM::CreateNewServiceChallan($this->getDoctrine()->getManager(), $request->request,
  3103.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  3104.                     $this->getLoggedUserCompanyId($request));
  3105.                 //now add Approval info
  3106.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3107. //                $approveRole = 1;  //created
  3108.                 $options = array(
  3109.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3110.                     'notification_server' => $this->container->getParameter('notification_server'),
  3111.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3112.                     'url' => $this->generateUrl(
  3113.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ServiceChallan']]
  3114.                         ['entity_view_route_path_name']
  3115.                     )
  3116.                 );
  3117.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3118.                     array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3119.                     $receiptId,
  3120.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3121.                 );
  3122.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3123.                     $receiptId,
  3124.                     $loginId,
  3125.                     $approveRole,
  3126.                     $request->request->get('approvalHash'));
  3127.                 $this->addFlash(
  3128.                     'success',
  3129.                     'New Service Challan Created'
  3130.                 );
  3131.                 $url $this->generateUrl(
  3132.                     'view_service_challan'
  3133.                 );
  3134.                 return $this->redirect($url "/" $receiptId);
  3135.             }
  3136.         }
  3137.         return $this->render('@Inventory/pages/input_forms/create_service_challan.html.twig',
  3138.             array(
  3139.                 'page_title' => 'New Service Challan',
  3140.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  3141.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  3142.                 'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  3143.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  3144.                 'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
  3145.                 'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
  3146.                 'deliveryOrders' => SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
  3147.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
  3148.                 'serviceList' => Inventory::ServiceList($em$this->getLoggedUserCompanyId($request))
  3149.             )
  3150.         );
  3151.     }
  3152.     public function GetItemListForDrAction(Request $request)
  3153.     {
  3154.         $em $this->getDoctrine()->getManager();
  3155.         $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3156.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3157.         if ($request->isMethod('POST')) {
  3158.             $em $this->getDoctrine();
  3159.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3160.             );
  3161.             $Content = [];
  3162.             $Transport_data = [];
  3163.             $Lul_data = [];
  3164.             if ($request->request->get('doId') != '')
  3165.                 $find_array['deliveryOrderId'] = $request->request->get('doId');
  3166. //            if($request->request->get('warehouseId')!='')
  3167. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3168.             $QD $this->getDoctrine()
  3169.                 ->getRepository('ApplicationBundle:DeliveryOrderItem')
  3170.                 ->findBy(
  3171.                     $find_array,
  3172.                     array()
  3173.                 );
  3174. //            if($request->request->get('wareHouseId')!='')
  3175.             $DO $this->getDoctrine()
  3176.                 ->getRepository('ApplicationBundle:DeliveryOrder')
  3177.                 ->findOneBy(
  3178.                     $find_array,
  3179.                     array()
  3180.                 );
  3181.             $sendData = array(
  3182. //                'salesType'=>$SO->getSalesType(),
  3183. //                'packageData'=>[],
  3184.                 'productList' => [],
  3185. //                'productListByPackage'=>[],
  3186.             );
  3187.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3188.             $pckg_item_cross_match_data = [];
  3189.             $unitList Inventory::UnitTypeList($em);
  3190.             $colorList Inventory::GetColorList($em);
  3191.             foreach ($QD as $product) {
  3192. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  3193.                 if (($product->getBalance()) <= 0)
  3194.                     continue;
  3195.                 $fdm $product->getProductFdm();
  3196.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3197.                 $find_query = array();
  3198.                 $soItem $this->getDoctrine()
  3199.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  3200.                     ->findOneBy(
  3201.                         array(
  3202.                             'id' => $product->getSalesorderItemId()
  3203.                         )
  3204.                     );
  3205.                 if (!$soItem)
  3206.                     continue;
  3207. //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3208. //                $soBalance = $soItem->getBalance();
  3209.                 $soBalance $soItem->getQty();
  3210. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3211. //                $doBalance = $product->getBalance();
  3212.                 $doBalance $product->getQty();
  3213.                 //now check if any so ir do item id there that is at
  3214.                 //least pending
  3215.                 $approvalPendingDrs $this->getDoctrine()
  3216.                     ->getRepository('ApplicationBundle:DeliveryReceipt')
  3217.                     ->findBy(
  3218.                         array(
  3219.                             'deliveryOrderId' => $DO->getDeliveryOrderId(),
  3220.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3221.                         )
  3222.                     );
  3223.                 foreach ($approvalPendingDrs as $appPendDr) {
  3224.                     $appPendDrItem $this->getDoctrine()
  3225.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3226.                         ->findOneBy(
  3227.                             array(
  3228.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3229.                                 'salesorderItemId' => $product->getSalesorderItemId()
  3230.                             )
  3231.                         );
  3232.                     if ($appPendDrItem) {
  3233.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3234.                             $soBalance $soBalance $appPendDrItem->getQty();
  3235.                             $doBalance $doBalance $appPendDrItem->getQty();
  3236.                         }
  3237.                     }
  3238.                 }
  3239.                 $colorId $product->getColorId();
  3240.                 $size $product->getSizeId();
  3241. //                $find_query['colorId']=
  3242.                 if ($productData['productId'] != 0) {
  3243.                     $find_query['productId'] = $productData['productId'];
  3244.                     if ($colorId == '' || $colorId == || $colorId == null)
  3245.                         $colorId $productData['defaultColorId'];
  3246.                     if ($size == '' || $size == || $size == null)
  3247.                         $size $productData['defaultSize'];
  3248.                     $find_query['productId'] = $productData['productId'];
  3249.                 } else {
  3250.                     if ($productData['igId'] != 0) {
  3251.                         $find_query['igId'] = $productData['igId'];
  3252.                     }
  3253.                     if ($productData['categoryId'] != 0) {
  3254.                         $find_query['categoryId'] = $productData['categoryId'];
  3255.                     }
  3256.                     if ($productData['subCategoryId'] != 0) {
  3257.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3258.                     }
  3259.                     if ($productData['brandId'] != 0) {
  3260.                         $find_query['brandId'] = $productData['brandId'];
  3261.                     }
  3262.                 }
  3263.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3264.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3265.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3266. //                    $find_query['color'] = $colorId;
  3267.                 } else
  3268.                     $find_query['color'] = $colorId;
  3269.                 if ($size == '' || $size == || $size == null) {
  3270. //                    $find_query['size'] = $size;
  3271.                 } else
  3272.                     $find_query['size'] = 0;
  3273.                 $inventory_by_warehouse_list $this->getDoctrine()
  3274.                     ->getRepository('ApplicationBundle:InventoryStorage')
  3275.                     ->findBy(
  3276.                         $find_query,
  3277.                         array()
  3278.                     );
  3279.                 $new_pid $productData['productId'];
  3280.                 $p_data = array(
  3281.                     'details_id' => $product->getId(),
  3282. //                        'productId'=>$new_pid,
  3283.                     'productIdList' => [],
  3284.                     'multList' => [],
  3285.                     'drItemIds' => [],
  3286.                     'drItemQty' => [],
  3287.                     'drItemCodeIds' => [],
  3288.                     'drItemCartonIds' => [],
  3289.                     'colorIds' => [],
  3290.                     'colorNames' => [],
  3291.                     'sizeIds' => [],
  3292.                     'productNameList' => [],
  3293.                     'availableInventoryList' => [],
  3294.                     'warehouseActionId' => [],
  3295.                     'warehouseActionName' => [],
  3296.                     'availableBarcodes' => [],
  3297.                     'availableBarcodesStr' => [],
  3298. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3299. //                        'available_inventory'=>0,
  3300. //                        'package_id'=>$product->getPackageId(),
  3301.                     'qty' => $product->getQty(),
  3302.                     'delivered' => $product->getDelivered(),
  3303. //                    'deliverable' => $product->getDeliverable() - $product->getTransitQty(),
  3304.                     'deliverable' => min($soBalance$doBalance),
  3305. //                    'balance' => $product->getBalance(),
  3306.                     'balance' => min($soBalance$doBalance),
  3307.                     'productNameFdm' => $product->getProductNameFdm(),
  3308.                     'productFdm' => $product->getProductFdm(),
  3309. //                        'delivered'=>$product->getDelivered(),
  3310.                 );
  3311.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  3312.                     if ($inventory_by_warehouse->getQty() <= 0)
  3313.                         continue;
  3314.                     $unitType $product->getUnitTypeId();
  3315.                     $mult_unit 1;
  3316.                     if ($drId != 0) {
  3317.                         $drItem $this->getDoctrine()
  3318.                             ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3319.                             ->findOneBy(
  3320.                                 array(
  3321.                                     'deliveryReceiptId' => $drId,
  3322.                                     'productId' => $inventory_by_warehouse->getProductId(),
  3323.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  3324.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  3325.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  3326.                                 )
  3327.                             );
  3328.                         if ($drItem) {
  3329.                             $p_data['drItemIds'][] = $drItem->getId();
  3330.                             $p_data['drItemQty'][] = $drItem->getQty();
  3331.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  3332.                             if ($codes == null)
  3333.                                 $codes = [];
  3334.                             $p_data['drItemCodeIds'][] = $codes;
  3335.                             $codes json_decode($drItem->getCartonIds(), true);
  3336.                             if ($codes == null)
  3337.                                 $codes = [];
  3338.                             $p_data['drItemCartonIds'][] = $codes;
  3339.                         } else {
  3340.                             $p_data['drItemIds'][] = 0;
  3341.                             $p_data['drItemQty'][] = 0;
  3342.                             $p_data['drItemCodeIds'][] = 0;
  3343.                             $p_data['drItemCartonIds'][] = 0;
  3344.                         }
  3345.                     } else {
  3346.                         $p_data['drItemIds'][] = 0;
  3347.                         $p_data['drItemQty'][] = 0;
  3348.                         $p_data['drItemCodeIds'][] = 0;
  3349.                         $p_data['drItemCartonIds'][] = 0;
  3350.                     }
  3351.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  3352.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  3353.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  3354.                         }
  3355.                     };
  3356.                     if ($mult_unit == 0)
  3357.                         $mult_unit 1;
  3358.                     $inv_product_id $inventory_by_warehouse->getProductId();
  3359.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  3360.                     $p_data['multList'][] = $mult_unit;
  3361.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  3362.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  3363.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  3364.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  3365.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  3366. //                        $p_data['availableInventoryList'][]=$inventory_by_warehouse?(($inventory_by_warehouse->getQty())*$mult_unit):0;
  3367.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  3368.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  3369.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  3370.                 }
  3371.                 $sendData['productList'][] = $p_data;
  3372.             }
  3373.             //now package data
  3374.             if ($sendData) {
  3375.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3376.             }
  3377.             return new JsonResponse(array("success" => false));
  3378.         }
  3379.         return new JsonResponse(array("success" => false));
  3380.     }
  3381.     public function GetItemListForDrBySoAction(Request $request)
  3382.     {
  3383.         $em $this->getDoctrine()->getManager();
  3384.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3385.         if ($request->isMethod('POST')) {
  3386.             $em $this->getDoctrine();
  3387.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3388. //                'type'=>1//product only
  3389.             );
  3390.             $find_item_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3391.                 'type' => 1//product only
  3392.             );
  3393.             $Content = [];
  3394.             $Transport_data = [];
  3395.             $Lul_data = [];
  3396.             $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3397.             if ($request->request->get('soId') != '') {
  3398.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3399.                 $find_item_array['salesOrderId'] = $request->request->get('soId');
  3400.             }
  3401. //            if($request->request->get('warehouseId')!='')
  3402. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3403.             $QD $this->getDoctrine()
  3404.                 ->getRepository('ApplicationBundle:SalesOrderItem')
  3405.                 ->findBy(
  3406.                     $find_item_array,
  3407.                     array()
  3408.                 );
  3409. //            if($request->request->get('wareHouseId')!='')
  3410.             $DO $this->getDoctrine()
  3411.                 ->getRepository('ApplicationBundle:SalesOrder')
  3412.                 ->findOneBy(
  3413.                     $find_array,
  3414.                     array()
  3415.                 );
  3416.             $sendData = array(
  3417. //                'salesType'=>$SO->getSalesType(),
  3418. //                'packageData'=>[],
  3419.                 'productList' => [],
  3420. //                'productListByPackage'=>[],
  3421.             );
  3422.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3423.             $pckg_item_cross_match_data = [];
  3424.             $unitList Inventory::UnitTypeList($em);
  3425.             $colorList Inventory::GetColorList($em);
  3426.             foreach ($QD as $product) {
  3427.                 if (($product->getBalance() - $product->getTransitQty()) <= 0)
  3428.                     continue;
  3429.                 //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3430. //                $soBalance = $soItem->getBalance();
  3431.                 $soBalance $product->getQty();
  3432. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3433. //                $doBalance = $product->getBalance();
  3434. //                $doBalance = 0;
  3435.                 //now check if any so ir do item id there that is at
  3436.                 //least pending
  3437.                 $approvalPendingDrs $this->getDoctrine()
  3438.                     ->getRepository('ApplicationBundle:DeliveryReceipt')
  3439.                     ->findBy(
  3440.                         array(
  3441.                             'salesOrderId' => $DO->getSalesOrderId(),
  3442.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3443.                         )
  3444.                     );
  3445.                 foreach ($approvalPendingDrs as $appPendDr) {
  3446.                     $appPendDrItem $this->getDoctrine()
  3447.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3448.                         ->findOneBy(
  3449.                             array(
  3450.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3451. //                                'salesorderItemId' => $product->getId(),
  3452.                                 'salesorderItemId' => $product->getId()
  3453.                             )
  3454.                         );
  3455.                     if ($appPendDrItem) {
  3456.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3457.                             $soBalance $soBalance $appPendDrItem->getQty();
  3458.                         }
  3459. //                        $doBalance=$doBalance-$appPendDrItem->getQty();
  3460.                     }
  3461.                 }
  3462.                 $fdm $product->getProductFdm();
  3463.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3464.                 $find_query = array();
  3465.                 $colorId $product->getColorId();
  3466.                 $size $product->getSizeId();
  3467. //                $find_query['colorId']=
  3468.                 if ($productData['productId'] != 0) {
  3469.                     $find_query['productId'] = $productData['productId'];
  3470.                     if ($colorId == '' || $colorId == || $colorId == null)
  3471.                         $colorId $productData['defaultColorId'];
  3472.                     if ($size == '' || $size == || $size == null)
  3473.                         $size $productData['defaultSize'];
  3474.                 } else {
  3475.                     if ($productData['igId'] != 0) {
  3476.                         $find_query['igId'] = $productData['igId'];
  3477.                     }
  3478.                     if ($productData['categoryId'] != 0) {
  3479.                         $find_query['categoryId'] = $productData['categoryId'];
  3480.                     }
  3481.                     if ($productData['subCategoryId'] != 0) {
  3482.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3483.                     }
  3484.                     if ($productData['brandId'] != 0) {
  3485.                         $find_query['brandId'] = $productData['brandId'];
  3486.                     }
  3487.                 }
  3488.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3489.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3490.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3491. //                    $find_query['color'] = $colorId;
  3492.                 } else
  3493.                     $find_query['color'] = $colorId;
  3494.                 if ($size == '' || $size == || $size == null) {
  3495. //                    $find_query['size'] = $size;
  3496.                 } else
  3497.                     $find_query['size'] = 0;
  3498.                 $inventory_by_warehouse_list $this->getDoctrine()
  3499.                     ->getRepository('ApplicationBundle:InventoryStorage')
  3500.                     ->findBy(
  3501.                         $find_query,
  3502.                         array()
  3503.                     );
  3504.                 $new_pid $productData['productId'];
  3505.                 $unitType $product->getUnitTypeId();
  3506.                 $p_data = array(
  3507.                     'details_id' => $product->getId(),
  3508.                     'unitType' => $unitType,
  3509.                     'productIdList' => [],
  3510.                     'multList' => [],
  3511.                     'drItemIds' => [],
  3512.                     'drItemQty' => [],
  3513.                     'drItemCodeIds' => [],
  3514.                     'drItemCartonIds' => [],
  3515.                     'colorIds' => [],
  3516.                     'colorNames' => [],
  3517.                     'sizeIds' => [],
  3518.                     'productNameList' => [],
  3519.                     'availableInventoryList' => [],
  3520.                     'warehouseActionId' => [],
  3521.                     'warehouseActionName' => [],
  3522.                     'availableBarcodes' => [],
  3523.                     'availableBarcodesStr' => [],
  3524. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3525. //                        'available_inventory'=>0,
  3526. //                        'package_id'=>$product->getPackageId(),
  3527.                     'qty' => $product->getQty(),
  3528.                     'delivered' => $product->getDelivered(),
  3529. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  3530. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  3531.                     'deliverable' => $soBalance,
  3532. //                    'deliverable' => $product->getBalance(),
  3533.                     'balance' => $soBalance,
  3534. //                    'balance' => $product->getBalance(),
  3535.                     'productNameFdm' => $product->getProductNameFdm(),
  3536.                     'productFdm' => $product->getProductFdm(),
  3537. //                        'delivered'=>$product->getDelivered(),
  3538.                 );
  3539.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  3540.                     if ($inventory_by_warehouse->getQty() <= 0)
  3541.                         continue;
  3542.                     $mult_unit 1;
  3543.                     if ($drId != 0) {
  3544.                         $drItem $this->getDoctrine()
  3545.                             ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3546.                             ->findOneBy(
  3547.                                 array(
  3548.                                     'deliveryReceiptId' => $drId,
  3549.                                     'productId' => $inventory_by_warehouse->getProductId(),
  3550.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  3551.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  3552.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  3553.                                 )
  3554.                             );
  3555.                         if ($drItem) {
  3556.                             $p_data['drItemIds'][] = $drItem->getId();
  3557.                             $p_data['drItemQty'][] = $drItem->getQty();
  3558.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  3559.                             if ($codes == null)
  3560.                                 $codes = [];
  3561.                             $p_data['drItemCodeIds'][] = $codes;
  3562.                             $codes json_decode($drItem->getCartonIds(), true);
  3563.                             if ($codes == null)
  3564.                                 $codes = [];
  3565.                             $p_data['drItemCartonIds'][] = $codes;
  3566.                         } else {
  3567.                             $p_data['drItemIds'][] = 0;
  3568.                             $p_data['drItemQty'][] = 0;
  3569.                             $p_data['drItemCodeIds'][] = 0;
  3570.                             $p_data['drItemCartonIds'][] = 0;
  3571.                         }
  3572.                     } else {
  3573.                         $p_data['drItemIds'][] = 0;
  3574.                         $p_data['drItemQty'][] = 0;
  3575.                         $p_data['drItemCodeIds'][] = 0;
  3576.                         $p_data['drItemCartonIds'][] = 0;
  3577.                     }
  3578.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  3579.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  3580.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  3581.                         }
  3582.                     };
  3583.                     if ($mult_unit == 0)
  3584.                         $mult_unit 1;
  3585.                     $inv_product_id $inventory_by_warehouse->getProductId();
  3586.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  3587.                     $p_data['multList'][] = $mult_unit;
  3588.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  3589.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  3590.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  3591.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  3592.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  3593.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  3594.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  3595.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  3596.                 }
  3597.                 $sendData['productList'][] = $p_data;
  3598.             }
  3599.             //now package data
  3600.             if ($sendData) {
  3601.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3602.             }
  3603.             return new JsonResponse(array("success" => false));
  3604.         }
  3605.         return new JsonResponse(array("success" => false));
  3606.     }
  3607.     public function GetItemListForStockReqBySoAction(Request $request)
  3608.     {
  3609.         $em $this->getDoctrine()->getManager();
  3610.         if ($request->isMethod('POST')) {
  3611.             $em $this->getDoctrine();
  3612.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3613.             );
  3614.             $Content = [];
  3615.             $Transport_data = [];
  3616.             $Lul_data = [];
  3617.             $find_array['serviceId'] = [0null];
  3618.             $sendData = array(
  3619. //                'salesType'=>$SO->getSalesType(),
  3620. //                'packageData'=>[],
  3621.                 'productList' => [],
  3622. //                'productListByPackage'=>[],
  3623.             );
  3624.             if ($request->request->get('soId') != '') {
  3625.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3626. //            if($request->request->get('warehouseId')!='')
  3627. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3628.                 $QD $this->getDoctrine()
  3629.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  3630.                     ->findBy(
  3631.                         $find_array,
  3632.                         array()
  3633.                     );
  3634. //            if($request->request->get('wareHouseId')!='')
  3635. //            $DO = $this->getDoctrine()
  3636. //                ->getRepository('ApplicationBundle:SalesOrder')
  3637. //                ->findOneBy(
  3638. //                    $find_array,
  3639. //                    array()
  3640. //                );
  3641.                 $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3642.                 $pckg_item_cross_match_data = [];
  3643.                 $unitList Inventory::UnitTypeList($em);
  3644.                 foreach ($QD as $product) {
  3645. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  3646. //                    continue;
  3647.                     $fdm $product->getProductFdm();
  3648.                     $unitType $product->getUnitTypeId();
  3649.                     $p_data = array(
  3650.                         'details_id' => $product->getId(),
  3651.                         'unitType' => $unitType,
  3652.                         'productIdList' => [],
  3653.                         'multList' => [],
  3654.                         'productNameList' => [],
  3655.                         'availableInventoryList' => [],
  3656.                         'warehouseActionId' => [],
  3657.                         'warehouseActionName' => [],
  3658.                         'availableBarcodes' => [],
  3659.                         'availableBarcodesStr' => [],
  3660. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3661. //                        'available_inventory'=>0,
  3662. //                        'package_id'=>$product->getPackageId(),
  3663.                         'qty' => $product->getQty(),
  3664.                         'delivered' => $product->getDelivered(),
  3665. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  3666. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  3667.                         'deliverable' => $product->getBalance(),
  3668.                         'balance' => $product->getBalance(),
  3669.                         'productNameFdm' => $product->getProductNameFdm(),
  3670.                         'productFdm' => $product->getProductFdm(),
  3671. //                        'delivered'=>$product->getDelivered(),
  3672.                     );
  3673.                     $sendData['productList'][] = $p_data;
  3674.                 }
  3675.             }
  3676.             //now package data
  3677.             if ($sendData) {
  3678.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3679.             }
  3680.             return new JsonResponse(array("success" => false));
  3681.         }
  3682.         return new JsonResponse(array("success" => false));
  3683.     }
  3684.     public function GetBarcodesListForStAction(Request $request)
  3685.     {
  3686.         $em $this->getDoctrine()->getManager();
  3687.         $sendData = [];
  3688.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3689.         if ($request->isMethod('POST')) {
  3690.             $em $this->getDoctrine();
  3691.             $find_query = array();
  3692.             $find_query['warehouseId'] = $request->request->get('warehouseId');
  3693.             $find_query['actionTagId'] = $request->request->get('warehouseActionId');
  3694.             $find_query['productId'] = $request->request->get('productId');
  3695.             $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3696.             $inventory_by_warehouse_list $this->getDoctrine()
  3697.                 ->getRepository('ApplicationBundle:InventoryStorage')
  3698.                 ->findBy(
  3699.                     $find_query,
  3700.                     array()
  3701.                 );
  3702.             $new_pid $request->request->get('productId');
  3703.             $p_data = array();
  3704.             //now get bacodes if available
  3705. //                    $query = "SELECT product_by_code_id, GROUP_CONCAT(DISTINCT sales_code SEPARATOR ',') sales_code_list_str
  3706. //FROM product_by_code
  3707. //where company_id=" . $this->getLoggedUserCompanyId($request).
  3708. //                        " and product_id=".$inv_product_id.
  3709. //                        " and warehouse_id=".$inventory_by_warehouse->getWarehouseId().
  3710. //                        " and warehouse_action_id=".$inventory_by_warehouse->getActionTagId();
  3711. //                        " GROUP BY product_by_code_id" ;
  3712.             $query "SELECT product_by_code_id, sales_code
  3713. FROM product_by_code
  3714. where company_id=" $this->getLoggedUserCompanyId($request) .
  3715.                 " and product_id=" $request->request->get('productId') .
  3716.                 " and warehouse_id=" $request->request->get('warehouseId') .
  3717.                 " and warehouse_action_id=" $request->request->get('warehouseActionId');
  3718.             $stmt $em->getConnection()->prepare($query);
  3719.             $stmt->execute();
  3720.             $results $stmt->fetchAll();
  3721.             $sales_code_list_str '';
  3722.             foreach ($results as $pika => $result) {
  3723.                 if ($pika != 0)
  3724.                     $sales_code_list_str .= ',';
  3725.                 $sales_code_list_str .= str_pad($result['sales_code'], 13'0'STR_PAD_LEFT);
  3726.             }
  3727.             if ($results) {
  3728.                 $p_data['availableBarcodes'] = $sales_code_list_str != '' || $sales_code_list_str != null
  3729.                     explode(','$sales_code_list_str) : [];
  3730.                 $p_data['availableBarcodesStr'] = $sales_code_list_str != '' || $sales_code_list_str != null
  3731.                     $sales_code_list_str "";
  3732. //
  3733.             } else {
  3734.                 $p_data['availableBarcodes'] = [];
  3735.                 $p_data['availableBarcodesStr'] = "";
  3736. //
  3737.             }
  3738.             $sendData $p_data;
  3739.         }
  3740.         //now package data
  3741.         if (!empty($sendData['availableBarcodes'])) {
  3742.             return new JsonResponse(array("success" => true"content" => $sendData));
  3743.         }
  3744.         return new JsonResponse(array("success" => false));
  3745.     }
  3746.     public function GetItemListForSalesReturnAction(Request $request)
  3747.     {
  3748.         if ($request->isMethod('POST')) {
  3749.             $em $this->getDoctrine();
  3750.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3751.             );
  3752.             $Content = [];
  3753.             $Transport_data = [];
  3754.             $Lul_data = [];
  3755.             if ($request->request->get('drId') != '')
  3756.                 $find_array['deliveryReceiptId'] = $request->request->get('drId');
  3757. //            if($request->request->get('warehouseId')!='')
  3758. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3759.             $QD $this->getDoctrine()
  3760.                 ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3761.                 ->findBy(
  3762.                     $find_array,
  3763.                     array()
  3764.                 );
  3765. //            if($request->request->get('wareHouseId')!='')
  3766.             $DR $this->getDoctrine()
  3767.                 ->getRepository('ApplicationBundle:DeliveryReceipt')
  3768.                 ->findOneBy(
  3769.                     $find_array,
  3770.                     array()
  3771.                 );
  3772.             $sendData = array(
  3773.                 'productList' => [],
  3774.             );
  3775.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3776.             $pckg_item_cross_match_data = [];
  3777.             $unitList Inventory::UnitTypeList($em);
  3778.             foreach ($QD as $product) {
  3779.                 if (($product->getQty()) <= 0)
  3780.                     continue;
  3781.                 $new_pid $product->getProductId();
  3782.                 $sales_code_range = [];
  3783.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  3784.                     $sales_code_range json_decode($product->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  3785.                 } else {
  3786.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  3787.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getSalesCodeRange());
  3788.                     $sales_code_range json_decode($json_without_bigintstrue);
  3789.                 }
  3790.                 $p_data = array(
  3791.                     'details_id' => $product->getId(),
  3792.                     'dr_id' => $product->getDeliveryReceiptId(),
  3793.                     'productId' => $new_pid,
  3794.                     'product_name' => isset($productList[$new_pid]) ? $productList[$new_pid]['name'] : '',
  3795.                     'qty' => $product->getQty(),
  3796.                     'delivered' => $product->getDelivered(),
  3797.                     'unitTypeId' => $product->getUnitTypeId(),
  3798.                     'deliverable' => $product->getDeliverable(),
  3799.                     'balance' => $product->getBalance(),
  3800.                     'salesCodeRangeStr' => $product->getSalesCodeRange(),
  3801.                     'salesCodeRange' => $sales_code_range,
  3802.                     'sales_codes' => $sales_code_range,
  3803.                     'sales_price' => $product->getPrice(),
  3804.                     'purchase_price' => $product->getCurrentPurchasePrice()
  3805. //                        'delivered'=>$product->getDelivered(),
  3806.                 );
  3807.                 $sendData['productList'][] = $p_data;
  3808.             }
  3809.             //now package data
  3810.             if ($sendData) {
  3811.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3812.             }
  3813.             return new JsonResponse(array("success" => false));
  3814.         }
  3815.         return new JsonResponse(array("success" => false));
  3816.     }
  3817.     public function GetItemListForIrrAction(Request $request)
  3818.     {
  3819.         if ($request->isMethod('POST')) {
  3820.             $em $this->getDoctrine();
  3821.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3822.             );
  3823.             $Content = [];
  3824.             $Transport_data = [];
  3825.             $Lul_data = [];
  3826.             if ($request->request->get('srId') != '')
  3827.                 $find_array['salesReturnId'] = $request->request->get('srId');
  3828. //            if($request->request->get('warehouseId')!='')
  3829. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3830.             $QD $this->getDoctrine()
  3831.                 ->getRepository('ApplicationBundle:SalesReturnItem')
  3832.                 ->findBy(
  3833.                     $find_array,
  3834.                     array()
  3835.                 );
  3836. //            if($request->request->get('wareHouseId')!='')
  3837.             $sendData = array(
  3838.                 'productList' => [],
  3839.             );
  3840.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3841.             $pckg_item_cross_match_data = [];
  3842.             $unitList Inventory::UnitTypeList($em);
  3843.             foreach ($QD as $product) {
  3844.                 if (($product->getReceivedBalance()) <= && ($product->getReplacedBalance()) <= 0)
  3845.                     continue;
  3846.                 $DR_ITEM null;
  3847.                 $DR_TAGGED_CODES = [];
  3848.                 $DR_TAGGED_CODES_FOR_SELECTIZE = [];
  3849.                 $RESTRICT_RECEIVED_CODES_FLAG 0;
  3850.                 $sales_code_range = [];
  3851.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  3852.                     $sales_code_range json_decode($product->getReceivedCodeRange(), true512JSON_BIGINT_AS_STRING);
  3853.                 } else {
  3854.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  3855.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getReceivedCodeRange());
  3856.                     $sales_code_range json_decode($json_without_bigintstrue);
  3857.                 }
  3858.                 $DR_TAGGED_CODES $sales_code_range;
  3859.                 if (!empty($DR_TAGGED_CODES)) {
  3860.                     $RESTRICT_RECEIVED_CODES_FLAG 1;
  3861.                     foreach ($DR_TAGGED_CODES as $DTC) {
  3862.                         $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  3863.                             'value' => $DTC
  3864.                         );
  3865.                     }
  3866.                 }
  3867. //                if ($product->getTaggedDetailsId() != 0 && $product->getTaggedDetailsId() != null) {
  3868. //
  3869. //                    $DR_ITEM = $this->getDoctrine()
  3870. //                        ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3871. //                        ->findOneBy(
  3872. //                            array(
  3873. //                                'id' => $product->getTaggedDetailsId()
  3874. //                            ),
  3875. //                            array()
  3876. //                        );
  3877. //                    if ($DR_ITEM) {
  3878. //                        if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  3879. //
  3880. //                            $DR_TAGGED_CODES = json_decode($DR_ITEM->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  3881. //                        } else {
  3882. //
  3883. //                            $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  3884. //                            $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $DR_ITEM->getSalesCodeRange());
  3885. //                            $DR_TAGGED_CODES = json_decode($json_without_bigints, true);
  3886. //                        }
  3887. //
  3888. //                        if ($DR_TAGGED_CODES == null)
  3889. //                            $DR_TAGGED_CODES = [];
  3890. //                        if (!empty($DR_TAGGED_CODES)) {
  3891. //                            $RESTRICT_RECEIVED_CODES_FLAG = 1;
  3892. //                            foreach ($DR_TAGGED_CODES as $DTC) {
  3893. //                                $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  3894. //                                    'value' => $DTC
  3895. //                                );
  3896. //                            }
  3897. //                        }
  3898. //                    }
  3899. //                }
  3900.                 $p_data = array(
  3901.                     'details_id' => $product->getId(),
  3902.                     'receivedDrTaggedCodes' => $DR_TAGGED_CODES,
  3903.                     'receivedDrTaggedCodesStr' => implode(','$DR_TAGGED_CODES),
  3904.                     'receivedDrTaggedCodesForSel' => $DR_TAGGED_CODES_FOR_SELECTIZE,
  3905.                     'receivedRestrictCodesFlag' => $RESTRICT_RECEIVED_CODES_FLAG,
  3906.                     'receivedProductId' => $product->getReceivedProductId(),
  3907.                     'receivedBalance' => $product->getReceivedBalance(),
  3908.                     'receivedUnitSalesPrice' => $product->getReceivedUnitSalesPrice(),
  3909.                     'receivedUnitPurchasePrice' => $product->getReceivedUnitPurchasePrice(),
  3910.                     'receivedProductName' => isset($productList[$product->getReceivedProductId()]) ? $productList[$product->getReceivedProductId()]['name'] : '',
  3911.                     'replacedProductId' => $product->getReplacedProductId(),
  3912.                     'replacedBalance' => $product->getReplacedBalance(),
  3913.                     'replacedUnitSalesPrice' => $product->getReplacedUnitSalesPrice(),
  3914.                     'replacedUnitPurchasePrice' => $product->getReplacedUnitPurchasePrice(),
  3915.                     'replacedProductName' => isset($productList[$product->getReplacedProductId()]) ? $productList[$product->getReplacedProductId()]['name'] : '',
  3916.                     'disposeBalance' => $product->getDisposeBalance(),
  3917.                     'unusedBalance' => $product->getUnusedBalance(),
  3918.                     'disposeTag' => $product->getDisposeTag(),
  3919.                     'unitTypeId' => $product->getUnitTypeId(),
  3920. //                        'delivered'=>$product->getDelivered(),
  3921.                 );
  3922.                 $sendData['productList'][] = $p_data;
  3923.             }
  3924.             //now package data
  3925.             if ($sendData) {
  3926.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3927.             }
  3928.             return new JsonResponse(array("success" => false));
  3929.         }
  3930.         return new JsonResponse(array("success" => false));
  3931.     }
  3932.     public function LabelFormatAction(Request $request$id 0)
  3933.     {
  3934.         $data = array(
  3935.             'formatId' => '',
  3936.             'formatCode' => '',
  3937.             'name' => '',
  3938.             'labelType' => 0,
  3939.             'width' => 60,
  3940.             'pageWidth' => 6,
  3941.             'height' => 39,
  3942.             'pageHeight' => 2,
  3943.             'formatData' => '',
  3944.         );
  3945.         if ($request->isMethod('POST')) {
  3946.             $post $request->request;
  3947.             $exists_already 0;
  3948.             if ($request->request->get('formatId') != '') {
  3949.                 $query_here $this->getDoctrine()
  3950.                     ->getRepository('ApplicationBundle:LabelFormat')
  3951.                     ->findOneBy(
  3952.                         array(
  3953.                             'formatId' => $request->request->get('formatId')
  3954.                         )
  3955.                     );
  3956.                 if (!empty($query_here)) {
  3957.                     $exists_already 1;
  3958.                     $new $query_here;
  3959.                 } else
  3960.                     $new = new LabelFormat();
  3961.             } else
  3962.                 $new = new LabelFormat();
  3963.             $new->setName($request->request->get('name'));
  3964.             $new->setLabelType($request->request->get('labelType'));
  3965.             $new->setWidth($request->request->get('width'));
  3966.             $new->setHeight($request->request->get('height'));
  3967.             $new->setFormatCode($request->request->get('formatCode'));
  3968.             $new->setActive(GeneralConstant::ACTIVE);
  3969.             $new->setPageHeight($request->request->get('pageHeight'));
  3970.             $new->setPageWidth($request->request->get('pageWidth'));
  3971.             $new->setFormatData($request->request->get('formatData'));
  3972.             if ($exists_already == 0)
  3973.                 $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3974.             $new->setEditLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3975.             $new->setCompanyId($request->getSession()->get(UserConstants::USER_COMPANY_ID));
  3976.             $em $this->getDoctrine()->getManager();
  3977.             $em->persist($new);
  3978.             $em->flush();
  3979.         }
  3980.         if ($id != 0) {
  3981.             $query_here $this->getDoctrine()
  3982.                 ->getRepository('ApplicationBundle:LabelFormat')
  3983.                 ->findOneBy(
  3984.                     array(
  3985.                         'formatId' => $id
  3986.                     )
  3987.                 );
  3988.             if ($query_here)
  3989.                 $data $query_here;
  3990.         } else if ($request->query->has('formatId')) {
  3991.             $query_here $this->getDoctrine()
  3992.                 ->getRepository('ApplicationBundle:LabelFormat')
  3993.                 ->findOneBy(
  3994.                     array(
  3995.                         'formatId' => $request->query->get('formatId')
  3996.                     )
  3997.                 );
  3998.             if ($query_here)
  3999.                 $data $query_here;
  4000.         }
  4001.         return $this->render(
  4002.             '@Inventory/pages/input_forms/label_format.html.twig',
  4003.             array(
  4004.                 'page_title' => 'Label Format',
  4005.                 'data' => $data,
  4006.                 'labelTypeList' => LabelConstant::$label_type_list,
  4007.                 'labelFieldsList' => LabelConstant::$label_fields_list,
  4008.                 'formatList' => $this->getDoctrine()
  4009.                     ->getRepository('ApplicationBundle:LabelFormat')
  4010.                     ->findBy(
  4011.                         array( //                            'formatId' => $request->query->get('formatId')
  4012.                         )
  4013.                     )
  4014.                 //                'incomeLedgerHeads'=>Accounts::getChildLedgerHeads($this->getDoctrine()->getManager(),AccountsConstant::INCOME)
  4015.             )
  4016.         );
  4017.     }
  4018.     public function GetServiceListForScAction(Request $request)
  4019.     {
  4020.         if ($request->isMethod('POST')) {
  4021.             $em $this->getDoctrine();
  4022.             $find_array = array(
  4023.                 'type' => 2//service
  4024.             );
  4025.             $Content = [];
  4026.             $Transport_data = [];
  4027.             $Lul_data = [];
  4028.             if ($request->request->get('soId') != '')
  4029.                 $find_array['salesOrderId'] = $request->request->get('soId');
  4030. //            if($request->request->get('warehouseId')!='')
  4031. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4032.             $QD $this->getDoctrine()
  4033.                 ->getRepository('ApplicationBundle:SalesOrderItem')
  4034.                 ->findBy(
  4035.                     $find_array,
  4036.                     array()
  4037.                 );
  4038. //            if($request->request->get('wareHouseId')!='')
  4039.             $SO $this->getDoctrine()
  4040.                 ->getRepository('ApplicationBundle:SalesOrder')
  4041.                 ->findOneBy(
  4042.                     array(
  4043.                         'salesOrderId' => $request->request->get('soId')
  4044.                     ),
  4045.                     array()
  4046.                 );
  4047.             $sendData = array(
  4048. //                'salesType'=>$SO->getSalesType(),
  4049. //                'packageData'=>[],
  4050.                 'productList' => [],
  4051. //                'productListByPackage'=>[],
  4052.             );
  4053.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager(), $SO->getCompanyId());
  4054.             $pckg_item_cross_match_data = [];
  4055.             foreach ($QD as $product) {
  4056.                 $p_data = array(
  4057.                     'details_id' => $product->getId(),
  4058.                     'service_id' => $product->getServiceId(),
  4059.                     'service_name' => $serviceList[$product->getServiceId()]['name'],
  4060.                     'available_inventory' => $product->getBalance(),
  4061. //                        'package_id'=>$product->getPackageId(),
  4062.                     'qty' => $product->getQty(),
  4063.                     'delivered' => $product->getDelivered(),
  4064. //                    'deliverable'=>$product->getDeliverable(),
  4065.                     'balance' => $product->getBalance(),
  4066. //                        'delivered'=>$product->getDelivered(),
  4067.                 );
  4068.                 $sendData['serviceList'][] = $p_data;
  4069.             }
  4070.             //now package data
  4071.             if ($sendData) {
  4072.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4073.             }
  4074.             return new JsonResponse(array("success" => false));
  4075.         }
  4076.         return new JsonResponse(array("success" => false));
  4077.     }
  4078.     public function CreateReceivedNoteAction(Request $request)
  4079.     {
  4080.         if ($request->isMethod('POST')) {
  4081.             $em $this->getDoctrine()->getManager();
  4082.             $entity_id array_flip(GeneralConstant::$Entity_list)['Grn']; //change
  4083.             $dochash $request->request->get('docHash'); //change
  4084.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4085.             $approveRole 1;  //created
  4086.             $approveHash $request->request->get('approvalHash');
  4087.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4088.                 $loginId$approveRole$approveHash)
  4089.             ) {
  4090.                 $this->addFlash(
  4091.                     'error',
  4092.                     'Sorry Couldnot insert Data.'
  4093.                 );
  4094.             } else {
  4095.                 $data $request->request;
  4096.                 $grnId Inventory::CreateGrn($this->getDoctrine()->getManager(), $data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4097.                 //now add Approval info
  4098.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4099.                 $approveRole 1;  //created
  4100.                 $options = array(
  4101.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4102.                     'notification_server' => $this->container->getParameter('notification_server'),
  4103.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4104.                     'url' => $this->generateUrl(
  4105.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['Grn']]
  4106.                         ['entity_view_route_path_name']
  4107.                     )
  4108.                 );
  4109.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4110.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  4111.                     $grnId,
  4112.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4113.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['Grn'], $grnId,
  4114.                     $loginId,
  4115.                     $approveRole,
  4116.                     $request->request->get('approvalHash'));
  4117.                 $this->addFlash(
  4118.                     'success',
  4119.                     'New GRN Added.'
  4120.                 );
  4121.                 $url $this->generateUrl(
  4122.                     'view_grn'
  4123.                 );
  4124.                 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),
  4125.                     "Good Received Note : " $dochash " Has Been Created And is Under Processing",
  4126.                     'pos',
  4127.                     System::getPositionIdsByDepartment($em, [GeneralConstant::SALES_DEPARTMENTGeneralConstant::PURCHASE_DEPARTMENTGeneralConstant::ACCOUNTS_DEPARTMENTGeneralConstant::INVENTORY_DEPARTMENT]),
  4128.                     'success',
  4129.                     $url "/" $grnId,
  4130.                     "GRN"
  4131.                 );
  4132.                 return $this->redirect($url "/" $grnId);
  4133.             }
  4134.         }
  4135.         return $this->render('@Inventory/pages/input_forms/received_note.html.twig',
  4136.             array(
  4137.                 'page_title' => 'GRN',
  4138.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  4139.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  4140.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  4141.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  4142.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  4143.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  4144.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  4145.                 'material_inward' => $this->getDoctrine()
  4146.                     ->getRepository('ApplicationBundle:MaterialInward')
  4147.                     ->findBy(
  4148.                         array(
  4149.                             'stage' => GeneralConstant::STAGE_PENDING_TAG
  4150.                         )
  4151.                     )
  4152. //                'po'=>Inventory::getPurchaseOrderList
  4153.             )
  4154.         );
  4155.     }
  4156.     public function GetQcListForGrnAction(Request $request)
  4157.     {
  4158.         if ($request->isMethod('POST')) {
  4159.             $find_array = array(
  4160.                 'stage' => GeneralConstant::STAGE_PENDING_TAG
  4161.             );
  4162.             $Content = [];
  4163.             $ContentByProductId = [];
  4164.             $Transport_data = [];
  4165.             $Lul_data = [];
  4166.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4167.             if ($request->request->get('poId') != '')
  4168.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4169.             if ($request->request->get('warehouseId') != '')
  4170.                 $find_array['warehouseId'] = $request->request->get('warehouseId');
  4171.             $QD $this->getDoctrine()
  4172.                 ->getRepository('ApplicationBundle:MaterialInward')
  4173.                 ->findBy(
  4174.                     $find_array,
  4175.                     array(
  4176.                         'inwardDate' => 'ASC',
  4177.                         'qcDate' => 'ASC'
  4178.                     )
  4179.                 );
  4180.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4181.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4182.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4183.             $lotNumArray = [];
  4184.             foreach ($QD as $entry) {
  4185. //                $inwardDate=strtotime($entry->getInwardDate());
  4186. //                $qcDate=strtotime($entry->getQcDate());
  4187.                 $inwardDate = ($entry->getInwardDate() instanceof \DateTime) ? $entry->getInwardDate()->format('m/d/Y') : '';
  4188.                 $qcDate = ($entry->getQcDate() instanceof \DateTime) ? $entry->getQcDate()->format('m/d/Y') : '';
  4189.                 if (!in_array($entry->getLotNumber(), $lotNumArray))
  4190.                     $lotNumArray[] = $entry->getLotNumber();
  4191.                 if (isset($ContentByProductId[$entry->getPurchaseOrderItemId()])) {
  4192.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['inwardDateList'][] = $inwardDate;
  4193.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcDateList'][] = $inwardDate;
  4194.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcIdList'][] = $entry->getQcId();
  4195.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['appQtyList'][] = $entry->getApprovedQty();
  4196.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['totQty'] += ($entry->getApprovedQty());
  4197.                 } else {
  4198.                     $ContentByProductId[$entry->getPurchaseOrderItemId()] = array(
  4199.                         'productName' => $productList[$entry->getProductId()]['name'],
  4200.                         'productUnitName' => $unitList[$productList[$entry->getProductId()]['unit_type']]['name'],
  4201.                         'qcHash' => $entry->getDocumentHash(),
  4202.                         'warehouseName' => $warehouse[$entry->getWarehouseId()]['name'],
  4203.                         'inwardDate' => $inwardDate,
  4204.                         'inwardDateList' => [$inwardDate],
  4205.                         'qcDateList' => [$qcDate],
  4206.                         'qcIdList' => [$entry->getQcId()],
  4207.                         'qcDate' => $qcDate,
  4208.                         'poQty' => $entry->getPoQty(),
  4209.                         'poPrevbalance' => $entry->getPoBalance(),
  4210.                         'appQty' => $entry->getApprovedQty(),
  4211.                         'appQtyList' => [$entry->getApprovedQty()],
  4212.                         'totQty' => $entry->getApprovedQty(),
  4213.                         'poBalance' => $entry->getPoBalance() - $entry->getApprovedQty(),
  4214.                         'qcId' => $entry->getQcId(),
  4215.                         'productId' => $entry->getProductId()
  4216.                     );
  4217.                 }
  4218.                 $Expense_Cost[$entry->getQcId()] = json_decode($entry->getExpenseCost());
  4219.                 $Expense_Id[$entry->getQcId()] = json_decode($entry->getExpenseId());
  4220.             }
  4221.             foreach ($ContentByProductId as $c) {
  4222.                 $Content[] = $c;
  4223.             }
  4224.             if ($QD) {
  4225.                 return new JsonResponse(array("success" => true"content" => $Content"lotNumber" => implode(', '$lotNumArray), 'Expense_Cost' => $Expense_Cost'Expense_Id' => $Expense_Id));
  4226.             }
  4227.             return new JsonResponse(array("success" => false));
  4228.         }
  4229.         return new JsonResponse(array("success" => false));
  4230.     }
  4231.     public function GetSrListForIrAction(Request $request)
  4232.     {
  4233.         if ($request->isMethod('POST')) {
  4234.             $find_array = array();
  4235.             $Content = [];
  4236.             if ($request->request->get('srId') != '')
  4237.                 $find_array['stockRequisitionId'] = $request->request->get('srId');
  4238.             $find_array['forceSkipTag'] = [0null];
  4239.             $QD $this->getDoctrine()
  4240.                 ->getRepository('ApplicationBundle:StockRequisitionItem')
  4241.                 ->findBy(
  4242.                     $find_array
  4243.                 );
  4244.             $itemList Inventory::ItemGroupList($this->getDoctrine()->getManager());
  4245.             $catgoryList Inventory::ProductCategoryList($this->getDoctrine()->getManager());
  4246.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4247.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4248.             $fdmData = array();
  4249.             $em $this->getDoctrine()->getManager();
  4250.             $matchType 'MAXIMUM';
  4251.             if ($request->request->has('matchType') != '') {
  4252.                 $matchType $request->request->get('matchType');
  4253.             }
  4254.             if ($matchType == 'MINIMUM') {
  4255.                 foreach ($QD as $entry) {
  4256.                     if ($entry->getTagPendingAmount() <= 0)
  4257.                         continue;
  4258.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4259.                     $combined_id $entry->getProductFdm();
  4260.                     if (isset($fdmData[$combined_id])) {
  4261.                         $fdmData[$combined_id]['unit'] += $entry->getTagPendingAmount();
  4262.                         $fdmData[$combined_id]['specific_unit'][] = $entry->getTagPendingAmount();
  4263.                         $fdmData[$combined_id]['detailsIds'][] = $entry->getId();
  4264.                         $fdmData[$combined_id]['docIds'][] = $entry->getStockRequisitionId();
  4265.                     } else {
  4266.                         $fdmData[$combined_id] = array(
  4267.                             'id' => 0,
  4268.                             'alias' => $entry->getNote(),
  4269.                             'unit' => $entry->getTagPendingAmount(),
  4270.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4271.                             'warranty' => 0,
  4272.                             'unitTypeId' => 0,
  4273.                             'unit_price' => 0,
  4274.                             'fdm' => $combined_id,
  4275.                             'extDetailsId' => 0,
  4276.                             'product_name' => $productData['productName'],
  4277.                             'total_price' => 0,
  4278.                             'detailsIds' => [$entry->getId()],
  4279.                             'docIds' => [$entry->getStockRequisitionId()],
  4280.                         );
  4281.                     }
  4282.                 }
  4283.             }
  4284.             if ($matchType == 'MAXIMUM') {
  4285.                 foreach ($QD as $entry) {
  4286.                     if ($entry->getTagPendingAmount() <= 0)
  4287.                         continue;
  4288.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4289.                     $combined_id $entry->getProductFdm();
  4290.                     $assigned 0;
  4291.                     foreach ($fdmData as $key_ind => $rel_val) {
  4292.                         $matchFdm Inventory::MatchFdm($key_ind$combined_id);
  4293.                         if ($matchFdm['hasMatched'] == 1) {
  4294.                             if ($matchFdm['isIdentical'] == 1) {
  4295.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4296.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4297.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4298.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4299.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4300.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4301.                                 $assigned 1;
  4302.                             } elseif ($matchFdm['SecondBelongsToFirst'] == 1) {
  4303.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4304.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4305.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4306.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4307.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4308.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4309.                                 $assigned 1;
  4310.                             } elseif ($matchFdm['FirstBelongsToSecond'] == 1) {
  4311.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4312.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4313.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4314.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4315.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4316.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4317.                                 $fdmData[$combined_id] = $fdmData[$key_ind];
  4318.                                 unset($fdmData[$key_ind]);
  4319.                                 $assigned 1;
  4320.                             }
  4321.                         } else {
  4322.                         }
  4323.                         if ($assigned == 1)
  4324.                             break;
  4325.                     }
  4326.                     if ($assigned == 0) {
  4327.                         $fdmData[$combined_id] = array(
  4328.                             'id' => 0,
  4329.                             'alias' => $entry->getNote(),
  4330.                             'unit' => $entry->getTagPendingAmount(),
  4331.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4332.                             'specific_unit_type_id' => [$entry->getUnitTypeId()],
  4333.                             'warranty' => 0,
  4334.                             'unitTypeId' => $productData['unitTypeId'],
  4335. //                            'unitTypeId' => $productData['unitTypeId'],
  4336.                             'unit_price' => 0,
  4337.                             'fdm' => $combined_id,
  4338.                             'extDetailsId' => 0,
  4339.                             'product_name' => htmlspecialchars($productData['productName']),
  4340.                             'total_price' => 0,
  4341.                             'detailsIds' => [$entry->getId()],
  4342.                             'docIds' => [$entry->getStockRequisitionId()],
  4343.                         );
  4344.                     }
  4345.                     if (isset($fdmData[$combined_id])) {
  4346.                     } else {
  4347.                     }
  4348.                 }
  4349.             }
  4350.             $QD $this->getDoctrine()
  4351.                 ->getRepository('ApplicationBundle:StockRequisition')
  4352.                 ->findBy(
  4353.                     array('stockRequisitionId' => $request->request->get('srId'))
  4354.                 );
  4355.             $contentNote "";
  4356.             foreach ($QD as $r) {
  4357.                 $contentNote .= $r->getNote();
  4358.                 $contentNote .= " , ";
  4359.             }
  4360.             foreach ($fdmData as $dt) {
  4361.                 $Content[] = $dt;
  4362.             }
  4363.             if ($Content) {
  4364.                 return new JsonResponse(array("success" => true"content" => $Content"contentNote" => $contentNote));
  4365.             }
  4366.             return new JsonResponse(array("success" => false));
  4367.         }
  4368.         return new JsonResponse(array("success" => false));
  4369.     }
  4370.     public function GetGrnListForEiAction(Request $request)
  4371.     {
  4372.         if ($request->isMethod('POST')) {
  4373.             $find_array = array(
  4374.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  4375.                 'approved' => GeneralConstant::APPROVED,
  4376.                 'invoiceTagged' => 1
  4377.             );
  4378.             $Content = [];
  4379.             $Content_obj = [];
  4380.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4381.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4382.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4383.             if ($request->request->get('poId') != '')
  4384.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4385.             if ($request->request->get('grnId') != '')
  4386.                 $find_array['grnId'] = $request->request->get('grnId');
  4387.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4388.             $QD_GRN $this->getDoctrine()
  4389.                 ->getRepository('ApplicationBundle:Grn')
  4390.                 ->findBy(
  4391.                     $find_array,
  4392.                     array(
  4393.                         'grnDate' => 'ASC'
  4394.                     )
  4395.                 );
  4396.             $poId 0;
  4397. //
  4398. //            $expense_id=$QD_GRN->getExpenseId()!=''?json_decode($QD_GRN->getExpenseId()):[];
  4399. //                $expense_list=$QD_GRN->getExpenseCost()!=''?json_decode($QD_GRN->getExpenseCost()):[];
  4400. //                $expense_tagged=$QD_GRN->getExpenseTagged()!=''?json_decode($QD_GRN->getExpenseTagged()):[];
  4401.             $partyId $request->request->get('partyId');
  4402.             $bill_details = [];
  4403.             $bill_details_data = [];
  4404.             $bill_details_for_grn = [];
  4405.             $exp_list InventoryConstant::$Expense_list_details;
  4406.             $supp_list Inventory::ProductSupplierList($this->getDoctrine()->getManager());
  4407.             $head_qry $this->getDoctrine()
  4408.                 ->getRepository('ApplicationBundle:AccAccountsHead')
  4409.                 ->findAll();
  4410.             $head_list = [];
  4411.             $head_list_by_advance = [];
  4412.             foreach ($head_qry as $data) {
  4413.                 $head_list[$data->getAccountsHeadId()] = array(
  4414.                     'id' => $data->getAccountsHeadId(),
  4415.                     'name' => $data->getName(),
  4416.                     'advanceTagged' => $data->getAdvanceTagged(),
  4417.                     'advanceOf' => $data->getAdvanceOf(),
  4418.                     'balance' => $data->getCurrentBalance()
  4419.                 );
  4420.                 if ($data->getAdvanceOf() != null && $data->getAdvanceOf() != && $data->getAdvanceOf() != '')
  4421.                     $head_list_by_advance[$data->getAdvanceOf()] = array(
  4422.                         'id' => $data->getAccountsHeadId(),
  4423.                         'name' => $data->getName(),
  4424.                         'advanceTagged' => $data->getAdvanceTagged(),
  4425.                         'advanceOf' => $data->getAdvanceOf(),
  4426.                         'balance' => $data->getCurrentBalance()
  4427.                     );
  4428.             }
  4429.             $exp_def_head = [];
  4430.             foreach ($exp_list as $key => $item) {
  4431.                 $def_settings $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  4432.                     'name' => $item['name'] . '_onsite_head'
  4433.                 ));
  4434.                 if ($def_settings)
  4435.                     $exp_def_head[$item['id']] = $def_settings->getData();
  4436.                 else
  4437.                     $exp_def_head[$item['id']] = '';
  4438.             }
  4439.             $bill_details_by_party = [];
  4440. //            System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($QD_GRN),'debug_data');
  4441. //            System::log_it($this->container->getParameter('kernel.root_dir'),$partyId,'debug_data');
  4442. //            System::log_it($this->container->getParameter('kernel.root_dir'),"\nexp list here".json_encode($exp_list),'debug_data');
  4443. //
  4444.             foreach ($QD_GRN as $key => $value) {
  4445.                 $expense_id $value->getExpenseId() != '' json_decode($value->getExpenseId(), true) : [];
  4446.                 $expense_list $value->getExpenseCost() != '' json_decode($value->getExpenseCost(), true) : [];
  4447.                 $expense_tagged $value->getExpenseTagged() != '' json_decode($value->getExpenseTagged(), true) : [];
  4448. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_id),'debug_data');
  4449. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_list),'debug_data');
  4450.                 foreach ($exp_list as $chabi => $entry) {
  4451. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nChabi ".$chabi,'debug_data');
  4452. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nkeys are ".array_keys($expense_id),'debug_data');
  4453.                     if (array_key_exists($chabi$expense_id)) {
  4454. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nFOUND KEY!! ",'debug_data');
  4455.                         if ($partyId == ''//all
  4456.                         {
  4457.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  4458.                                 $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  4459.                                 $advance_balance 0;
  4460.                                 if ($partyHeadId != 0) {
  4461.                                     $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  4462.                                     $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  4463.                                     $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  4464.                                 }
  4465.                                 $bill_details_by_party[$my_val][] = array(
  4466.                                     'partyId' => $my_val,
  4467.                                     'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  4468.                                     'partyHeadId' => $partyHeadId,
  4469.                                     'expTypeId' => $chabi,
  4470.                                     'expTypeName' => $exp_list[$chabi]['name'],
  4471.                                     'expTypeAlias' => $exp_list[$chabi]['alias'],
  4472.                                     'expAmount' => $expense_list[$chabi][$index],
  4473.                                     'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  4474.                                     'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  4475.                                     'AdvanceBalance' => $advance_balance,
  4476.                                     'grnId' => $value->getGrnId(),
  4477.                                     'grnName' => $value->getDocumentHash(),
  4478.                                 );
  4479.                             }
  4480.                         } else {
  4481.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  4482.                                 if (in_array($my_val$partyId)) {
  4483.                                     $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  4484.                                     $advance_balance 0;
  4485.                                     if ($partyHeadId != 0) {
  4486.                                         $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  4487.                                         $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  4488.                                         $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  4489.                                     }
  4490.                                     $bill_details_by_party[$my_val][] = array(
  4491.                                         'partyId' => $my_val,
  4492.                                         'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  4493.                                         'partyHeadId' => $partyHeadId,
  4494.                                         'expTypeId' => $chabi,
  4495.                                         'expTypeName' => $exp_list[$chabi]['name'],
  4496.                                         'expTypeAlias' => $exp_list[$chabi]['alias'],
  4497.                                         'expAmount' => $expense_list[$chabi][$index],
  4498.                                         'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  4499.                                         'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  4500.                                         'AdvanceBalance' => $advance_balance,
  4501.                                         'grnId' => $value->getGrnId(),
  4502.                                         'grnName' => $value->getDocumentHash(),
  4503.                                     );
  4504.                                 }
  4505.                             }
  4506.                         }
  4507.                     }
  4508.                 }
  4509.             }
  4510. //            $Content_obj=
  4511. //
  4512. //            foreach($Content_obj as $item)
  4513. //            {
  4514. //                $Content[]=$item;
  4515. //
  4516. //            }
  4517.             $list_of_keys array_keys($bill_details_by_party);
  4518.             if ($bill_details_by_party) {
  4519.                 return new JsonResponse(array("success" => true"content" => $bill_details_by_party'index' => $list_of_keys'h_l_b_a' => $head_list_by_advance));
  4520.             }
  4521.             return new JsonResponse(array("success" => false));
  4522.         }
  4523.         return new JsonResponse(array("success" => false));
  4524.     }
  4525.     public function GetServiceListForPiAction(Request $request)
  4526.     {
  4527.         if ($request->isMethod('POST')) {
  4528. //            $find_array=array(
  4529. //                'stage' =>  GeneralConstant::STAGE_PENDING_TAG,
  4530. //                'approved'=>GeneralConstant::APPROVED
  4531. //            );
  4532.             $Content = [];
  4533.             $Content_obj = [];
  4534.             $ContentService = [];
  4535.             $Content_service_obj = [];
  4536. //            $warehouse=Inventory::WarehouseList($this->getDoctrine()->getManager());
  4537. //            $poList=Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4538. //            $productList=Inventory::ProductList($this->getDoctrine()->getManager());
  4539.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  4540.             if ($request->request->get('poId') != '')
  4541.                 $poId $request->request->get('poId');
  4542.             if ($request->request->get('grnId') != '')
  4543.                 $find_array['grnId'] = $request->request->get('grnId');
  4544.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4545.             //adding service data temporarily
  4546.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(
  4547.                 array('purchaseOrderId' => $poId));
  4548.             $multiply_type $po->getCurrencyMultiply();
  4549.             $multiply_rate $po->getCurrencyMultiplyRate();
  4550.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  4551.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  4552.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4553.                 array('purchaseOrderId' => $poId));
  4554.             foreach ($po_items as $item) {
  4555. //                $po_item_list[$item->getProductId()]=$item;
  4556.                 //temporary service add
  4557.                 if ($item->getType() == 2)
  4558.                     $Content_service_obj[$item->getId()] = array(
  4559.                         'serviceId' => $item->getServiceId(),
  4560.                         'poItemId' => $item->getId(),
  4561.                         'colorId' => 0,
  4562.                         'sizeId' => 0,
  4563.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  4564.                         'qty' => $item->getQty(),
  4565.                         'balance' => $item->getBalance(),
  4566.                         'unit_name' => '',
  4567.                         'unit_price' => $item->getPrice() * $multiplier,
  4568.                         'grn_id' => 0,
  4569.                     );
  4570.                 //temprary service add end
  4571.             }
  4572.             //temporary service data adding done
  4573.             $po_data = [];
  4574.             $po_data = array(
  4575.                 'docHash' => $po->getDocumentHash(),
  4576.                 'docDate' => $po->getPurchaseOrderDate(),
  4577.                 'supplierId' => $po->getSupplierId(),
  4578.                 'supplierName' => $po->getSupplierId(),
  4579.                 'vatRate' => $po->getVatRate(),
  4580.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  4581.                 'aitRate' => $po->getAitRate(),
  4582.                 'aitAmount' => $po->getAitAmount(),
  4583.                 'tdsRate' => $po->getTdsRate(),
  4584.                 'tdsAmount' => $po->getTdsAmount(),
  4585.                 'vdsRate' => $po->getVdsRate(),
  4586.                 'vdsAmount' => $po->getVdsAmount(),
  4587.                 'discountRate' => $po->getDiscountRate(),
  4588.                 'discountAmount' => $po->getVatAmount(),
  4589.             );
  4590.             foreach ($Content_obj as $item) {
  4591.                 $Content[] = $item;
  4592.             }
  4593.             foreach ($Content_service_obj as $item) {
  4594.                 $ContentService[] = $item;
  4595.             }
  4596.             if ($Content || $ContentService) {
  4597.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  4598.             }
  4599.             return new JsonResponse(array("success" => false));
  4600.         }
  4601.         return new JsonResponse(array("success" => false));
  4602.     }
  4603.     public function GetGrnListForPiAction(Request $request)
  4604.     {
  4605.         if ($request->isMethod('POST')) {
  4606.             $find_array = array(
  4607.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  4608.                 'approved' => GeneralConstant::APPROVED
  4609.             );
  4610.             $Content = [];
  4611.             $Content_obj = [];
  4612.             $ContentService = [];
  4613.             $Content_service_obj = [];
  4614.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4615.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4616.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4617.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  4618.             if ($request->request->get('poId') != '')
  4619.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4620.             if ($request->request->get('grnId') != '')
  4621.                 $find_array['grnId'] = $request->request->get('grnId');
  4622.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4623.             $QD_GRN $this->getDoctrine()
  4624.                 ->getRepository('ApplicationBundle:Grn')
  4625.                 ->findBy(
  4626.                     $find_array,
  4627.                     array(
  4628.                         'grnDate' => 'ASC'
  4629.                     )
  4630.                 );
  4631.             $poId 0;
  4632.             foreach ($QD_GRN as $value) {
  4633.                 $grn_items $this->getDoctrine()->getRepository('ApplicationBundle:GrnItem')->findBy(
  4634.                     array('grnId' => $value->getGrnId()));
  4635.                 $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4636.                     array('purchaseOrderId' => $value->getPurchaseOrderId()));
  4637.                 $poId $value->getPurchaseOrderId();
  4638.                 $po_item_list = [];
  4639.                 foreach ($po_items as $item) {
  4640.                     $po_item_list[$item->getProductId()] = $item;
  4641.                 }
  4642.                 foreach ($grn_items as $entry) {
  4643.                     //adding transaction
  4644. //                    System::log_it($this->container->getParameter('kernel.root_dir'),$entry->getProductId(),'debug_data');
  4645.                     $Content_obj[$entry->getId()] = array(
  4646.                         'productId' => $entry->getProductId(),
  4647.                         'poItemId' => $entry->getId(),
  4648.                         'productName' => $productList[$entry->getProductId()]['name'],
  4649.                         'colorId' => $entry->getColorId(),
  4650.                         'sizeId' => $entry->getSizeId(),
  4651.                         'qty' => isset($Content_obj[$entry->getId()]) ? $Content_obj[$entry->getId()]['qty'] + $entry->getQty() : $entry->getQty(),
  4652.                         'unit_name' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  4653. //                            'unit_price'=>$po_item_list[$entry->getProductId()]->getPrice(),
  4654.                         'unit_price' => $entry->getPrice(),
  4655.                         'grn_id' => $entry->getId(),
  4656.                     );
  4657.                 }
  4658. //            for
  4659.             }
  4660.             //adding service data temporarily
  4661.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(
  4662.                 array('purchaseOrderId' => $poId));
  4663.             $multiply_type $po->getCurrencyMultiply();
  4664.             $multiply_rate $po->getCurrencyMultiplyRate();
  4665.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  4666.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  4667.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4668.                 array('purchaseOrderId' => $poId));
  4669.             foreach ($po_items as $item) {
  4670. //                $po_item_list[$item->getProductId()]=$item;
  4671.                 //temporary service add
  4672.                 if ($item->getType() == 2)
  4673.                     $Content_service_obj[$item->getId()] = array(
  4674.                         'serviceId' => $item->getServiceId(),
  4675.                         'poItemId' => $item->getId(),
  4676.                         'colorId' => 0,
  4677.                         'sizeId' => 0,
  4678.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  4679.                         'qty' => $item->getQty(),
  4680.                         'balance' => $item->getBalance(),
  4681.                         'unit_name' => '',
  4682.                         'unit_price' => $item->getPrice() * $multiplier,
  4683.                         'grn_id' => 0,
  4684.                     );
  4685.                 //temprary service add end
  4686.             }
  4687.             //temporary service data adding done
  4688.             $po_data = [];
  4689.             $po_data = array(
  4690.                 'docHash' => $po->getDocumentHash(),
  4691.                 'docDate' => $po->getPurchaseOrderDate(),
  4692.                 'supplierId' => $po->getSupplierId(),
  4693.                 'supplierName' => $po->getSupplierId(),
  4694.                 'vatRate' => $po->getVatRate(),
  4695.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  4696.                 'aitRate' => $po->getAitRate(),
  4697.                 'aitAmount' => $po->getAitAmount(),
  4698.                 'tdsRate' => $po->getTdsRate(),
  4699.                 'tdsAmount' => $po->getTdsAmount(),
  4700.                 'vdsRate' => $po->getVdsRate(),
  4701.                 'vdsAmount' => $po->getVdsAmount(),
  4702.                 'discountRate' => $po->getDiscountRate(),
  4703.                 'discountAmount' => $po->getVatAmount(),
  4704.             );
  4705.             foreach ($Content_obj as $item) {
  4706.                 $Content[] = $item;
  4707.             }
  4708.             foreach ($Content_service_obj as $item) {
  4709.                 $ContentService[] = $item;
  4710.             }
  4711.             if ($Content) {
  4712.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  4713.             }
  4714.             return new JsonResponse(array("success" => false));
  4715.         }
  4716.         return new JsonResponse(array("success" => false));
  4717.     }
  4718.     public function GetPoDetailsForPiAction(Request $request$poId)
  4719.     {
  4720.     }
  4721.     public function GetPoDetailsAction(Request $request$poId)
  4722.     {
  4723.         if ($request->isMethod('POST')) {
  4724.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findBy(
  4725.                 array('purchaseOrderId' => $poId));
  4726.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4727.                 array('purchaseOrderId' => $poId));
  4728.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4729.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4730.             $Content = [];
  4731.             $po_items_list = [];
  4732.             foreach ($po_items as $entry) {
  4733.                 $po_items_list[] = array(
  4734.                     'productId' => $entry->getProductId(),
  4735.                     'productName' => $productList[$entry->getProductId()]['name'],
  4736.                     'price' => $entry->getPrice(),
  4737.                     'unit' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  4738.                     'received' => $entry->getReceived(),
  4739.                     'qty' => $entry->getQty(),
  4740.                     'balance' => $entry->getBalance()
  4741.                 );
  4742.             }
  4743.             $po_data = [];
  4744.             $po_data = array(
  4745.                 'docHash' => $po->getDocumentHash(),
  4746.                 'docDate' => $po->getPurchaseOrderDate(),
  4747.                 'supplierId' => $po->getSupplierId(),
  4748.                 'supplierName' => $po->getSupplierId(),
  4749.             );
  4750.             if ($po_data) {
  4751.                 return new JsonResponse(array("success" => true"content" => $po_data));
  4752.             }
  4753.             return new JsonResponse(array("success" => false));
  4754.         }
  4755.         return new JsonResponse(array("success" => false));
  4756.     }
  4757.     public function CreateSalesReplacementAction(Request $request)
  4758.     {
  4759.         $em $this->getDoctrine()->getManager();
  4760.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4761.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4762.         if ($request->isMethod('POST')) {
  4763.             $em $this->getDoctrine()->getManager();
  4764.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesReplacement']; //change
  4765.             $dochash $request->request->get('voucherNumber'); //change
  4766.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4767.             $approveRole $request->request->get('approvalRole');
  4768.             $approveHash $request->request->get('approvalHash');
  4769.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4770.                 $loginId$approveRole$approveHash)
  4771.             ) {
  4772.                 $this->addFlash(
  4773.                     'error',
  4774.                     'Sorry Couldnot insert Data.'
  4775.                 );
  4776.             } else {
  4777.                 if ($request->request->has('check_allowed'))
  4778.                     $check_allowed 1;
  4779.                 $StID Inventory::CreateNewSalesReplacement(
  4780.                     $this->getDoctrine()->getManager(),
  4781.                     $request->request,
  4782.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  4783.                     $this->getLoggedUserCompanyId($request)
  4784.                 );
  4785.                 //now add Approval info
  4786.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4787.                 $approveRole 1;  //created
  4788.                 $options = array(
  4789.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4790.                     'notification_server' => $this->container->getParameter('notification_server'),
  4791.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4792.                     'url' => $this->generateUrl(
  4793.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesReplacement']]
  4794.                         ['entity_view_route_path_name']
  4795.                     )
  4796.                 );
  4797.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4798.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4799.                     $StID,
  4800.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  4801.                 );
  4802.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesReplacement'], $StID,
  4803.                     $loginId,
  4804.                     $approveRole,
  4805.                     $request->request->get('approvalHash'));
  4806.                 $this->addFlash(
  4807.                     'success',
  4808.                     'Stock Transfer Added.'
  4809.                 );
  4810.                 $url $this->generateUrl(
  4811.                     'view_st'
  4812.                 );
  4813.                 return $this->redirect($url "/" $StID);
  4814.             }
  4815.         }
  4816.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  4817.             array(
  4818.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  4819.             )
  4820.         );
  4821.         $INVLIST = [];
  4822.         foreach ($slotList as $slot) {
  4823.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  4824.         }
  4825.         return $this->render('@Inventory/pages/input_forms/sales_replacement.html.twig',
  4826.             array(
  4827.                 'page_title' => 'Sales Replacement Note',
  4828.                 'warehouseList' => Inventory::WarehouseList($em),
  4829.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  4830.                 'warehouseActionList' => $warehouse_action_list,
  4831.                 'warehouseActionListArray' => $warehouse_action_list_array,
  4832.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  4833.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  4834.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  4835.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  4836.                 'prefix_list' => array(
  4837.                     [
  4838.                         'id' => 1,
  4839.                         'value' => 'GN',
  4840.                         'text' => 'GN'
  4841.                     ]
  4842.                 ),
  4843.                 'assoc_list' => array(
  4844.                     [
  4845.                         'id' => 1,
  4846.                         'value' => 1,
  4847.                         'text' => 'GN'
  4848.                     ]
  4849.                 ),
  4850.                 'INVLIST' => $INVLIST
  4851.             )
  4852.         );
  4853.     }
  4854.     public function SalesReplacementListAction(Request $request)
  4855.     {
  4856.         $q $this->getDoctrine()
  4857.             ->getRepository('ApplicationBundle:SalesReplacement')
  4858.             ->findBy(
  4859.                 array(
  4860.                     'status' => GeneralConstant::ACTIVE,
  4861.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  4862. //                    'approved' =>  GeneralConstant::APPROVED,
  4863.                 )
  4864.             );
  4865.         $stage_list = array(
  4866.             => 'Pending',
  4867.             => 'Pending',
  4868.             => 'Complete',
  4869.             => 'Partial',
  4870.         );
  4871.         $data = [];
  4872.         foreach ($q as $entry) {
  4873.             $data[] = array(
  4874.                 'doc_date' => $entry->getSalesReplacementDate(),
  4875.                 'id' => $entry->getSalesReplacementId(),
  4876.                 'doc_hash' => $entry->getDocumentHash(),
  4877.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  4878.                 'stage' => $stage_list[$entry->getStage()]
  4879.             );
  4880.         }
  4881.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  4882.             array(
  4883.                 'page_title' => 'Stock Transfer List',
  4884.                 'data' => $data
  4885.             )
  4886.         );
  4887.     }
  4888.     public function ViewSalesReplacementAction(Request $request$id)
  4889.     {
  4890.         $em $this->getDoctrine()->getManager();
  4891.         $dt Inventory::GetSalesReplacementDetails($em$id);
  4892.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  4893.             array(
  4894.                 'page_title' => 'Stock Transfer',
  4895.                 'data' => $dt,
  4896.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4897.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  4898.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  4899.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4900.                     $id,
  4901.                     $dt['created_by'],
  4902.                     $dt['edited_by'])
  4903.             )
  4904.         );
  4905.     }
  4906.     public function PrintSalesReplacementAction(Request $request$id)
  4907.     {
  4908.         $em $this->getDoctrine()->getManager();
  4909.         $dt Inventory::GetSalesReplacementDetails($em$id);
  4910.         $company_data Company::getCompanyData($em1);
  4911.         $document_mark = array(
  4912.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4913.             'copy' => ''
  4914.         );
  4915.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  4916.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  4917.                 array(
  4918.                     //full array here
  4919.                     'pdf' => true,
  4920.                     'page_title' => 'Stock Transfer',
  4921.                     'export' => 'pdf,print',
  4922.                     'data' => $dt,
  4923.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4924.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  4925.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  4926.                         array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4927.                         $id,
  4928.                         $dt['created_by'],
  4929.                         $dt['edited_by']),
  4930.                     'document_mark_image' => $document_mark['original'],
  4931.                     'company_name' => $company_data->getName(),
  4932.                     'company_data' => $company_data,
  4933.                     'company_address' => $company_data->getAddress(),
  4934.                     'company_image' => $company_data->getImage(),
  4935.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  4936.                     'red' => 0
  4937.                 )
  4938.             );
  4939.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  4940. //                'orientation' => 'landscape',
  4941. //                'enable-javascript' => true,
  4942. //                'javascript-delay' => 1000,
  4943.                 'no-stop-slow-scripts' => false,
  4944.                 'no-background' => false,
  4945.                 'lowquality' => false,
  4946.                 'encoding' => 'utf-8',
  4947. //            'images' => true,
  4948. //            'cookie' => array(),
  4949.                 'dpi' => 300,
  4950.                 'image-dpi' => 300,
  4951. //                'enable-external-links' => true,
  4952. //                'enable-internal-links' => true
  4953.             ));
  4954.             return new Response(
  4955.                 $pdf_response,
  4956.                 200,
  4957.                 array(
  4958.                     'Content-Type' => 'application/pdf',
  4959.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  4960.                 )
  4961.             );
  4962.         }
  4963.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  4964.             array(
  4965.                 'page_title' => 'Stock Transfer',
  4966.                 'export' => 'pdf,print',
  4967.                 'data' => $dt,
  4968.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4969.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  4970.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  4971.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4972.                     $id,
  4973.                     $dt['created_by'],
  4974.                     $dt['edited_by']),
  4975.                 'document_mark_image' => $document_mark['original'],
  4976.                 'company_name' => $company_data->getName(),
  4977.                 'company_data' => $company_data,
  4978.                 'company_address' => $company_data->getAddress(),
  4979.                 'company_image' => $company_data->getImage(),
  4980.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  4981.                 'red' => 0
  4982.             )
  4983.         );
  4984.     }
  4985.     public function CreateStockTransferAction(Request $request)
  4986.     {
  4987.         $em $this->getDoctrine()->getManager();
  4988.         $companyId $this->getLoggedUserCompanyId($request);
  4989.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4990.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4991.         if ($request->isMethod('POST')) {
  4992.             $em $this->getDoctrine()->getManager();
  4993.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  4994.             $dochash $request->request->get('docHash'); //change
  4995.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4996.             $approveRole $request->request->get('approvalRole');
  4997.             $approveHash $request->request->get('approvalHash');
  4998.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4999.                 $loginId$approveRole$approveHash)
  5000.             ) {
  5001.                 $this->addFlash(
  5002.                     'error',
  5003.                     'Sorry Could Not insert Data.'
  5004.                 );
  5005.             } else {
  5006.                 if ($request->request->has('check_allowed'))
  5007.                     $check_allowed 1;
  5008.                 $StID Inventory::CreateNewStockTransfer(
  5009.                     $this->getDoctrine()->getManager(),
  5010.                     $request->request,
  5011.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5012.                     $this->getLoggedUserCompanyId($request)
  5013.                 );
  5014.                 //now add Approval info
  5015.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5016.                 $approveRole 1;  //created
  5017.                 $options = array(
  5018.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5019.                     'notification_server' => $this->container->getParameter('notification_server'),
  5020.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5021.                     'url' => $this->generateUrl(
  5022.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  5023.                         ['entity_view_route_path_name']
  5024.                     )
  5025.                 );
  5026.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5027.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5028.                     $StID,
  5029.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  5030.                 );
  5031.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  5032.                     $loginId,
  5033.                     $approveRole,
  5034.                     $request->request->get('approvalHash'));
  5035.                 $this->addFlash(
  5036.                     'success',
  5037.                     'Stock Transfer Added.'
  5038.                 );
  5039.                 $url $this->generateUrl(
  5040.                     'view_st'
  5041.                 );
  5042.                 return $this->redirect($url "/" $StID);
  5043.             }
  5044.         }
  5045.         $INVLIST = [];
  5046.         return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  5047.             array(
  5048.                 'page_title' => 'Stock Transfer Note',
  5049.                 'warehouseList' => Inventory::WarehouseList($em),
  5050.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5051.                 'colorList' => Inventory::GetColorList($em),
  5052.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  5053.                 'srList' => [],
  5054.                 'warehouseActionList' => $warehouse_action_list,
  5055.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5056.                 'item_list' => Inventory::ItemGroupList($em),
  5057.                 'item_list_array' => Inventory::ItemGroupListArray($em),
  5058.                 'category_list_array' => Inventory::ProductCategoryListArray($em),
  5059.                 'product_list_array' => Inventory::ProductListDetailedArray($em),
  5060. //                'product_list_array' => [],
  5061.                 'product_list' => Inventory::ProductList($em$companyId),
  5062. //                'product_list' => [],
  5063.                 'prefix_list' => array(
  5064.                     [
  5065.                         'id' => 1,
  5066.                         'value' => 'GN',
  5067.                         'text' => 'GN'
  5068.                     ]
  5069.                 ),
  5070.                 'assoc_list' => array(
  5071.                     [
  5072.                         'id' => 1,
  5073.                         'value' => 1,
  5074.                         'text' => 'GN'
  5075.                     ]
  5076.                 ),
  5077.                 'INVLIST' => $INVLIST
  5078.             )
  5079.         );
  5080.     }
  5081.     public function GetSrItemForTransferAction(Request $request)
  5082.     {
  5083.         $em $this->getDoctrine()->getManager();
  5084.         $search_query = [];
  5085.         $res_data_by_so_item_id = [];
  5086.         $Content = [];
  5087.         $productionProcessSettings = array(
  5088.             'id' => 0
  5089.         );
  5090.         if ($request->query->has('srId'))
  5091.             $search_query['stockRequisitionId'] = $request->query->get('srId');
  5092.         $DT $this->getDoctrine()
  5093.             ->getRepository('ApplicationBundle:StockRequisitionItem')
  5094.             ->findBy(
  5095.                 $search_query
  5096.             );
  5097.         $Content = array(
  5098.             'requisitioned_product_item_id' => [],
  5099.             'requisitioned_products' => [],
  5100.             'requisitioned_product_fdm' => [],
  5101.             'requisitioned_product_name' => [],
  5102.             'requisitioned_product_units' => [],
  5103.             'requisitioned_product_unit_type' => [],
  5104.             'requisitioned_product_balance' => [],
  5105.         );
  5106.         foreach ($DT as $dt) {
  5107. //            $data=json_decode($DT->getData(),true);
  5108.             $Content['requisitioned_products'][] = $dt->getProductId();
  5109.             $Content['requisitioned_product_item_id'][] = $dt->getId();
  5110.             $Content['requisitioned_product_fdm'][] = $dt->getProductFdm();
  5111.             $Content['requisitioned_product_name'][] = $dt->getProductNameFdm();
  5112.             $Content['requisitioned_product_units'][] = $dt->getQty();
  5113.             $Content['requisitioned_product_balance'][] = $dt->getAlottmentPendingAmount();
  5114.         }
  5115.         $INVLIST = [];
  5116.         if (!empty($Content)) {
  5117.             return new JsonResponse(array("success" => true"content" => $Content"INVLIST" => $INVLIST));
  5118.         } else {
  5119.             return new JsonResponse(array("success" => false"content" => $Content"INVLIST" => $INVLIST));
  5120.         }
  5121.     }
  5122.     public function StockTransferListAction(Request $request)
  5123.     {
  5124.         $q $this->getDoctrine()
  5125.             ->getRepository('ApplicationBundle:StockTransfer')
  5126.             ->findBy(
  5127.                 array(
  5128.                     'status' => GeneralConstant::ACTIVE,
  5129.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5130. //                    'approved' =>  GeneralConstant::APPROVED,
  5131.                 )
  5132.             );
  5133.         $stage_list = array(
  5134.             => 'Pending',
  5135.             => 'Pending',
  5136.             => 'Complete',
  5137.             => 'Partial',
  5138.         );
  5139.         $data = [];
  5140.         foreach ($q as $entry) {
  5141.             $data[] = array(
  5142.                 'doc_date' => $entry->getStockTransferDate(),
  5143.                 'id' => $entry->getStockTransferId(),
  5144.                 'doc_hash' => $entry->getDocumentHash(),
  5145.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5146.                 'stage' => $stage_list[$entry->getStage()]
  5147.             );
  5148.         }
  5149.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5150.             array(
  5151.                 'page_title' => 'Stock Transfer List',
  5152.                 'data' => $data
  5153.             )
  5154.         );
  5155.     }
  5156.     public function ViewStockTransferAction(Request $request$id)
  5157.     {
  5158.         $em $this->getDoctrine()->getManager();
  5159.         $dt Inventory::GetStockTransferDetails($em$id);
  5160.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  5161.             array(
  5162.                 'page_title' => 'Stock Transfer',
  5163.                 'data' => $dt,
  5164.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5165.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5166.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5167.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5168.                     $id,
  5169.                     $dt['created_by'],
  5170.                     $dt['edited_by'])
  5171.             )
  5172.         );
  5173.     }
  5174.     public function PrintStockTransferAction(Request $request$id)
  5175.     {
  5176.         $em $this->getDoctrine()->getManager();
  5177.         $dt Inventory::GetStockTransferDetails($em$id);
  5178.         $company_data Company::getCompanyData($em1);
  5179.         $document_mark = array(
  5180.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5181.             'copy' => ''
  5182.         );
  5183.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5184.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5185.                 array(
  5186.                     //full array here
  5187.                     'pdf' => true,
  5188.                     'page_title' => 'Stock Transfer',
  5189.                     'export' => 'pdf,print',
  5190.                     'data' => $dt,
  5191.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5192.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5193.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5194.                         array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5195.                         $id,
  5196.                         $dt['created_by'],
  5197.                         $dt['edited_by']),
  5198.                     'document_mark_image' => $document_mark['original'],
  5199.                     'company_name' => $company_data->getName(),
  5200.                     'company_data' => $company_data,
  5201.                     'company_address' => $company_data->getAddress(),
  5202.                     'company_image' => $company_data->getImage(),
  5203.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5204.                     'red' => 0
  5205.                 )
  5206.             );
  5207.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5208. //                'orientation' => 'landscape',
  5209. //                'enable-javascript' => true,
  5210. //                'javascript-delay' => 1000,
  5211.                 'no-stop-slow-scripts' => false,
  5212.                 'no-background' => false,
  5213.                 'lowquality' => false,
  5214.                 'encoding' => 'utf-8',
  5215. //            'images' => true,
  5216. //            'cookie' => array(),
  5217.                 'dpi' => 300,
  5218.                 'image-dpi' => 300,
  5219. //                'enable-external-links' => true,
  5220. //                'enable-internal-links' => true
  5221.             ));
  5222.             return new Response(
  5223.                 $pdf_response,
  5224.                 200,
  5225.                 array(
  5226.                     'Content-Type' => 'application/pdf',
  5227.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5228.                 )
  5229.             );
  5230.         }
  5231.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5232.             array(
  5233.                 'page_title' => 'Stock Transfer',
  5234.                 'export' => 'pdf,print',
  5235.                 'data' => $dt,
  5236.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5237.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5238.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5239.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5240.                     $id,
  5241.                     $dt['created_by'],
  5242.                     $dt['edited_by']),
  5243.                 'document_mark_image' => $document_mark['original'],
  5244.                 'company_name' => $company_data->getName(),
  5245.                 'company_data' => $company_data,
  5246.                 'company_address' => $company_data->getAddress(),
  5247.                 'company_image' => $company_data->getImage(),
  5248.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5249.                 'red' => 0
  5250.             )
  5251.         );
  5252.     }
  5253.     public function CreateStockConsumptionNoteAction(Request $request)
  5254.     {
  5255.         $em $this->getDoctrine()->getManager();
  5256.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5257.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5258.         if ($request->isMethod('POST')) {
  5259.             $em $this->getDoctrine()->getManager();
  5260.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']; //change
  5261.             $dochash $request->request->get('voucherNumber'); //change
  5262.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5263.             $approveRole $request->request->get('approvalRole');
  5264.             $approveHash $request->request->get('approvalHash');
  5265.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5266.                 $loginId$approveRole$approveHash)
  5267.             ) {
  5268.                 $this->addFlash(
  5269.                     'error',
  5270.                     'Sorry Could not insert Data.'
  5271.                 );
  5272.             } else {
  5273.                 if ($request->request->has('check_allowed'))
  5274.                     $check_allowed 1;
  5275.                 $StID Inventory::CreateNewStockConsumptionNote(
  5276.                     $this->getDoctrine()->getManager(),
  5277.                     $request->request,
  5278.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5279.                     $this->getLoggedUserCompanyId($request)
  5280.                 );
  5281.                 //now add Approval info
  5282.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5283.                 $approveRole 1;  //created
  5284.                 $options = array(
  5285.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5286.                     'notification_server' => $this->container->getParameter('notification_server'),
  5287.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5288.                     'url' => $this->generateUrl(
  5289.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']]
  5290.                         ['entity_view_route_path_name']
  5291.                     )
  5292.                 );
  5293.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5294.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5295.                     $StID,
  5296.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5297.                 );
  5298.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'], $StID,
  5299.                     $loginId,
  5300.                     $approveRole,
  5301.                     $request->request->get('approvalHash'));
  5302.                 $this->addFlash(
  5303.                     'success',
  5304.                     'Stock Consumption Added.'
  5305.                 );
  5306.                 $url $this->generateUrl(
  5307.                     'view_stock_consumption_note'
  5308.                 );
  5309.                 return $this->redirect($url "/" $StID);
  5310.             }
  5311.         }
  5312.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5313.             array(
  5314.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5315.             )
  5316.         );
  5317.         $INVLIST = [];
  5318.         foreach ($slotList as $slot) {
  5319.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5320.         }
  5321.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5322.             array(
  5323.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5324.             )
  5325.         );
  5326.         $consumptionTypeList = [];
  5327.         $consumptionTypeListArray = [];
  5328.         foreach ($consumptionTypeQry as $entry) {
  5329.             $p = array(
  5330.                 'name' => $entry->getName(),
  5331.                 'id' => $entry->getConsumptionTypeId(),
  5332.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5333.                 'cost_center_id' => $entry->getCostCenterId(),
  5334.             );
  5335.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5336.             $consumptionTypeListArray[] = $p;
  5337.         }
  5338.         //add bill list
  5339.         $service_purchase_bill_query $this->getDoctrine()
  5340.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5341.             ->findBy(
  5342.                 array(
  5343.                     'typeHash' => 'SPB',
  5344.                     'approved' => GeneralConstant::APPROVED
  5345.                 )
  5346.             );
  5347.         $service_purchase_bill_list = [];
  5348.         $service_purchase_bill_list_array = [];
  5349.         $bill = array(
  5350.             'id' => 0,
  5351.             'type' => 'SPB',
  5352.             'name' => 'New Expense',
  5353.             'text' => 'New Expense',
  5354.             'amount' => 0,
  5355.         );
  5356.         $service_purchase_bill_list[0] = $bill;
  5357.         $service_purchase_bill_list_array[] = $bill;
  5358.         foreach ($service_purchase_bill_query as $d) {
  5359.             $bill = array(
  5360.                 'id' => $d->getPurchaseInvoiceId(),
  5361.                 'type' => 'SPB',
  5362.                 'name' => $d->getDocumentHash(),
  5363.                 'text' => $d->getDocumentHash(),
  5364.                 'amount' => $d->getInvoiceAmount(),
  5365.             );
  5366.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5367.             $service_purchase_bill_list_array[] = $bill;
  5368.         }
  5369.         return $this->render('@Inventory/pages/input_forms/stock_consumption_note.html.twig',
  5370.             array(
  5371.                 'page_title' => 'Stock Consumption Note',
  5372.                 'warehouseList' => Inventory::WarehouseList($em),
  5373.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5374.                 'consumptionTypeList' => $consumptionTypeList,
  5375.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5376.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5377.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5378.                 'warehouseActionList' => $warehouse_action_list,
  5379.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5380.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5381.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5382.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5383.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5384.                 'product_list' => Inventory::ProductListDetailed($this->getDoctrine()->getManager()),
  5385.                 'prefix_list' => array(
  5386.                     [
  5387.                         'id' => 1,
  5388.                         'value' => 'GN',
  5389.                         'text' => 'GN'
  5390.                     ]
  5391.                 ),
  5392.                 'assoc_list' => array(
  5393.                     [
  5394.                         'id' => 1,
  5395.                         'value' => 1,
  5396.                         'text' => 'GN'
  5397.                     ]
  5398.                 ),
  5399.                 'INVLIST' => $INVLIST
  5400.             )
  5401.         );
  5402.     }
  5403.     public function StockConsumptionNoteListAction(Request $request)
  5404.     {
  5405.         $q $this->getDoctrine()
  5406.             ->getRepository('ApplicationBundle:StockConsumptionNote')
  5407.             ->findBy(
  5408.                 array(
  5409.                     'status' => GeneralConstant::ACTIVE,
  5410.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5411. //                    'approved' =>  GeneralConstant::APPROVED,
  5412.                 )
  5413.             );
  5414.         $stage_list = array(
  5415.             => 'Pending',
  5416.             => 'Pending',
  5417.             => 'Complete',
  5418.             => 'Partial',
  5419.         );
  5420.         $data = [];
  5421.         foreach ($q as $entry) {
  5422.             $data[] = array(
  5423.                 'doc_date' => $entry->getStockConsumptionNoteDate(),
  5424.                 'id' => $entry->getStockConsumptionNoteId(),
  5425.                 'doc_hash' => $entry->getDocumentHash(),
  5426.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5427.                 'stage' => $stage_list[$entry->getStage()]
  5428.             );
  5429.         }
  5430.         return $this->render('@Inventory/pages/views/stock_consumption_note_list.html.twig',
  5431.             array(
  5432.                 'page_title' => 'Stock Consumption Note List',
  5433.                 'data' => $data
  5434.             )
  5435.         );
  5436.     }
  5437.     public function ViewStockConsumptionNoteAction(Request $request$id)
  5438.     {
  5439.         $em $this->getDoctrine()->getManager();
  5440.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5441.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5442.             array(
  5443.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5444.             )
  5445.         );
  5446.         $consumptionTypeList = [];
  5447.         $consumptionTypeListArray = [];
  5448.         foreach ($consumptionTypeQry as $entry) {
  5449.             $p = array(
  5450.                 'name' => $entry->getName(),
  5451.                 'id' => $entry->getConsumptionTypeId(),
  5452.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5453.                 'cost_center_id' => $entry->getCostCenterId(),
  5454.             );
  5455.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5456.             $consumptionTypeListArray[] = $p;
  5457.         }
  5458.         //add bill list
  5459.         $service_purchase_bill_query $this->getDoctrine()
  5460.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5461.             ->findBy(
  5462.                 array(
  5463.                     'typeHash' => 'SPB',
  5464.                     'approved' => GeneralConstant::APPROVED
  5465.                 )
  5466.             );
  5467.         $service_purchase_bill_list = [];
  5468.         $service_purchase_bill_list_array = [];
  5469.         $bill = array(
  5470.             'id' => 0,
  5471.             'type' => 'SPB',
  5472.             'name' => 'New Expense',
  5473.             'text' => 'New Expense',
  5474.             'amount' => 0,
  5475.         );
  5476.         $service_purchase_bill_list[0] = $bill;
  5477.         $service_purchase_bill_list_array[] = $bill;
  5478.         foreach ($service_purchase_bill_query as $d) {
  5479.             $bill = array(
  5480.                 'id' => $d->getPurchaseInvoiceId(),
  5481.                 'type' => 'SPB',
  5482.                 'name' => $d->getDocumentHash(),
  5483.                 'text' => $d->getDocumentHash(),
  5484.                 'amount' => $d->getInvoiceAmount(),
  5485.             );
  5486.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5487.             $service_purchase_bill_list_array[] = $bill;
  5488.         }
  5489.         return $this->render('@Inventory/pages/views/view_stock_consumption_note.html.twig',
  5490.             array(
  5491.                 'page_title' => 'Stock Transfer',
  5492.                 'data' => $dt,
  5493.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5494.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5495.                 'consumptionTypeList' => $consumptionTypeList,
  5496.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5497.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5498.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5499.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5500.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5501.                     $id,
  5502.                     $dt['created_by'],
  5503.                     $dt['edited_by'])
  5504.             )
  5505.         );
  5506.     }
  5507.     public function PrintStockConsumptionNoteAction(Request $request$id)
  5508.     {
  5509.         $em $this->getDoctrine()->getManager();
  5510.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5511.         $company_data Company::getCompanyData($em1);
  5512.         $document_mark = array(
  5513.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5514.             'copy' => ''
  5515.         );
  5516.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5517.             array(
  5518.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5519.             )
  5520.         );
  5521.         $consumptionTypeList = [];
  5522.         $consumptionTypeListArray = [];
  5523.         foreach ($consumptionTypeQry as $entry) {
  5524.             $p = array(
  5525.                 'name' => $entry->getName(),
  5526.                 'id' => $entry->getConsumptionTypeId(),
  5527.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5528.                 'cost_center_id' => $entry->getCostCenterId(),
  5529.             );
  5530.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5531.             $consumptionTypeListArray[] = $p;
  5532.         }
  5533.         //add bill list
  5534.         $service_purchase_bill_query $this->getDoctrine()
  5535.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5536.             ->findBy(
  5537.                 array(
  5538.                     'typeHash' => 'SPB',
  5539.                     'approved' => GeneralConstant::APPROVED
  5540.                 )
  5541.             );
  5542.         $service_purchase_bill_list = [];
  5543.         $service_purchase_bill_list_array = [];
  5544.         $bill = array(
  5545.             'id' => 0,
  5546.             'type' => 'SPB',
  5547.             'name' => 'New Expense',
  5548.             'text' => 'New Expense',
  5549.             'amount' => 0,
  5550.         );
  5551.         $service_purchase_bill_list[0] = $bill;
  5552.         $service_purchase_bill_list_array[] = $bill;
  5553.         foreach ($service_purchase_bill_query as $d) {
  5554.             $bill = array(
  5555.                 'id' => $d->getPurchaseInvoiceId(),
  5556.                 'type' => 'SPB',
  5557.                 'name' => $d->getDocumentHash(),
  5558.                 'text' => $d->getDocumentHash(),
  5559.                 'amount' => $d->getInvoiceAmount(),
  5560.             );
  5561.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5562.             $service_purchase_bill_list_array[] = $bill;
  5563.         }
  5564.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5565.             $html $this->renderView('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  5566.                 array(
  5567.                     //full array here
  5568.                     'pdf' => true,
  5569.                     'page_title' => 'Stock Consumption',
  5570.                     'export' => 'pdf,print',
  5571.                     'data' => $dt,
  5572.                     'service_purchase_bill_list' => $service_purchase_bill_list,
  5573.                     'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5574.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5575.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5576.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5577.                         array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5578.                         $id,
  5579.                         $dt['created_by'],
  5580.                         $dt['edited_by']),
  5581.                     'document_mark_image' => $document_mark['original'],
  5582.                     'consumptionTypeList' => $consumptionTypeList,
  5583.                     'consumptionTypeListArray' => $consumptionTypeListArray,
  5584.                     'company_name' => $company_data->getName(),
  5585.                     'company_data' => $company_data,
  5586.                     'company_address' => $company_data->getAddress(),
  5587.                     'company_image' => $company_data->getImage(),
  5588.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5589.                     'red' => 0
  5590.                 )
  5591.             );
  5592.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5593. //                'orientation' => 'landscape',
  5594. //                'enable-javascript' => true,
  5595. //                'javascript-delay' => 1000,
  5596.                 'no-stop-slow-scripts' => false,
  5597.                 'no-background' => false,
  5598.                 'lowquality' => false,
  5599.                 'encoding' => 'utf-8',
  5600. //            'images' => true,
  5601. //            'cookie' => array(),
  5602.                 'dpi' => 300,
  5603.                 'image-dpi' => 300,
  5604. //                'enable-external-links' => true,
  5605. //                'enable-internal-links' => true
  5606.             ));
  5607.             return new Response(
  5608.                 $pdf_response,
  5609.                 200,
  5610.                 array(
  5611.                     'Content-Type' => 'application/pdf',
  5612.                     'Content-Disposition' => 'attachment; filename="stock_consumption_note_' $id '.pdf"'
  5613.                 )
  5614.             );
  5615.         }
  5616.         return $this->render('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  5617.             array(
  5618.                 'page_title' => 'Stock Consumption',
  5619.                 'export' => 'pdf,print',
  5620.                 'data' => $dt,
  5621.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5622.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5623.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5624.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5625.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5626.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5627.                     $id,
  5628.                     $dt['created_by'],
  5629.                     $dt['edited_by']),
  5630.                 'document_mark_image' => $document_mark['original'],
  5631.                 'consumptionTypeList' => $consumptionTypeList,
  5632.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5633.                 'company_name' => $company_data->getName(),
  5634.                 'company_data' => $company_data,
  5635.                 'company_address' => $company_data->getAddress(),
  5636.                 'company_image' => $company_data->getImage(),
  5637.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5638.                 'red' => 0
  5639.             )
  5640.         );
  5641.     }
  5642.     public function CreateStockReceivedNoteAction(Request $request$id 0)
  5643.     {
  5644.         $em $this->getDoctrine()->getManager();
  5645.         $companyId $this->getLoggedUserCompanyId($request);
  5646.         $extDocData = [];
  5647.         $userId $request->getSession()->get(UserConstants::USER_ID);
  5648.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  5649.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  5650.         $userBranchIdList $request->getSession()->get('branchIdList');
  5651.         if ($userBranchIdList == null$userBranchIdList = [];
  5652.         $userBranchId $request->getSession()->get('branchId');
  5653.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  5654.             $em $this->getDoctrine()->getManager();
  5655.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'];
  5656.             $dochash $request->request->get('docHash');
  5657.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5658.             $approveRole $request->request->get('approvalRole');
  5659.             $approveHash $request->request->get('approvalHash');
  5660.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5661.                 $loginId$approveRole$approveHash$id)
  5662.             ) {
  5663.                 if ($request->request->has('returnJson')) {
  5664.                     return new JsonResponse(array(
  5665.                         'success' => false,
  5666.                         'documentHash' => 0,
  5667.                         'documentId' => 0,
  5668.                         'billIds' => [],
  5669.                         'drIds' => [],
  5670.                         'pmntTransIds' => [],
  5671.                         'viewUrl' => '',
  5672.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  5673.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  5674.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  5675.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  5676.                     ));
  5677.                 } else
  5678.                     $this->addFlash(
  5679.                         'error',
  5680.                         'Sorry Could not insert Data.'
  5681.                     );
  5682.             } else {
  5683.                 if ($request->request->has('check_allowed'))
  5684.                     $check_allowed 1;
  5685.                 $StID Inventory::CreateNewStockReceivedNote(
  5686.                     $this->getDoctrine()->getManager(),
  5687.                     $request->request,
  5688.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5689.                     $this->getLoggedUserCompanyId($request)
  5690.                 );
  5691.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5692.                 $approveRole 1;
  5693.                 $options = array(
  5694.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5695.                     'notification_server' => $this->container->getParameter('notification_server'),
  5696.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5697.                     'url' => $this->generateUrl(
  5698.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  5699.                         ['entity_view_route_path_name']
  5700.                     )
  5701.                 );
  5702.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5703.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5704.                     $StID,
  5705.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5706.                 );
  5707.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  5708.                     $loginId,
  5709.                     $approveRole,
  5710.                     $request->request->get('approvalHash'));
  5711.                 $url $this->generateUrl(
  5712.                     'view_srcv'
  5713.                 );
  5714.                 if ($request->request->has('returnJson')) {
  5715.                     return new JsonResponse(array(
  5716.                         'success' => true,
  5717.                         'documentHash' => $dochash,
  5718.                         'documentId' => $StID,
  5719.                         'viewUrl' => $url "/" $StID,
  5720.                     ));
  5721.                 } else {
  5722.                     $this->addFlash(
  5723.                         'success',
  5724.                         'Stock Received Note Added.'
  5725.                     );
  5726.                     return $this->redirect($url "/" $StID);
  5727.                 }
  5728.             }
  5729.         }
  5730.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5731.             array(
  5732.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5733.             )
  5734.         );
  5735.         if ($id == 0) {
  5736.         } else {
  5737.             $extDoc $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  5738.                 array(
  5739.                     'salesOrderId' => $id,
  5740.                 )
  5741.             );
  5742.             if ($extDoc) {
  5743.                 if ($extDoc->getEditFlag() != 1) {
  5744.                     $url $this->generateUrl(
  5745.                         'view_srcv'
  5746.                     );
  5747.                     return $this->redirect($url "/" $id);
  5748.                 } else {
  5749.                     $extDocData $extDoc;
  5750.                     $extDocDataDetails $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findOneBy(
  5751.                         array(
  5752.                             'stockReceivedNoteId' => $id,
  5753.                         )
  5754.                     );
  5755.                 }
  5756.             } else {
  5757.             }
  5758.         }
  5759.         $INVLIST = [];
  5760.         foreach ($slotList as $slot) {
  5761.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5762.         }
  5763.         $dataArray = array(
  5764.             'page_title' => 'Stock Received Note',
  5765. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  5766.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  5767.             'users' => Users::getUserListById($em),
  5768.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  5769.             'warehouseList' => Inventory::WarehouseList($em),
  5770.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  5771.             'warehouseActionList' => $warehouse_action_list,
  5772.             'warehouseActionListArray' => $warehouse_action_list_array,
  5773.             'extDocData' => $extDocData,
  5774.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  5775.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5776.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5777.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5778. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5779. //            'product_list' => Inventory::ProductList($em, $companyId),
  5780.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  5781.             'prefix_list' => array(
  5782.                 [
  5783.                     'id' => 1,
  5784.                     'value' => 'GN',
  5785.                     'text' => 'GN'
  5786.                 ]
  5787.             ),
  5788.             'assoc_list' => array(
  5789.                 [
  5790.                     'id' => 1,
  5791.                     'value' => 1,
  5792.                     'text' => 'GN'
  5793.                 ]
  5794.             ),
  5795.             'INVLIST' => $INVLIST,
  5796.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  5797.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  5798.             'userBranchIdList' => $userBranchIdList,
  5799.             'userBranchId' => $userBranchId,
  5800. //            'headList' => Accounts::HeadList($em),
  5801.         );
  5802.         //json
  5803.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  5804.         {
  5805.             $dataArray['success'] = true;
  5806.             return new JsonResponse(
  5807.                 $dataArray
  5808.             );
  5809.         }
  5810.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  5811.             $dataArray
  5812.         );
  5813.     }
  5814.     public function GetItemListForStockReceivedAction(Request $request)
  5815.     {
  5816.         if ($request->isMethod('POST')) {
  5817.             $em $this->getDoctrine();
  5818.             $receiveType 1;//transfer
  5819.             if ($request->request->has('receiveType'))
  5820.                 $receiveType $request->request->get('receiveType');
  5821.             $QD = [];
  5822.             if ($receiveType == 1)
  5823.                 $QD $this->getDoctrine()
  5824.                     ->getRepository('ApplicationBundle:StockTransferItem')
  5825.                     ->findBy(
  5826.                         array(
  5827. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  5828.                             'stockTransferId' => $request->request->get('stId')
  5829.                         ),
  5830.                         array()
  5831.                     );
  5832.             if ($receiveType == 2)
  5833.                 $QD $this->getDoctrine()
  5834.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  5835.                     ->findBy(
  5836.                         array(
  5837. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  5838.                             'salesOrderId' => $request->request->get('soId')
  5839.                         ),
  5840.                         array()
  5841.                     );
  5842. //            if($request->request->get('wareHouseId')!='')
  5843. //
  5844. //            $DO=$this->getDoctrine()
  5845. //                ->getRepository('ApplicationBundle:DeliveryOrder')
  5846. //                ->findOneBy(
  5847. //                    $find_array,
  5848. //                    array(
  5849. //
  5850. //                    )
  5851. //                );
  5852.             $sendData = array(
  5853. //                'salesType'=>$SO->getSalesType(),
  5854. //                'packageData'=>[],
  5855.                 'productList' => [],
  5856. //                'productListByPackage'=>[],
  5857.             );
  5858.             $productList Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request));
  5859.             $pckg_item_cross_match_data = [];
  5860.             foreach ($QD as $product) {
  5861. //                $b_code=json_decode($product->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  5862.                 $b_code = [];
  5863.                 $newProductId $product->getProductId();
  5864.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  5865.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  5866.                     if ($to_analyze_codes_str != null)
  5867.                         $b_code json_decode($to_analyze_codes_strtrue512JSON_BIGINT_AS_STRING);
  5868.                     else
  5869.                         $b_code = [];
  5870.                 } else {
  5871.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  5872.                     if ($to_analyze_codes_str != null) {
  5873.                         $max_int_length strlen((string)PHP_INT_MAX) - 1;
  5874.                         $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$to_analyze_codes_str);
  5875.                         $b_code json_decode($json_without_bigintstrue);
  5876.                     } else {
  5877.                         $b_code = [];
  5878.                     }
  5879.                 }
  5880.                 $b_code_data = [];
  5881.                 foreach ($b_code as $d) {
  5882.                     $b_code_data[] = array(
  5883.                         'id' => $d,
  5884.                         'name' => str_pad($d13'0'STR_PAD_LEFT),
  5885.                     );
  5886.                 }
  5887.                 $p_data = array(
  5888.                     'details_id' => $product->getId(),
  5889.                     'productId' => $product->getProductId(),
  5890.                     'product_name' => isset($productList[$product->getProductId()]) ? $productList[$product->getProductId()]['name'] : 'Unknown Product',
  5891.                     'product_barcodes' => $b_code_data,
  5892. //                    'available_inventory'=>$inventory_by_warehouse?$inventory_by_warehouse->getQty():0,
  5893. //                        'package_id'=>$product->getPackageId(),
  5894.                     'qty' => $receiveType == $product->getQty() : $product->getToBeReceived(),
  5895.                     'unit_price' => $receiveType == $product->getPrice() : $productList[$product->getProductId()]['purchase_price'],
  5896.                     'balance' => $receiveType == $product->getBalance() : ($product->getToBeReceived() - $product->getReceived()),
  5897. //                        'delivered'=>$product->getDelivered(),
  5898.                 );
  5899.                 $sendData['productList'][] = $p_data;
  5900.             }
  5901.             //now package data
  5902.             if ($sendData) {
  5903.                 return new JsonResponse(array("success" => true"content" => $sendData));
  5904.             }
  5905.             return new JsonResponse(array("success" => false));
  5906.         }
  5907.         return new JsonResponse(array("success" => false));
  5908.     }
  5909.     public function StockReceivedNoteListAction(Request $request)
  5910.     {
  5911.         $q $this->getDoctrine()
  5912.             ->getRepository('ApplicationBundle:StockReceivedNote')
  5913.             ->findBy(
  5914.                 array(
  5915.                     'status' => GeneralConstant::ACTIVE,
  5916.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5917. //                    'approved' =>  GeneralConstant::APPROVED,
  5918.                 )
  5919.             );
  5920.         $stage_list = array(
  5921.             => 'Pending',
  5922.             => 'Pending',
  5923.             => 'Complete',
  5924.             => 'Partial',
  5925.         );
  5926.         $data = [];
  5927.         foreach ($q as $entry) {
  5928.             $data[] = array(
  5929.                 'doc_date' => $entry->getStockReceivedNoteDate(),
  5930.                 'id' => $entry->getStockReceivedNoteId(),
  5931.                 'doc_hash' => $entry->getDocumentHash(),
  5932.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5933.                 'stage' => $stage_list[$entry->getStage()]
  5934.             );
  5935.         }
  5936.         return $this->render('@Inventory/pages/views/stock_received_note_list.html.twig',
  5937.             array(
  5938.                 'page_title' => 'Stock Received List',
  5939.                 'data' => $data
  5940.             )
  5941.         );
  5942.     }
  5943.     public function ViewStockReceivedNoteAction(Request $request$id)
  5944.     {
  5945.         $em $this->getDoctrine()->getManager();
  5946.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  5947.         return $this->render('@Inventory/pages/views/view_stock_received_note.html.twig',
  5948.             array(
  5949.                 'page_title' => 'Stock Received Note',
  5950.                 'data' => $dt,
  5951.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  5952.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5953.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5954.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5955.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5956.                     $id,
  5957.                     $dt['created_by'],
  5958.                     $dt['edited_by'])
  5959.             )
  5960.         );
  5961.     }
  5962.     public function PrintStockReceivedNoteAction(Request $request$id)
  5963.     {
  5964.         $em $this->getDoctrine()->getManager();
  5965.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  5966.         $company_data Company::getCompanyData($em1);
  5967.         $document_mark = array(
  5968.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5969.             'copy' => ''
  5970.         );
  5971.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5972.             $html $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
  5973.                 array(
  5974.                     //full array here
  5975.                     'pdf' => true,
  5976.                     'page_title' => 'Stock Received Note',
  5977.                     'export' => 'pdf,print',
  5978.                     'data' => $dt,
  5979.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5980.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5981.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5982.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5983.                         $id,
  5984.                         $dt['created_by'],
  5985.                         $dt['edited_by']),
  5986.                     'document_mark_image' => $document_mark['original'],
  5987.                     'company_name' => $company_data->getName(),
  5988.                     'company_data' => $company_data,
  5989.                     'company_address' => $company_data->getAddress(),
  5990.                     'company_image' => $company_data->getImage(),
  5991.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5992.                     'red' => 0
  5993.                 )
  5994.             );
  5995.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5996. //                'orientation' => 'landscape',
  5997. //                'enable-javascript' => true,
  5998. //                'javascript-delay' => 1000,
  5999.                 'no-stop-slow-scripts' => false,
  6000.                 'no-background' => false,
  6001.                 'lowquality' => false,
  6002.                 'encoding' => 'utf-8',
  6003. //            'images' => true,
  6004. //            'cookie' => array(),
  6005.                 'dpi' => 300,
  6006.                 'image-dpi' => 300,
  6007. //                'enable-external-links' => true,
  6008. //                'enable-internal-links' => true
  6009.             ));
  6010.             return new Response(
  6011.                 $pdf_response,
  6012.                 200,
  6013.                 array(
  6014.                     'Content-Type' => 'application/pdf',
  6015.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  6016.                 )
  6017.             );
  6018.         }
  6019.         return $this->render('@Inventory/pages/print/print_stock_received_note.html.twig',
  6020.             array(
  6021.                 'page_title' => 'Stock Received Note',
  6022.                 'export' => 'pdf,print',
  6023.                 'data' => $dt,
  6024.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6025.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6026.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6027.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6028.                     $id,
  6029.                     $dt['created_by'],
  6030.                     $dt['edited_by']),
  6031.                 'document_mark_image' => $document_mark['original'],
  6032.                 'company_name' => $company_data->getName(),
  6033.                 'company_data' => $company_data,
  6034.                 'company_address' => $company_data->getAddress(),
  6035.                 'company_image' => $company_data->getImage(),
  6036.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6037.                 'red' => 0
  6038.             )
  6039.         );
  6040.     }
  6041.     public function CreateStoreRequisitionSlipAction(Request $request$id 0)
  6042.     {
  6043.         $em $this->getDoctrine()->getManager();
  6044. //        $id;
  6045.         if ($request->isMethod('POST')) {
  6046.             $em $this->getDoctrine()->getManager();
  6047.             $entity_id array_flip(GeneralConstant::$Entity_list)['StoreRequisition']; //change
  6048.             $dochash $request->request->get('voucherNumber'); //change
  6049.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6050.             $approveRole $request->request->get('approvalRole');
  6051.             $approveHash $request->request->get('approvalHash');
  6052.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6053.                 $loginId$approveRole$approveHash$id)
  6054.             ) {
  6055.                 $this->addFlash(
  6056.                     'error',
  6057.                     'Sorry, could not insert Data.'
  6058.                 );
  6059.             } else {
  6060.                 if ($request->request->has('check_allowed'))
  6061.                     $check_allowed 1;
  6062.                 $IrID Inventory::CreateNewStoreRequisition($id,
  6063.                     $this->getDoctrine()->getManager(),
  6064.                     $request->request,
  6065.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6066.                     $this->getLoggedUserCompanyId($request)
  6067.                 );
  6068.                 //now add Approval info
  6069.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6070.                 $approveRole $request->request->get('approvalRole');
  6071.                 $options = array(
  6072.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6073.                     'notification_server' => $this->container->getParameter('notification_server'),
  6074.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6075.                     'url' => $this->generateUrl(
  6076.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StoreRequisition']]
  6077.                         ['entity_view_route_path_name']
  6078.                     )
  6079.                 );
  6080.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6081.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  6082.                     $IrID,
  6083.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6084.                 );
  6085.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StoreRequisition'], $IrID,
  6086.                     $loginId,
  6087.                     $approveRole,
  6088.                     $request->request->get('approvalHash'));
  6089.                 $this->addFlash(
  6090.                     'success',
  6091.                     'New Indent Added.'
  6092.                 );
  6093.                 $url $this->generateUrl(
  6094.                     'view_ir'
  6095.                 );
  6096.                 return $this->redirect($url "/" $IrID);
  6097.             }
  6098.         }
  6099.         $extDocData = [];
  6100.         $extDocDetailsData = [];
  6101.         if ($id == 0) {
  6102.         } else {
  6103.             $extDoc $em->getRepository('ApplicationBundle:StoreRequisition')->findOneBy(
  6104.                 array(
  6105.                     'storeRequisitionId' => $id///material
  6106.                 )
  6107.             );
  6108.             //now if its not editable, redirect to view
  6109.             if ($extDoc) {
  6110.                 if ($extDoc->getEditFlag() != 1) {
  6111.                     $url $this->generateUrl(
  6112.                         'view_ir'
  6113.                     );
  6114.                     return $this->redirect($url "/" $id);
  6115.                 } else {
  6116.                     $extDocData $extDoc;
  6117.                     $extDocDetailsData $em->getRepository('ApplicationBundle:StoreRequisitionItem')->findBy(
  6118.                         array(
  6119.                             'storeRequisitionId' => $id///material
  6120.                         )
  6121.                     );;
  6122.                 }
  6123.             } else {
  6124.             }
  6125.         }
  6126.         $companyId $this->getLoggedUserCompanyId($request);
  6127.         $productListArray = [];
  6128.         $subCategoryListArray = [];
  6129.         $categoryListArray = [];
  6130.         $igListArray = [];
  6131.         $unitListArray = [];
  6132.         $brandListArray = [];
  6133.         $productList Inventory::ProductList($em$companyId);
  6134.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6135.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6136.         $igList Inventory::ItemGroupList($em$companyId);
  6137.         $unitList Inventory::UnitTypeList($em);
  6138.         $brandList Inventory::GetBrandList($em$companyId);
  6139.         foreach ($productList as $product$productListArray[] = $product;
  6140.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6141.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6142.         foreach ($igList as $product$igListArray[] = $product;
  6143.         foreach ($unitList as $product$unitListArray[] = $product;
  6144.         foreach ($brandList as $product$brandListArray[] = $product;
  6145.         $sr_list = [];
  6146.         $QD $this->getDoctrine()
  6147.             ->getRepository('ApplicationBundle:StockRequisition')
  6148.             ->findBy(
  6149.                 array(
  6150.                     'indentTagged' => 0,
  6151.                     'approved' => 1
  6152.                 )
  6153.             );
  6154.         foreach ($QD as $dt) {
  6155.             $sr_list[$dt->getStockRequisitionId()] = array(
  6156.                 'id' => $dt->getStockRequisitionId(),
  6157.                 'name' => $dt->getDocumentHash(),
  6158.                 'text' => $dt->getDocumentHash(),
  6159.             );
  6160.         }
  6161.         return $this->render('@Inventory/pages/input_forms/store_requisition.html.twig',
  6162.             array(
  6163.                 'page_title' => 'Indent Requisition Slip',
  6164.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6165.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6166.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6167.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6168.                 'sr_list' => $sr_list,
  6169.                 'productList' => $productList,
  6170.                 'subCategoryList' => $subCategoryList,
  6171.                 'categoryList' => $categoryList,
  6172.                 'igList' => $igList,
  6173.                 'extId' => $id,
  6174.                 'extDocDetailsData' => $extDocDetailsData,
  6175.                 'extDocData' => $extDocData,
  6176.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6177.                 'unitList' => $unitList,
  6178.                 'brandList' => $brandList,
  6179.                 'brandListArray' => $brandListArray,
  6180.                 'productListArray' => $productListArray,
  6181.                 'subCategoryListArray' => $subCategoryListArray,
  6182.                 'categoryListArray' => $categoryListArray,
  6183.                 'igListArray' => $igListArray,
  6184.                 'unitListArray' => $unitListArray,
  6185.                 'prefix_list' => array(
  6186.                     [
  6187.                         'id' => 1,
  6188.                         'value' => 'GN',
  6189.                         'text' => 'General'
  6190.                     ],
  6191.                     [
  6192.                         'id' => 1,
  6193.                         'value' => 'SD',
  6194.                         'text' => 'For Sales Demand'
  6195.                     ]
  6196.                 ),
  6197.                 'assoc_list' => array(
  6198.                     [
  6199.                         'id' => 1,
  6200.                         'value' => 1,
  6201.                         'text' => 'GN'
  6202.                     ]
  6203.                 )
  6204.             )
  6205.         );
  6206.     }
  6207.     public function CreateStockRequisitionSlipAction(Request $request$id 0)
  6208.     {
  6209.         $em $this->getDoctrine()->getManager();
  6210.         if ($request->isMethod('POST')) {
  6211.             $em $this->getDoctrine()->getManager();
  6212.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockRequisition']; //change
  6213.             $dochash $request->request->get('voucherNumber'); //change
  6214.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6215.             $approveRole $request->request->get('approvalRole');
  6216.             $approveHash $request->request->get('approvalHash');
  6217.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6218.                 $loginId$approveRole$approveHash$id)
  6219.             ) {
  6220.                 $this->addFlash(
  6221.                     'error',
  6222.                     'Sorry, could not insert Data.'
  6223.                 );
  6224.             } else {
  6225.                 if ($request->request->has('check_allowed'))
  6226.                     $check_allowed 1;
  6227.                 $SrID Inventory::CreateNewStockRequisition($id,
  6228.                     $this->getDoctrine()->getManager(),
  6229.                     $request->request,
  6230.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6231.                     $this->getLoggedUserCompanyId($request)
  6232.                 );
  6233.                 //now add Approval info
  6234.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6235.                 $approveRole $request->request->get('approvalRole');
  6236.                 $options = array(
  6237.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6238.                     'notification_server' => $this->container->getParameter('notification_server'),
  6239.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6240.                     'url' => $this->generateUrl(
  6241.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockRequisition']]
  6242.                         ['entity_view_route_path_name']
  6243.                     )
  6244.                 );
  6245.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6246.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  6247.                     $SrID,
  6248.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6249.                 );
  6250.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockRequisition'], $SrID,
  6251.                     $loginId,
  6252.                     $approveRole,
  6253.                     $request->request->get('approvalHash'));
  6254.                 $this->addFlash(
  6255.                     'success',
  6256.                     'New Requisition Added.'
  6257.                 );
  6258.                 $url $this->generateUrl(
  6259.                     'view_sr'
  6260.                 );
  6261. //                return $this->redirect($url . "/" . $SrID);
  6262.             }
  6263.         }
  6264.         $extDocData = [];
  6265.         $extDocDetailsData = [];
  6266.         if ($id == 0) {
  6267.         } else {
  6268.             $extDoc $em->getRepository('ApplicationBundle:StockRequisition')->findOneBy(
  6269.                 array(
  6270.                     'stockRequisitionId' => $id///material
  6271.                 )
  6272.             );
  6273.             //now if its not editable, redirect to view
  6274.             if ($extDoc) {
  6275.                 if ($extDoc->getEditFlag() != 1) {
  6276.                     $url $this->generateUrl(
  6277.                         'view_sr'
  6278.                     );
  6279.                     return $this->redirect($url "/" $id);
  6280.                 } else {
  6281.                     $extDocData $extDoc;
  6282.                     $extDocDetailsData $em->getRepository('ApplicationBundle:StockRequisitionItem')->findBy(
  6283.                         array(
  6284.                             'stockRequisitionId' => $id///material
  6285.                         )
  6286.                     );;
  6287.                 }
  6288.             } else {
  6289.             }
  6290.         }
  6291.         $companyId $this->getLoggedUserCompanyId($request);
  6292.         $productListArray = [];
  6293.         $subCategoryListArray = [];
  6294.         $categoryListArray = [];
  6295.         $igListArray = [];
  6296.         $unitListArray = [];
  6297.         $brandListArray = [];
  6298.         $productList Inventory::ProductList($em$companyId);
  6299.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6300.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6301.         $igList Inventory::ItemGroupList($em$companyId);
  6302.         $unitList Inventory::UnitTypeList($em);
  6303.         $brandList Inventory::GetBrandList($em$companyId);
  6304.         foreach ($productList as $product$productListArray[] = $product;
  6305.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6306.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6307.         foreach ($igList as $product$igListArray[] = $product;
  6308.         foreach ($unitList as $product$unitListArray[] = $product;
  6309.         foreach ($brandList as $product$brandListArray[] = $product;
  6310.         return $this->render('@Inventory/pages/input_forms/stock_requisition_slip.html.twig',
  6311.             array(
  6312.                 'page_title' => 'Stock Requisition Slip',
  6313.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6314.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6315.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6316.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6317.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  6318.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6319.                 'productList' => $productList,
  6320.                 'extId' => $id,
  6321.                 'extDocDetailsData' => $extDocDetailsData,
  6322.                 'extDocData' => $extDocData,
  6323.                 'subCategoryList' => $subCategoryList,
  6324.                 'categoryList' => $categoryList,
  6325.                 'igList' => $igList,
  6326.                 'unitList' => $unitList,
  6327.                 'brandList' => $brandList,
  6328.                 'brandListArray' => $brandListArray,
  6329.                 'productListArray' => $productListArray,
  6330.                 'subCategoryListArray' => $subCategoryListArray,
  6331.                 'categoryListArray' => $categoryListArray,
  6332.                 'igListArray' => $igListArray,
  6333.                 'unitListArray' => $unitListArray,
  6334.                 'productionBomList' => ProductionM::ProductionBomList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6335.                 'productionScheduleList' => ProductionM::ProductionScheduleList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6336.                 'prefix_list' => array(
  6337.                     [
  6338.                         'id' => 1,
  6339.                         'value' => 'GN',
  6340.                         'text' => 'General'
  6341.                     ],
  6342.                     [
  6343.                         'id' => 1,
  6344.                         'value' => 'SD',
  6345.                         'text' => 'For Sales Demand'
  6346.                     ]
  6347.                 ),
  6348.                 'projectList' => $em->getRepository('ApplicationBundle:Project')->findBy(
  6349.                     array(
  6350.                         'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  6351.                     ), array('projectDate' => 'desc')
  6352.                 ),
  6353.                 'salesOrderList' => SalesOrderM::SalesOrderListPendingDelivery($em),
  6354.                 'assoc_list' => array(
  6355.                     [
  6356.                         'id' => 1,
  6357.                         'value' => 'GN',
  6358.                         'text' => 'General'
  6359.                     ]
  6360.                 )
  6361.             )
  6362.         );
  6363.     }
  6364.     public function CreateStockReturnAction(Request $request)
  6365.     {
  6366.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  6367.             array(
  6368.                 'page_title' => 'Stock Return',
  6369. //                'dataList'=>$dta_list
  6370.             )
  6371.         );
  6372.     }
  6373.     public function MaterialInwardAction(Request $request)
  6374.     {
  6375.         $data = [];
  6376.         if ($request->isMethod('POST')) {
  6377.             //first of all resolve the transport costs
  6378.             $total_price_value 0;
  6379.             $data_list $dt $this->getDoctrine()
  6380.                 ->getRepository('ApplicationBundle:PurchaseOrderItem')
  6381.                 ->findBy(
  6382.                     array(
  6383.                         'purchaseOrderId' => $request->request->get('poId'),
  6384.                         'productId' => $request->request->get('products')
  6385.                     )
  6386.                 );
  6387.             $purchase_items = [];
  6388.             foreach ($data_list as $key => $value) {
  6389.                 $purchase_items[$value->getProductId()] = $value;
  6390.             }
  6391.             foreach ($request->request->get('products') as $key => $entry) {
  6392.                 $total_price_value $total_price_value + ($request->request->get('receivedQty')[$key]) * ($purchase_items[$entry]->getPrice());
  6393.             }
  6394.             $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$request->request->get('poId')];
  6395.             $supplier_id $po_data['supplier_id'];
  6396.             $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6397.             foreach ($request->request->get('products') as $key => $entry) {
  6398.                 if ($request->request->get('receivedQty')[$key] > 0)
  6399.                     Inventory::NewMaterialInward($this->getDoctrine()->getManager(),
  6400.                         $request->request,
  6401.                         $key,
  6402.                         $request->request->get('poId'),
  6403.                         $request->request->get('purchaseOrderItemId'),
  6404.                         $supplier_id,
  6405.                         $request->request->get('warehouseId'),
  6406.                         $request->request->get('lotNumber'),
  6407.                         $request->request->get('type_hash'),
  6408.                         $request->request->get('prefix_hash'),
  6409.                         $request->request->get('assoc_hash'),
  6410.                         $request->request->get('number_hash'),
  6411.                         $request->request->get('docHash'),
  6412.                         $request->request->get('docDate'),
  6413.                         $purchase_items[$entry],
  6414.                         $total_price_value,
  6415.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6416.             }
  6417.             $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$request->request->get('warehouseId')]['name'];
  6418. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6419.             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),
  6420.                 "A stack of material Has Arrived at The " $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6421.                 'all',
  6422.                 "",
  6423.                 'information',
  6424.                 "",
  6425.                 "Inbound Material"
  6426.             );
  6427. //                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);
  6428.         }
  6429.         return $this->render('@Inventory/pages/input_forms/material_inward.html.twig',
  6430.             array(
  6431.                 'page_title' => 'Material Inward',
  6432.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6433.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  6434.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  6435.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  6436.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  6437.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  6438.                 "unitList" => Inventory::UnitTypeList($this->getDoctrine()->getManager())
  6439. //                'po'=>Inventory::getPurchaseOrderList
  6440.             )
  6441.         );
  6442.     }
  6443.     public function QualityControlAction(Request $request)
  6444.     {
  6445.         $checked_qc_list_flag 0;
  6446.         if ($request->query->has('checked_qc_list_flag'))
  6447.             $checked_qc_list_flag $request->query->has('checked_qc_list_flag');
  6448.         if ($request->isMethod('POST')) {
  6449.             foreach ($request->request->get('qc_checked', []) as $key => $entry) {
  6450.                 $em $this->getDoctrine()->getManager();
  6451.                 $data $this->getDoctrine()
  6452.                     ->getRepository('ApplicationBundle:MaterialInward')
  6453.                     ->findOneBy(
  6454.                         array(
  6455.                             'qcId' => $entry
  6456.                         )
  6457.                     );
  6458.                 if ($request->request->get('approvedQty')[$entry] <= 0) {
  6459.                     $em->remove($data);
  6460.                     $em->flush();
  6461.                 } else {
  6462.                     $data->setApprovedQty($request->request->get('approvedQty')[$entry]);
  6463.                     $data->setRejectedQty($data->getInwardQty() - $request->request->get('approvedQty')[$entry]);
  6464.                     $data->setQcDate(new \DateTime($request->request->get('qcDate')));
  6465.                     $data->setStage(GeneralConstant::STAGE_PENDING_TAG);
  6466.                     $em->flush();
  6467.                 }
  6468.                 //notification
  6469.                 $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$data->getPurchaseOrderId()];
  6470.                 $supplier_id $po_data['supplier_id'];
  6471.                 $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6472.                 $product_name Inventory::ProductList($this->getDoctrine()->getManager())[$data->getProductId()]['name'];
  6473.                 $qty $request->request->get('approvedQty')[$entry];
  6474.                 $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$data->getWarehouseId()]['name'];
  6475. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6476.                 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),
  6477.                     $qty " among " $data->getInwardQty() . " units of " $product_name " has passed the Quality Control in " .
  6478.                     $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6479.                     'all',
  6480.                     "",
  6481.                     'success',
  6482.                     "",
  6483.                     "Quality Control"
  6484.                 );
  6485.             }
  6486.         }
  6487.         return $this->render('@Inventory/pages/input_forms/qc.html.twig',
  6488.             array(
  6489.                 'page_title' => 'Quality Control',
  6490.                 'checked_qc_list_flag' => $checked_qc_list_flag,
  6491.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6492.                 'warehouse_indexed' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6493.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  6494.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  6495.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  6496.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  6497.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6498.                 'material_inward' => $this->getDoctrine()
  6499.                     ->getRepository('ApplicationBundle:MaterialInward')
  6500.                     ->findBy(
  6501.                         array(
  6502.                             'stage' => $checked_qc_list_flag == GeneralConstant::STAGE_PENDING GeneralConstant::STAGE_PENDING_TAG
  6503.                         )
  6504.                     )
  6505. //                'po'=>Inventory::getPurchaseOrderList
  6506.             )
  6507.         );
  6508.     }
  6509.     public function InventoryTransactionViewAction(Request $request)
  6510.     {
  6511.         $em $this->getDoctrine()->getManager();
  6512.         $qry_data = array(
  6513.             'warehouseId' => [0],
  6514.             'igId' => [0],
  6515.             'brandId' => [0],
  6516.             'categoryId' => [0],
  6517.             'actionTagId' => [0],
  6518.         );
  6519.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6520.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6521.         $data_searched = [];
  6522.         $em $this->getDoctrine()->getManager();
  6523.         $companyId $this->getLoggedUserCompanyId($request);
  6524.         $company_data Company::getCompanyData($em$companyId);
  6525.         $data = [];
  6526.         $print_title "Inventory Report";
  6527.         $document_mark = array(
  6528.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6529.             'copy' => ''
  6530.         );
  6531.         if ($request->isMethod('POST'))
  6532.             $method 'POST';
  6533.         else
  6534.             $method 'GET';
  6535.         {
  6536.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  6537.                 $request->request$method,
  6538.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6539.                 $companyId);
  6540.             if ($request->query->has('returnJson') || $request->request->has('returnJson')) {
  6541.                 return new JsonResponse(
  6542.                     array(
  6543.                         'success' => true,
  6544. //                    'page_title' => 'Product Details',
  6545. //                    'company_data' => $company_data,
  6546.                         'page_title' => 'Inventory Transactions',
  6547.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6548.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6549.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6550.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6551.                         'data_products' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6552.                         'action_tag' => $warehouse_action_list,
  6553.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6554.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6555.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6556.                         'data_searched' => $data_searched
  6557.                     )
  6558.                 );
  6559.             } else if ($request->request->get('print_data_enabled') == 1) {
  6560.                 $print_sub_title "";
  6561.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  6562.                     array(
  6563.                         'page_title' => 'Inventory Report',
  6564.                         'page_header' => 'Report',
  6565.                         'print_title' => $print_title,
  6566.                         'document_type' => 'Journal voucher',
  6567.                         'document_mark_image' => $document_mark['original'],
  6568.                         'page_header_sub' => 'Add',
  6569.                         'item_data' => [],
  6570.                         'received' => 2,
  6571.                         'return' => 1,
  6572.                         'total_w_vat' => 1,
  6573.                         'total_vat' => 1,
  6574.                         'total_wo_vat' => 1,
  6575.                         'invoice_id' => 'abcd1234',
  6576.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6577.                         'created_by' => 'created by',
  6578.                         'created_at' => '',
  6579.                         'red' => 0,
  6580.                         'company_name' => $company_data->getName(),
  6581.                         'company_data' => $company_data,
  6582.                         'company_address' => $company_data->getAddress(),
  6583.                         'company_image' => $company_data->getImage(),
  6584.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6585.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6586.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6587.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6588.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6589.                         'action_tag' => $warehouse_action_list,
  6590.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6591.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6592.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6593.                         'data_searched' => $data_searched
  6594.                     )
  6595.                 );
  6596.             }
  6597.         }
  6598.         return $this->render('@Inventory/pages/report/inventory_transaction_view.html.twig',
  6599.             array(
  6600.                 'page_title' => 'Inventory Transactions',
  6601.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6602.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6603.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6604.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6605.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6606.                 'action_tag' => $warehouse_action_list,
  6607.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6608.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6609.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6610.                 'data_searched' => $data_searched
  6611.             )
  6612.         );
  6613.     }
  6614.     public function StockConsumptionViewAction(Request $request)
  6615.     {
  6616.         $em $this->getDoctrine()->getManager();
  6617.         $start_date $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
  6618.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : new \DateTime();
  6619.         $qry_data = array(
  6620.             'warehouseId' => [0],
  6621.             'igId' => [0],
  6622.             'brandId' => [0],
  6623.             'categoryId' => [0],
  6624.             'actionTagId' => [0],
  6625.         );
  6626.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6627.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6628.         $data_searched = [];
  6629.         $em $this->getDoctrine()->getManager();
  6630.         $company_data Company::getCompanyData($em1);
  6631.         $data = [];
  6632.         $print_title "Inventory Report";
  6633.         $document_mark = array(
  6634.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6635.             'copy' => ''
  6636.         );
  6637.         if ($request->isMethod('POST'))
  6638.             $method 'POST';
  6639.         else
  6640.             $method 'GET';
  6641.         $post_data $method == 'POST' $request->request $request->query;
  6642.         $data_searched Inventory::GetStockConsumptionData($this->getDoctrine()->getManager(),
  6643.             $post_data,
  6644.             $method,
  6645.             $start_date,
  6646.             $end_date,
  6647.             $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6648.         if ($post_data->get('print_data_enabled') == 1) {
  6649.             $print_sub_title "";
  6650.             if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6651.                 $html $this->renderView('@Inventory/pages/print/print_stock_consumption.html.twig',
  6652.                     array(
  6653.                         'pdf' => 'true',
  6654.                         'page_title' => 'Inventory Report',
  6655.                         'page_header' => 'Report',
  6656.                         'print_title' => $print_title,
  6657.                         'document_type' => 'Journal voucher',
  6658.                         'document_mark_image' => $document_mark['original'],
  6659.                         'page_header_sub' => 'Add',
  6660.                         'item_data' => [],
  6661.                         'received' => 2,
  6662.                         'return' => 1,
  6663.                         'total_w_vat' => 1,
  6664.                         'total_vat' => 1,
  6665.                         'total_wo_vat' => 1,
  6666.                         'invoice_id' => 'abcd1234',
  6667.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6668.                         'created_by' => 'created by',
  6669.                         'created_at' => '',
  6670.                         'red' => 0,
  6671.                         'start_date' => $start_date,
  6672.                         'end_date' => $end_date,
  6673.                         'openFilter' => empty($post_data->keys()) ? 0,
  6674.                         'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6675.                         'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6676.                         'company_name' => $company_data->getName(),
  6677.                         'company_data' => $company_data,
  6678.                         'company_address' => $company_data->getAddress(),
  6679.                         'company_image' => $company_data->getImage(),
  6680.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6681.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6682.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6683.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6684.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6685.                         'action_tag' => $warehouse_action_list,
  6686.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6687.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6688.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6689.                         'data_searched' => $data_searched,
  6690.                         'export' => 'all'
  6691.                     )
  6692.                 );
  6693.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6694.                     'orientation' => count($data_searched['query_columns_filter']) > 'landscape' 'portrait',
  6695.                     'no-stop-slow-scripts' => true,
  6696.                     'no-background' => false,
  6697.                     'lowquality' => false,
  6698.                     'encoding' => 'utf-8',
  6699.                     'dpi' => 300,
  6700.                     'image-dpi' => 300,
  6701.                 ));
  6702.                 return new Response(
  6703.                     $pdf_response,
  6704.                     200,
  6705.                     array(
  6706.                         'Content-Type' => 'application/pdf',
  6707.                         'Content-Disposition' => 'attachment; filename="Stock_Consumption.pdf"'
  6708.                     )
  6709.                 );
  6710.             }
  6711.             return $this->render('@Inventory/pages/print/print_stock_consumption.html.twig',
  6712.                 array(
  6713.                     'page_title' => 'Inventory Report',
  6714.                     'page_header' => 'Report',
  6715.                     'print_title' => $print_title,
  6716.                     'document_type' => 'Journal voucher',
  6717.                     'document_mark_image' => $document_mark['original'],
  6718.                     'page_header_sub' => 'Add',
  6719.                     'item_data' => [],
  6720.                     'received' => 2,
  6721.                     'return' => 1,
  6722.                     'total_w_vat' => 1,
  6723.                     'total_vat' => 1,
  6724.                     'total_wo_vat' => 1,
  6725.                     'invoice_id' => 'abcd1234',
  6726.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6727.                     'created_by' => 'created by',
  6728.                     'created_at' => '',
  6729.                     'red' => 0,
  6730.                     'start_date' => $start_date,
  6731.                     'end_date' => $end_date,
  6732.                     'openFilter' => empty($post_data->keys()) ? 0,
  6733.                     'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6734.                     'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6735.                     'company_name' => $company_data->getName(),
  6736.                     'company_data' => $company_data,
  6737.                     'company_address' => $company_data->getAddress(),
  6738.                     'company_image' => $company_data->getImage(),
  6739.                     'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6740.                     'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6741.                     'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6742.                     'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6743.                     'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6744.                     'action_tag' => $warehouse_action_list,
  6745.                     'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6746.                     'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6747.                     'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6748.                     'data_searched' => $data_searched,
  6749.                     'export' => 'all'
  6750.                 )
  6751.             );
  6752.         }
  6753.         return $this->render('@Inventory/pages/report/stock_consumption.html.twig',
  6754.             array(
  6755.                 'page_title' => 'Stock Consumption',
  6756.                 'start_date' => $start_date,
  6757.                 'end_date' => $end_date,
  6758.                 'openFilter' => empty($post_data->keys()) ? 0,
  6759.                 'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6760.                 'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6761.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6762.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6763.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6764.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6765.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6766.                 'action_tag' => $warehouse_action_list,
  6767.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6768.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6769.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6770.                 'data_searched' => $data_searched
  6771.             )
  6772.         );
  6773.     }
  6774.     public function ItemViewAction(Request $request)
  6775.     {
  6776.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  6777.             array(
  6778.                 'page_title' => 'Stock Return'
  6779.             )
  6780.         );
  6781.     }
  6782.     public function ProductViewAction(Request $request$id 0)
  6783.     {
  6784.         $em $this->getDoctrine()->getManager();
  6785.         $companyId $this->getLoggedUserCompanyId($request);
  6786.         $company_data Company::getCompanyData($em$companyId);
  6787.         $data = [];
  6788.         $productData $em->getRepository('ApplicationBundle:InvProducts')
  6789.             ->findOneBy(
  6790.                 array(
  6791.                     'id' => $id
  6792.                 )
  6793.             );
  6794.         $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  6795.             ->findBy(
  6796.                 array(
  6797.                     'productId' => $id
  6798.                 )
  6799.             );
  6800.         $trans_history $em->getRepository('ApplicationBundle:InvItemTransaction')
  6801.             ->findBy(
  6802.                 array(
  6803.                     'productId' => $id
  6804.                 ), array(
  6805.                     'transactionDate' => 'ASC',
  6806.                     'id' => 'ASC'
  6807.                 )
  6808.             );
  6809.         $productDataObj = array();
  6810.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  6811.             $getters array_filter(get_class_methods($productData), function ($method) {
  6812.                 return 'get' === substr($method03);
  6813.             });
  6814.             foreach ($getters as $getter) {
  6815.                 if ($getter == 'getGlobalId')
  6816.                     continue;
  6817.         //                    if ($getter == 'getId')
  6818.         //                        continue;
  6819.                 $Fieldname str_replace('get'''$getter);
  6820.                 $productDataObj[$Fieldname] = $productData->{$getter}(); // `foo!`
  6821.             }
  6822.             if ($request->request->has('genInfoOnly') && $request->request->get('genInfoOnly') == 1) {
  6823.                 $dataArray = array(
  6824.                     'success' => true,
  6825.                     'page_title' => 'Product Details',
  6826.                     'company_data' => $company_data,
  6827.                     'productData' => $productData,
  6828.                     'productDataObj' => $productDataObj,
  6829.                     'defaultImageAppendUrl' => '/uploads/Products/',
  6830.                 );
  6831.             } else {
  6832.                 $dataArray = array(
  6833.                     'success' => true,
  6834.                     'page_title' => 'Product Details',
  6835.                     'company_data' => $company_data,
  6836.                     'productData' => $productData,
  6837.                     'productDataObj' => $productDataObj,
  6838.                     'currInvList' => $currInvList,
  6839.                     'trans_history' => $trans_history,
  6840.                     'entityList' => GeneralConstant::$Entity_list_details,
  6841.         //                    'productList' => Inventory::ProductList($em, $companyId),
  6842.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  6843.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  6844.                     'igList' => Inventory::ItemGroupList($em$companyId),
  6845.                     'unitList' => Inventory::UnitTypeList($em),
  6846.                     'brandList' => Inventory::GetBrandList($em$companyId),
  6847.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  6848.                     'warehouseList' => Inventory::WarehouseList($em),
  6849.                     'defaultImageAppendUrl' => '/uploads/Products/',
  6850.                 );
  6851.             }
  6852.             return new JsonResponse(
  6853.                 $dataArray
  6854.             );
  6855.         }
  6856.         $dataArray = array(
  6857.             'page_title' => 'Product Details',
  6858.             'company_data' => $company_data,
  6859.             'productData' => $productData,
  6860.             'currInvList' => $currInvList,
  6861.             'trans_history' => $trans_history,
  6862.             'entityList' => GeneralConstant::$Entity_list_details,
  6863.         //            'productList' => Inventory::ProductList($em, $companyId),
  6864.             'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  6865.             'categoryList' => Inventory::ProductCategoryList($em$companyId),
  6866.             'igList' => Inventory::ItemGroupList($em$companyId),
  6867.             'unitList' => Inventory::UnitTypeList($em),
  6868.             'brandList' => Inventory::GetBrandList($em$companyId),
  6869.             'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  6870.             'warehouseList' => Inventory::WarehouseList($em),
  6871.         );
  6872.         return $this->render('@Inventory/pages/views/product_view.html.twig'$dataArray
  6873.         );
  6874.     }
  6875.     public function CheckForProductInWarehouseAction(Request $request$queryStr '')
  6876.     {
  6877.         $em $this->getDoctrine()->getManager();
  6878.         $companyId $this->getLoggedUserCompanyId($request);
  6879.         $data = [
  6880.             'availableQty' => 0,
  6881.             'productByCodesArray' => [],
  6882.             'indRowId' => 0
  6883.         ];
  6884.         $html '';
  6885.         $productByCodeData = [];
  6886.         if ($request->isMethod('POST')) {
  6887.             $warehouseId $request->request->get('warehouseId'0);
  6888.             $warehouseActionId $request->request->get('warehouseActionId'0);
  6889.             $productId $request->request->get('productId'0);
  6890.             $indRowId $request->request->get('indRowId'0);
  6891.             $data['indRowId'] = $indRowId;
  6892.             $inStorage $em->getRepository('ApplicationBundle:InventoryStorage')
  6893.                 ->findBy(
  6894.                     array(
  6895.                         'productId' => $productId,
  6896.                         'warehouseId' => $warehouseId,
  6897.                         'actionTagId' => $warehouseActionId,
  6898.                         'CompanyId' => $companyId,
  6899.                     )
  6900.                 );
  6901.             foreach ($inStorage as $strg) {
  6902.                 $data['availableQty'] += $strg->getQty();
  6903.             }
  6904.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  6905.                 ->findBy(
  6906.                     array(
  6907.                         'productId' => $productId,
  6908.                         'warehouseId' => $warehouseId,
  6909.                         'warehouseActionId' => $warehouseActionId,
  6910.                         'CompanyId' => $companyId,
  6911.                     )
  6912.                 );
  6913.             foreach ($productByCodeData as $pbc) {
  6914.                 $data['productByCodesArray'][] = array(
  6915.                     'id' => $pbc->getProductByCodeId(),
  6916.                     'productId' => $pbc->getProductId(),
  6917.                     'warehouseId' => $pbc->getWarehouseId(),
  6918.                     'warehouseActionId' => $pbc->getWarehouseActionId(),
  6919. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  6920.                     'sales_code' => str_pad($pbc->getSalesCode(), 13'0'STR_PAD_LEFT),
  6921. //                'sales_code'=>$d['sales_code'],
  6922.                 );
  6923.             }
  6924.             return new JsonResponse(array(
  6925.                     'success' => true,
  6926.                     'data' => $data,
  6927.                 )
  6928.             );
  6929.         }
  6930.         return new JsonResponse(
  6931.             array(
  6932.                 'success' => false,
  6933.                 'data' => $data,
  6934.             )
  6935.         );
  6936.     }
  6937.     public function ProductByCodeListAjaxAction(Request $request$queryStr '')
  6938.     {
  6939.         $em $this->getDoctrine()->getManager();
  6940.         $companyId $this->getLoggedUserCompanyId($request);
  6941.         $company_data Company::getCompanyData($em$companyId);
  6942.         $data = [];
  6943.         $html '';
  6944.         $productByCodeData = [];
  6945.         if ($request->request->has('query') && $queryStr == '')
  6946.             $queryStr $request->request->get('queryStr');
  6947.         $get_kids_sql "select product_by_code_id id, product_id, warehouse_id, warehouse_action_id,
  6948.                             sales_code ,
  6949.                             serial_no,
  6950.                             imei1,
  6951.                             imei2,
  6952.                             imei3,
  6953.                             imei4
  6954.                             from product_by_code
  6955.                             where ( CONVERT(sales_code,char)  like '%" $queryStr "%'
  6956.                                     or  CONVERT(serial_no,char)  like '%" $queryStr "%'
  6957.                                     or  CONVERT(imei1,char)  like '%" $queryStr "%'
  6958.                                     or  CONVERT(imei2,char)  like '%" $queryStr "%'
  6959.                                     or  CONVERT(imei3,char)  like '%" $queryStr "%'
  6960.                                     or  CONVERT(imei4,char)  like '%" $queryStr "%'
  6961.                                     ) ";
  6962.         if ($request->query->has('warehouseId'))
  6963.             $get_kids_sql .= " and warehouse_id=" $request->query->get('warehouseId') . " ";
  6964.         if ($request->query->has('position'))
  6965.             $get_kids_sql .= " and position=" $request->query->get('position') . " ";
  6966.         if ($request->query->has('deliveryReceiptId'))
  6967.             $get_kids_sql .= " and deliveryReceiptId=" $request->query->get('deliveryReceiptId') . " ";
  6968.         if ($request->query->has('warehouseActionId'))
  6969.             $get_kids_sql .= " and warehouse_action_id=" $request->query->get('warehouseActionId') . " ";
  6970.         if ($request->query->has('productId'))
  6971.             $get_kids_sql .= " and product_id=" $request->query->get('productId') . " ";
  6972.         $get_kids_sql .= " and company_id=" $companyId " limit 25";
  6973.         $stmt $em->getConnection()->prepare($get_kids_sql);
  6974.         $stmt->execute();
  6975.         $get_kids $stmt->fetchAll();
  6976.         if (!empty($get_kids)) {
  6977.             foreach ($get_kids as $d) {
  6978.                 $dt = array(
  6979.                     'id' => $d['id'],
  6980.                     'productId' => $d['product_id'],
  6981.                     'warehouseId' => $d['warehouse_id'],
  6982.                     'warehouseActionId' => $d['warehouse_action_id'],
  6983. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  6984.                     'sales_code' => str_pad($d['sales_code'], 13'0'STR_PAD_LEFT),
  6985.                     'serial_no' => str_pad($d['serial_no'], 13'0'STR_PAD_LEFT),
  6986.                     'imei1' => str_pad($d['imei1'], 13'0'STR_PAD_LEFT),
  6987.                     'imei2' => str_pad($d['imei2'], 13'0'STR_PAD_LEFT),
  6988.                     'imei3' => str_pad($d['imei3'], 13'0'STR_PAD_LEFT),
  6989.                     'imei4' => str_pad($d['imei4'], 13'0'STR_PAD_LEFT),
  6990. //                'sales_code'=>$d['sales_code'],
  6991.                 );
  6992.                 $data[] = $dt;
  6993.             }
  6994.         }
  6995. //        if($request->query->has('returnJson'))
  6996.         {
  6997.             return new JsonResponse(
  6998.                 array(
  6999.                     'success' => true,
  7000. //                    'page_title' => 'Product Details',
  7001. //                    'company_data' => $company_data,
  7002.                     'data' => $data,
  7003. //                    'exId'=>$id,
  7004. //                'productByCodeData' => $productByCodeData,
  7005. //                'productData' => $productData,
  7006. //                'currInvList' => $currInvList,
  7007. //                'productList' => Inventory::ProductList($em, $companyId),
  7008. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  7009. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  7010. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  7011. //                'unitList' => Inventory::UnitTypeList($em),
  7012. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  7013. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  7014. //                'warehouseList' => Inventory::WarehouseList($em),
  7015.                 )
  7016.             );
  7017.         }
  7018.     }
  7019.     public function selectDataAjaxAction(Request $request$queryStr '',
  7020.                                                  $version 'latest',
  7021.                                                  $identifier '_default_',
  7022.                                                  $apiKey '_ignore_'
  7023.     )
  7024.     {
  7025.         $em $this->getDoctrine()->getManager();
  7026.         $em_goc $this->getDoctrine()->getManager('company_group');
  7027.         $companyId 0;
  7028.         $skipCurrentUserIdRestriction $request->get('skipCurrentUserIdRestriction'0);
  7029.         $dataOnly $request->get('dataOnly'0);
  7030.         $skipCurrentEmployeeIdRestriction $request->get('skipCurrentEmployeeIdRestriction'0);
  7031.         $skipCurrentUserLoginIdRestriction $request->get('skipCurrentUserLoginIdRestriction'0);
  7032.         $currentUserId $request->getSession()->get(UserConstants::USER_ID0);
  7033.         $currentEmployeeId $request->getSession()->get(UserConstants::USER_EMPLOYEE_ID0);
  7034.         $currentUserLoginIds = [];
  7035.         if ($request->request->get('entity_group'0)) {
  7036.             $companyId 0;
  7037.             $em $this->getDoctrine()->getManager('company_group');
  7038.         } else {
  7039.             if ($request->request->get('appId'0) != 0) {
  7040.                 $gocEnabled 0;
  7041.                 if ($this->container->hasParameter('entity_group_enabled'))
  7042.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7043.                 else
  7044.                     $gocEnabled 1;
  7045.                 if ($gocEnabled == 1) {
  7046.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7047.                         $this->getDoctrine()->getManager('company_group'),
  7048.                         $gocEnabled,
  7049.                         $request->request->get('appId'0)
  7050.                     );
  7051.                     if (!empty($dataToConnect)) {
  7052.                         $connector $this->container->get('application_connector');
  7053.                         $connector->resetConnection(
  7054.                             'default',
  7055.                             $dataToConnect['dbName'],
  7056.                             $dataToConnect['dbUser'],
  7057.                             $dataToConnect['dbPass'],
  7058.                             $dataToConnect['dbHost'],
  7059.                             $reset true
  7060.                         );
  7061.                         $em $this->getDoctrine()->getManager();
  7062.                     }
  7063.                 }
  7064.             } else if ($request->getSession()->get(UserConstants::USER_APP_ID) != && $request->getSession()->get(UserConstants::USER_APP_ID) != null) {
  7065.                 $gocEnabled 0;
  7066.                 if ($this->container->hasParameter('entity_group_enabled'))
  7067.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7068.                 else
  7069.                     $gocEnabled 1;
  7070.                 if ($gocEnabled == 1) {
  7071.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7072.                         $this->getDoctrine()->getManager('company_group'),
  7073.                         $gocEnabled,
  7074.                         $request->getSession()->get(UserConstants::USER_APP_ID)
  7075.                     );
  7076.                     if (!empty($dataToConnect)) {
  7077.                         $connector $this->container->get('application_connector');
  7078.                         $connector->resetConnection(
  7079.                             'default',
  7080.                             $dataToConnect['dbName'],
  7081.                             $dataToConnect['dbUser'],
  7082.                             $dataToConnect['dbPass'],
  7083.                             $dataToConnect['dbHost'],
  7084.                             $reset true
  7085.                         );
  7086.                         $em $this->getDoctrine()->getManager();
  7087.                     }
  7088.                 }
  7089.             }
  7090.             $companyId $this->getLoggedUserCompanyId($request);
  7091.         }
  7092.         $configData = [];
  7093.         $isSingleDataset 1;
  7094.         $dataSet $request->request->has('dataset') ? $request->request->get('dataset') : [];
  7095.         if (is_string($dataSet)) $dataSet json_decode($dataSettrue);
  7096.         $valuePairs $request->get('valuePairs', []);
  7097.         if (is_string($valuePairs)) $valuePairs json_decode($valuePairstrue);
  7098.         $allResult = [];
  7099.         $datasetFromConfig = [];
  7100.         if ($identifier != '_default_') {
  7101.             $config_file $this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' $identifier 'Config.json';
  7102.             if (!file_exists($config_file)) {
  7103.             } else {
  7104.                 $fileText file_get_contents($config_file);
  7105.                 //now replace any value pairs
  7106.                 foreach ($valuePairs as $kkeeyy => $vvaalluuee) {
  7107.                     if (is_array($vvaalluuee)) {
  7108.                         if (isset($vvaalluuee['value']) && isset($vvaalluuee['type'])) {
  7109.                             if ($vvaalluuee['type'] == 'array'$fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee['value']), $fileText);
  7110.                             if ($vvaalluuee['type'] == 'value'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7111.                             if ($vvaalluuee['type'] == 'text'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7112.                         } else {
  7113.                             $fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee), $fileText);
  7114.                         }
  7115.                     }
  7116.                     $fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee$fileText);
  7117.                 }
  7118.                 $fileText str_ireplace('_query_'$request->get('query'$queryStr), $fileText);
  7119.                 $fileText str_ireplace('_itemLimit_'$request->get('itemLimit''_all_'), $fileText);
  7120.                 $fileText str_ireplace('_offset_'$request->get('offset', ($request->get('itemLimit'10))*($request->get('page'1)-1)), $fileText);
  7121.                 if (!(strpos($fileText'_CURRENT_USER_LOGIN_IDS_') === false) && $skipCurrentUserLoginIdRestriction == 0) {
  7122.                     $userInfo = [];
  7123.                     if ($request->getSession()->get(UserConstants::USER_TYPE0) == UserConstants::USER_TYPE_APPLICANT) {
  7124.                         $userInfo $em_goc->getRepository('CompanyGroupBundle:EntityLoginLog')->findBy(
  7125.                             array('userId' => $currentUserId)
  7126.                         );
  7127.                     } else {
  7128.                         $userInfo $em->getRepository('ApplicationBundle:SysLoginLog')->findBy(
  7129.                             array('userId' => $currentUserId)
  7130.                         );
  7131.                     }
  7132.                     foreach ($userInfo as $uLogininfo) {
  7133.                         $currentUserLoginIds[] = $uLogininfo->getLoginId();
  7134.                     }
  7135.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_'json_encode($currentUserLoginIds), $fileText);
  7136.                 } else {
  7137.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_''_EMPTY_'$fileText);
  7138.                 }
  7139.                 if (!(strpos($fileText'_CURRENT_USER_ID_') === false) && $skipCurrentUserIdRestriction == 0) {
  7140.                     $fileText str_ireplace('_CURRENT_USER_ID_'$currentUserId$fileText);
  7141.                 } else {
  7142.                     $fileText str_ireplace('_CURRENT_USER_ID_''_EMPTY_'$fileText);
  7143.                 }
  7144.                 if (!(strpos($fileText'_CURRENT_USER_EMPLOYEE_ID_') === false) && $skipCurrentEmployeeIdRestriction == 0) {
  7145.                     if ((strpos($fileText'skipCurrentEmployeeIdRestriction') === false)) {
  7146.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_'$currentEmployeeId$fileText);
  7147.                     } else {
  7148.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  7149.                     }
  7150.                 } else {
  7151.                     $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  7152.                 }
  7153.                 if ($fileText)
  7154.                     $datasetFromConfig json_decode($fileTexttrue);
  7155.                 $skipCurrentUserIdRestriction = isset($datasetFromConfig['skipCurrentUserIdRestriction']) ? $datasetFromConfig['skipCurrentUserIdRestriction'] : $skipCurrentUserIdRestriction;
  7156.                 $skipCurrentEmployeeIdRestriction = isset($datasetFromConfig['skipCurrentEmployeeIdRestriction']) ? $datasetFromConfig['skipCurrentEmployeeIdRestriction'] : $skipCurrentEmployeeIdRestriction;
  7157.                 $skipCurrentUserLoginIdRestriction = isset($datasetFromConfig['skipCurrentUserLoginIdRestriction']) ? $datasetFromConfig['skipCurrentUserLoginIdRestriction'] : $skipCurrentUserLoginIdRestriction;
  7158.             }
  7159.         }
  7160.         if ($dataSet == null$dataSet = [];
  7161. //        return new JsonResponse(array(
  7162. //            'queryStr'=>$queryStr
  7163. //        ));
  7164.         if (!empty($datasetFromConfig)) {
  7165.             if (isset($datasetFromConfig['tableName'])) {
  7166.                 $isSingleDataset 1;
  7167.                 $dataSet[] = $datasetFromConfig;
  7168.             } else {
  7169.                 if (count($datasetFromConfig) == 1)
  7170.                     $isSingleDataset 1;
  7171.                 $dataSet $datasetFromConfig;
  7172.             }
  7173.         }
  7174.         if (empty($dataSet)) {
  7175.             $isSingleDataset 1;
  7176.             $singleDataSet = array(
  7177.                 "valueField" => $request->request->has('valueField') ? $request->request->get('valueField') : 'id',
  7178.                 "query" => $request->get('query'$queryStr),
  7179.                 "headMarkers" => $request->get('headMarkers'''),
  7180.                 "headMarkersStrictMatch" => $request->get('headMarkersStrictMatch'0),
  7181.                 "itemLimit" => $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25,
  7182.                 "selectorId" => $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_',
  7183.                 "textField" => $request->request->has('textField') ? $request->request->get('textField') : 'name',
  7184.                 "tableName" => $request->request->has('tableName') ? $request->request->get('tableName') : '',
  7185.                 "isMultiple" => $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0,
  7186.                 "orConditions" => $request->request->has('orConditions') ? $request->request->get('orConditions') : [],
  7187.                 "andConditions" => $request->request->has('andConditions') ? $request->request->get('andConditions') : [],
  7188.                 "andOrConditions" => $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [],
  7189.                 "mustConditions" => $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [],
  7190.                 "joinTableData" => $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [],
  7191.                 "renderTextFormat" => $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '',
  7192.                 "setDataForSingle" => $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0,
  7193.                 "dataId" => $request->request->has('dataId') ? $request->request->get('dataId') : 0,
  7194.                 "lastChildrenOnly" => $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0,
  7195.                 "parentOnly" => $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0,
  7196.                 "parentIdField" => $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id',
  7197.                 "skipDefaultCompanyId" => $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1,
  7198.                 "offset" => $request->request->has('offset') ? $request->request->get('offset') : 0,
  7199.                 "returnTotalMatchedEntriesFlag" => $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0,
  7200.                 "nextOffset" => 0,
  7201.                 "totalMatchedEntries" => 0,
  7202.                 "convertToObject" => $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [],
  7203.                 "convertDateToStringFieldList" => $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [],
  7204.                 "orderByConditions" => $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [],
  7205.                 "convertToUrl" => $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [],
  7206.                 "fullPathList" => $request->request->has('fullPathList') ? $request->request->get('fullPathList') : [],
  7207.                 "ret_data" => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  7208.             );
  7209.             $dataSet[] = $singleDataSet;
  7210.         }
  7211. //        $lastResult = [
  7212. //            'identifier' => $identifier,
  7213. //            'dataSet' => $dataSet,
  7214. //        ];
  7215. //        return new JsonResponse($lastResult);
  7216.         $userId $request->getSession()->get(UserConstants::USER_ID);
  7217. //        public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [],$userId=0)
  7218.         foreach ($dataSet as $dsIndex => $dataConfig) {
  7219.             $companyId 0;
  7220.             $queryStringIndividual $queryStr;
  7221.             $data = [];
  7222.             $data_by_id = [];
  7223.             $setValueArray = [];
  7224.             $silentChangeSelectize 0;
  7225.             $setValue 0;
  7226.             $setValueType 0;// 0 for id , 1 for query
  7227.             $selectAll 0;
  7228.             if ($queryStringIndividual == '_EMPTY_')
  7229.                 $queryStringIndividual '';
  7230.             if (isset($dataConfig['query']))
  7231.                 $queryStringIndividual $dataConfig['query'];
  7232.             if ($queryStringIndividual == '_EMPTY_')
  7233.                 $queryStringIndividual '';
  7234.             $queryStringIndividual str_replace('_FSLASH_''/'$queryStringIndividual);
  7235.             if ($queryStringIndividual === '#setValue:') {
  7236.                 $queryStringIndividual '';
  7237.             }
  7238.             if (!(strpos($queryStringIndividual'_silent_change_') === false)) {
  7239.                 $silentChangeSelectize 1;
  7240.                 $queryStringIndividual str_ireplace('_silent_change_'''$queryStringIndividual);
  7241.             }
  7242.             if (!(strpos($queryStringIndividual'#setValue:') === false)) {
  7243.                 $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStringIndividual));
  7244.                 foreach ($setValueArrayBeforeFilter as $svf) {
  7245.                     if ($svf == '_ALL_') {
  7246.                         $selectAll 1;
  7247.                         $setValueArray = [];
  7248.                         continue;
  7249.                     }
  7250.                     if (is_numeric($svf)) {
  7251.                         $setValueArray[] = ($svf 1);
  7252.                         $setValue $svf 1;
  7253.                     }
  7254.                 }
  7255.                 $queryStringIndividual '';
  7256.             }
  7257.             $valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
  7258.             $headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''//Special Field
  7259.             $headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0//Special Field
  7260.             $itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
  7261.             $selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
  7262.             $textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
  7263.             $table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
  7264.             $isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
  7265.             $orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
  7266.             $andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
  7267.             $andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
  7268.             $mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
  7269.             $joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
  7270.             $renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
  7271.             $setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
  7272.             $dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
  7273.             $lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
  7274.             $parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
  7275.             $parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
  7276.             $skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
  7277.             $offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
  7278.             $returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
  7279.             $nextOffset 0;
  7280.             $totalMatchedEntries 0;
  7281.             $convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
  7282.             $convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
  7283.             $orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
  7284.             $convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
  7285.             $fullPathList = isset($dataConfig['fullPathList']) ? $dataConfig['fullPathList'] : [];
  7286.             if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  7287.             if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  7288.             if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  7289.             if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  7290.             if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  7291.             if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  7292.             if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  7293.             if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  7294.             if (is_string($fullPathList)) $fullPathList json_decode($fullPathListtrue);
  7295. //            return new JsonResponse(array(
  7296. //                'dataSet'=>$dataSet,
  7297. //                'dataConfig'=>$dataConfig,
  7298. //                'hi'=>$this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json',
  7299. //                'hiD'=>file_get_contents($this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json')
  7300. //            ));
  7301.             if ($table == '') {
  7302.                 $lastResult = array(
  7303.                     'success' => false,
  7304.                     'currentTs' => (new \Datetime())->format('U'),
  7305.                     'isMultiple' => $isMultiple,
  7306.                     'setValueArray' => $setValueArray,
  7307.                     'setValue' => $setValue,
  7308.                     'data' => $data,
  7309.                     'dataId' => $dataId,
  7310.                     'selectorId' => $selectorId,
  7311.                     'dataById' => $data_by_id,
  7312.                     'selectedId' => 0,
  7313.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  7314.                 );
  7315.             } else {
  7316.                 $restrictionData = array(
  7317. //            'table'=>'relevantField in restriction'
  7318.                     'warehouse_action' => 'warehouseActionIds',
  7319.                     'branch' => 'branchIds',
  7320.                     'warehouse' => 'warehouseIds',
  7321.                     'production_process_settings' => 'productionProcessIds',
  7322.                 );
  7323.                 $restrictionIdList = [];
  7324.                 $filterQryForCriteria "select ";
  7325.                 $selectQry "";
  7326. //        $selectQry=" `$table`.* ";
  7327.                 $selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
  7328.                 $selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
  7329.                 if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  7330.                 foreach ($selectFieldList as $selField) {
  7331.                     if ($selectQry != '')
  7332.                         $selectQry .= ", ";
  7333.                     if ($selField == '*')
  7334.                         $selectQry .= " `$table`.$selField ";
  7335.                     else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7336.                         if ($selectPrefix == '')
  7337.                             $selectQry .= " count(*)  ";
  7338.                         else
  7339.                             $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  7340.                     } else {
  7341.                         if ($selectPrefix == '')
  7342.                             $selectQry .= " `$table`.`$selField` ";
  7343.                         else
  7344.                             $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  7345.                     }
  7346.                 }
  7347.                 $joinQry " from $table ";
  7348. //        $filterQryForCriteria = "select * from $table ";
  7349.                 foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  7350. //            $conditionStr.=' 1=1 ';
  7351.                     $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  7352.                     $joinTableAlias $joinTableName '_' $joinIndex;
  7353.                     $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  7354.                     $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  7355.                     $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  7356.                     $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  7357.                     $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  7358.                     $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  7359.                     $joinMustConditions = isset($joinTableDatum['joinMustConditions']) ? $joinTableDatum['joinMustConditions'] : [];
  7360.                     $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  7361.                     $joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
  7362.                     $joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
  7363.                     if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  7364.                     if (is_string($joinMustConditions)) $joinMustConditions json_decode($joinMustConditionstrue);
  7365.                     if (is_string($joinAndOrConditions)) $joinAndOrConditions json_decode($joinAndOrConditionstrue);
  7366.                     if (is_string($joinOrConditions)) $joinOrConditions json_decode($joinOrConditionstrue);
  7367.                     foreach ($selectFieldList as $selField) {
  7368.                         if ($selField == '*')
  7369.                             $selectQry .= ", `$joinTableAlias`.$selField ";
  7370.                         else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7371.                             if ($selectPrefix == '')
  7372.                                 $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  7373.                             else
  7374.                                 $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  7375.                         } else {
  7376.                             if ($selectPrefix == '')
  7377.                                 $selectQry .= ", `$joinTableAlias`.`$selField`  ";
  7378.                             else
  7379.                                 $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  7380.                         }
  7381.                     }
  7382.                     $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  7383. //            if($joinTablePrimaryField!='')
  7384. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7385. //            $joinAndString = '';
  7386.                     $joinMustString '';
  7387.                     if ($joinTablePrimaryField != '')
  7388.                         $joinQry .= "  `$joinTableAlias`.`$joinTableOnField$fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7389.                     foreach ($joinMustConditions as $mustCondition) {
  7390. //            $conditionStr.=' 1=1 ';
  7391.                         $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  7392.                         $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  7393.                         $aliasInCondition $table;
  7394.                         if (!(strpos($cfield'.') === false)) {
  7395.                             $fullCfieldArray explode('.'$cfield);
  7396.                             $aliasInCondition $fullCfieldArray[0];
  7397.                             $cfield $fullCfieldArray[1];
  7398.                         }
  7399.                         $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  7400.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7401.                             if ($joinMustString != '')
  7402.                                 $joinMustString .= " and ";
  7403.                             if ($ctype == 'like') {
  7404.                                 $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7405.                                 $wordsBySpaces explode(' '$cvalue);
  7406.                                 foreach ($wordsBySpaces as $word) {
  7407.                                     if ($joinMustString != '')
  7408.                                         $joinMustString .= " and ";
  7409.                                     $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7410.                                 }
  7411.                             } else if ($ctype == 'not like') {
  7412.                                 $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7413.                                 $wordsBySpaces explode(' '$cvalue);
  7414.                                 foreach ($wordsBySpaces as $word) {
  7415.                                     if ($joinMustString != '')
  7416.                                         $joinMustString .= " and ";
  7417.                                     $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7418.                                 }
  7419.                             } else if ($ctype == 'not_in') {
  7420.                                 $joinMustString .= " ( ";
  7421.                                 if (in_array('null'$cvalue)) {
  7422.                                     $joinMustString .= " `$joinTableAlias`.$cfield is not null";
  7423.                                     $cvalue array_diff($cvalue, ['null']);
  7424.                                     if (!empty($cvalue))
  7425.                                         $joinMustString .= " and ";
  7426.                                 }
  7427.                                 if (in_array(''$cvalue)) {
  7428.                                     $joinMustString .= "`$joinTableAlias`.$cfield != '' ";
  7429.                                     $cvalue array_diff($cvalue, ['']);
  7430.                                     if (!empty($cvalue))
  7431.                                         $joinMustString .= " and ";
  7432.                                 }
  7433.                                 $joinMustString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7434.                             } else if ($ctype == 'in') {
  7435.                                 if (in_array('null'$cvalue)) {
  7436.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null";
  7437.                                     $cvalue array_diff($cvalue, ['null']);
  7438.                                     if (!empty($cvalue))
  7439.                                         $joinMustString .= " and ";
  7440.                                 }
  7441.                                 if (in_array(''$cvalue)) {
  7442.                                     $joinMustString .= "`$joinTableAlias`.$cfield = '' ";
  7443.                                     $cvalue array_diff($cvalue, ['']);
  7444.                                     if (!empty($cvalue))
  7445.                                         $joinMustString .= " and ";
  7446.                                 }
  7447.                                 $joinMustString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7448.                             } else if ($ctype == '=') {
  7449. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7450. //                            $fullCfieldArray = explode('.', $cfield);
  7451. //                            $aliasInCondition = $fullCfieldArray[0];
  7452. //                            $cfield = $fullCfieldArray[1];
  7453. //                        }
  7454.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7455.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null ";
  7456.                                 else
  7457.                                     $joinMustString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7458.                             } else if ($ctype == '!=') {
  7459.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7460.                                     $joinMustString .= "`$joinTableAlias`.$cfield is not null ";
  7461.                                 else
  7462.                                     $joinMustString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7463.                             } else {
  7464.                                 if (is_string($cvalue))
  7465.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7466.                                 else
  7467.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7468.                             }
  7469.                         }
  7470.                     }
  7471. //            if ($joinMustString != '') {
  7472. //                if ($conditionStr != '')
  7473. //                    $conditionStr .= (" and (" . $joinMustString . ") ");
  7474. //                else
  7475. //                    $conditionStr .= ("  (" . $joinMustString . ") ");
  7476. //            }
  7477.                     if ($joinMustString != '') {
  7478.                         $joinQry .= (' and ' $joinMustString);
  7479. //                        $joinQry.=' and (';
  7480.                     }
  7481.                     $mustBracketDone 0;
  7482.                     $joinAndString '';
  7483. //                    if ($joinTablePrimaryField != '')
  7484. //                        $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7485.                     foreach ($joinAndConditions as $andCondition) {
  7486. //            $conditionStr.=' 1=1 ';
  7487.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  7488.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  7489.                         $aliasInCondition $table;
  7490.                         if (!(strpos($cfield'.') === false)) {
  7491.                             $fullCfieldArray explode('.'$cfield);
  7492.                             $aliasInCondition $fullCfieldArray[0];
  7493.                             $cfield $fullCfieldArray[1];
  7494.                         }
  7495.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  7496.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7497.                             if ($joinAndString != '')
  7498.                                 $joinAndString .= " and ";
  7499.                             if ($ctype == 'like') {
  7500.                                 $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7501.                                 $wordsBySpaces explode(' '$cvalue);
  7502.                                 foreach ($wordsBySpaces as $word) {
  7503.                                     if ($joinAndString != '')
  7504.                                         $joinAndString .= " and ";
  7505.                                     $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7506.                                 }
  7507.                             } else if ($ctype == 'not like') {
  7508.                                 $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7509.                                 $wordsBySpaces explode(' '$cvalue);
  7510.                                 foreach ($wordsBySpaces as $word) {
  7511.                                     if ($joinAndString != '')
  7512.                                         $joinAndString .= " and ";
  7513.                                     $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7514.                                 }
  7515.                             } else if ($ctype == 'not_in') {
  7516.                                 $joinAndString .= " ( ";
  7517.                                 if (in_array('null'$cvalue)) {
  7518.                                     $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  7519.                                     $cvalue array_diff($cvalue, ['null']);
  7520.                                     if (!empty($cvalue))
  7521.                                         $joinAndString .= " and ";
  7522.                                 }
  7523.                                 if (in_array(''$cvalue)) {
  7524.                                     $joinAndString .= "`$joinTableAlias`.$cfield != '' ";
  7525.                                     $cvalue array_diff($cvalue, ['']);
  7526.                                     if (!empty($cvalue))
  7527.                                         $joinAndString .= " and ";
  7528.                                 }
  7529.                                 $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7530.                             } else if ($ctype == 'in') {
  7531.                                 if (in_array('null'$cvalue)) {
  7532.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null";
  7533.                                     $cvalue array_diff($cvalue, ['null']);
  7534.                                     if (!empty($cvalue))
  7535.                                         $joinAndString .= " and ";
  7536.                                 }
  7537.                                 if (in_array(''$cvalue)) {
  7538.                                     $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  7539.                                     $cvalue array_diff($cvalue, ['']);
  7540.                                     if (!empty($cvalue))
  7541.                                         $joinAndString .= " and ";
  7542.                                 }
  7543.                                 $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7544.                             } else if ($ctype == '=') {
  7545. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7546. //                            $fullCfieldArray = explode('.', $cfield);
  7547. //                            $aliasInCondition = $fullCfieldArray[0];
  7548. //                            $cfield = $fullCfieldArray[1];
  7549. //                        }
  7550.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7551.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  7552.                                 else
  7553.                                     $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7554.                             } else if ($ctype == '!=') {
  7555.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7556.                                     $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  7557.                                 else
  7558.                                     $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7559.                             } else {
  7560.                                 if (is_string($cvalue))
  7561.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7562.                                 else
  7563.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7564.                             }
  7565.                         }
  7566.                     }
  7567. //            if ($joinAndString != '') {
  7568. //                if ($conditionStr != '')
  7569. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  7570. //                else
  7571. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  7572. //            }
  7573.                     if ($joinAndString != '') {
  7574.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7575.                             $joinQry .= ' and (';
  7576.                             $mustBracketDone 1;
  7577.                         }
  7578.                         if ($joinQry != '')
  7579.                             $joinQry .= (" and (" $joinAndString ") ");
  7580.                         else
  7581.                             $joinQry .= ("  (" $joinAndString ") ");
  7582.                     }
  7583.                     $joinAndOrString "";
  7584.                     foreach ($joinAndOrConditions as $andOrCondition) {
  7585. //            $conditionStr.=' 1=1 ';
  7586.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  7587.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  7588.                         $aliasInCondition $table;
  7589.                         if (!(strpos($cfield'.') === false)) {
  7590.                             $fullCfieldArray explode('.'$cfield);
  7591.                             $aliasInCondition $fullCfieldArray[0];
  7592.                             $cfield $fullCfieldArray[1];
  7593.                         }
  7594.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  7595.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7596.                             if ($joinAndOrString != '')
  7597.                                 $joinAndOrString .= " or ";
  7598.                             if ($ctype == 'like') {
  7599.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7600.                                 $wordsBySpaces explode(' '$cvalue);
  7601.                                 foreach ($wordsBySpaces as $word) {
  7602.                                     if ($joinAndOrString != '')
  7603.                                         $joinAndOrString .= " or ";
  7604.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7605.                                 }
  7606.                             } else if ($ctype == 'not like') {
  7607.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7608.                                 $wordsBySpaces explode(' '$cvalue);
  7609.                                 foreach ($wordsBySpaces as $word) {
  7610.                                     if ($joinAndOrString != '')
  7611.                                         $joinAndOrString .= " or ";
  7612.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7613.                                 }
  7614.                             } else if ($ctype == 'not_in') {
  7615.                                 $joinAndOrString .= " ( ";
  7616.                                 if (in_array('null'$cvalue)) {
  7617.                                     $joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
  7618.                                     $cvalue array_diff($cvalue, ['null']);
  7619.                                     if (!empty($cvalue))
  7620.                                         $joinAndOrString .= " or ";
  7621.                                 }
  7622.                                 if (in_array(''$cvalue)) {
  7623.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != '' ";
  7624.                                     $cvalue array_diff($cvalue, ['']);
  7625.                                     if (!empty($cvalue))
  7626.                                         $joinAndOrString .= " or ";
  7627.                                 }
  7628.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7629.                             } else if ($ctype == 'in') {
  7630.                                 if (in_array('null'$cvalue)) {
  7631.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null";
  7632.                                     $cvalue array_diff($cvalue, ['null']);
  7633.                                     if (!empty($cvalue))
  7634.                                         $joinAndOrString .= " or ";
  7635.                                 }
  7636.                                 if (in_array(''$cvalue)) {
  7637.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  7638.                                     $cvalue array_diff($cvalue, ['']);
  7639.                                     if (!empty($cvalue))
  7640.                                         $joinAndOrString .= " or ";
  7641.                                 }
  7642.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7643.                             } else if ($ctype == '=') {
  7644. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7645. //                            $fullCfieldArray = explode('.', $cfield);
  7646. //                            $aliasInCondition = $fullCfieldArray[0];
  7647. //                            $cfield = $fullCfieldArray[1];
  7648. //                        }
  7649.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7650.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
  7651.                                 else
  7652.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7653.                             } else if ($ctype == '!=') {
  7654.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7655.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
  7656.                                 else
  7657.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7658.                             } else {
  7659.                                 if (is_string($cvalue))
  7660.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7661.                                 else
  7662.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7663.                             }
  7664.                         }
  7665.                     }
  7666. //            if ($joinAndOrString != '')
  7667. //                $joinQry .= $joinAndOrString;
  7668.                     if ($joinAndOrString != '') {
  7669.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7670.                             $joinQry .= ' and (';
  7671.                             $mustBracketDone 1;
  7672.                         }
  7673.                         if ($joinQry != '')
  7674.                             $joinQry .= (" and (" $joinAndOrString ") ");
  7675.                         else
  7676.                             $joinQry .= ("  (" $joinAndOrString ") ");
  7677.                     }
  7678.                     //pika
  7679.                     $joinOrString "";
  7680.                     foreach ($joinOrConditions as $orCondition) {
  7681. //            $conditionStr.=' 1=1 ';
  7682.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  7683.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  7684.                         $aliasInCondition $table;
  7685.                         if (!(strpos($cfield'.') === false)) {
  7686.                             $fullCfieldArray explode('.'$cfield);
  7687.                             $aliasInCondition $fullCfieldArray[0];
  7688.                             $cfield $fullCfieldArray[1];
  7689.                         }
  7690.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  7691.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7692.                             if ($joinOrString != '' || $joinAndString != '' || $joinMustString != '')
  7693.                                 $joinOrString .= " or ";
  7694.                             if ($ctype == 'like') {
  7695.                                 $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7696.                                 $wordsBySpaces explode(' '$cvalue);
  7697.                                 foreach ($wordsBySpaces as $word) {
  7698.                                     if ($joinOrString != '')
  7699.                                         $joinOrString .= " or ";
  7700.                                     $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7701.                                 }
  7702.                             } else if ($ctype == 'not like') {
  7703.                                 $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7704.                                 $wordsBySpaces explode(' '$cvalue);
  7705.                                 foreach ($wordsBySpaces as $word) {
  7706.                                     if ($joinOrString != '')
  7707.                                         $joinOrString .= " or ";
  7708.                                     $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7709.                                 }
  7710.                             } else if ($ctype == 'not_in') {
  7711.                                 $joinOrString .= " ( ";
  7712.                                 if (in_array('null'$cvalue)) {
  7713.                                     $joinOrString .= " `$joinTableAlias`.$cfield is not null";
  7714.                                     $cvalue array_diff($cvalue, ['null']);
  7715.                                     if (!empty($cvalue))
  7716.                                         $joinOrString .= " or ";
  7717.                                 }
  7718.                                 if (in_array(''$cvalue)) {
  7719.                                     $joinOrString .= "`$joinTableAlias`.$cfield != '' ";
  7720.                                     $cvalue array_diff($cvalue, ['']);
  7721.                                     if (!empty($cvalue))
  7722.                                         $joinOrString .= " or ";
  7723.                                 }
  7724.                                 $joinOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7725.                             } else if ($ctype == 'in') {
  7726.                                 if (in_array('null'$cvalue)) {
  7727.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null";
  7728.                                     $cvalue array_diff($cvalue, ['null']);
  7729.                                     if (!empty($cvalue))
  7730.                                         $joinOrString .= " or ";
  7731.                                 }
  7732.                                 if (in_array(''$cvalue)) {
  7733.                                     $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  7734.                                     $cvalue array_diff($cvalue, ['']);
  7735.                                     if (!empty($cvalue))
  7736.                                         $joinOrString .= " or ";
  7737.                                 }
  7738.                                 $joinOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7739.                             } else if ($ctype == '=') {
  7740. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7741. //                            $fullCfieldArray = explode('.', $cfield);
  7742. //                            $aliasInCondition = $fullCfieldArray[0];
  7743. //                            $cfield = $fullCfieldArray[1];
  7744. //                        }
  7745.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7746.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null ";
  7747.                                 else
  7748.                                     $joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7749.                             } else if ($ctype == '!=') {
  7750.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7751.                                     $joinOrString .= "`$joinTableAlias`.$cfield is not null ";
  7752.                                 else
  7753.                                     $joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7754.                             } else {
  7755.                                 if (is_string($cvalue))
  7756.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7757.                                 else
  7758.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7759.                             }
  7760.                         }
  7761.                     }
  7762. //            if ($joinOrString != '')
  7763. //                $joinQry .= $joinOrString;
  7764.                     if ($joinOrString != '') {
  7765.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7766.                             $joinQry .= ' and (';
  7767.                             $mustBracketDone 1;
  7768.                         }
  7769.                         if ($joinQry != '')
  7770.                             $joinQry .= (" or (" $joinOrString ") ");
  7771.                         else
  7772.                             $joinQry .= ("  (" $joinOrString ") ");
  7773.                     }
  7774.                     if ($joinMustString != '' && $mustBracketDone == 1) {
  7775.                         $joinQry .= ' ) ';
  7776.                     }
  7777. //
  7778. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7779.                 }
  7780.                 $filterQryForCriteria .= $selectQry;
  7781.                 $filterQryForCriteria .= $joinQry;
  7782.                 if ($skipDefaultCompanyId == && $companyId != && !isset($dataConfig['entity_group']))
  7783.                     $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  7784.                 else
  7785.                     $filterQryForCriteria .= " where 1=1 ";
  7786.                 $conditionStr "";
  7787.                 $aliasInCondition $table;
  7788.                 if ($headMarkers != '' && $table == 'acc_accounts_head') {
  7789.                     $markerList explode(','$headMarkers);
  7790.                     $spMarkerQry "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
  7791.                     $markerPassedHeads = [];
  7792.                     foreach ($markerList as $mrkr) {
  7793.                         $spMarkerQry .= " and marker_hash like '%" $mrkr "%'";
  7794.                     }
  7795.                     $spStmt $em->getConnection()->prepare($spMarkerQry);
  7796.                     $spStmt->execute();
  7797.                     $spStmtResults $spStmt->fetchAll();
  7798.                     foreach ($spStmtResults as $ggres) {
  7799.                         $markerPassedHeads[] = $ggres['accounts_head_id'];
  7800.                     }
  7801.                     if (!empty($markerPassedHeads)) {
  7802.                         if ($conditionStr != '')
  7803.                             $conditionStr .= " and (";
  7804.                         else
  7805.                             $conditionStr .= " (";
  7806.                         if ($headMarkersStrictMatch != 1) {
  7807.                             foreach ($markerPassedHeads as $mh) {
  7808.                                 $conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" $mh "/%' or ";
  7809.                             }
  7810.                         }
  7811.                         $conditionStr .= "  `$aliasInCondition`.`accounts_head_id` in (" implode(','$markerPassedHeads) . ") ";
  7812.                         $conditionStr .= " )";
  7813.                     }
  7814.                 }
  7815.                 if (isset($restrictionData[$table])) {
  7816.                     $userRestrictionData Users::getUserApplicationAccessSettings($em$userId)['options'];
  7817.                     if (isset($userRestrictionData[$restrictionData[$table]])) {
  7818.                         $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  7819.                         if ($restrictionIdList == null)
  7820.                             $restrictionIdList = [];
  7821.                     }
  7822.                     if (!empty($restrictionIdList)) {
  7823.                         if ($conditionStr != '')
  7824.                             $conditionStr .= " and ";
  7825.                         $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  7826.                     }
  7827.                 }
  7828. //        $aliasInCondition = $table;
  7829.                 if (!empty($setValueArray) || $selectAll == 1) {
  7830.                     if (!empty($setValueArray)) {
  7831.                         if ($conditionStr != '')
  7832.                             $conditionStr .= " and ";
  7833.                         $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  7834.                     }
  7835.                 } else {
  7836.                     $andString '';
  7837.                     foreach ($andConditions as $andCondition) {
  7838. //            $conditionStr.=' 1=1 ';
  7839.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  7840.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  7841.                         $aliasInCondition $table;
  7842.                         if (!(strpos($cfield'.') === false)) {
  7843.                             $fullCfieldArray explode('.'$cfield);
  7844.                             $aliasInCondition $fullCfieldArray[0];
  7845.                             $cfield $fullCfieldArray[1];
  7846.                         }
  7847.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  7848.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7849.                             if ($andString != '')
  7850.                                 $andString .= " and ";
  7851.                             if ($ctype == 'like') {
  7852.                                 $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7853.                                 $wordsBySpaces explode(' '$cvalue);
  7854.                                 foreach ($wordsBySpaces as $word) {
  7855.                                     if ($andString != '')
  7856.                                         $andString .= " and ";
  7857.                                     $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7858.                                 }
  7859.                             } else if ($ctype == 'not like') {
  7860.                                 $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7861.                                 $wordsBySpaces explode(' '$cvalue);
  7862.                                 foreach ($wordsBySpaces as $word) {
  7863.                                     if ($andString != '')
  7864.                                         $andString .= " and ";
  7865.                                     $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7866.                                 }
  7867.                             } else if ($ctype == 'not_in') {
  7868.                                 $andString .= " ( ";
  7869.                                 if (in_array('null'$cvalue)) {
  7870.                                     $andString .= " `$aliasInCondition`.$cfield is not null";
  7871.                                     $cvalue array_diff($cvalue, ['null']);
  7872.                                     if (!empty($cvalue))
  7873.                                         $andString .= " and ";
  7874.                                 }
  7875.                                 if (in_array(''$cvalue)) {
  7876.                                     $andString .= "`$aliasInCondition`.$cfield != '' ";
  7877.                                     $cvalue array_diff($cvalue, ['']);
  7878.                                     if (!empty($cvalue))
  7879.                                         $andString .= " and ";
  7880.                                 }
  7881.                                 $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7882.                             } else if ($ctype == 'in') {
  7883.                                 if (in_array('null'$cvalue)) {
  7884.                                     $andString .= "`$aliasInCondition`.$cfield is null";
  7885.                                     $cvalue array_diff($cvalue, ['null']);
  7886.                                     if (!empty($cvalue))
  7887.                                         $andString .= " and ";
  7888.                                 }
  7889.                                 if (in_array(''$cvalue)) {
  7890.                                     $andString .= "`$aliasInCondition`.$cfield = '' ";
  7891.                                     $cvalue array_diff($cvalue, ['']);
  7892.                                     if (!empty($cvalue))
  7893.                                         $andString .= " and ";
  7894.                                 }
  7895.                                 $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  7896.                             } else if ($ctype == '=') {
  7897.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7898.                                     $andString .= "`$aliasInCondition`.$cfield is null ";
  7899.                                 else
  7900.                                     $andString .= "`$aliasInCondition`.$cfield = $cvalue ";
  7901.                             } else if ($ctype == '!=') {
  7902.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7903.                                     $andString .= "`$aliasInCondition`.$cfield is not null ";
  7904.                                 else
  7905.                                     $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  7906.                             } else {
  7907.                                 if (is_string($cvalue))
  7908.                                     $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  7909.                                 else
  7910.                                     $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  7911.                             }
  7912.                         }
  7913.                     }
  7914.                     if ($andString != '') {
  7915.                         if ($conditionStr != '')
  7916.                             $conditionStr .= (" and (" $andString ") ");
  7917.                         else
  7918.                             $conditionStr .= ("  (" $andString ") ");
  7919.                     }
  7920.                     $orString '';
  7921.                     foreach ($orConditions as $orCondition) {
  7922.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  7923.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  7924.                         $aliasInCondition $table;
  7925.                         if (!(strpos($cfield'.') === false)) {
  7926.                             $fullCfieldArray explode('.'$cfield);
  7927.                             $aliasInCondition $fullCfieldArray[0];
  7928.                             $cfield $fullCfieldArray[1];
  7929.                         }
  7930.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  7931.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7932.                             if ($orString != '')
  7933.                                 $orString .= " or ";
  7934.                             if ($ctype == 'like') {
  7935.                                 $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7936.                                 $wordsBySpaces explode(' '$cvalue);
  7937.                                 foreach ($wordsBySpaces as $word) {
  7938.                                     if ($orString != '')
  7939.                                         $orString .= " or ";
  7940.                                     $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7941.                                 }
  7942.                             } else if ($ctype == 'not like') {
  7943.                                 $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7944.                                 $wordsBySpaces explode(' '$cvalue);
  7945.                                 foreach ($wordsBySpaces as $word) {
  7946.                                     if ($orString != '')
  7947.                                         $orString .= " or ";
  7948.                                     $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7949.                                 }
  7950.                             } else if ($ctype == 'not_in') {
  7951.                                 $orString .= " ( ";
  7952.                                 if (in_array('null'$cvalue)) {
  7953.                                     $orString .= " `$aliasInCondition`.$cfield is not null";
  7954.                                     $cvalue array_diff($cvalue, ['null']);
  7955.                                     if (!empty($cvalue))
  7956.                                         $orString .= " or ";
  7957.                                 }
  7958.                                 if (in_array(''$cvalue)) {
  7959.                                     $orString .= "`$aliasInCondition`.$cfield != '' ";
  7960.                                     $cvalue array_diff($cvalue, ['']);
  7961.                                     if (!empty($cvalue))
  7962.                                         $orString .= " or ";
  7963.                                 }
  7964.                                 $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7965.                             } else if ($ctype == 'in') {
  7966.                                 $orString .= " ( ";
  7967.                                 if (in_array('null'$cvalue)) {
  7968.                                     $orString .= " `$aliasInCondition`.$cfield is null";
  7969.                                     $cvalue array_diff($cvalue, ['null']);
  7970.                                     if (!empty($cvalue))
  7971.                                         $orString .= " or ";
  7972.                                 }
  7973.                                 if (in_array(''$cvalue)) {
  7974.                                     $orString .= "`$aliasInCondition`.$cfield = '' ";
  7975.                                     $cvalue array_diff($cvalue, ['']);
  7976.                                     if (!empty($cvalue))
  7977.                                         $orString .= " or ";
  7978.                                 }
  7979.                                 $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  7980.                             } else if ($ctype == '=') {
  7981.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7982.                                     $orString .= "`$aliasInCondition`.$cfield is null ";
  7983.                                 else
  7984.                                     $orString .= "`$aliasInCondition`.$cfield = $cvalue ";
  7985.                             } else if ($ctype == '!=') {
  7986.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7987.                                     $orString .= "`$aliasInCondition`.$cfield is not null ";
  7988.                                 else
  7989.                                     $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  7990.                             } else {
  7991.                                 if (is_string($cvalue))
  7992.                                     $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  7993.                                 else
  7994.                                     $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  7995.                             }
  7996.                         }
  7997.                     }
  7998.                     if ($orString != '') {
  7999.                         if ($conditionStr != '')
  8000.                             $conditionStr .= (" or (" $orString ") ");
  8001.                         else
  8002.                             $conditionStr .= ("  (" $orString ") ");
  8003.                     }
  8004.                     $andOrString '';
  8005.                     foreach ($andOrConditions as $andOrCondition) {
  8006.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  8007.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  8008.                         $aliasInCondition $table;
  8009.                         if (!(strpos($cfield'.') === false)) {
  8010.                             $fullCfieldArray explode('.'$cfield);
  8011.                             $aliasInCondition $fullCfieldArray[0];
  8012.                             $cfield $fullCfieldArray[1];
  8013.                         }
  8014.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  8015.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8016.                             if ($andOrString != '')
  8017.                                 $andOrString .= " or ";
  8018.                             if ($ctype == 'like') {
  8019.                                 $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8020.                                 $wordsBySpaces explode(' '$cvalue);
  8021.                                 foreach ($wordsBySpaces as $word) {
  8022.                                     if ($andOrString != '')
  8023.                                         $andOrString .= " or ";
  8024.                                     $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8025.                                 }
  8026.                             } else if ($ctype == 'not like') {
  8027.                                 $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8028.                                 $wordsBySpaces explode(' '$cvalue);
  8029.                                 foreach ($wordsBySpaces as $word) {
  8030.                                     if ($andOrString != '')
  8031.                                         $andOrString .= " or ";
  8032.                                     $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8033.                                 }
  8034.                             } else if ($ctype == 'in') {
  8035.                                 $andOrString .= " ( ";
  8036.                                 if (in_array('null'$cvalue)) {
  8037.                                     $andOrString .= " `$aliasInCondition`.$cfield is null";
  8038.                                     $cvalue array_diff($cvalue, ['null']);
  8039.                                     if (!empty($cvalue))
  8040.                                         $andOrString .= " or ";
  8041.                                 }
  8042.                                 if (in_array(''$cvalue)) {
  8043.                                     $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  8044.                                     $cvalue array_diff($cvalue, ['']);
  8045.                                     if (!empty($cvalue))
  8046.                                         $andOrString .= " or ";
  8047.                                 }
  8048.                                 if (!empty($cvalue))
  8049.                                     $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8050.                                 else
  8051.                                     $andOrString .= "  ) ";
  8052.                             } else if ($ctype == 'not_in') {
  8053.                                 $andOrString .= " ( ";
  8054.                                 if (in_array('null'$cvalue)) {
  8055.                                     $andOrString .= " `$aliasInCondition`.$cfield is not null";
  8056.                                     $cvalue array_diff($cvalue, ['null']);
  8057.                                     if (!empty($cvalue))
  8058.                                         $andOrString .= " or ";
  8059.                                 }
  8060.                                 if (in_array(''$cvalue)) {
  8061.                                     $andOrString .= "`$aliasInCondition`.$cfield != '' ";
  8062.                                     $cvalue array_diff($cvalue, ['']);
  8063.                                     if (!empty($cvalue))
  8064.                                         $andOrString .= " or ";
  8065.                                 }
  8066.                                 if (!empty($cvalue))
  8067.                                     $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8068.                                 else
  8069.                                     $andOrString .= "  ) ";
  8070.                             } else if ($ctype == '=') {
  8071.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8072.                                     $andOrString .= "`$aliasInCondition`.$cfield is null ";
  8073.                                 else
  8074.                                     $andOrString .= "`$aliasInCondition`.$cfield = $cvalue ";
  8075.                             } else if ($ctype == '!=') {
  8076.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8077.                                     $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  8078.                                 else
  8079.                                     $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8080.                             } else {
  8081.                                 if (is_string($cvalue))
  8082.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8083.                                 else
  8084.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8085.                             }
  8086.                         }
  8087.                     }
  8088.                     if ($andOrString != '') {
  8089.                         if ($conditionStr != '')
  8090.                             $conditionStr .= (" and (" $andOrString ") ");
  8091.                         else
  8092.                             $conditionStr .= ("  (" $andOrString ") ");
  8093.                     }
  8094.                 }
  8095.                 $mustStr '';
  8096. ///now must conditions
  8097.                 foreach ($mustConditions as $mustCondition) {
  8098. //            $conditionStr.=' 1=1 ';
  8099.                     $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  8100.                     $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  8101.                     $aliasInCondition $table;
  8102.                     if (!(strpos($cfield'.') === false)) {
  8103.                         $fullCfieldArray explode('.'$cfield);
  8104.                         $aliasInCondition $fullCfieldArray[0];
  8105.                         $cfield $fullCfieldArray[1];
  8106.                     }
  8107.                     $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  8108.                     if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8109.                         if ($mustStr != '')
  8110.                             $mustStr .= " and ";
  8111.                         if ($ctype == 'like') {
  8112.                             $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8113.                             $wordsBySpaces explode(' '$cvalue);
  8114.                             foreach ($wordsBySpaces as $word) {
  8115.                                 if ($mustStr != '')
  8116.                                     $mustStr .= " or ";
  8117.                                 $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8118.                             }
  8119.                             $mustStr .= " )";
  8120.                         } else if ($ctype == 'not like') {
  8121.                             $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8122.                             $wordsBySpaces explode(' '$cvalue);
  8123.                             foreach ($wordsBySpaces as $word) {
  8124.                                 if ($mustStr != '')
  8125.                                     $mustStr .= " and ";
  8126.                                 $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8127.                             }
  8128.                         } else if ($ctype == 'in') {
  8129.                             $mustStr .= " ( ";
  8130.                             if (in_array('null'$cvalue)) {
  8131.                                 $mustStr .= " `$aliasInCondition`.$cfield is null";
  8132.                                 $cvalue array_diff($cvalue, ['null']);
  8133.                                 if (!empty($cvalue))
  8134.                                     $mustStr .= " or ";
  8135.                             }
  8136.                             if (in_array(''$cvalue)) {
  8137.                                 $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  8138.                                 $cvalue array_diff($cvalue, ['']);
  8139.                                 if (!empty($cvalue))
  8140.                                     $mustStr .= " or ";
  8141.                             }
  8142.                             $mustStr .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8143.                         } else if ($ctype == 'not_in') {
  8144.                             $mustStr .= " ( ";
  8145.                             if (in_array('null'$cvalue)) {
  8146.                                 $mustStr .= " `$aliasInCondition`.$cfield is not null";
  8147.                                 $cvalue array_diff($cvalue, ['null']);
  8148.                                 if (!empty($cvalue))
  8149.                                     $mustStr .= " and ";
  8150.                             }
  8151.                             if (in_array(''$cvalue)) {
  8152.                                 $mustStr .= "`$aliasInCondition`.$cfield != '' ";
  8153.                                 $cvalue array_diff($cvalue, ['']);
  8154.                                 if (!empty($cvalue))
  8155.                                     $mustStr .= " and ";
  8156.                             }
  8157.                             $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8158.                         } else if ($ctype == '=') {
  8159.                             if ($cvalue == 'null' || $cvalue == 'Null')
  8160.                                 $mustStr .= "`$aliasInCondition`.$cfield is null ";
  8161.                             else
  8162.                                 $mustStr .= "`$aliasInCondition`.$cfield = $cvalue ";
  8163.                         } else if ($ctype == '!=') {
  8164.                             if ($cvalue == 'null' || $cvalue == 'Null')
  8165.                                 $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  8166.                             else
  8167.                                 $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  8168.                         } else {
  8169.                             if (is_string($cvalue))
  8170.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8171.                             else
  8172.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8173.                         }
  8174.                     }
  8175.                 }
  8176.                 if ($mustStr != '') {
  8177.                     if ($conditionStr != '')
  8178.                         $conditionStr .= (" and (" $mustStr ") ");
  8179.                     else
  8180.                         $conditionStr .= ("  (" $mustStr ") ");
  8181.                 }
  8182.                 if ($conditionStr != '')
  8183.                     $filterQryForCriteria .= (" and (" $conditionStr ") ");
  8184.                 if ($lastChildrenOnly == 1) {
  8185.                     if ($filterQryForCriteria != '')
  8186.                         $filterQryForCriteria .= ' and';
  8187.                     $filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  8188.                 } else if ($parentOnly == 1) {
  8189.                     if ($filterQryForCriteria != '')
  8190.                         $filterQryForCriteria .= ' and';
  8191.                     $filterQryForCriteria .= "`$table`.`$valueField`  in ( select distinct $parentIdField from  $table)";
  8192.                 }
  8193.                 if (!empty($orderByConditions)) {
  8194.                     $filterQryForCriteria .= "  order by ";
  8195.                     $fone 1;
  8196.                     foreach ($orderByConditions as $orderByCondition) {
  8197.                         if ($fone != 1) {
  8198.                             $filterQryForCriteria .= " , ";
  8199.                         }
  8200.                         if (isset($orderByCondition['valueList'])) {
  8201.                             if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  8202.                             if ($orderByCondition['valueList'] == null)
  8203.                                 $orderByCondition['valueList'] = [];
  8204.                             $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  8205.                         } else
  8206.                             $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  8207.                         $fone 0;
  8208.                     }
  8209.                 }
  8210.                 if ($returnTotalMatchedEntriesFlag == 1) {
  8211. //            $stmt = $em->getConnection()->prepare($get_kids_sql);
  8212. //            $stmt->execute();
  8213. //            $get_kids = $stmt->fetchAll();
  8214.                 }
  8215.                 if ($filterQryForCriteria != '')
  8216.                     if (!empty($setValueArray) || $selectAll == 1) {
  8217.                     } else {
  8218.                         if ($itemLimit != '_ALL_')
  8219.                             $filterQryForCriteria .= "  limit $offset$itemLimit ";
  8220.                         else
  8221.                             $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  8222.                     }
  8223.                 $get_kids_sql $filterQryForCriteria;
  8224.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  8225.                 $stmt->execute();
  8226.                 $get_kids $stmt->fetchAll();
  8227.                 $selectedId 0;
  8228.                 if ($table == 'warehouse_action') {
  8229.                     if (empty($get_kids)) {
  8230.                         $get_kids_sql_2 "select * from warehouse_action";
  8231.                         $stmt $em->getConnection()->prepare($get_kids_sql_2);
  8232.                         $stmt->execute();
  8233.                         $get_kids2 $stmt->fetchAll();
  8234.                         if (empty($get_kids2))
  8235.                             $get_kids GeneralConstant::$warehouse_action_list;
  8236.                     }
  8237.                 }
  8238.                 if (!empty($get_kids)) {
  8239.                     $nextOffset $offset count($get_kids);
  8240.                     $nextOffset++;
  8241.                     foreach ($get_kids as $pa) {
  8242.                         if (!empty($setValueArray) && $selectAll == 0) {
  8243.                             if (!in_array($pa[$valueField], $setValueArray))
  8244.                                 continue;
  8245.                         }
  8246.                         if (!empty($restrictionIdList)) {
  8247.                             if (!in_array($pa[$valueField], $restrictionIdList))
  8248.                                 continue;
  8249.                         }
  8250.                         if ($selectAll == 1) {
  8251.                             $setValueArray[] = $pa[$valueField];
  8252.                             $setValue $pa[$valueField];
  8253.                         } else if (count($get_kids) == && $setDataForSingle == 1) {
  8254.                             $setValueArray[] = $pa[$valueField];
  8255.                             $setValue $pa[$valueField];
  8256.                         }
  8257.                         if ($valueField != '')
  8258.                             $pa['value'] = $pa[$valueField];
  8259.                         $renderedText $renderTextFormat;
  8260.                         $compare_array = [];
  8261.                         if ($renderTextFormat != '') {
  8262.                             $renderedText $renderTextFormat;
  8263.                             $compare_arrayFull = [];
  8264.                             $compare_array = [];
  8265.                             $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  8266.                             );
  8267.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  8268.                             if (isset($compare_arrayFull[0]))
  8269.                                 $compare_array $compare_arrayFull[0];
  8270. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  8271.                             foreach ($compare_array as $cmpdt) {
  8272.                                 $tbr str_replace("__"""$cmpdt);
  8273.                                 if ($tbr != '') {
  8274.                                     if (isset($pa[$tbr])) {
  8275.                                         if ($pa[$tbr] == null)
  8276.                                             $renderedText str_replace($cmpdt''$renderedText);
  8277.                                         else
  8278.                                             $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  8279.                                     } else {
  8280.                                         $renderedText str_replace($cmpdt''$renderedText);
  8281.                                     }
  8282.                                 }
  8283.                             }
  8284.                         }
  8285.                         $pa['rendered_text'] = $renderedText;
  8286.                         $pa['text'] = ($textField != '' $pa[$textField] : '');
  8287. //                $pa['compare_array'] = $compare_array;
  8288.                         foreach ($convertToObjectFieldList as $convField) {
  8289.                             if (isset($pa[$convField])) {
  8290.                                 $taA json_decode($pa[$convField], true);
  8291.                                 if ($taA == null$taA = [];
  8292.                                 $pa[$convField] = $taA;
  8293.                             } else {
  8294.                                 $pa[$convField] = [];
  8295.                             }
  8296.                         }
  8297.                         foreach ($convertDateToStringFieldList as $convField) {
  8298.                             if (is_array($convField)) {
  8299.                                 $fld $convField['field'];
  8300.                                 $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  8301.                             } else {
  8302.                                 $fld $convField;
  8303.                                 $frmt 'Y-m-d H:i:s';
  8304.                             }
  8305.                             if (isset($pa[$fld])) {
  8306.                                 $taA = new \DateTime($pa[$fld]);
  8307.                                 $pa[$fld] = $taA->format($frmt);
  8308.                             }
  8309.                         }
  8310.                         foreach ($convertToUrl as $convField) {
  8311. //
  8312. //                            $fld = $convField;
  8313. //
  8314. //
  8315. //                            if (isset($pa[$fld])) {
  8316. //
  8317. //
  8318. //                                $pa[$fld] =
  8319. //                                    $this->generateUrl(
  8320. //                                        'dashboard', [
  8321. //
  8322. //                                    ], UrlGenerator::ABSOLUTE_URL
  8323. //                                    ).'/'.$pa[$fld];
  8324. //
  8325. //                            }
  8326.                         }
  8327.                         foreach ($fullPathList as $pathField) {
  8328.                             $fld $pathField;
  8329.                             if (isset($pa[$fld])) {
  8330.                             if ($pa[$fld] !='' && $pa[$fld] !=null) {
  8331.                                 $pa[$fld]=($this->generateUrl(
  8332.                                     'dashboard', [
  8333.                                 ], UrlGenerator::ABSOLUTE_URL
  8334.                                 ).$pa[$fld]);
  8335.                             }
  8336.                             }
  8337.                         }
  8338.                         $pa['currentTs'] = (new \Datetime())->format('U');
  8339.                         $data[] = $pa;
  8340.                         if ($valueField != '') {
  8341.                             $data_by_id[$pa[$valueField]] = $pa;
  8342.                             $selectedId $pa[$valueField];
  8343.                         }
  8344.                     }
  8345.                 }
  8346.                 if ($dataOnly == 1)
  8347.                     $lastResult = array(
  8348.                         'success' => true,
  8349.                         'data' => $data,
  8350.                         'currentTs' => (new \Datetime())->format('U'),
  8351.                         'restrictionIdList' => $restrictionIdList,
  8352.                         'nextOffset' => $nextOffset,
  8353.                         'totalMatchedEntries' => $totalMatchedEntries,
  8354.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8355.                     );
  8356.                 else
  8357.                     $lastResult = array(
  8358.                     'success' => true,
  8359.                     'data' => $data,
  8360.                     'tableName' => $table,
  8361.                     'setValue' => $setValue,
  8362.                     'currentTs' => (new \Datetime())->format('U'),
  8363.                     'restrictionIdList' => $restrictionIdList,
  8364.                     'andConditions' => $andConditions,
  8365.                     'queryStr' => $queryStringIndividual,
  8366.                     'isMultiple' => $isMultiple,
  8367.                     'nextOffset' => $nextOffset,
  8368.                     'totalMatchedEntries' => $totalMatchedEntries,
  8369.                     'selectorId' => $selectorId,
  8370.                     'setValueArray' => $setValueArray,
  8371.                     'silentChangeSelectize' => $silentChangeSelectize,
  8372.                     'convertToObjectFieldList' => $convertToObjectFieldList,
  8373.                     'conditionStr' => $conditionStr,
  8374. //                    'andStr' => $andString,
  8375. //                    'andOrStr' => $andOrString,
  8376.                     'dataById' => $data_by_id,
  8377.                     'selectedId' => $selectedId,
  8378.                     'dataId' => $dataId,
  8379.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8380.                 );
  8381.             }
  8382.             $allResult[] = $lastResult;
  8383.         }
  8384.         if ($isSingleDataset == 1)
  8385.             return new JsonResponse($lastResult);
  8386.         else
  8387.             return new JsonResponse($allResult);
  8388.     }
  8389.     public function updatePlanningItemSequenceAction(Request $request$queryStr '')
  8390.     {
  8391.         $em $this->getDoctrine()->getManager();
  8392.         $stmt $em->getConnection()->prepare("select  `id` , parent_id, sequence from planning_item where sequence is null 
  8393.             ORDER BY parent_id ASC, id ASC
  8394.                         ");
  8395.         $stmt->execute();
  8396.         $query_output $stmt->fetchAll();
  8397.         foreach ($query_output as $dupe) {
  8398.             System::updatePlanningItemSequence($em$dupe["id"]);
  8399.         }
  8400.         System::updatePlanningItemSequence(
  8401.             $em,
  8402.             $request->request->get('planningItemId'0),
  8403.             $request->request->get('assignType''_ASSIGN_')   ///can be _MOVE_UP_ or _MOVE_DOWN_
  8404.         );
  8405. //        if($request->query->has('returnJson'))
  8406.         return new JsonResponse(
  8407.             array(
  8408.                 'success' => true,
  8409.                 'data' => [],
  8410.             )
  8411.         );
  8412.     }
  8413.     public function insertDataAjaxAction(Request $request$queryStr '')
  8414.     {
  8415.         $em $this->getDoctrine()->getManager();
  8416. //        if($request->query->has('big_data_test'))
  8417. //        {
  8418. //            for($t=0;$t<$request->request->get('big_data_test',10000);$t++) {
  8419. //                $em = $this->getDoctrine()->getManager('company_group');
  8420. //                $NOTIFICATION = new EntityNotification();
  8421. //                $NOTIFICATION->setAppId(1);
  8422. //                $NOTIFICATION->setCompanyId(0);
  8423. //                $NOTIFICATION->setCompanyId(0);
  8424. //                $NOTIFICATION->setBody('Test Description'.$t);
  8425. //                $NOTIFICATION->setTitle('Test Title'.$t);
  8426. //                $NOTIFICATION->setExpireTs(0);
  8427. //                $NOTIFICATION->setIsBuddybee(0);
  8428. //                $NOTIFICATION->setType(0);
  8429. //                $em->persist($NOTIFICATION);
  8430. //                $em->flush();
  8431. //            }
  8432. //
  8433. //            return new JsonResponse(
  8434. //                array(
  8435. //                    'success' => true,
  8436. //                    'data' => [],
  8437. //
  8438. //
  8439. //                )
  8440. //            );
  8441. //
  8442. //
  8443. //        }
  8444.         if ($request->request->get('entity_group'0)) {
  8445.             $companyId 0;
  8446.             $em $this->getDoctrine()->getManager('company_group');
  8447.         } else
  8448.             $companyId $this->getLoggedUserCompanyId($request);
  8449.         if ($companyId) {
  8450.             $company_data = [];
  8451. //            $company_data = Company::getCompanyData($em, $companyId);
  8452.         } else {
  8453.             $companyId 0;
  8454.             $company_data = [];
  8455.         }
  8456. //        $theEntity= new EntityNotification();
  8457. //        $entityName = 'EntityNotification';
  8458. //
  8459. //        $className='\\CompanyGroupBundle\\Entity\\'.$entityName;
  8460. //
  8461. //
  8462. //            $theEntity= new $className();
  8463.         $dataToAdd $request->request->has('dataToAdd') ? $request->request->get('dataToAdd') : [];
  8464.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8465.         if ($dataToAdd == null$dataToAdd = [];
  8466.         $dataToRemove $request->request->has('dataToRemove') ? $request->request->get('dataToRemove') : [];
  8467.         if (is_string($dataToRemove)) $dataToAdd json_decode($dataToRemovetrue);
  8468.         if ($dataToRemove == null$dataToRemove = [];
  8469.         $relData = [];
  8470.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8471.         $updatedDataList = [];
  8472.         foreach ($dataToAdd as $dataInd => $dat) {
  8473.             $entityName $dat['entityName'];
  8474.             $idField $dat['idField'];
  8475.             $findByField = isset($dat['findByField']) ? $dat['findByField'] : '';
  8476.             $findByValue = isset($dat['findByValue']) ? $dat['findByValue'] : '';
  8477.             $returnRefIndex $dat['returnRefIndex'];
  8478.             $findById $dat['findId'];
  8479.             $dataFields = isset($dat['dataFields']) ? $dat['dataFields'] : [];
  8480.             $noCreation = isset($dat['noCreation']) ? $dat['noCreation'] : 0;
  8481.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  8482.             $preAdditionalSql = isset($dat['preAdditionalSql']) ? $dat['preAdditionalSql'] : '';
  8483.             if ($preAdditionalSql != '') {
  8484. //            if ($entityName == 'PlanningItem') {
  8485. //
  8486. //                $stmt='select disctinct parent_id from planning_item;';
  8487. //                $stmt->execute();
  8488. //                $get_kids = $stmt->fetchAll();
  8489. //                $p_ids=[];
  8490. //                foreach($get_kids as $g)
  8491. //                {
  8492. //                    $p_ids[]=$g['parent_id'];
  8493. //                }
  8494. //
  8495. //
  8496. //
  8497.                 $stmt $em->getConnection()->prepare($preAdditionalSql);
  8498.                 $stmt->execute();
  8499.                 $stmt->closeCursor();
  8500. //
  8501. //
  8502.             }
  8503.             if ($entityName == 'PlanningItem') {
  8504.                 $stmt $em->getConnection()->prepare("select  `id` , parent_id, sequence from planning_item where sequence is null
  8505.             ORDER BY parent_id ASC, id ASC
  8506.                         ");
  8507.                 $stmt->execute();
  8508.                 $query_output $stmt->fetchAll();
  8509.                 foreach ($query_output as $dupe) {
  8510.                     System::updatePlanningItemSequence($em$dupe["id"]);
  8511.                 }
  8512.             }
  8513.             $className = ($request->request->get('entity_group'0) ? '\\CompanyGroupBundle\\Entity\\' '\\ApplicationBundle\\Entity\\') . $entityName;
  8514.             if (
  8515.                 ($findById == || $findById == '_NA_') && $findByField == '' && $noCreation == 0
  8516.             ) {
  8517.                 $theEntity = new $className();
  8518. //                $theEntity= new EntityNotification();
  8519.             } else {
  8520.                 if ($findByField != '') {
  8521.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findOneBy(
  8522.                         array
  8523.                         (
  8524.                             $findByField => $findByValue,
  8525.                         )
  8526.                     );
  8527.                 } else {
  8528.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findOneBy(
  8529.                         array
  8530.                         (
  8531.                             $idField => $findById,
  8532.                         )
  8533.                     );
  8534.                 }
  8535.             }
  8536.             if (!$theEntity && $noCreation == 0)
  8537.                 $theEntity = new $className();
  8538.             foreach ($dataFields as $dt) {
  8539.                 $setMethod 'set' ucfirst($dt['field']);
  8540.                 $getMethod 'get' ucfirst($dt['field']);
  8541.                 $type = isset($dt['type']) ? $dt['type'] : '_VALUE_';
  8542.                 $action = isset($dt['action']) ? $dt['action'] : '_REPLACE_';
  8543.                 if (method_exists($theEntity$setMethod)) {
  8544.                     $oldValue $theEntity->{$getMethod}();
  8545.                     $newValue $oldValue;
  8546.                     if ($type == '_VALUE_') {
  8547.                         $newValue $dt['value'];
  8548.                     }
  8549.                     if ($type == '_DECIMAL_') {
  8550.                         $newValue $dt['value'];
  8551.                     }
  8552.                     if ($type == '_DATE_') {
  8553.                         $newValue = new \DateTime($dt['value']);
  8554.                     }
  8555.                     if ($type == '_ARRAY_') {
  8556.                         $oldValue json_decode($oldValue);
  8557.                         if ($oldValue == null$oldValue = [];
  8558.                         if ($action == '_REPLACE_') {
  8559.                             $newValue json_encode($dt['value']);
  8560.                         }
  8561.                         if ($action == '_APPEND_') {
  8562.                             $newValue array_merge($oldValuearray_values(array_diff([$dt['value']], $oldValue)));
  8563.                         }
  8564.                         if ($action == '_MERGE_') {
  8565.                             $newValue array_merge($oldValuearray_values(array_diff($dt['value'], $oldValue)));
  8566.                         }
  8567.                         if ($action == '_EXCLUDE_') {
  8568.                             $newValue array_values(array_diff($oldValue, [$dt['value']]));
  8569.                         }
  8570.                         if ($action == '_EXCLUDE_ARRAY_') {
  8571.                             $newValue array_values(array_diff($oldValue$dt['value']));
  8572.                         }
  8573.                         $newValue json_encode($newValue);
  8574.                     }
  8575.                     $theEntity->{$setMethod}($newValue); // `foo!`
  8576. //                    $theEntity->setCompletionPercentage(78); // `foo!`
  8577.                 }
  8578.             }
  8579.             if ($additionalSql != '') {
  8580. //            if ($entityName == 'PlanningItem') {
  8581. //
  8582. //                $stmt='select disctinct parent_id from planning_item;';
  8583. //                $stmt->execute();
  8584. //                $get_kids = $stmt->fetchAll();
  8585. //                $p_ids=[];
  8586. //                foreach($get_kids as $g)
  8587. //                {
  8588. //                    $p_ids[]=$g['parent_id'];
  8589. //                }
  8590. //
  8591. //
  8592. //
  8593.                 $stmt $em->getConnection()->prepare($additionalSql);
  8594.                 $stmt->execute();
  8595.                 $stmt->closeCursor();
  8596. //
  8597. //
  8598.             }
  8599.             if (($findById == || $findById == '_NA_') && $noCreation == 0) {
  8600.                 $em->persist($theEntity);
  8601.                 $em->flush();
  8602.                 $getMethod 'get' ucfirst($idField);
  8603.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8604.             } else if ($theEntity) {
  8605.                 $em->flush();
  8606.                 $getMethod 'get' ucfirst($idField);
  8607.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8608.             }
  8609.             if ($entityName == 'PlanningItem') {
  8610.                 $stmt $em->getConnection()->prepare('select distinct parent_id from planning_item;');
  8611.                 $stmt->execute();
  8612.                 $get_kids $stmt->fetchAll();
  8613.                 $p_ids = [];
  8614.                 foreach ($get_kids as $g) {
  8615.                     $p_ids[] = $g['parent_id'];
  8616.                 }
  8617.                 $stmt $em->getConnection()->prepare('UPDATE planning_item d SET d.`has_child` =0 WHERE d.id NOT IN (' implode(','$p_ids) . '); 
  8618.                           UPDATE planning_item d SET d.`has_child` =1 WHERE d.id  IN (' implode(','$p_ids) . ')');
  8619.                 $stmt->execute();
  8620.                 $stmt->closeCursor();
  8621.                 $updatedData System::updatePlanningItemSequence($em$theEntity->getId());
  8622.                 $theEntity $updatedData['primaryOne'];
  8623.                 $theEntityUpdated $theEntity;
  8624.                 if ($theEntityUpdated->getEntryType() == 4)///cashflow
  8625.                 {
  8626.                     MiscActions::AddCashFlowProjection($em0, [
  8627.                         'planningItemId' => $theEntityUpdated->getId(),
  8628.                         'fundRequisitionId' => 0,
  8629.                         'concernedPersonId' => 0,
  8630.                         'type' => 1//exp
  8631.                         'subType' => 1//1== khoroch hobe 2: ashbe
  8632.                         'cashFlowType' => 1//2== RCV /in  1: Payment/out
  8633.                         'creationType' => 1//auto
  8634.                         'amountType' => 1//fund
  8635.                         'cashFlowAmount' => 0,
  8636.                         'expAstAmount' => 0,
  8637.                         'accumulatedCashFlowAmount' => 0,
  8638.                         'accumulatedCashFlowBalance' => 0,
  8639.                         'accumulatedExpAstAmount' => 0,
  8640.                         'relevantExpAstHeadId' => 0,
  8641.                         'balancingHeadId' => 0,
  8642.                         'cashFlowHeadId' => 0,
  8643.                         'cashFlowHeadType' => 1,
  8644.                         'relevantProductIds' => [],
  8645.                         'reminderDateTs' => 0,
  8646.                         'cashFlowDateTs' => 0,
  8647.                         'expAstRealizationDateTs' => 0,
  8648.                     ]);
  8649.                 }
  8650.             } else if ($entityName == 'TaskLog') {
  8651.                 $session $request->getSession();
  8652.                 if ($theEntity) {
  8653.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  8654.                     $currTime = new \DateTime();
  8655.                     $options = array(
  8656.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8657.                         'notification_server' => $this->container->getParameter('notification_server'),
  8658.                     );
  8659.                     $positionsArray = [
  8660.                         array(
  8661.                             'employeeId' => $empId,
  8662.                             'userId' => $session->get(UserConstants::USER_ID0),
  8663.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  8664.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  8665.                             'lat' => 23.8623834,
  8666.                             'lng' => 90.3979294,
  8667.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING,
  8668. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  8669.                         )
  8670.                     ];
  8671.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  8672.                     if ($positionsArray == null$positionsArray = [];
  8673.                     $dataByAttId = [];
  8674.                     $workPlaceType '_UNSET_';
  8675.                     foreach ($positionsArray as $findex => $d) {
  8676.                         $sysUserId 0;
  8677.                         $userId 0;
  8678.                         $empId 0;
  8679.                         $dtTs 0;
  8680.                         $timeZoneStr '+0000';
  8681.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  8682.                         if (isset($d['userId'])) $userId $d['userId'];
  8683.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  8684.                         if (isset($d['tsMilSec'])) {
  8685.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  8686.                         }
  8687.                         if ($dtTs == 0) {
  8688.                             $currTsTime = new \DateTime();
  8689.                             $dtTs $currTsTime->format('U');
  8690.                         } else {
  8691.                             $currTsTime = new \DateTime('@' $dtTs);
  8692.                         }
  8693.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  8694.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  8695.                         $EmployeeAttendance $this->getDoctrine()
  8696.                             ->getRepository(EmployeeAttendance::class)
  8697.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  8698.                         if (!$EmployeeAttendance) {
  8699.                             $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8700.                             $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8701.                             $EmployeeAttendance = new EmployeeAttendance;
  8702.                         } else {
  8703.                             if ($EmployeeAttendance->getCurrentLocation() == 'out') {
  8704.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8705.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8706.                             } else {
  8707.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8708.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8709.                             }
  8710.                         }
  8711.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  8712.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  8713.                             $workPlaceType '_STATIC_';
  8714.                         }
  8715.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  8716.                             $dataByAttId[$attendanceInfo->getId()] = array(
  8717.                                 'attendanceInfo' => $attendanceInfo,
  8718.                                 'empId' => $empId,
  8719.                                 'lat' => 0,
  8720.                                 'lng' => 0,
  8721.                                 'address' => 0,
  8722.                                 'sysUserId' => $sysUserId,
  8723.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8724.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8725.                                 'positionArray' => []
  8726.                             );
  8727.                         $posData = array(
  8728.                             'ts' => $dtTs,
  8729.                             'lat' => $d['lat'],
  8730.                             'lng' => $d['lng'],
  8731.                             'marker' => $d['markerId'],
  8732.                             'src' => 2,
  8733.                         );
  8734.                         $posDataArray = array(
  8735.                             $dtTs,
  8736.                             $d['lat'],
  8737.                             $d['lng'],
  8738.                             $d['markerId'],
  8739.                             2
  8740.                         );
  8741.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  8742.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  8743.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  8744.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  8745.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  8746.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  8747.                         if (isset($d['address']))
  8748.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  8749. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  8750.                     }
  8751.                     $response = array(
  8752.                         'success' => true,
  8753.                     );
  8754.                     foreach ($dataByAttId as $attInfoId => $d) {
  8755.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  8756.                             $d['empId'],
  8757.                             $d['sysUserId'],
  8758.                             $d['companyId'],
  8759.                             $d['appId'],
  8760.                             $request,
  8761.                             $d['attendanceInfo'],
  8762.                             $options,
  8763.                             $d['positionArray'],
  8764.                             $d['lat'],
  8765.                             $d['lng'],
  8766.                             $d['address'],
  8767.                             $d['markerId']
  8768.                         );
  8769.                     }
  8770.                     $session->set(UserConstants::USER_CURRENT_TASK_ID$theEntity->getId());
  8771.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$theEntity->getPlanningItemId());
  8772.                 } else {
  8773.                     $session->set(UserConstants::USER_CURRENT_TASK_ID0);
  8774.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID0);
  8775.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  8776.                     $currTime = new \DateTime();
  8777.                     $options = array(
  8778.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8779.                         'notification_server' => $this->container->getParameter('notification_server'),
  8780.                     );
  8781.                     $positionsArray = [
  8782.                         array(
  8783.                             'employeeId' => $empId,
  8784.                             'userId' => $session->get(UserConstants::USER_ID0),
  8785.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  8786.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  8787.                             'lat' => 23.8623834,
  8788.                             'lng' => 90.3979294,
  8789.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT,
  8790. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  8791.                         )
  8792.                     ];
  8793.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  8794.                     if ($positionsArray == null$positionsArray = [];
  8795.                     $dataByAttId = [];
  8796.                     $workPlaceType '_UNSET_';
  8797.                     foreach ($positionsArray as $findex => $d) {
  8798.                         $sysUserId 0;
  8799.                         $userId 0;
  8800.                         $empId 0;
  8801.                         $dtTs 0;
  8802.                         $timeZoneStr '+0000';
  8803.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  8804.                         if (isset($d['userId'])) $userId $d['userId'];
  8805.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  8806.                         if (isset($d['tsMilSec'])) {
  8807.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  8808.                         }
  8809.                         if ($dtTs == 0) {
  8810.                             $currTsTime = new \DateTime();
  8811.                             $dtTs $currTsTime->format('U');
  8812.                         } else {
  8813.                             $currTsTime = new \DateTime('@' $dtTs);
  8814.                         }
  8815.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  8816.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  8817.                         $EmployeeAttendance $this->getDoctrine()
  8818.                             ->getRepository(EmployeeAttendance::class)
  8819.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  8820.                         if (!$EmployeeAttendance) {
  8821.                             continue;
  8822.                         } else {
  8823.                         }
  8824.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  8825.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT) {
  8826.                             $workPlaceType '_STATIC_';
  8827.                         }
  8828.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  8829.                             $dataByAttId[$attendanceInfo->getId()] = array(
  8830.                                 'attendanceInfo' => $attendanceInfo,
  8831.                                 'empId' => $empId,
  8832.                                 'lat' => 0,
  8833.                                 'lng' => 0,
  8834.                                 'address' => 0,
  8835.                                 'sysUserId' => $sysUserId,
  8836.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8837.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8838.                                 'positionArray' => []
  8839.                             );
  8840.                         $posData = array(
  8841.                             'ts' => $dtTs,
  8842.                             'lat' => $d['lat'],
  8843.                             'lng' => $d['lng'],
  8844.                             'marker' => $d['markerId'],
  8845.                             'src' => 2,
  8846.                         );
  8847.                         $posDataArray = array(
  8848.                             $dtTs,
  8849.                             $d['lat'],
  8850.                             $d['lng'],
  8851.                             $d['markerId'],
  8852.                             2
  8853.                         );
  8854.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  8855.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  8856.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  8857.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  8858.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  8859.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  8860.                         if (isset($d['address']))
  8861.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  8862. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  8863.                     }
  8864.                     $response = array(
  8865.                         'success' => true,
  8866.                     );
  8867.                     foreach ($dataByAttId as $attInfoId => $d) {
  8868.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  8869.                             $d['empId'],
  8870.                             $d['sysUserId'],
  8871.                             $d['companyId'],
  8872.                             $d['appId'],
  8873.                             $request,
  8874.                             $d['attendanceInfo'],
  8875.                             $options,
  8876.                             $d['positionArray'],
  8877.                             $d['lat'],
  8878.                             $d['lng'],
  8879.                             $d['address'],
  8880.                             $d['markerId']
  8881.                         );
  8882.                     }
  8883.                 }
  8884.                 $theEntityUpdated $theEntity;
  8885.             } else
  8886.                 $theEntityUpdated $theEntity;
  8887. //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  8888.             $getters = [];
  8889.             if ($theEntityUpdated)
  8890.                 $getters array_filter(get_class_methods($theEntityUpdated), function ($method) {
  8891.                     return 'get' === substr($method03);
  8892.                 });
  8893.             $updatedData = [];
  8894.             foreach ($getters as $getter) {
  8895.                 $indForThis str_replace('get'''$getter);
  8896.                 $indForThis lcfirst($indForThis);
  8897.                 $updatedData[$indForThis] = $theEntityUpdated->{$getter}();
  8898.             }
  8899.             $updatedDataList[$dataInd] = $updatedData;
  8900.         }
  8901.         foreach ($dataToRemove as $dataInd => $dat) {
  8902.             $entityName $dat['entityName'];
  8903.             $idField $dat['idField'];
  8904.             $findById $dat['findId'];
  8905.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  8906.             $theEntityList $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findBy(
  8907.                 array
  8908.                 (
  8909.                     $idField => $findById,
  8910.                 )
  8911.             );
  8912.             foreach ($theEntityList as $dt) {
  8913.                 $em->remove($dt);
  8914.                 $em->flush();
  8915.             }
  8916.             if ($additionalSql != '') {
  8917. //            if ($entityName == 'PlanningItem') {
  8918. //
  8919. //                $stmt='select disctinct parent_id from planning_item;';
  8920. //                $stmt->execute();
  8921. //                $get_kids = $stmt->fetchAll();
  8922. //                $p_ids=[];
  8923. //                foreach($get_kids as $g)
  8924. //                {
  8925. //                    $p_ids[]=$g['parent_id'];
  8926. //                }
  8927. //
  8928. //
  8929. //
  8930.                 $stmt $em->getConnection()->prepare($additionalSql);
  8931.                 $stmt->execute();
  8932.                 $stmt->closeCursor();
  8933. //
  8934. //
  8935.             }
  8936.             $updatedDataList[$dataInd] = [];
  8937.         }
  8938. //        if ($table == '') {
  8939. //            return new JsonResponse(
  8940. //                array(
  8941. //                    'success' => false,
  8942. ////                    'page_title' => 'Product Details',
  8943. ////                    'company_data' => $company_data,
  8944. //                    'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8945. //
  8946. //                )
  8947. //            );
  8948. //        }
  8949. //        if($request->query->has('returnJson'))
  8950.         return new JsonResponse(
  8951.             array(
  8952.                 'success' => true,
  8953.                 'data' => $relData,
  8954.                 'updatedDataList' => $updatedDataList,
  8955.             )
  8956.         );
  8957.     }
  8958.     public function GetAvailableQtyAction(Request $request$id 0)
  8959.     {
  8960.         $em $this->getDoctrine()->getManager();
  8961.         $productId $request->request->has('productId') ? $request->request->get('productId') : 0;
  8962.         $colorId $request->request->has('colorId') ? $request->request->get('colorId') : 0;
  8963.         $dataId $request->request->has('dataId') ? $request->request->get('dataId') : 0;
  8964.         $allowedWarehouseIds $request->request->has('warehouseId') ? [$request->request->get('warehouseId')] : [];
  8965.         $allowedWarehouseActionIds $request->request->has('warehouseActionId') ? [$request->request->get('warehouseActionId')] : [];
  8966.         $qty Inventory::getProductQty($em$productId$allowedWarehouseIds$allowedWarehouseActionIds$colorId);
  8967.         return new JsonResponse(array("success" => true,
  8968.             "qty" => $qty,
  8969.             "dataId" => $dataId,
  8970.         ));
  8971.     }
  8972.     public
  8973.     function ProductListSelectAjaxAction(Request $request$queryStr '')
  8974.     {
  8975.         $em $this->getDoctrine()->getManager();
  8976.         $companyId $this->getLoggedUserCompanyId($request);
  8977.         $company_data Company::getCompanyData($em$companyId);
  8978.         $data = [];
  8979.         $data_by_id = [];
  8980.         $html '';
  8981.         $productByCodeData = [];
  8982.         if ($queryStr == '_EMPTY_')
  8983.             $queryStr '';
  8984.         if ($request->request->has('query') && $queryStr == '')
  8985.             $queryStr $request->request->get('queryStr');
  8986.         if ($queryStr == '_EMPTY_')
  8987.             $queryStr '';
  8988. //        $queryStr=urldecode($queryStr);
  8989.         $queryStr str_replace('_FSLASH_''/'$queryStr);
  8990.         $filterQryForCriteria "select * from inv_products where 1=1 ";
  8991.         if ($request->request->has('sellableOnly') && $request->request->get('sellableOnly') != 0)
  8992.             $filterQryForCriteria .= " and sellable=1";
  8993.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  8994.             $filterQryForCriteria .= " and sub_category_id=" $request->request->get('subCategoryId');
  8995.         else if ($request->request->has('categoryId') && $request->request->get('categoryId') != '')
  8996.             $filterQryForCriteria .= " and category_id=" $request->request->get('categoryId');
  8997.         else if ($request->request->has('igId') && $request->request->get('igId') != '')
  8998.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  8999.         if ($request->request->has('brandId') && $request->request->get('brandId') != '')
  9000.             $filterQryForCriteria .= " and brand_company=" $request->request->get('brandId');
  9001.         if ($request->request->has('restrictedBrandIds') && $request->request->get('restrictedBrandIds') != [])
  9002.             $filterQryForCriteria .= " and brand_company in (" implode(','$request->request->get('restrictedBrandIds')) . ")";
  9003.         if ($request->request->has('productIds'))
  9004.             $filterQryForCriteria .= " and id in (" implode(','$request->request->get('productIds')) . ") ";
  9005.         else if ($request->request->has('productCode'))
  9006.             $filterQryForCriteria .= " and product_code  like '%" $request->request->get('productCode') . "%'  ";
  9007.         else if ($queryStr != '')
  9008.             $filterQryForCriteria .= " and  (product_code  like '%" $queryStr "%' or `name`   like '%" $queryStr "%' or model_no like '%" $queryStr "%') ";
  9009.         if ($filterQryForCriteria != '')
  9010.             $filterQryForCriteria .= "  limit 25";
  9011.         $get_kids_sql $filterQryForCriteria;
  9012. //        if ($request->request->has('productIds'))
  9013. //
  9014. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9015. //        else if ($request->request->has('productCode'))
  9016. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9017. //        else if ($filterQryForCriteria!='')
  9018. //            $get_kids_sql = $filterQryForCriteria;
  9019. //
  9020. //        else
  9021. //               $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";
  9022.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9023.         $stmt->execute();
  9024.         $get_kids $stmt->fetchAll();
  9025.         $productId 0;
  9026.         if (!empty($get_kids)) {
  9027.             foreach ($get_kids as $product) {
  9028.                 $pa = array();
  9029.                 $pa['id'] = $product['id'];
  9030.                 $pa['name'] = $product['name'];
  9031.                 $pa['id_name'] = $product['id'] . '. ' $product['name'];
  9032.                 $pa['id_mn'] = $product['id'] . '. ' $product['model_no'];;
  9033.                 $pa['id_name_mn'] = $product['id'] . '. ' $product['name'] . ' ( ' $product['model_no'] . ' )';
  9034.                 $pa['globalId'] = $product['global_id'];
  9035.                 $pa['classSuffix'] = $product['class_suffix'];
  9036.                 $pa['productFdm'] = $product['product_fdm'];
  9037.                 $pa['modelNo'] = $product['model_no'];
  9038.                 $pa['partId'] = $product['part_id'];
  9039.                 $pa['hsCode'] = $product['hs_code'];
  9040.                 $pa['productCode'] = $product['product_code'];
  9041.                 $pa['text'] = $product['name'];
  9042.                 $pa['value'] = $product['id'];
  9043.                 $pa['tac'] = $product['tac'];
  9044.                 $pa['igId'] = $product['ig_id'];
  9045.                 $pa['categoryId'] = $product['category_id'];
  9046.                 $pa['subCategoryId'] = $product['sub_category_id'];
  9047.                 $pa['brandCompany'] = $product['brand_company'];
  9048.                 $pa['sales_price'] = $product['curr_sales_price'];
  9049.                 $pa['purchase_price'] = $product['curr_purchase_price'];
  9050.                 $pa['unit_type'] = $product['unit_type_id'];
  9051.                 $pa['single_weight'] = $product['single_weight'];
  9052.                 $pa['single_weight_variance_type'] = $product['single_weight_variance_type'];
  9053.                 $pa['single_weight_variance_value'] = $product['single_weight_variance_value'];
  9054.                 $pa['weight'] = $product['weight'];
  9055.                 $pa['weight_variance_type'] = $product['weight_variance_type'];
  9056.                 $pa['weight_variance_value'] = $product['weight_variance_value'];
  9057.                 $pa['carton_capacity_count'] = $product['carton_capacity_count'];
  9058.                 $pa['type'] = $product['type'];
  9059.                 $pa['qty'] = $product['qty'];
  9060. //                $pa['alias'] = '';
  9061.                 $pa['alias'] = $product['alias'];
  9062.                 $pa['note'] = $product['note'];
  9063.                 $pa['defaultTaxConfigId'] = $product['default_tax_config_id'] == null $product['default_tax_config_id'];
  9064.                 $tax_config_ids json_decode($product['tax_config_ids'], true);
  9065.                 if ($tax_config_ids == null)
  9066.                     $tax_config_ids = [];
  9067.                 $pa['taxConfigIds'] = $tax_config_ids;
  9068.                 $inco_terms json_decode($product['inco_terms'], true);
  9069.                 if ($inco_terms == null)
  9070.                     $inco_terms = [];
  9071.                 $pa['incoTerms'] = $inco_terms;
  9072.                 $pa['defaultIncoTerm'] = $product['default_inco_term'] == null $product['default_inco_term'];
  9073.                 $pa['has_serial'] = $product['has_serial'];
  9074.                 $pa['expiry_days'] = $product['expiry_days'];
  9075.                 $pa['image'] = $product['default_image'];
  9076.                 $pa['sales_warranty'] = $product['sales_warranty_months'];;
  9077.                 $pa['defaultColorId'] = $product['default_color_id'];;
  9078.                 $allowedColorIds json_decode($product['colors'], true);
  9079.                 if ($allowedColorIds == null$allowedColorIds = [];
  9080.                 if (!in_array($product['default_color_id'], $allowedColorIds))
  9081.                     $allowedColorIds[] = $product['default_color_id'];
  9082.                 $pa['allowedColorIds'] = $allowedColorIds;;
  9083.                 $data[] = $pa;
  9084.                 $data_by_id[$product['id']] = $pa;
  9085.                 $productId $product['id'];
  9086.             }
  9087.         }
  9088. //        if($request->query->has('returnJson'))
  9089.         {
  9090.             return new JsonResponse(
  9091.                 array(
  9092.                     'success' => true,
  9093. //                    'page_title' => 'Product Details',
  9094. //                    'company_data' => $company_data,
  9095.                     'data' => $data,
  9096.                     'dataById' => $data_by_id,
  9097.                     'productId' => $productId,
  9098.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9099. //                    'exId'=>$id,
  9100. //                'productByCodeData' => $productByCodeData,
  9101. //                'productData' => $productData,
  9102. //                'currInvList' => $currInvList,
  9103. //                'productList' => Inventory::ProductList($em, $companyId),
  9104. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9105. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9106. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9107. //                'unitList' => Inventory::UnitTypeList($em),
  9108. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9109. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9110. //                'warehouseList' => Inventory::WarehouseList($em),
  9111.                 )
  9112.             );
  9113.         }
  9114.     }
  9115.     public
  9116.     function labelFormatSelectAjaxAction(Request $request$queryStr '')
  9117.     {
  9118.         $em $this->getDoctrine()->getManager();
  9119.         $companyId $this->getLoggedUserCompanyId($request);
  9120.         $company_data Company::getCompanyData($em$companyId);
  9121.         $data = [];
  9122.         $data_by_id = [];
  9123.         $html '';
  9124.         $productByCodeData = [];
  9125.         if ($queryStr == '_EMPTY_')
  9126.             $queryStr '';
  9127.         if ($request->request->has('query') && $queryStr == '')
  9128.             $queryStr $request->request->get('queryStr');
  9129.         if ($queryStr == '_EMPTY_')
  9130.             $queryStr '';
  9131.         $filterQryForCriteria "select * from label_format where company_id=" $companyId " ";
  9132.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  9133.             $filterQryForCriteria .= " and label_type=" $request->request->get('dataType');
  9134.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  9135.             $filterQryForCriteria .= " and format_id=" $request->request->get('formatId');
  9136.         else if ($queryStr != '')
  9137.             $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' or `format_code` like '%" $queryStr "%') ";
  9138.         if ($filterQryForCriteria != '')
  9139.             $filterQryForCriteria .= "  limit 25";
  9140.         $get_kids_sql $filterQryForCriteria;
  9141. //        if ($request->request->has('productIds'))
  9142. //
  9143. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9144. //        else if ($request->request->has('productCode'))
  9145. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9146. //        else if ($filterQryForCriteria!='')
  9147. //            $get_kids_sql = $filterQryForCriteria;
  9148. //
  9149. //        else
  9150. //               $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";
  9151.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9152.         $stmt->execute();
  9153.         $get_kids $stmt->fetchAll();
  9154.         $productId 0;
  9155.         if (!empty($get_kids)) {
  9156.             foreach ($get_kids as $product) {
  9157.                 $pa = array();
  9158.                 $pa['id'] = $product['format_id'];
  9159.                 $pa['name'] = $product['name'];
  9160.                 $pa['format_code'] = $product['format_code'] . '. ' $product['name'];
  9161.                 $pa['id_code_name'] = $product['format_id'] . '. ' $product['format_code'] . ' - ' $product['name'] . ' ';
  9162.                 $pa['text'] = $product['name'];
  9163.                 $pa['value'] = $product['format_id'];
  9164.                 $data[] = $pa;
  9165.                 $data_by_id[$product['format_id']] = $pa;
  9166.                 $productId $product['format_id'];
  9167.             }
  9168.         }
  9169. //        if($request->query->has('returnJson'))
  9170.         {
  9171.             return new JsonResponse(
  9172.                 array(
  9173.                     'success' => true,
  9174. //                    'page_title' => 'Product Details',
  9175. //                    'company_data' => $company_data,
  9176.                     'data' => $data,
  9177.                     'dataById' => $data_by_id,
  9178.                     'productId' => $productId,
  9179.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9180. //                    'exId'=>$id,
  9181. //                'productByCodeData' => $productByCodeData,
  9182. //                'productData' => $productData,
  9183. //                'currInvList' => $currInvList,
  9184. //                'productList' => Inventory::ProductList($em, $companyId),
  9185. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9186. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9187. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9188. //                'unitList' => Inventory::UnitTypeList($em),
  9189. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9190. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9191. //                'warehouseList' => Inventory::WarehouseList($em),
  9192.                 )
  9193.             );
  9194.         }
  9195.     }
  9196.     public
  9197.     function CategoryListSelectAjaxAction(Request $request$queryStr '')
  9198.     {
  9199.         $em $this->getDoctrine()->getManager();
  9200.         $companyId $this->getLoggedUserCompanyId($request);
  9201.         $company_data Company::getCompanyData($em$companyId);
  9202.         $data = [];
  9203.         $data_by_id = [];
  9204.         $html '';
  9205.         $productByCodeData = [];
  9206.         if ($queryStr == '_EMPTY_')
  9207.             $queryStr '';
  9208.         if ($request->request->has('query') && $queryStr == '')
  9209.             $queryStr $request->request->get('queryStr');
  9210.         if ($queryStr == '_EMPTY_')
  9211.             $queryStr '';
  9212.         $filterQryForCriteria "select * from inv_product_categories where company_id=" $companyId " ";
  9213.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  9214.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  9215.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  9216.         if ($filterQryForCriteria != '')
  9217.             $filterQryForCriteria .= "  limit 25";
  9218.         $get_kids_sql $filterQryForCriteria;
  9219. //        if ($request->request->has('productIds'))
  9220. //
  9221. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9222. //        else if ($request->request->has('productCode'))
  9223. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9224. //        else if ($filterQryForCriteria!='')
  9225. //            $get_kids_sql = $filterQryForCriteria;
  9226. //
  9227. //        else
  9228. //               $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";
  9229.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9230.         $stmt->execute();
  9231.         $get_kids $stmt->fetchAll();
  9232.         $productId 0;
  9233.         if (!empty($get_kids)) {
  9234.             foreach ($get_kids as $product) {
  9235.                 $pa = array();
  9236.                 $pa['id'] = $product['id'];
  9237.                 $pa['name'] = $product['name'];
  9238.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  9239.                 $pa['globalId'] = $product['global_id'];
  9240.                 $pa['text'] = $product['name'];
  9241.                 $pa['value'] = $product['id'];
  9242.                 $pa['igId'] = $product['ig_id'];
  9243. //                $pa['categoryId'] = $product['category_id'];
  9244. //                $pa['subCategoryId'] = $product['sub_category_id'];
  9245.                 $data[] = $pa;
  9246.                 $data_by_id[$product['id']] = $pa;
  9247.                 $productId $product['id'];
  9248.             }
  9249.         }
  9250. //        if($request->query->has('returnJson'))
  9251.         {
  9252.             return new JsonResponse(
  9253.                 array(
  9254.                     'success' => true,
  9255. //                    'page_title' => 'Product Details',
  9256. //                    'company_data' => $company_data,
  9257.                     'data' => $data,
  9258.                     'dataById' => $data_by_id,
  9259.                     'productId' => $productId,
  9260.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9261. //                    'exId'=>$id,
  9262. //                'productByCodeData' => $productByCodeData,
  9263. //                'productData' => $productData,
  9264. //                'currInvList' => $currInvList,
  9265. //                'productList' => Inventory::ProductList($em, $companyId),
  9266. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9267. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9268. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9269. //                'unitList' => Inventory::UnitTypeList($em),
  9270. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9271. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9272. //                'warehouseList' => Inventory::WarehouseList($em),
  9273.                 )
  9274.             );
  9275.         }
  9276.     }
  9277.     public
  9278.     function SubCategoryListSelectAjaxAction(Request $request$queryStr '')
  9279.     {
  9280.         $em $this->getDoctrine()->getManager();
  9281.         $companyId $this->getLoggedUserCompanyId($request);
  9282.         $company_data Company::getCompanyData($em$companyId);
  9283.         $data = [];
  9284.         $data_by_id = [];
  9285.         $html '';
  9286.         $productByCodeData = [];
  9287.         if ($queryStr == '_EMPTY_')
  9288.             $queryStr '';
  9289.         if ($request->request->has('query') && $queryStr == '')
  9290.             $queryStr $request->request->get('queryStr');
  9291.         if ($queryStr == '_EMPTY_')
  9292.             $queryStr '';
  9293.         $filterQryForCriteria "select * from inv_product_sub_categories where company_id=" $companyId " ";
  9294.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9295.             $filterQryForCriteria .= " and sub_category_id=" $request->request->get('subCategoryId');
  9296.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  9297.             $filterQryForCriteria .= " and category_id=" $request->request->get('categoryId');
  9298.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  9299.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  9300.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  9301.             if ($request->request->get('parentId') != 0)
  9302.                 $filterQryForCriteria .= " and  parent_id=" $request->request->get('parentId');
  9303.             else
  9304.                 $filterQryForCriteria .= " and ( parent_id =0 or parent_id is null ) ";
  9305.         if ($request->request->has('level') && $request->request->get('level') != '')
  9306.             if ($request->request->get('level') != 0)
  9307.                 $filterQryForCriteria .= " and level=" $request->request->get('level');
  9308.             else
  9309.                 $filterQryForCriteria .= " and ( level =0 or level is null) ";
  9310.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  9311.         if ($filterQryForCriteria != '')
  9312.             $filterQryForCriteria .= "  limit 25";
  9313.         $get_kids_sql $filterQryForCriteria;
  9314. //        if ($request->request->has('productIds'))
  9315. //
  9316. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9317. //        else if ($request->request->has('productCode'))
  9318. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9319. //        else if ($filterQryForCriteria!='')
  9320. //            $get_kids_sql = $filterQryForCriteria;
  9321. //
  9322. //        else
  9323. //               $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";
  9324.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9325.         $stmt->execute();
  9326.         $get_kids $stmt->fetchAll();
  9327.         $productId 0;
  9328.         if (!empty($get_kids)) {
  9329.             foreach ($get_kids as $product) {
  9330.                 $pa = array();
  9331.                 $pa['id'] = $product['id'];
  9332.                 $pa['name'] = $product['name'];
  9333.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  9334.                 $pa['globalId'] = $product['global_id'];
  9335.                 $pa['parentId'] = $product['parent_id'];
  9336.                 $pa['text'] = $product['name'];
  9337.                 $pa['value'] = $product['id'];
  9338.                 $pa['igId'] = $product['ig_id'];
  9339.                 $pa['categoryId'] = $product['category_id'];
  9340. //                $pa['subCategoryId'] = $product['sub_category_id'];
  9341.                 $data[] = $pa;
  9342.                 $data_by_id[$product['id']] = $pa;
  9343.                 $productId $product['id'];
  9344.             }
  9345.         }
  9346. //        if($request->query->has('returnJson'))
  9347.         {
  9348.             return new JsonResponse(
  9349.                 array(
  9350.                     'success' => true,
  9351. //                    'page_title' => 'Product Details',
  9352. //                    'company_data' => $company_data,
  9353.                     'data' => $data,
  9354.                     'dataById' => $data_by_id,
  9355.                     'productId' => $productId,
  9356.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9357. //                    'exId'=>$id,
  9358. //                'productByCodeData' => $productByCodeData,
  9359. //                'productData' => $productData,
  9360. //                'currInvList' => $currInvList,
  9361. //                'productList' => Inventory::ProductList($em, $companyId),
  9362. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9363. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9364. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9365. //                'unitList' => Inventory::UnitTypeList($em),
  9366. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9367. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9368. //                'warehouseList' => Inventory::WarehouseList($em),
  9369.                 )
  9370.             );
  9371.         }
  9372.     }
  9373.     public
  9374.     function ProductByCodeViewAction(Request $request$id 0)
  9375.     {
  9376.         $em $this->getDoctrine()->getManager();
  9377.         $companyId $this->getLoggedUserCompanyId($request);
  9378.         $company_data Company::getCompanyData($em$companyId);
  9379.         $data = [];
  9380.         $html '';
  9381.         $productByCodeData = [];
  9382.         if ($id != 0) {
  9383.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9384.                 ->findOneBy(
  9385.                     array(
  9386.                         'productByCodeId' => $id
  9387.                     )
  9388.                 );
  9389.         } else {
  9390.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9391.                 ->findOneBy(
  9392.                     array(
  9393. //                        'productByCodeId' => $id,
  9394.                         'CompanyId' => $companyId
  9395.                     ), array(
  9396.                         'productByCodeId' => 'DESC'
  9397.                     )
  9398.                 );
  9399.             if ($productByCodeData)
  9400.                 $id $productByCodeData->getProductByCodeId();
  9401.         }
  9402.         if ($id != 0) {
  9403.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9404.                 ->findOneBy(
  9405.                     array(
  9406.                         'id' => $productByCodeData->getProductId()
  9407.                     )
  9408.                 );
  9409.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9410.                 ->findBy(
  9411.                     array(
  9412.                         'productId' => $id
  9413.                     )
  9414.                 );
  9415.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  9416.                 array(
  9417.                     'page_title' => 'Product Details',
  9418.                     'company_data' => $company_data,
  9419.                     'productByCodeData' => $productByCodeData,
  9420.                     'productData' => $productData,
  9421.                     'currInvList' => $currInvList,
  9422.                     'exId' => $id,
  9423.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9424.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9425.                     'productList' => Inventory::ProductList($em$companyId),
  9426.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9427.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9428.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9429.                     'unitList' => Inventory::UnitTypeList($em),
  9430.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9431.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9432.                     'warehouseList' => Inventory::WarehouseList($em),
  9433.                 )
  9434.             );
  9435.         } else {
  9436.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  9437.                 array(
  9438.                     'exId' => $id,
  9439.                 )
  9440.             );
  9441.         }
  9442.         if ($request->query->has('returnJson')) {
  9443.             return new JsonResponse(
  9444.                 array(
  9445.                     'success' => true,
  9446.                     'page_title' => 'Product Details',
  9447.                     'company_data' => $company_data,
  9448.                     'renderedHtml' => $html,
  9449.                     'exId' => $id,
  9450. //                'productByCodeData' => $productByCodeData,
  9451. //                'productData' => $productData,
  9452. //                'currInvList' => $currInvList,
  9453. //                'productList' => Inventory::ProductList($em, $companyId),
  9454. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9455. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9456. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9457. //                'unitList' => Inventory::UnitTypeList($em),
  9458. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9459. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9460. //                'warehouseList' => Inventory::WarehouseList($em),
  9461.                 )
  9462.             );
  9463.         } else {
  9464. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9465. //                ->findBy(
  9466. //                    array(
  9467. ////                        'productByCodeId' => $id,
  9468. //                    'CompanyId'=>$companyId
  9469. //                    )
  9470. //                );
  9471.             $productByCodeList = []; //called by ajax
  9472.             return $this->render('@Inventory/pages/views/product_by_code_view.html.twig',
  9473.                 array(
  9474.                     'page_title' => 'Product Details',
  9475.                     'company_data' => $company_data,
  9476.                     'renderedHtml' => $html,
  9477.                     'exId' => $id,
  9478.                     'productByCodeList' => $productByCodeList,
  9479. //                'productByCodeData' => $productByCodeData,
  9480. //                'productData' => $productData,
  9481. //                'currInvList' => $currInvList,
  9482. //                'productList' => Inventory::ProductList($em, $companyId),
  9483. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9484. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9485. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9486. //                'unitList' => Inventory::UnitTypeList($em),
  9487. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9488. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9489. //                'warehouseList' => Inventory::WarehouseList($em),
  9490.                 )
  9491.             );
  9492.         }
  9493.     }
  9494.     public
  9495.     function ConsumptionSettingsAction(Request $request$id)
  9496.     {
  9497.         $cc_id '';
  9498.         $cc_name '';
  9499.         $em $this->getDoctrine()->getManager();
  9500.         $companyId $this->getLoggedUserCompanyId($request);
  9501.         $consumptionTypeId 0;
  9502.         if ($request->isMethod('POST')) {
  9503.             $new_cc = [];
  9504.             if ($request->request->get('consumptionTypeId') != '' && $request->request->get('consumptionTypeId') != 0) {
  9505.                 $em $this->getDoctrine()->getManager();
  9506.                 $new_cc $this->getDoctrine()
  9507.                     ->getRepository('ApplicationBundle:ConsumptionType')
  9508.                     ->findOneBy(
  9509.                         array(
  9510.                             'consumptionTypeId' => $request->request->get('consumptionTypeId'),
  9511.                         )
  9512.                     );
  9513.                 $new_cc->setName($request->request->get('name'));
  9514.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9515.                 $new_cc->setCompanyId($companyId);
  9516.                 $em->flush();
  9517.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9518.                 $this->addFlash(
  9519.                     'success',
  9520.                     'Consumption Information Updated'
  9521.                 );
  9522.             } else {
  9523.                 $new_cc = new ConsumptionType();
  9524.                 $new_cc->setName($request->request->get('name'));
  9525.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9526.                 $new_cc->setCompanyId($companyId);
  9527.                 $em->persist($new_cc);
  9528.                 $em->flush();
  9529.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9530.                 $em->flush();
  9531.                 $this->addFlash(
  9532.                     'success',
  9533.                     'New Consumption Type Added'
  9534.                 );
  9535.             }
  9536.         }
  9537.         $extData = [];
  9538.         if ($id != 0) {
  9539.             $extData $this->getDoctrine()
  9540.                 ->getRepository('ApplicationBundle:ConsumptionType')
  9541.                 ->findOneBy(
  9542.                     array(
  9543.                         'consumptionTypeId' => $id
  9544.                     )
  9545.                 );
  9546. //            $cc_data_list = [];
  9547. //            foreach ($cc_data as $value) {
  9548. //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  9549. //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  9550. //
  9551. //                if ($value->getSupplierCategoryId() == $id) {
  9552. //                    $cc_id = $value->getSupplierCategoryId();
  9553. //                    $cc_name = $value->getName();
  9554. //                }
  9555. //            }
  9556.         }
  9557.         return $this->render('@Inventory/pages/input_forms/consumption_settings.html.twig',
  9558.             array(
  9559.                 'page_title' => 'Consumption Settings',
  9560.                 'consumptionTypeList' => $this->getDoctrine()
  9561.                     ->getRepository('ApplicationBundle:ConsumptionType')
  9562.                     ->findBy(
  9563.                         array(
  9564.                             'CompanyId' => $companyId
  9565.                         )
  9566.                     ),
  9567.                 'extData' => $extData,
  9568.                 'headList' => Accounts::getParentLedgerHeads($em),
  9569. //                'countryList'=>SalesOrderM::Co
  9570.             )
  9571.         );
  9572.     }
  9573.     public
  9574.     function ProductByCodeCheckAssignPrintAction(Request $request$id 0)
  9575.     {
  9576.         $em $this->getDoctrine()->getManager();
  9577.         $companyId $this->getLoggedUserCompanyId($request);
  9578.         $company_data Company::getCompanyData($em$companyId);
  9579.         $data = [];
  9580.         $html '';
  9581.         $productByCodeData = [];
  9582.         $productDataWeightPackageGm '';
  9583.         $productDataWeightVarianceValue 0;
  9584.         $productDataWeightVarianceType 0;
  9585.         $productByCodeDataObj = [];
  9586.         $dr_id 0;//for dr_id
  9587.         $skipRenderData 0;
  9588.         if ($request->query->has('skipRenderData'))
  9589.             $skipRenderData $request->query->get('skipRenderData');
  9590.         if ($id != 0) {
  9591.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9592.                 ->findOneBy(
  9593.                     array(
  9594.                         'productByCodeId' => $id
  9595.                     )
  9596.                 );
  9597.         } else {
  9598.             if ($request->query->has('scanCode')) {
  9599.                 $query $em->getRepository('ApplicationBundle:ProductByCode')
  9600.                     ->createQueryBuilder('p');
  9601.                 if ($request->query->has('assigned')) {
  9602.                     $query->where('p.assigned > :av')
  9603.                         ->setParameter('av'$request->query->get('assigned'));
  9604.                 } else
  9605.                     $query->where("1=0");
  9606.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  9607.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  9608.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  9609.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  9610.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  9611.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  9612.                 $query->setMaxResults(1);
  9613.                 $results $query->getQuery()->getResult();
  9614.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  9615.             } else
  9616.                 $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9617.                     ->findOneBy(
  9618.                         array(
  9619. //                        'productByCodeId' => $id,
  9620.                             'CompanyId' => $companyId
  9621.                         ), array(
  9622.                             'productByCodeId' => 'DESC'
  9623.                         )
  9624.                     );
  9625.             if ($productByCodeData)
  9626.                 $id $productByCodeData->getProductByCodeId();
  9627.         }
  9628.         if ($id != 0) {
  9629.             $productByCodeDataObj = array(
  9630.                 'salesCode' => $productByCodeData->getSalesCode(),
  9631.                 'sales_code' => $productByCodeData->getSalesCode(),
  9632.                 'sn' => $productByCodeData->getSerialNo(),
  9633.                 'serialNo' => $productByCodeData->getSerialNo(),
  9634.                 'imei1' => $productByCodeData->getImei1(),
  9635.                 'imei2' => $productByCodeData->getImei2(),
  9636.                 'soId' => $productByCodeData->getSalesOrderId(),
  9637.                 'poId' => $productByCodeData->getPurchaseOrderId(),
  9638.                 'irrId' => $productByCodeData->getIrrId(),
  9639.                 'productId' => $productByCodeData->getProductId(),
  9640.                 'productByCodeId' => $productByCodeData->getProductByCodeId(),
  9641.                 'warehouseId' => $productByCodeData->getWarehouseId(),
  9642.                 'warehouseActionId' => $productByCodeData->getWarehouseActionId(),
  9643.                 'stId' => $productByCodeData->getStockTransferId(),
  9644.                 'srId' => $productByCodeData->getStockReceivedNoteId(),
  9645.                 'scmpId' => $productByCodeData->getStockConsumptionNoteId(),
  9646.                 'clientId' => $productByCodeData->getClientId(),
  9647.                 'supplierId' => $productByCodeData->getSupplierId(),
  9648.                 'drId' => $productByCodeData->getDeliveryReceiptId(),
  9649.                 'consumerName' => $productByCodeData->getConsumerName(),
  9650.                 'drItemData' => [],
  9651. //                'salesCodes' => $productByCodeData->getDeliveryReceiptId(),
  9652.             );
  9653.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9654.                 ->findOneBy(
  9655.                     array(
  9656.                         'id' => $productByCodeData->getProductId()
  9657.                     )
  9658.                 );
  9659.             if ($productByCodeData->getProductionId() != null) {
  9660.                 $productionDataHere $em->getRepository('ApplicationBundle:Production')
  9661.                     ->findOneBy(
  9662.                         array(
  9663.                             'productionId' => $productByCodeData->getProductionId()
  9664.                         )
  9665.                     );
  9666.                 if ($productionDataHere) {
  9667.                     $productDataWeightPackageGm $productionDataHere->getPackageWeight();
  9668.                     $productDataWeightVarianceValue $productionDataHere->getPackageWeightVarianceValue();
  9669.                     $productDataWeightVarianceType $productionDataHere->getPackageWeightVarianceType();
  9670.                 }
  9671.             } else {
  9672.                 if ($productData) {
  9673.                     $productDataWeightPackageGm $productData->getWeight();
  9674.                     $productDataWeightVarianceValue $productData->getWeightVarianceValue();
  9675.                     $productDataWeightVarianceType $productData->getWeightVarianceType();
  9676.                 }
  9677.             }
  9678.             if ($productData) {
  9679.                 $productByCodeDataObj['unitTypeId'] = $productData->getUnitTypeId();
  9680.                 $productByCodeDataObj['purchasePrice'] = $productData->getPurchasePrice();
  9681.                 $productByCodeDataObj['productFdm'] = $productData->getProductFdm();
  9682.                 $productByCodeDataObj['productName'] = $productData->getName();
  9683.                 if ($request->request->has('forSalesReturn') || $request->query->has('forSalesReturn')) {
  9684.                     $QD $this->getDoctrine()
  9685.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  9686.                         ->findOneBy(
  9687.                             array(
  9688.                                 'deliveryReceiptId' => $productByCodeData->getDeliveryReceiptId(),
  9689.                                 'productId' => $productByCodeData->getProductId(),
  9690.                             )
  9691.                         );
  9692. //            if($request->request->get('wareHouseId')!='')
  9693.                     if ($QD) {
  9694.                         $new_pid $QD->getProductId();
  9695.                         $sales_code_range = [];
  9696.                         if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  9697.                             $sales_code_range json_decode($QD->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  9698.                         } else {
  9699.                             $max_int_length strlen((string)PHP_INT_MAX) - 1;
  9700.                             $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$QD->getSalesCodeRange());
  9701.                             $sales_code_range json_decode($json_without_bigintstrue);
  9702.                         }
  9703.                         $p_data = array(
  9704.                             'details_id' => $QD->getId(),
  9705.                             'productId' => $new_pid,
  9706.                             'dr_id' => $productByCodeData->getDeliveryReceiptId(),
  9707.                             'product_name' => $productData->getName(),
  9708.                             'qty' => $QD->getQty(),
  9709.                             'delivered' => $QD->getDelivered(),
  9710.                             'unitTypeId' => $QD->getUnitTypeId(),
  9711.                             'deliverable' => $QD->getDeliverable(),
  9712.                             'balance' => $QD->getBalance(),
  9713.                             'salesCodeRangeStr' => $QD->getSalesCodeRange(),
  9714.                             'salesCodeRange' => $sales_code_range,
  9715.                             'sales_codes' => $sales_code_range,
  9716.                             'sales_price' => $QD->getPrice(),
  9717.                             'purchase_price' => $QD->getCurrentPurchasePrice()
  9718. //                        'delivered'=>$product->getDelivered(),
  9719.                         );
  9720.                         $productByCodeDataObj['drItemData'][] = $p_data;
  9721.                     }
  9722.                 }
  9723.             }
  9724.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9725.                 ->findBy(
  9726.                     array(
  9727.                         'productId' => $id
  9728.                     )
  9729.                 );
  9730.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  9731.                 array(
  9732.                     'page_title' => 'Details',
  9733.                     'company_data' => $company_data,
  9734.                     'productByCodeData' => $productByCodeData,
  9735.                     'productByCodeDataObj' => $productByCodeDataObj,
  9736.                     'productData' => $productData,
  9737.                     'currInvList' => $currInvList,
  9738.                     'productDataWeightPackageGm' => $productDataWeightPackageGm,
  9739.                     'productDataWeightVarianceValue' => $productDataWeightVarianceValue,
  9740.                     'productDataWeightVarianceType' => $productDataWeightVarianceType,
  9741.                     'exId' => $id,
  9742.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9743.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9744.                     'productList' => Inventory::ProductList($em$companyId),
  9745.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9746.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9747.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9748.                     'unitList' => Inventory::UnitTypeList($em),
  9749.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9750.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9751.                     'warehouseList' => Inventory::WarehouseList($em),
  9752.                 )
  9753.             ));
  9754.         } else {
  9755.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  9756.                 array(
  9757.                     'exId' => $id,
  9758.                 )
  9759.             ));
  9760.         }
  9761.         if ($request->query->has('returnJson')) {
  9762.             return new JsonResponse(
  9763.                 array(
  9764.                     'success' => true,
  9765.                     'page_title' => 'Product Details',
  9766.                     'company_data' => $company_data,
  9767.                     'renderedHtml' => $html,
  9768.                     'exId' => $id,
  9769.                     'productByCodeDataObj' => $productByCodeDataObj,
  9770. //                'productData' => $productData,
  9771. //                'currInvList' => $currInvList,
  9772. //                'productList' => Inventory::ProductList($em, $companyId),
  9773. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9774. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9775. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9776. //                'unitList' => Inventory::UnitTypeList($em),
  9777. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9778. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9779. //                'warehouseList' => Inventory::WarehouseList($em),
  9780.                 )
  9781.             );
  9782.         } else {
  9783. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9784. //                ->findBy(
  9785. //                    array(
  9786. ////                        'productByCodeId' => $id,
  9787. //                    'CompanyId'=>$companyId
  9788. //                    )
  9789. //                );
  9790.             $productByCodeList = []; //called by ajax
  9791.             return $this->render('@Inventory/pages/views/product_by_code_assign_check_print.html.twig',
  9792.                 array(
  9793.                     'page_title' => 'Serial Manager',
  9794.                     'company_data' => $company_data,
  9795.                     'renderedHtml' => $html,
  9796.                     'exId' => $id,
  9797.                     'productByCodeList' => $productByCodeList,
  9798.                     'productByCodeDataObj' => $productByCodeDataObj,
  9799. //                'productByCodeData' => $productByCodeData,
  9800. //                'productData' => $productData,
  9801. //                'currInvList' => $currInvList,
  9802. //                'productList' => Inventory::ProductList($em, $companyId),
  9803. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9804. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9805. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9806. //                'unitList' => Inventory::UnitTypeList($em),
  9807. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9808. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9809. //                'warehouseList' => Inventory::WarehouseList($em),
  9810.                 )
  9811.             );
  9812.         }
  9813.     }
  9814.     public
  9815.     function TestProductByCodeCheckAssignPrintAction(Request $request$id 0)
  9816.     {
  9817.         $em $this->getDoctrine()->getManager();
  9818.         $companyId $this->getLoggedUserCompanyId($request);
  9819.         $company_data Company::getCompanyData($em$companyId);
  9820.         $data = [];
  9821.         $html '';
  9822.         $productByCodeData = [];
  9823.         $productByCodeDataObj = [];
  9824.         if ($id != 0) {
  9825.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9826.                 ->findOneBy(
  9827.                     array(
  9828.                         'productByCodeId' => $id
  9829.                     )
  9830.                 );
  9831.         } else {
  9832.             if ($request->query->has('scanCode')) {
  9833.                 $query $em->getRepository('ApplicationBundle:ProductByCode')
  9834.                     ->createQueryBuilder('p');
  9835.                 if ($request->query->has('assigned')) {
  9836.                     $query->where('p.assigned > :av')
  9837.                         ->setParameter('av'$request->query->get('assigned'));
  9838.                 } else
  9839.                     $query->where("1=0");
  9840.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  9841.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  9842.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  9843.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  9844.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  9845.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  9846.                 $query->setMaxResults(1);
  9847.                 $results $query->getQuery()->getResult();
  9848.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  9849.             } else
  9850.                 $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9851.                     ->findOneBy(
  9852.                         array(
  9853. //                        'productByCodeId' => $id,
  9854.                             'CompanyId' => $companyId
  9855.                         ), array(
  9856.                             'productByCodeId' => 'DESC'
  9857.                         )
  9858.                     );
  9859.             if ($productByCodeData)
  9860.                 $id $productByCodeData->getProductByCodeId();
  9861.         }
  9862.         if ($id != 0) {
  9863.             $productByCodeDataObj = array(
  9864.                 'sn' => $productByCodeData->getSalesCode(),
  9865.                 'imei1' => $productByCodeData->getImei1(),
  9866.                 'imei2' => $productByCodeData->getImei2(),
  9867.                 'colorId' => $productByCodeData->getColorId(),
  9868.             );
  9869.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9870.                 ->findOneBy(
  9871.                     array(
  9872.                         'id' => $productByCodeData->getProductId()
  9873.                     )
  9874.                 );
  9875.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9876.                 ->findBy(
  9877.                     array(
  9878.                         'productId' => $id
  9879.                     )
  9880.                 );
  9881.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  9882.                 array(
  9883.                     'page_title' => 'Details',
  9884.                     'company_data' => $company_data,
  9885.                     'productByCodeData' => $productByCodeData,
  9886.                     'productData' => $productData,
  9887.                     'currInvList' => $currInvList,
  9888.                     'exId' => $id,
  9889.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9890.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9891.                     'productList' => Inventory::ProductList($em$companyId),
  9892.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9893.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9894.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9895.                     'unitList' => Inventory::UnitTypeList($em),
  9896.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9897.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9898.                     'warehouseList' => Inventory::WarehouseList($em),
  9899.                 )
  9900.             );
  9901.         } else {
  9902.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  9903.                 array(
  9904.                     'exId' => $id,
  9905.                 )
  9906.             );
  9907.         }
  9908.         if ($request->query->has('returnJson')) {
  9909.             return new JsonResponse(
  9910.                 array(
  9911.                     'success' => true,
  9912.                     'page_title' => 'Product Details',
  9913.                     'company_data' => $company_data,
  9914.                     'renderedHtml' => $html,
  9915.                     'exId' => $id,
  9916.                     'productByCodeDataObj' => $productByCodeDataObj,
  9917. //                'productData' => $productData,
  9918. //                'currInvList' => $currInvList,
  9919. //                'productList' => Inventory::ProductList($em, $companyId),
  9920. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9921. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9922. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9923. //                'unitList' => Inventory::UnitTypeList($em),
  9924. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9925. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9926. //                'warehouseList' => Inventory::WarehouseList($em),
  9927.                 )
  9928.             );
  9929.         } else {
  9930. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9931. //                ->findBy(
  9932. //                    array(
  9933. ////                        'productByCodeId' => $id,
  9934. //                    'CompanyId'=>$companyId
  9935. //                    )
  9936. //                );
  9937.             $productByCodeList = []; //called by ajax
  9938.             return $this->render('@Inventory/pages/views/test_product_by_code_assign_check_print.html.twig',
  9939.                 array(
  9940.                     'page_title' => ' Test Serial Manager',
  9941.                     'company_data' => $company_data,
  9942.                     'renderedHtml' => $html,
  9943.                     'exId' => $id,
  9944.                     'productByCodeList' => $productByCodeList,
  9945.                     'productByCodeDataObj' => $productByCodeDataObj,
  9946. //                'productByCodeData' => $productByCodeData,
  9947. //                'productData' => $productData,
  9948. //                'currInvList' => $currInvList,
  9949. //                'productList' => Inventory::ProductList($em, $companyId),
  9950. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9951. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9952. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9953. //                'unitList' => Inventory::UnitTypeList($em),
  9954. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9955. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9956. //                'warehouseList' => Inventory::WarehouseList($em),
  9957.                 )
  9958.             );
  9959.         }
  9960.     }
  9961.     public
  9962.     function DeleteProductAction(Request $request$id '')
  9963.     {
  9964.         $em $this->getDoctrine()->getManager();
  9965.         $idListArray = [];
  9966.         if ($request->isMethod('POST')) {
  9967.             if ($id == 0)
  9968.                 $id $request->request->get('productId');
  9969.             //now check the product closing , if nothing then we cna remove it
  9970.             $query_here $this->getDoctrine()
  9971.                 ->getRepository('ApplicationBundle:InvClosingBalance')
  9972.                 ->findBy(
  9973.                     array(
  9974.                         'productId' => $request->request->get('productId')
  9975.                     )
  9976.                 );
  9977.             if (!empty($query_here)) {
  9978.                 return new JsonResponse(
  9979.                     array(
  9980.                         'success' => false,
  9981.                     )
  9982.                 );
  9983.             } else {
  9984.                 $qry $em->getRepository('ApplicationBundle:ProductByCode')->findBy(array(
  9985.                     'productId' => $id
  9986.                 ));
  9987.                 foreach ($qry as $det) {
  9988.                     //remove any barcoded products
  9989.                     $em->remove($det);
  9990.                     $em->flush();
  9991.                 }
  9992.                 $qry $em->getRepository('ApplicationBundle:InvProducts')->findBy(array(
  9993.                     'id' => $id
  9994.                 ));
  9995.                 foreach ($qry as $det) {
  9996.                     //remove any barcoded products
  9997.                     $em->remove($det);
  9998.                     $em->flush();
  9999.                 }
  10000.                 $qry $em->getRepository('ApplicationBundle:InvItemTransaction')->findBy(array(
  10001.                     'productId' => $id
  10002.                 ));
  10003.                 foreach ($qry as $det) {
  10004.                     //remove any barcoded products
  10005.                     $em->remove($det);
  10006.                     $em->flush();
  10007.                 }
  10008.                 return new JsonResponse(
  10009.                     array(
  10010.                         'success' => true,
  10011.                     )
  10012.                 );
  10013.             }
  10014.         }
  10015.         return new JsonResponse(
  10016.             array(
  10017.                 'success' => false,
  10018.             )
  10019.         );
  10020.     }
  10021.     public
  10022.     function RegisterProductAction(Request $request$idListStr '')
  10023.     {
  10024.         $em $this->getDoctrine()->getManager();
  10025.         $companyId $this->getLoggedUserCompanyId($request);
  10026.         $company_data Company::getCompanyData($em$companyId);
  10027.         $session $request->getSession();
  10028. //        System::setSessionForUser($session );
  10029.         $idListArray = [];
  10030.         if ($idListStr != '')
  10031.             $idListArray explode(','$idListStr);
  10032.         $data = [];
  10033. //        if ($request->isMethod('POST')) {
  10034. //            $post = $request->request;
  10035. //            if ($request->request->get('formatId') != '') {
  10036. //                $query_here = $this->getDoctrine()
  10037. //                    ->getRepository('ApplicationBundle:CheckFormat')
  10038. //                    ->findOneBy(
  10039. //                        array(
  10040. //                            'formatId' => $request->request->get('formatId')
  10041. //                        )
  10042. //                    );
  10043. //                if (!empty($query_here))
  10044. //                    $new = $query_here;
  10045. //            } else
  10046. //                $new = new CheckFormat();
  10047. //            $new->setName($request->request->get('name'));
  10048. //            $new->setWidth($request->request->get('width'));
  10049. //            $new->setHeight($request->request->get('height'));
  10050. //            $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
  10051. //            $new->setCheckPayToTop($request->request->get('checkPayToTop'));
  10052. //            $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
  10053. //            $new->setCheckAmountTop($request->request->get('checkAmountTop'));
  10054. //            $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
  10055. //            $new->setCheckAiWTop($request->request->get('checkAiWTop'));
  10056. //            $new->setCheckDateLeft($request->request->get('checkDateLeft'));
  10057. //            $new->setCheckDateTop($request->request->get('checkDateTop'));
  10058. //            $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
  10059. //            $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
  10060. //            $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
  10061. //            $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
  10062. //            $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
  10063. //            $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
  10064. //            $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
  10065. //            $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
  10066. //            $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
  10067. //            $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
  10068. //            $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 1 : 0);
  10069. //            $new->setCheckImage($request->request->get('checkImage'));
  10070. //
  10071. //            $em = $this->getDoctrine()->getManager();
  10072. //            $em->persist($new);
  10073. //            $em->flush();
  10074. //
  10075. //        }
  10076. //        if (!empty($idListArray)) {
  10077. //            $query_here = $this->getDoctrine()
  10078. //                ->getRepository('ApplicationBundle:ProductByCode')
  10079. //                ->findBy(
  10080. //                    array(
  10081. //                        'productByCodeId' => $idListArray
  10082. //                    )
  10083. //                );
  10084. //            if (!empty($query_here))
  10085. //                $data = $query_here;
  10086. //
  10087. //        }
  10088. //        else if ($request->query->has('formatId')) {
  10089. //            $query_here = $this->getDoctrine()
  10090. //                ->getRepository('ApplicationBundle:CheckFormat')
  10091. //                ->findOneBy(
  10092. //                    array(
  10093. //                        'formatId' => $request->query->get('formatId')
  10094. //                    )
  10095. //                );
  10096. //            if (!empty($query_here))
  10097. //                $data = $query_here;
  10098. //        }
  10099.         $data = [];
  10100.         $html '';
  10101.         $productByCodeData = [];
  10102.         if ($request->query->has('returnJson')) {
  10103.             return new JsonResponse(
  10104.                 array(
  10105.                     'success' => true,
  10106.                     'page_title' => 'Product Details',
  10107.                     'company_data' => $company_data,
  10108.                     'renderedHtml' => $html,
  10109.                     'data' => $data,
  10110.                     'idListArray' => $idListArray,
  10111. //                    'exId'=>$id,
  10112. //                'productByCodeData' => $productByCodeData,
  10113. //                'productData' => $productData,
  10114. //                'currInvList' => $currInvList,
  10115. //                'productList' => Inventory::ProductList($em, $companyId),
  10116. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10117. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10118. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10119. //                'unitList' => Inventory::UnitTypeList($em),
  10120. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10121. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10122. //                'warehouseList' => Inventory::WarehouseList($em),
  10123.                 )
  10124.             );
  10125.         } else {
  10126.             return $this->render('@Inventory/pages/input_forms/register_product.html.twig',
  10127.                 array(
  10128.                     'page_title' => 'Register Product',
  10129.                     'company_data' => $company_data,
  10130.                     'renderedHtml' => $html,
  10131. //                    'exIdList'=>$i,
  10132.                     'idListArray' => $idListArray,
  10133.                     'data' => $data,
  10134.                     'productByCodeList' => [],
  10135.                     'productByCodeData' => [],
  10136.                     'productList' => Inventory::ProductList($em$companyId),
  10137.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10138.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10139.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10140.                     'unitList' => Inventory::UnitTypeList($em),
  10141.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10142.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10143.                     'warehouseList' => Inventory::WarehouseList($em),
  10144.                 )
  10145.             );
  10146.         }
  10147.     }
  10148.     public
  10149.     function BrandViewAction(Request $request)
  10150.     {
  10151.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  10152.             array(
  10153.                 'page_title' => 'Stock Return'
  10154.             )
  10155.         );
  10156.     }
  10157.     public
  10158.     function PrintTableDataAction(Request $request)
  10159.     {
  10160.         $em $this->getDoctrine()->getManager();
  10161.         $company_data Company::getCompanyData($em1);
  10162.         $data = [];
  10163.         $print_title "test";
  10164.         $document_mark = array(
  10165.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10166.             'copy' => ''
  10167.         );
  10168.         $mis_data = [];
  10169.         $p 1;
  10170.         return $this->render('@Inventory/pages/print/print_table_data.html.twig',
  10171.             array(
  10172.                 'page_title' => 'Data Report',
  10173.                 'data' => $data,
  10174.                 'page_header' => 'Report',
  10175.                 'print_title' => $print_title,
  10176.                 'document_type' => 'Journal voucher',
  10177.                 'document_mark_image' => $document_mark['original'],
  10178.                 'page_header_sub' => 'Add',
  10179. //                'type_list'=>$type_list,
  10180.                 'mis_data' => $mis_data,
  10181.                 'item_data' => [],
  10182.                 'received' => 2,
  10183.                 'return' => 1,
  10184.                 'total_w_vat' => 1,
  10185.                 'total_vat' => 1,
  10186.                 'total_wo_vat' => 1,
  10187.                 'invoice_id' => 'abcd1234',
  10188.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10189.                 'created_by' => 'created by',
  10190.                 'created_at' => '',
  10191.                 'red' => 0,
  10192.                 'company_name' => $company_data->getName(),
  10193.                 'company_data' => $company_data,
  10194.                 'company_address' => $company_data->getAddress(),
  10195.                 'company_image' => $company_data->getImage(),
  10196.                 'p' => $p
  10197.             )
  10198.         );
  10199.     }
  10200.     public
  10201.     function ReplacementReportAction(Request $request)
  10202.     {
  10203.         $qry_data = array(
  10204.             'warehouseId' => [0],
  10205.             'igId' => [0],
  10206.             'brandId' => [0],
  10207.             'categoryId' => [0],
  10208.             'actionTagId' => [0],
  10209.         );
  10210.         $em $this->getDoctrine()->getManager();
  10211.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  10212.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  10213.         $data_searched = [];
  10214.         $companyId $this->getLoggedUserCompanyId($request);
  10215.         $company_data Company::getCompanyData($em$companyId);
  10216.         $data = [];
  10217.         $print_title "Inventory Report";
  10218.         $document_mark = array(
  10219.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10220.             'copy' => ''
  10221.         );
  10222.         $post_data $request->request;
  10223.         $start_date $post_data->has('start_date') ? $post_data->get('start_date') : '';
  10224.         $end_date $post_data->has('end_date') ? $post_data->get('end_date') : '';
  10225.         if ($request->isMethod('POST'))
  10226.             $method 'POST';
  10227.         else
  10228.             $method 'GET';
  10229.         {
  10230. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  10231.             $data_searched Inventory::GetReplacementReportData($this->getDoctrine()->getManager(),
  10232.                 $request->request$method,
  10233.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  10234.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  10235.                 return new JsonResponse(
  10236.                     array(
  10237.                         'page_title' => 'Inventory ',
  10238.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10239.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10240.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10241.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10242.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10243.                         'action_tag' => $warehouse_action_list,
  10244.                         'start_date' => $start_date,
  10245.                         'end_date' => $end_date,
  10246.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10247.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10248.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10249.                         'data_searched' => $data_searched,
  10250.                         'success' => empty($data_searched['query_result']) ? false true
  10251.                     )
  10252.                 );
  10253.             }
  10254.             if ($request->request->get('print_data_enabled') == 1) {
  10255.                 $print_sub_title "";
  10256.                 return $this->render('@Inventory/pages/print/print_replacement_report.html.twig',
  10257.                     array(
  10258.                         'page_title' => 'Replacement Report',
  10259.                         'page_header' => 'Report',
  10260.                         'print_title' => $print_title,
  10261.                         'document_type' => 'Journal voucher',
  10262.                         'document_mark_image' => $document_mark['original'],
  10263.                         'page_header_sub' => 'Add',
  10264.                         'item_data' => [],
  10265.                         'received' => 2,
  10266.                         'return' => 1,
  10267.                         'total_w_vat' => 1,
  10268.                         'total_vat' => 1,
  10269.                         'total_wo_vat' => 1,
  10270.                         'invoice_id' => 'abcd1234',
  10271.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  10272.                         'created_by' => 'created by',
  10273.                         'created_at' => '',
  10274.                         'red' => 0,
  10275.                         'company_name' => $company_data->getName(),
  10276.                         'company_data' => $company_data,
  10277.                         'company_address' => $company_data->getAddress(),
  10278.                         'company_image' => $company_data->getImage(),
  10279.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10280.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10281.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10282.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10283.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10284.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10285.                         'action_tag' => $warehouse_action_list,
  10286.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10287.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10288.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10289.                         'start_date' => $start_date,
  10290.                         'end_date' => $end_date,
  10291.                         'data_searched' => $data_searched
  10292.                     )
  10293.                 );
  10294.             }
  10295.         }
  10296.         return $this->render('@Inventory/pages/report/replacement_report.html.twig',
  10297.             array(
  10298.                 'page_title' => 'Replacement Report',
  10299.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10300.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10301.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10302.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10303.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10304. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10305.                 'action_tag' => $warehouse_action_list,
  10306.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10307.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10308.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10309.                 'start_date' => $start_date,
  10310.                 'end_date' => $end_date,
  10311.                 'data_searched' => $data_searched,
  10312.                 'success' => empty($data_searched['query_result']) ? false true
  10313.             )
  10314.         );
  10315.     }
  10316.     public
  10317.     function InventoryViewAction(Request $request)
  10318.     {
  10319.         $qry_data = array(
  10320.             'warehouseId' => [0],
  10321.             'igId' => [0],
  10322.             'brandId' => [0],
  10323.             'categoryId' => [0],
  10324.             'actionTagId' => [0],
  10325.         );
  10326.         $em $this->getDoctrine()->getManager();
  10327.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  10328.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  10329.         $data_searched = [];
  10330.         $companyId $this->getLoggedUserCompanyId($request);
  10331.         $company_data Company::getCompanyData($em$companyId);
  10332.         $data = [];
  10333.         $print_title "Inventory Report";
  10334.         $document_mark = array(
  10335.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10336.             'copy' => ''
  10337.         );
  10338.         if ($request->isMethod('POST'))
  10339.             $method 'POST';
  10340.         else
  10341.             $method 'GET';
  10342.         {
  10343. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  10344.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  10345.                 $request->request$method,
  10346.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  10347.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  10348.                 return new JsonResponse(
  10349.                     array(
  10350.                         'page_title' => 'Inventory ',
  10351.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10352.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10353.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10354.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10355.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10356.                         'action_tag' => $warehouse_action_list,
  10357.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10358.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10359.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10360.                         'data_searched' => $data_searched,
  10361.                         'success' => empty($data_searched['query_result']) ? false true
  10362.                     )
  10363.                 );
  10364.             }
  10365.             if ($request->request->get('print_data_enabled') == 1) {
  10366.                 $print_sub_title "";
  10367.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  10368.                     array(
  10369.                         'page_title' => 'Inventory Report',
  10370.                         'page_header' => 'Report',
  10371.                         'print_title' => $print_title,
  10372.                         'document_type' => 'Journal voucher',
  10373.                         'document_mark_image' => $document_mark['original'],
  10374.                         'page_header_sub' => 'Add',
  10375.                         'item_data' => [],
  10376.                         'received' => 2,
  10377.                         'return' => 1,
  10378.                         'total_w_vat' => 1,
  10379.                         'total_vat' => 1,
  10380.                         'total_wo_vat' => 1,
  10381.                         'invoice_id' => 'abcd1234',
  10382.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  10383.                         'created_by' => 'created by',
  10384.                         'created_at' => '',
  10385.                         'red' => 0,
  10386.                         'company_name' => $company_data->getName(),
  10387.                         'company_data' => $company_data,
  10388.                         'company_address' => $company_data->getAddress(),
  10389.                         'company_image' => $company_data->getImage(),
  10390.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10391.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10392.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10393.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10394.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10395.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10396.                         'action_tag' => $warehouse_action_list,
  10397.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10398.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10399.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10400.                         'data_searched' => $data_searched
  10401.                     )
  10402.                 );
  10403.             }
  10404.         }
  10405.         return $this->render('@Inventory/pages/report/inventory_view.html.twig',
  10406.             array(
  10407.                 'page_title' => 'Inventory',
  10408.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10409.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10410.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10411.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10412.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10413. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10414.                 'action_tag' => $warehouse_action_list,
  10415.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10416.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10417.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10418.                 'data_searched' => $data_searched
  10419.             )
  10420.         );
  10421.     }
  10422.     public
  10423.     function GrnListAction(Request $request)
  10424.     {
  10425.         $q $this->getDoctrine()
  10426.             ->getRepository('ApplicationBundle:Grn')
  10427.             ->findBy(
  10428.                 array(
  10429.                     'status' => GeneralConstant::ACTIVE,
  10430. //                    'approved' =>  GeneralConstant::APPROVED,
  10431.                 )
  10432.             );
  10433.         $stage_list = array(
  10434.             => 'Pending',
  10435.             => 'Pending',
  10436.             => 'Complete',
  10437.             => 'Partial',
  10438.         );
  10439.         $data = [];
  10440.         foreach ($q as $entry) {
  10441.             $data[] = array(
  10442.                 'doc_date' => $entry->getGrnDate(),
  10443.                 'id' => $entry->getGrnId(),
  10444.                 'doc_hash' => $entry->getDocumentHash(),
  10445.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  10446.                 'stage' => $stage_list[$entry->getStage()]
  10447.             );
  10448.         }
  10449.         return $this->render('@Inventory/pages/views/grn_list.html.twig',
  10450.             array(
  10451.                 'page_title' => 'Grn List',
  10452.                 'data' => $data
  10453.             )
  10454.         );
  10455.     }
  10456.     public
  10457.     function ViewGrnAction(Request $request$id)
  10458.     {
  10459.         $em $this->getDoctrine()->getManager();
  10460.         $dt Inventory::GetGrnDetails($em$id);
  10461.         return $this->render('@Inventory/pages/views/view_grn.html.twig',
  10462.             array(
  10463.                 'page_title' => 'View',
  10464.                 'data' => $dt,
  10465.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  10466.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10467.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10468.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10469.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10470.                     $id,
  10471.                     $dt['created_by'],
  10472.                     $dt['edited_by'])
  10473.             )
  10474.         );
  10475.     }
  10476.     public
  10477.     function PrintGrnAction(Request $request$id)
  10478.     {
  10479.         $em $this->getDoctrine()->getManager();
  10480.         $dt Inventory::GetGrnDetails($em$id);
  10481.         $company_data Company::getCompanyData($em1);
  10482.         $document_mark = array(
  10483.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10484.             'copy' => ''
  10485.         );
  10486.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10487.             $html $this->renderView('@Inventory/pages/print/print_received_note.html.twig',
  10488.                 array(
  10489.                     //full array here
  10490.                     'pdf' => true,
  10491.                     'page_title' => 'Grn',
  10492.                     'export' => 'pdf,print',
  10493.                     'data' => $dt,
  10494.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10495.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10496.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10497.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10498.                         $id,
  10499.                         $dt['created_by'],
  10500.                         $dt['edited_by']),
  10501.                     'document_mark_image' => $document_mark['original'],
  10502.                     'company_name' => $company_data->getName(),
  10503.                     'company_data' => $company_data,
  10504.                     'company_address' => $company_data->getAddress(),
  10505.                     'company_image' => $company_data->getImage(),
  10506.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10507.                     'red' => 0
  10508.                 )
  10509.             );
  10510.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10511. //                'orientation' => 'landscape',
  10512. //                'enable-javascript' => true,
  10513. //                'javascript-delay' => 1000,
  10514.                 'no-stop-slow-scripts' => false,
  10515.                 'no-background' => false,
  10516.                 'lowquality' => false,
  10517.                 'encoding' => 'utf-8',
  10518. //            'images' => true,
  10519. //            'cookie' => array(),
  10520.                 'dpi' => 300,
  10521.                 'image-dpi' => 300,
  10522. //                'enable-external-links' => true,
  10523. //                'enable-internal-links' => true
  10524.             ));
  10525.             return new Response(
  10526.                 $pdf_response,
  10527.                 200,
  10528.                 array(
  10529.                     'Content-Type' => 'application/pdf',
  10530.                     'Content-Disposition' => 'attachment; filename="grn.pdf"'
  10531.                 )
  10532.             );
  10533.         }
  10534.         return $this->render('@Inventory/pages/print/print_received_note.html.twig',
  10535.             array(
  10536.                 'page_title' => 'Grn',
  10537.                 'export' => 'pdf,print',
  10538.                 'data' => $dt,
  10539.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10540.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10541.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10542.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10543.                     $id,
  10544.                     $dt['created_by'],
  10545.                     $dt['edited_by']),
  10546.                 'document_mark_image' => $document_mark['original'],
  10547.                 'company_name' => $company_data->getName(),
  10548.                 'company_data' => $company_data,
  10549.                 'company_address' => $company_data->getAddress(),
  10550.                 'company_image' => $company_data->getImage(),
  10551.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10552.                 'red' => 0
  10553.             )
  10554.         );
  10555.     }
  10556.     public
  10557.     function PrintGrnBarcodeAction(Request $request$id)
  10558.     {
  10559.         $em $this->getDoctrine()->getManager();
  10560.         $dt Inventory::GetGrnDetails($em$id);
  10561.         $company_data Company::getCompanyData($em1);
  10562.         $repeatCount 1;
  10563.         if ($request->query->has('repeatCount'))
  10564.             $repeatCount $request->query->get('repeatCount');
  10565.         $document_mark = array(
  10566.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10567.             'copy' => ''
  10568.         );
  10569.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10570.             $html $this->renderView('@Inventory/pages/print/print_grn_barcodes.html.twig',
  10571.                 array(
  10572.                     //full array here
  10573.                     'pdf' => true,
  10574.                     'page_title' => 'Grn Barcodes',
  10575.                     'export' => 'print',
  10576.                     'data' => $dt,
  10577.                     'repeatCount' => $repeatCount,
  10578.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10579.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10580.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10581.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10582.                         $id,
  10583.                         $dt['created_by'],
  10584.                         $dt['edited_by']),
  10585.                     'document_mark_image' => $document_mark['original'],
  10586.                     'company_name' => $company_data->getName(),
  10587.                     'company_data' => $company_data,
  10588.                     'company_address' => $company_data->getAddress(),
  10589.                     'company_image' => $company_data->getImage(),
  10590.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10591.                     'red' => 0
  10592.                 )
  10593.             );
  10594.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10595. //                'orientation' => 'landscape',
  10596.                 'enable-javascript' => true,
  10597. //                'javascript-delay' => 1000,
  10598.                 'no-stop-slow-scripts' => false,
  10599.                 'no-background' => false,
  10600.                 'lowquality' => false,
  10601.                 'encoding' => 'utf-8',
  10602. //            'images' => true,
  10603. //            'cookie' => array(),
  10604.                 'dpi' => 300,
  10605.                 'image-dpi' => 300,
  10606. //                'enable-external-links' => true,
  10607. //                'enable-internal-links' => true
  10608.             ));
  10609.             return new Response(
  10610.                 $pdf_response,
  10611.                 200,
  10612.                 array(
  10613.                     'Content-Type' => 'application/pdf',
  10614.                     'Content-Disposition' => 'attachment; filename="grn_barcodes.pdf"'
  10615.                 )
  10616.             );
  10617.         }
  10618.         return $this->render('@Inventory/pages/print/print_grn_barcodes.html.twig',
  10619.             array(
  10620.                 'page_title' => 'Grn barcodes',
  10621. //                'export'=>'pdf,print',
  10622.                 'data' => $dt,
  10623.                 'repeatCount' => $repeatCount,
  10624.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10625.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10626.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10627.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10628.                     $id,
  10629.                     $dt['created_by'],
  10630.                     $dt['edited_by']),
  10631.                 'document_mark_image' => $document_mark['original'],
  10632.                 'company_name' => $company_data->getName(),
  10633.                 'company_data' => $company_data,
  10634.                 'company_address' => $company_data->getAddress(),
  10635.                 'company_image' => $company_data->getImage(),
  10636.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10637.                 'red' => 0
  10638.             )
  10639.         );
  10640.     }
  10641.     public
  10642.     function GenerateBarcodeAction(Request $request$type$id$item_id)
  10643.     {
  10644.         $em $this->getDoctrine()->getManager();
  10645.         $repeatCount 1;
  10646.         $spec_item_id 0;
  10647.         $skip_ids = [];
  10648.         $clearUnnecessaryOnly 0;
  10649.         if ($request->query->has('skipIds'))
  10650.             $skip_ids $request->query->get('skipIds');
  10651.         if ($request->query->has('clearUnnecessaryOnly'))
  10652.             $clearUnnecessaryOnly $request->query->get('clearUnnecessaryOnly');
  10653.         if ($type == 'srcv') {
  10654.             $doc_data $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  10655.                 array(
  10656.                     'stockReceivedNoteId' => $id
  10657.                 )
  10658.             );
  10659.             if ($item_id == '_single_') {
  10660.                 $doc_item_data $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
  10661.                     array(
  10662.                         'stockReceivedNoteId' => $id,
  10663. //                        'id' => $item_id
  10664.                     )
  10665.                 );
  10666.             } else {
  10667.                 $doc_item_data $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
  10668.                     array(
  10669.                         'stockReceivedNoteId' => $id,
  10670.                         'id' => $item_id
  10671.                     )
  10672.                 );
  10673.             }
  10674.             $inv_acc_data = [
  10675.                 'fa_amount' => 0,
  10676.                 'tg_amount' => 0,
  10677.             ];
  10678.             $inv_acc_data_by_head = [
  10679.             ];
  10680.             $new_non_delivered_sales_code_range = [];
  10681.             foreach ($doc_item_data as $entry) {
  10682.                 //adding transaction
  10683.                 $sales_code_range_ser = [];
  10684.                 if (in_array($entry->getId(), $skip_ids))
  10685.                     continue;
  10686.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10687.                     ->findOneBy(
  10688.                         array(
  10689.                             'id' => $entry->getProductId()
  10690.                         )
  10691.                     );
  10692.                 $stitem $em->getRepository('ApplicationBundle:StockTransferItem')
  10693.                     ->findOneBy(
  10694.                         array(
  10695.                             'id' => $entry->getStockTransferItemId(),
  10696.                             'productId' => $entry->getProductId()
  10697.                         )
  10698.                     );
  10699.                 if ($product) {
  10700.                     if ($product->getHasSerial() == 1) {
  10701.                         //clear if exists
  10702.                         if ($clearUnnecessaryOnly == 1) {
  10703.                             $get_kids_sql "DELETE FROM product_by_code
  10704.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10705. //                $get_kids_sql .=' ORDER BY name ASC';
  10706.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  10707.                             $stmt->execute();
  10708.                             $em->flush();
  10709.                         } else {
  10710.                             $get_kids_sql "DELETE FROM product_by_code
  10711.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10712. //                $get_kids_sql .=' ORDER BY name ASC';
  10713.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  10714.                             $stmt->execute();
  10715.                             $em->flush();
  10716.                         }
  10717. //                        $check_here = $stmt->fetchAll();
  10718.                         //now addng product by code
  10719.                         $sales_code_range = [];
  10720.                         if ($doc_data->getType() == || $doc_data->getType() == 4) {
  10721. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10722. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10723.                             $product_action_tag_id $entry->getWarehouseActionId();
  10724.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getQty(),
  10725.                                 $doc_data->getStockReceivedNoteDate(), $entry->getWarrantyMon(), 0$doc_data->getCompanyId(), $entry->getWarehouseId(),
  10726.                                 $entry->getWarehouseActionId(), $entry->getPurchaseCodeRange(), nullnullnullnull$doc_data->getStockReceivedNoteId()
  10727.                             );
  10728.                             $sales_code_range $barcodeData['sales_code_range'];
  10729.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  10730.                             $em->flush();
  10731.                         }
  10732. //                        else {
  10733. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10734. //
  10735. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10736. //                            } else {
  10737. //
  10738. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10739. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10740. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10741. //                            }
  10742. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10743. //
  10744. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10745. //                            } else {
  10746. //
  10747. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10748. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10749. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10750. //                            }
  10751. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10752. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10753. //                            $new_non_delivered_sales_code_range = [];
  10754. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10755. //                                if (!(in_array($ndsc, $sales_code_range)))
  10756. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10757. //                            }
  10758. //                            if ($sales_code_range != null) {
  10759. //                                foreach ($sales_code_range as $ind => $dt) {
  10760. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  10761. //                                        ->findOneBy(
  10762. //                                            array(
  10763. //                                                'salesCode' => [$dt],
  10764. //                                                'productId' => $entry->getProductId()
  10765. //                                            )
  10766. //                                        );
  10767. //
  10768. //                                    if ($np) {
  10769. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10770. //                                        $np->setProductId($entry->getProductId());
  10771. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10772. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10773. //                                        $np->setPosition(1);//in warehouse
  10774. //                                        $np->setStockReceivedNoteId($id);
  10775. //
  10776. //
  10777. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10778. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10779. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10780. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10781. //                                            'direction' => 'in',
  10782. //                                            'warehouseId' => $entry->getWarehouseId(),
  10783. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10784. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10785. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10786. //                                        );
  10787. //                                        $np->setTransactionHistory(json_encode(
  10788. //                                            $trans_history
  10789. //                                        ));
  10790. //
  10791. //
  10792. //                                        $em->persist($np);
  10793. //                                        $em->flush();
  10794. //                                    }
  10795. //                                }
  10796. //                            }
  10797. //                        }
  10798.                     }
  10799.                 }
  10800.                 //adding transaction
  10801.                 if ($stitem) {
  10802.                     $stitem->setNonDeliveredSalesCodeRange(json_encode($new_non_delivered_sales_code_range));
  10803.                 }
  10804.                 $spec_item_id $entry->getId();
  10805.                 if ($item_id == '_single_') {
  10806.                     break;
  10807.                 }
  10808.             }
  10809.         }
  10810.         if ($type == 'irr') {
  10811.             $doc_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacement')->findOneBy(
  10812.                 array(
  10813.                     'itemReceivedAndReplacementId' => $id
  10814.                 )
  10815.             );
  10816.             if ($item_id == '_single_') {
  10817.                 $doc_item_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
  10818.                     array(
  10819.                         'itemReceivedAndReplacementId' => $id,
  10820. //                        'id' => $item_id
  10821.                     )
  10822.                 );
  10823.             } else {
  10824.                 $doc_item_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
  10825.                     array(
  10826.                         'itemReceivedAndReplacementId' => $id,
  10827.                         'id' => $item_id
  10828.                     )
  10829.                 );
  10830.             }
  10831.             $inv_acc_data = [
  10832.                 'fa_amount' => 0,
  10833.                 'tg_amount' => 0,
  10834.             ];
  10835.             $inv_acc_data_by_head = [
  10836.             ];
  10837.             $new_non_delivered_sales_code_range = [];
  10838.             foreach ($doc_item_data as $entry) {
  10839.                 //adding transaction
  10840.                 $sales_code_range_ser = [];
  10841.                 if (in_array($entry->getId(), $skip_ids))
  10842.                     continue;
  10843.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10844.                     ->findOneBy(
  10845.                         array(
  10846.                             'id' => $entry->getReceivedProductId()
  10847.                         )
  10848.                     );
  10849.                 if ($product) {
  10850.                     if ($product->getHasSerial() == 1) {
  10851.                         //clear if exists
  10852. //                        if($clearUnnecessaryOnly==1) {
  10853. //                            $get_kids_sql = "DELETE FROM product_by_code
  10854. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10855. ////                $get_kids_sql .=' ORDER BY name ASC';
  10856. //
  10857. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10858. //                            $stmt->execute();
  10859. //                            $em->flush();
  10860. //                        }
  10861. //                        else{
  10862. //                            $get_kids_sql = "DELETE FROM product_by_code
  10863. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10864. ////                $get_kids_sql .=' ORDER BY name ASC';
  10865. //
  10866. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10867. //                            $stmt->execute();
  10868. //                            $em->flush();
  10869. //                        }
  10870. //                        $check_here = $stmt->fetchAll();
  10871.                         //now addng product by code
  10872.                         $sales_code_range = [];
  10873.                         if ($entry->getReceivedQty() > 0) {
  10874. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10875. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10876. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  10877.                             $barcodeData Inventory::GenerateBarcode($em$entry->getReceivedProductId(), $entry->getReceivedQty(),
  10878.                                 $doc_data->getItemReceivedAndReplacementDate(), 00$doc_data->getCompanyId(), $entry->getReceivedWarehouseId(),
  10879.                                 $entry->getReceivedWarehouseActionId(), nullnullnullnullnullnullnullnull$doc_data->getItemReceivedAndReplacementId()
  10880.                             );
  10881.                             $sales_code_range $barcodeData['sales_code_range'];
  10882.                             $entry->setReceivedCodeRange(json_encode($sales_code_range));
  10883.                             $em->flush();
  10884.                         }
  10885. //                        else {
  10886. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10887. //
  10888. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10889. //                            } else {
  10890. //
  10891. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10892. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10893. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10894. //                            }
  10895. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10896. //
  10897. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10898. //                            } else {
  10899. //
  10900. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10901. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10902. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10903. //                            }
  10904. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10905. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10906. //                            $new_non_delivered_sales_code_range = [];
  10907. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10908. //                                if (!(in_array($ndsc, $sales_code_range)))
  10909. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10910. //                            }
  10911. //                            if ($sales_code_range != null) {
  10912. //                                foreach ($sales_code_range as $ind => $dt) {
  10913. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  10914. //                                        ->findOneBy(
  10915. //                                            array(
  10916. //                                                'salesCode' => [$dt],
  10917. //                                                'productId' => $entry->getProductId()
  10918. //                                            )
  10919. //                                        );
  10920. //
  10921. //                                    if ($np) {
  10922. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10923. //                                        $np->setProductId($entry->getProductId());
  10924. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10925. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10926. //                                        $np->setPosition(1);//in warehouse
  10927. //                                        $np->setStockReceivedNoteId($id);
  10928. //
  10929. //
  10930. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10931. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10932. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10933. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10934. //                                            'direction' => 'in',
  10935. //                                            'warehouseId' => $entry->getWarehouseId(),
  10936. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10937. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10938. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10939. //                                        );
  10940. //                                        $np->setTransactionHistory(json_encode(
  10941. //                                            $trans_history
  10942. //                                        ));
  10943. //
  10944. //
  10945. //                                        $em->persist($np);
  10946. //                                        $em->flush();
  10947. //                                    }
  10948. //                                }
  10949. //                            }
  10950. //                        }
  10951.                     }
  10952.                 }
  10953.                 //adding transaction
  10954.                 $spec_item_id $entry->getId();
  10955.                 if ($item_id == '_single_') {
  10956.                     break;
  10957.                 }
  10958.             }
  10959.         }
  10960.         if ($type == 'prdcn') {
  10961.             $doc_data $em->getRepository('ApplicationBundle:Production')->findOneBy(
  10962.                 array(
  10963.                     'productionId' => $id
  10964.                 )
  10965.             );
  10966.             if ($item_id == '_single_') {
  10967.                 $doc_item_data $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
  10968.                     array(
  10969.                         'productionId' => $id,
  10970. //                        'id' => $item_id
  10971.                     )
  10972.                 );
  10973.             } else {
  10974.                 $doc_item_data $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
  10975.                     array(
  10976.                         'productionId' => $id,
  10977.                         'id' => $item_id
  10978.                     )
  10979.                 );
  10980.             }
  10981.             $inv_acc_data = [
  10982.                 'fa_amount' => 0,
  10983.                 'tg_amount' => 0,
  10984.             ];
  10985.             $inv_acc_data_by_head = [
  10986.             ];
  10987.             $new_non_delivered_sales_code_range = [];
  10988.             foreach ($doc_item_data as $entry) {
  10989.                 //adding transaction
  10990.                 $sales_code_range_ser = [];
  10991.                 if (in_array($entry->getId(), $skip_ids))
  10992.                     continue;
  10993.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10994.                     ->findOneBy(
  10995.                         array(
  10996.                             'id' => $entry->getProductId()
  10997.                         )
  10998.                     );
  10999.                 if ($product) {
  11000.                     if ($product->getHasSerial() == 1) {
  11001.                         //clear if exists
  11002. //                        if($clearUnnecessaryOnly==1) {
  11003. //                            $get_kids_sql = "DELETE FROM product_by_code
  11004. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  11005. ////                $get_kids_sql .=' ORDER BY name ASC';
  11006. //
  11007. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  11008. //                            $stmt->execute();
  11009. //                            $em->flush();
  11010. //                        }
  11011. //                        else{
  11012. //                            $get_kids_sql = "DELETE FROM product_by_code
  11013. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  11014. ////                $get_kids_sql .=' ORDER BY name ASC';
  11015. //
  11016. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  11017. //                            $stmt->execute();
  11018. //                            $em->flush();
  11019. //                        }
  11020. //                        $check_here = $stmt->fetchAll();
  11021.                         //now addng product by code
  11022.                         $sales_code_range = [];
  11023.                         if ($entry->getProducedQty() > 0) {
  11024. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  11025. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  11026. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  11027.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getProducedQty(),
  11028.                                 $doc_data->getProductionDate(), 00$doc_data->getCompanyId(), $entry->getWarehouseId(),
  11029.                                 $entry->getProducedItemActionTagId(), nullnullnullnullnullnullnull$doc_data->getProductionId(), null
  11030.                             );
  11031.                             $sales_code_range $barcodeData['sales_code_range'];
  11032.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  11033.                             $em->flush();
  11034.                         }
  11035. //                        else {
  11036. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11037. //
  11038. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11039. //                            } else {
  11040. //
  11041. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11042. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  11043. //                                $sales_code_range = json_decode($json_without_bigints, true);
  11044. //                            }
  11045. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11046. //
  11047. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11048. //                            } else {
  11049. //
  11050. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11051. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  11052. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  11053. //                            }
  11054. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  11055. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  11056. //                            $new_non_delivered_sales_code_range = [];
  11057. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  11058. //                                if (!(in_array($ndsc, $sales_code_range)))
  11059. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  11060. //                            }
  11061. //                            if ($sales_code_range != null) {
  11062. //                                foreach ($sales_code_range as $ind => $dt) {
  11063. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  11064. //                                        ->findOneBy(
  11065. //                                            array(
  11066. //                                                'salesCode' => [$dt],
  11067. //                                                'productId' => $entry->getProductId()
  11068. //                                            )
  11069. //                                        );
  11070. //
  11071. //                                    if ($np) {
  11072. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  11073. //                                        $np->setProductId($entry->getProductId());
  11074. //                                        $np->setWarehouseId($entry->getWarehouseId());
  11075. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  11076. //                                        $np->setPosition(1);//in warehouse
  11077. //                                        $np->setStockReceivedNoteId($id);
  11078. //
  11079. //
  11080. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  11081. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  11082. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  11083. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  11084. //                                            'direction' => 'in',
  11085. //                                            'warehouseId' => $entry->getWarehouseId(),
  11086. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  11087. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  11088. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  11089. //                                        );
  11090. //                                        $np->setTransactionHistory(json_encode(
  11091. //                                            $trans_history
  11092. //                                        ));
  11093. //
  11094. //
  11095. //                                        $em->persist($np);
  11096. //                                        $em->flush();
  11097. //                                    }
  11098. //                                }
  11099. //                            }
  11100. //                        }
  11101.                     }
  11102.                 }
  11103.                 //adding transaction
  11104.                 $spec_item_id $entry->getId();
  11105.                 if ($item_id == '_single_') {
  11106.                     break;
  11107.                 }
  11108.             }
  11109.         }
  11110.         return new JsonResponse(array(
  11111.             'success' => $spec_item_id != true false,
  11112.             'skipIds' => [],
  11113.             'spec_item_id' => $spec_item_id
  11114.         ));
  11115. //        return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  11116. //            array(
  11117. //                'page_title' => 'Srcv barcodes',
  11118. ////                'export'=>'pdf,print',
  11119. //                'data' => $dt,
  11120. //                'repeatCount' => $repeatCount,
  11121. //                'item_id' => $item_id,
  11122. //                'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11123. //                    $id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11124. //                'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11125. //                    array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11126. //                    $id,
  11127. //                    $dt['created_by'],
  11128. //                    $dt['edited_by']),
  11129. //                'document_mark_image' => $document_mark['original'],
  11130. //                                    'company_name' => $company_data->getName(),
  11131. //                    'company_data'=>$company_data,
  11132. //                'company_address' => $company_data->getAddress(),
  11133. //                'company_image' => $company_data->getImage(),
  11134. //                'invoice_footer' => $company_data->getInvoiceFooter(),
  11135. //                'red' => 0
  11136. //
  11137. //            )
  11138. //        );
  11139.     }
  11140.     public
  11141.     function PrintLabelAction(Request $request$id)
  11142.     {
  11143.         $em $this->getDoctrine()->getManager();
  11144. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11145.         $repeatCount 1;
  11146.         $assignProductId '';
  11147.         $productByCodeIds = [];
  11148.         $print_selection_type 1;
  11149.         $print_selection_string 1;
  11150.         $assignLabelFormatId 0;
  11151.         $assignColorId 0;
  11152.         $assignProductionScheduleId 0;
  11153.         $warehouseId '';
  11154.         $warehouseActionId '';
  11155.         $toAssignPosition '';
  11156.         $printFlag $request->request->has('printFlag') ? $request->request->get('printFlag') : 1;
  11157.         $returnJson $request->request->has('returnJson') ? $request->request->get('returnJson') : 0;
  11158.         if ($returnJson == 1)
  11159.             $printFlag 0;
  11160.         $companyId $this->getLoggedUserCompanyId($request);
  11161.         if ($request->query->has('repeatCount'))
  11162.             $repeatCount $request->query->get('repeatCount');
  11163.         if ($request->request->has('print_selection_type'))
  11164.             $print_selection_type $request->request->get('print_selection_type');
  11165.         if ($request->request->has('print_selection_string'))
  11166.             $print_selection_string $request->request->get('print_selection_string');
  11167.         if ($request->request->has('productByCodeIds'))
  11168.             $productByCodeIds json_decode($request->request->get('productByCodeIds'), true);
  11169.         if ($request->request->has('formatId'))
  11170.             $assignLabelFormatId $request->request->get('formatId');
  11171.         if ($printFlag == 0) {
  11172.             if ($request->request->has('productSelector'))
  11173.                 $assignProductId $request->request->get('productSelector');
  11174.             if ($request->request->has('colorId'))
  11175.                 $assignColorId $request->request->get('colorId');
  11176.             if ($request->request->has('productionScheduleId'))
  11177.                 $assignProductionScheduleId $request->request->get('productionScheduleId');
  11178.             if ($request->request->has('warehouseId'))
  11179.                 $warehouseId $request->request->get('warehouseId');
  11180.             if ($request->request->has('warehouseActionId'))
  11181.                 $warehouseActionId $request->request->get('warehouseActionId');
  11182.             if ($request->request->has('position'))
  11183.                 $toAssignPosition $request->request->get('position');
  11184.             if ($assignColorId == '')
  11185.                 $assignColorId 0;
  11186.         }
  11187.         if ($productByCodeIds == null)
  11188.             $productByCodeIds = [];
  11189.         $productByCodeData = [];
  11190.         $productList = [];
  11191.         $productIds = [];
  11192.         if ($print_selection_type == 2) {
  11193.             //range
  11194.             $productByCodeIds Inventory::getIdsFromIdSelectionStr($print_selection_string);
  11195.         }
  11196.         $labelData = [
  11197.             'formatId' => 0
  11198.         ];
  11199.         $formatId 0;
  11200.         if (!empty($productByCodeIds)) {
  11201.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11202.                 ->findBy(
  11203.                     array(
  11204.                         'productByCodeId' => $productByCodeIds
  11205.                     )
  11206.                 );
  11207.             foreach ($productByCodeData as $d) {
  11208.                 if ($d->getStage() < 10$d->setStage(11);
  11209.                 if ($assignProductId != '') {
  11210.                     $d->setProductId($assignProductId);
  11211.                 }
  11212.                 if ($assignColorId != 0) {
  11213.                     $d->setColorId($assignColorId);
  11214.                 } else {
  11215.                     $productData $em->getRepository('ApplicationBundle:InvProducts')
  11216.                         ->findOneBy(
  11217.                             array(
  11218.                                 'id' => $assignProductId
  11219.                             )
  11220.                         );
  11221.                     if ($productData) {
  11222.                         $d->setColorId($productData->getDefaultColorId());
  11223.                     }
  11224.                 }
  11225.                 if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  11226.                     $d->setDefaultLabelFormatId($assignLabelFormatId);
  11227.                     $d->setDeviceLabelFormatId($assignLabelFormatId);
  11228.                 }
  11229.                 $toAssignPosition != '' $d->setPosition($toAssignPosition) : '';
  11230.                 $warehouseId != '' $d->setWarehouseId($warehouseId) : '';
  11231.                 $warehouseActionId != '' $d->setWarehouseActionId($warehouseActionId) : '';
  11232.                 if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  11233.                     $d->setProductionScheduleId($assignProductionScheduleId);
  11234.                     $productionSchedule $em->getRepository('ApplicationBundle:ProductionSchedule')
  11235.                         ->findOneBy(
  11236.                             array(
  11237.                                 'productionScheduleId' => $assignProductionScheduleId
  11238.                             )
  11239.                         );
  11240.                     if ($productionSchedule) {
  11241.                         if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  11242.                             //becuase it will assigned at previous lines
  11243.                         } else {
  11244.                             $d->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  11245.                             $d->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  11246.                         }
  11247.                         $d->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  11248.                         $d->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  11249.                     }
  11250.                 }
  11251.                 $em->flush();
  11252.                 if ($d->getProductId() != '' || $d->getProductId() != null)
  11253.                     $productIds[] = $d->getProductId();
  11254.                 $formatId $d->getDeviceLabelFormatId();
  11255.             }
  11256.         }
  11257.         $labelFormatHere $em->getRepository('ApplicationBundle:LabelFormat')
  11258.             ->findOneBy(
  11259.                 array(
  11260.                     'formatId' => $formatId,
  11261. //                        'CompanyId' => $companyId
  11262.                 )
  11263.             );
  11264.         if ($labelFormatHere) {
  11265.             $formatData json_decode($labelFormatHere->getFormatData(), true);
  11266.             if ($formatData == null$formatData = [];
  11267.             $labelData = array(
  11268.                 'id' => $labelFormatHere->getFormatId(),
  11269.                 'formatId' => $labelFormatHere->getFormatId(),
  11270.                 'labelType' => $labelFormatHere->getLabelType(),
  11271.                 'name' => $labelFormatHere->getName(),
  11272.                 'width' => $labelFormatHere->getWidth(),
  11273.                 'pageWidth' => $labelFormatHere->getPageWidth(),
  11274.                 'height' => $labelFormatHere->getheight(),
  11275.                 'pageHeight' => $labelFormatHere->getPageHeight(),
  11276.                 'formatData' => $formatData,
  11277.             );
  11278.         }
  11279.         $productList Inventory::ProductList($em$this->getLoggedUserCompanyId($request), 10''$productIds);
  11280.         $company_data Company::getCompanyData($em1);
  11281.         $document_mark = array(
  11282.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11283.             'copy' => ''
  11284.         );
  11285.         $dt $productByCodeData;
  11286.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11287.             $html $this->renderView('@Inventory/pages/print/print_label.html.twig',
  11288.                 array(
  11289.                     //full array here
  11290.                     'pdf' => true,
  11291.                     'page_title' => 'Device Labels',
  11292.                     'export' => 'print',
  11293.                     'repeatCount' => $repeatCount,
  11294.                     'labelData' => $labelData,
  11295.                     'brandList' => Inventory::GetBrandList($em$companyId),
  11296. //                    'item_id' => $item_id,
  11297.                     'data' => $dt,
  11298.                     'productList' => $productList,
  11299.                     'approval_data' => [],
  11300.                     'document_log' => [],
  11301.                     'document_mark_image' => $document_mark['original'],
  11302.                     'company_name' => $company_data->getName(),
  11303.                     'company_data' => $company_data,
  11304.                     'company_address' => $company_data->getAddress(),
  11305.                     'company_image' => $company_data->getImage(),
  11306.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11307.                     'red' => 0
  11308.                 )
  11309.             );
  11310.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11311. //                'orientation' => 'landscape',
  11312.                 'enable-javascript' => true,
  11313. //                'javascript-delay' => 1000,
  11314.                 'no-stop-slow-scripts' => false,
  11315.                 'no-background' => false,
  11316.                 'lowquality' => false,
  11317.                 'encoding' => 'utf-8',
  11318. //            'images' => true,
  11319. //            'cookie' => array(),
  11320.                 'dpi' => 300,
  11321.                 'image-dpi' => 300,
  11322. //                'enable-external-links' => true,
  11323. //                'enable-internal-links' => true
  11324.             ));
  11325.             return new Response(
  11326.                 $pdf_response,
  11327.                 200,
  11328.                 array(
  11329.                     'Content-Type' => 'application/pdf',
  11330.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11331.                 )
  11332.             );
  11333.         }
  11334.         $url $this->generateUrl(
  11335.             'print_label'
  11336.         );
  11337.         if ($returnJson == && $printFlag == 0) {
  11338. //                    $dr = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  11339. //                        array(
  11340. //                            'salesOrderId' => $orderId, ///material
  11341. //
  11342. //                        )
  11343. //                    );
  11344.             return new JsonResponse(array(
  11345.                 'success' => true,
  11346. //                        'documentHash' => $order->getDocumentHash(),
  11347. //                'documentId' => $receiptId,
  11348. //                'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
  11349. //
  11350. //                'viewUrl' => $url . "/" . $receiptId,
  11351.             ));
  11352.         } else return $this->render('@Inventory/pages/print/print_label.html.twig',
  11353.             array(
  11354.                 'page_title' => 'Product Labels',
  11355. //                'export'=>'pdf,print',
  11356.                 'data' => $dt,
  11357.                 'productList' => $productList,
  11358.                 'repeatCount' => $repeatCount,
  11359. //                'item_id' => $item_id,
  11360.                 'labelData' => $labelData,
  11361.                 'brandList' => Inventory::GetBrandList($em$companyId),
  11362.                 'approval_data' => [],
  11363.                 'document_log' => [],
  11364.                 'document_mark_image' => $document_mark['original'],
  11365.                 'company_name' => $company_data->getName(),
  11366.                 'company_data' => $company_data,
  11367.                 'company_address' => $company_data->getAddress(),
  11368.                 'company_image' => $company_data->getImage(),
  11369.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11370.                 'red' => 0
  11371.             )
  11372.         );
  11373.     }
  11374.     public
  11375.     function PrintCartonLabelAction(Request $request$id)
  11376.     {
  11377.         $em $this->getDoctrine()->getManager();
  11378. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11379.         $repeatCount 1;
  11380.         $assignProductId '';
  11381.         $productByCodeIds = [];
  11382.         $cartonId 0;
  11383.         if ($id != 0)
  11384.             $cartonId $id;
  11385.         $colorText '';
  11386.         $weightText '';
  11387.         if ($request->query->has('repeatCount'))
  11388.             $repeatCount $request->query->get('repeatCount');
  11389.         if ($request->request->has('printCartonId'))
  11390.             $cartonId $request->request->get('printCartonId');
  11391.         if ($request->request->has('printCartonColorText'))
  11392.             $colorText $request->request->get('printCartonColorText');
  11393.         if ($request->request->has('printCartonWeightText'))
  11394.             $weightText $request->request->get('printCartonWeightText');
  11395.         $labelData = [
  11396.             'formatId' => 0
  11397.         ];
  11398.         if ($productByCodeIds == null)
  11399.             $productByCodeIds = [];
  11400.         $productByCodeData = [];
  11401.         $cartonData = [];
  11402.         $product = [];
  11403.         if ($cartonId != 0) {
  11404.             $cartonData $em->getRepository('ApplicationBundle:Carton')
  11405.                 ->findOneBy(
  11406.                     array(
  11407.                         'id' => $cartonId
  11408.                     )
  11409.                 );
  11410.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11411.                 ->findBy(
  11412.                     array(
  11413.                         'cartonId' => $cartonId
  11414.                     )
  11415.                 );
  11416. //            if(!empty($productByCodeData))
  11417. //                $product = $em->getRepository('ApplicationBundle:InvProducts')
  11418. //                ->findOneBy(
  11419. //                    array(
  11420. //                        'id' => $productByCodeData[0]->getProductId()
  11421. //                    )
  11422. //                );
  11423. //            else
  11424.             $product $em->getRepository('ApplicationBundle:InvProducts')
  11425.                 ->findOneBy(
  11426.                     array(
  11427.                         'id' => $cartonData->getProductId()
  11428.                     )
  11429.                 );
  11430.             $formatId $cartonData->getCartonLabelFormatId();
  11431.             $labelFormatHere $em->getRepository('ApplicationBundle:LabelFormat')
  11432.                 ->findOneBy(
  11433.                     array(
  11434.                         'formatId' => $formatId,
  11435. //                        'CompanyId' => $companyId
  11436.                     )
  11437.                 );
  11438.             if ($labelFormatHere) {
  11439.                 $formatData json_decode($labelFormatHere->getFormatData(), true);
  11440.                 if ($formatData == null$formatData = [];
  11441.                 $labelData = array(
  11442.                     'id' => $labelFormatHere->getFormatId(),
  11443.                     'formatId' => $labelFormatHere->getFormatId(),
  11444.                     'labelType' => $labelFormatHere->getLabelType(),
  11445.                     'name' => $labelFormatHere->getName(),
  11446.                     'width' => $labelFormatHere->getWidth(),
  11447.                     'pageWidth' => $labelFormatHere->getPageWidth(),
  11448.                     'height' => $labelFormatHere->getheight(),
  11449.                     'pageHeight' => $labelFormatHere->getPageHeight(),
  11450.                     'formatData' => $formatData,
  11451.                 );
  11452.             }
  11453.         }
  11454.         $company_data Company::getCompanyData($em1);
  11455.         $document_mark = array(
  11456.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11457.             'copy' => ''
  11458.         );
  11459.         $dt $productByCodeData;
  11460.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11461.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  11462.                 array(
  11463.                     //full array here
  11464.                     'pdf' => true,
  11465.                     'page_title' => 'Carton Labels',
  11466.                     'export' => 'print',
  11467.                     'labelData' => $labelData,
  11468.                     'repeatCount' => $repeatCount,
  11469. //                    'item_id' => $item_id,
  11470.                     'data' => $dt,
  11471.                     'cartonData' => $cartonData,
  11472.                     'product' => $product,
  11473.                     'colorText' => $colorText,
  11474.                     'weightText' => $weightText,
  11475.                     'approval_data' => [],
  11476.                     'document_log' => [],
  11477.                     'document_mark_image' => $document_mark['original'],
  11478.                     'company_name' => $company_data->getName(),
  11479.                     'company_data' => $company_data,
  11480.                     'company_address' => $company_data->getAddress(),
  11481.                     'company_image' => $company_data->getImage(),
  11482.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11483.                     'red' => 0
  11484.                 )
  11485.             );
  11486.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11487. //                'orientation' => 'landscape',
  11488.                 'enable-javascript' => true,
  11489. //                'javascript-delay' => 1000,
  11490.                 'no-stop-slow-scripts' => false,
  11491.                 'no-background' => false,
  11492.                 'lowquality' => false,
  11493.                 'encoding' => 'utf-8',
  11494. //            'images' => true,
  11495. //            'cookie' => array(),
  11496.                 'dpi' => 300,
  11497.                 'image-dpi' => 300,
  11498. //                'enable-external-links' => true,
  11499. //                'enable-internal-links' => true
  11500.             ));
  11501.             return new Response(
  11502.                 $pdf_response,
  11503.                 200,
  11504.                 array(
  11505.                     'Content-Type' => 'application/pdf',
  11506.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11507.                 )
  11508.             );
  11509.         }
  11510.         if ($request->query->has('previewOnly')) {
  11511.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  11512.                 array(
  11513.                     'page_title' => 'Carton Labels',
  11514. //                'export'=>'pdf,print',
  11515.                     'data' => $dt,
  11516.                     'skip_parameters' => 1,
  11517.                     'labelData' => $labelData,
  11518.                     'cartonData' => $cartonData,
  11519.                     'product' => $product,
  11520.                     'colorText' => $colorText,
  11521.                     'weightText' => $weightText,
  11522.                     'repeatCount' => $repeatCount,
  11523. //                'item_id' => $item_id,
  11524.                     'approval_data' => [],
  11525.                     'document_log' => [],
  11526.                     'document_mark_image' => $document_mark['original'],
  11527.                     'company_name' => $company_data->getName(),
  11528.                     'company_data' => $company_data,
  11529.                     'company_address' => $company_data->getAddress(),
  11530.                     'company_image' => $company_data->getImage(),
  11531.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11532.                     'red' => 0
  11533.                 )
  11534.             );
  11535.             if ($request->query->has('returnJson')) {
  11536.                 return new JsonResponse(
  11537.                     array(
  11538.                         'success' => true,
  11539.                         'page_title' => 'Product Details',
  11540.                         'company_data' => $company_data,
  11541.                         'renderedHtml' => $html,
  11542. //                'productData' => $productData,
  11543. //                'currInvList' => $currInvList,
  11544. //                'productList' => Inventory::ProductList($em, $companyId),
  11545. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11546. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11547. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11548. //                'unitList' => Inventory::UnitTypeList($em),
  11549. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11550. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11551. //                'warehouseList' => Inventory::WarehouseList($em),
  11552.                     )
  11553.                 );
  11554.             }
  11555.         }
  11556.         return $this->render('@Inventory/pages/print/print_carton_label.html.twig',
  11557.             array(
  11558.                 'page_title' => 'Carton Labels',
  11559. //                'export'=>'pdf,print',
  11560.                 'data' => $dt,
  11561.                 'cartonData' => $cartonData,
  11562.                 'product' => $product,
  11563. //                'productByCodeData' => $productByCodeData,
  11564.                 'colorText' => $colorText,
  11565.                 'weightText' => $weightText,
  11566.                 'repeatCount' => $repeatCount,
  11567.                 'labelData' => $labelData,
  11568. //                'item_id' => $item_id,
  11569.                 'approval_data' => [],
  11570.                 'document_log' => [],
  11571.                 'document_mark_image' => $document_mark['original'],
  11572.                 'company_name' => $company_data->getName(),
  11573.                 'company_data' => $company_data,
  11574.                 'company_address' => $company_data->getAddress(),
  11575.                 'company_image' => $company_data->getImage(),
  11576.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11577.                 'red' => 0
  11578.             )
  11579.         );
  11580.     }
  11581.     public
  11582.     function AssignInfoToProductByCodeAction(Request $request$id)
  11583.     {
  11584.         $em $this->getDoctrine()->getManager();
  11585.         $companyId $this->getLoggedUserCompanyId($request);
  11586. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11587.         $cartonId '';
  11588.         $passStatus 5;
  11589.         $assignProductId '';
  11590.         $assignProductionId '';
  11591.         $assignProductionScheduleId '';
  11592.         $gbWeightGm '';
  11593.         $dvWeightGm '';
  11594.         $cartonWeightGm '';
  11595.         if ($request->request->has('cartonId'))
  11596.             $cartonId $request->request->get('cartonId');
  11597.         if ($request->request->has('passStatus'))
  11598.             $passStatus $request->request->get('passStatus');
  11599.         if ($request->request->has('productByCodeId'))
  11600.             $id $request->request->get('productByCodeId');
  11601.         if ($request->request->has('productId'))
  11602.             $assignProductId $request->request->get('productId');
  11603.         if ($request->request->has('productionId'))
  11604.             $assignProductionId $request->request->get('productionId');
  11605.         if ($request->request->has('productionScheduleId'))
  11606.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  11607.         if ($request->request->has('gbWeightGm'))
  11608.             $gbWeightGm $request->request->get('gbWeightGm');
  11609.         if ($request->request->has('dvWeightGm'))
  11610.             $dvWeightGm $request->request->get('dvWeightGm');
  11611.         if ($request->request->has('cartonWeightGm'))
  11612.             $cartonWeightGm $request->request->get('cartonWeightGm');
  11613.         $cartonAssignedAlready 0;
  11614.         $otherData = array(
  11615.             'currentCartonBalance' => 0,
  11616.             'currentCartonCapacity' => 0,
  11617.             'currentCartonAssigned' => 0,
  11618.             'currentCartonFull' => 0,
  11619.         );
  11620.         if ($id != && $id != '') {
  11621.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11622.                 ->findOneBy(
  11623.                     array(
  11624.                         'productByCodeId' => $id
  11625.                     )
  11626.                 );
  11627.             if ($assignProductId != ''$productByCodeData->setProductId($assignProductId);
  11628.             if ($productByCodeData->getCartonId() != '' || $productByCodeData->getCartonId() != null)
  11629.                 $cartonAssignedAlready 1;
  11630.             else if ($cartonId != ''$productByCodeData->setCartonId($cartonId);
  11631.             if ($dvWeightGm != ''$productByCodeData->setSingleWeightGm($dvWeightGm);
  11632.             if ($gbWeightGm != '') {
  11633.                 $productByCodeData->setPackagedWeightGm($gbWeightGm);
  11634.             }
  11635.             $colorText '_NA_';
  11636.             if ($passStatus != 5$productByCodeData->setStage($passStatus);
  11637.             $productByCodeData->setCompanyId($companyId);
  11638.             if ($assignProductionId != '') {
  11639.                 $productByCodeData->setProductionId($assignProductionId);
  11640.                 $productionData $em->getRepository('ApplicationBundle:Production')
  11641.                     ->findOneBy(
  11642.                         array(
  11643.                             'productionId' => $assignProductionId
  11644.                         )
  11645.                     );
  11646.                 if ($assignProductId != '' && $assignProductId != null && $assignProductId != 0)
  11647.                     $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11648.                         array(
  11649.                             'productionId' => $assignProductionId,
  11650.                             'productId' => $assignProductId,
  11651.                             'type' => 1,
  11652.                         )
  11653.                     );
  11654.                 else
  11655.                     $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11656.                         array(
  11657.                             'productionId' => $assignProductionId,
  11658. //                            'productId' => $assignProductId,
  11659.                             'type' => 1,
  11660.                         )
  11661.                     );
  11662.                 $assignProductionScheduleId $productionData->getProductionScheduleId();
  11663.                 if ($productionItemData) {
  11664.                     $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11665.                     $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11666.                     $productByCodeData->setPosition(1);//in inventory
  11667.                     $productByCodeData->setSerialAssigned(1);
  11668.                     $productByCodeData->setColorId($productionItemData->getColorId());
  11669.                     $productByCodeData->setColorText($productionItemData->getColorText());
  11670.                     $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11671.                     $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11672.                     if ($passStatus == 1)//passed
  11673.                     {
  11674. //                    $transDate = new \DateTime();
  11675. //                    Inventory::addItemToInventoryCompact($em,
  11676. //                        $productionItemData->getProductId(),
  11677. //                        $productionItemData->getWarehouseId(),
  11678. //                        $productionItemData->getWarehouseId(),
  11679. //                        $productionData->getProducedItemActionTagId(),
  11680. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11681. //                        $transDate,
  11682. //                        1,
  11683. //                        1,
  11684. //                        $entry['valueAdd'],
  11685. //                        $entry['valueSub'],
  11686. //                        $entry['price'],
  11687. //                        $this->getLoggedUserCompanyId($request),
  11688. //                        0,
  11689. //                        $entry['entity'],
  11690. //                        $entry['entityId'],
  11691. //                        $entry['entityDocHash']
  11692. //                    );
  11693.                     }
  11694.                     $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  11695.                     if ($transHistory == null)
  11696.                         $transHistory = [];
  11697.                     $transHistory[] = array(
  11698.                         'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  11699.                         'direction' => 'in',
  11700.                         'warehouseId' => $productionItemData->getWarehouseId(),
  11701.                         'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  11702.                         'fromWarehouseId' => 0,
  11703.                         'fromWarehouseActionId' => //stock of goods
  11704.                     );
  11705.                     $productByCodeData->setTransactionHistory(json_encode($transHistory));
  11706.                 }
  11707.             }
  11708.             if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  11709.                 $productByCodeData->setProductionScheduleId($assignProductionScheduleId);
  11710.                 $productionSchedule $em->getRepository('ApplicationBundle:ProductionSchedule')
  11711.                     ->findOneBy(
  11712.                         array(
  11713.                             'productionScheduleId' => $assignProductionScheduleId
  11714.                         )
  11715.                     );
  11716.                 if ($productionSchedule) {
  11717.                     $productByCodeData->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  11718.                     $productByCodeData->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  11719.                     $productByCodeData->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  11720.                     $productByCodeData->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  11721.                     if ($productByCodeData->getProductionId() == null || $productByCodeData->getProductionId() == '' || $productByCodeData->getProductionId() == 0) {
  11722.                         $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11723.                             array(
  11724.                                 'productionScheduleId' => $assignProductionScheduleId,
  11725.                                 'productId' => $productionSchedule->getProducedProductId(),
  11726.                                 'type' => 1,
  11727.                             )
  11728.                         );
  11729. //                        $assignProductionScheduleId=$productionData->getProductionScheduleId();
  11730.                         if ($productionItemData) {
  11731.                             $productByCodeData->setProductionId($productionItemData->getProductionId());
  11732.                             $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11733.                             $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11734.                             $productByCodeData->setPosition(1);//in inventory
  11735.                             $productByCodeData->setSerialAssigned(1);
  11736.                             $productByCodeData->setColorId($productionItemData->getColorId());
  11737.                             $productByCodeData->setColorText($productionItemData->getColorText());
  11738.                             $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11739.                             $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11740.                             if ($passStatus == 1)//passed
  11741.                             {
  11742. //                    $transDate = new \DateTime();
  11743. //                    Inventory::addItemToInventoryCompact($em,
  11744. //                        $productionItemData->getProductId(),
  11745. //                        $productionItemData->getWarehouseId(),
  11746. //                        $productionItemData->getWarehouseId(),
  11747. //                        $productionData->getProducedItemActionTagId(),
  11748. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11749. //                        $transDate,
  11750. //                        1,
  11751. //                        1,
  11752. //                        $entry['valueAdd'],
  11753. //                        $entry['valueSub'],
  11754. //                        $entry['price'],
  11755. //                        $this->getLoggedUserCompanyId($request),
  11756. //                        0,
  11757. //                        $entry['entity'],
  11758. //                        $entry['entityId'],
  11759. //                        $entry['entityDocHash']
  11760. //                    );
  11761.                             }
  11762.                             $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  11763.                             if ($transHistory == null)
  11764.                                 $transHistory = [];
  11765.                             $transHistory[] = array(
  11766.                                 'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  11767.                                 'direction' => 'in',
  11768.                                 'warehouseId' => $productionItemData->getWarehouseId(),
  11769.                                 'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  11770.                                 'fromWarehouseId' => 0,
  11771.                                 'fromWarehouseActionId' => //stock of goods
  11772.                             );
  11773.                             $productByCodeData->setTransactionHistory(json_encode($transHistory));
  11774.                         }
  11775.                     }
  11776.                 }
  11777.             }
  11778. //                $productByCodeData->setPurchaseWarrantyLastDate($new_pwld);
  11779.             $em->flush();
  11780.             //now adding carton
  11781.         }
  11782.         if ($cartonId != '') {
  11783.             $carton $em->getRepository('ApplicationBundle:Carton')
  11784.                 ->findOneBy(
  11785.                     array(
  11786.                         'id' => $cartonId
  11787.                     )
  11788.                 );
  11789.             if ($cartonWeightGm != ''$carton->setCartonWeightGm($cartonWeightGm);
  11790.             $otherData['currentCartonCapacity'] = $carton->getCartonCapacityCount();
  11791.             if ($cartonAssignedAlready == 0)
  11792.                 $carton->setCartonAssignedCount(($carton->getCartonAssignedCount()) + 1);
  11793.             $otherData['currentCartonAssigned'] = $carton->getCartonAssignedCount();
  11794.             $otherData['currentCartonBalance'] = $otherData['currentCartonCapacity'] - $otherData['currentCartonAssigned'];
  11795.             if ($otherData['currentCartonAssigned'] >= $otherData['currentCartonCapacity'])
  11796.                 $otherData['currentCartonFull'] = 1;
  11797.             $em->flush();
  11798.         }
  11799.         if ($cartonId != '') {
  11800. //                    if($cartonAssignedAlready==1)
  11801. //                    {
  11802.             $productByCodeDataListForThisCarton $em->getRepository('ApplicationBundle:ProductByCode')
  11803.                 ->findBy(
  11804.                     array(
  11805.                         'cartonId' => $cartonId
  11806.                     )
  11807.                 );
  11808.             $carton $em->getRepository('ApplicationBundle:Carton')
  11809.                 ->findOneBy(
  11810.                     array(
  11811.                         'id' => $cartonId
  11812.                     )
  11813.                 );
  11814.             $total_carton_predicted_weight 0;
  11815.             $colorTextList = [];
  11816.             $cartonProductByCodeIds = [];
  11817.             foreach ($productByCodeDataListForThisCarton as $pikamaster) {
  11818.                 if (!in_array($pikamaster->getProductByCodeId(), $cartonProductByCodeIds))
  11819.                     $cartonProductByCodeIds[] = $pikamaster->getProductByCodeId();
  11820.                 if (!in_array($pikamaster->getColorText(), $colorTextList) && $pikamaster->getColorText() != null)
  11821.                     $colorTextList[] = $pikamaster->getColorText();
  11822.                 $total_carton_predicted_weight += ($pikamaster->getPackagedWeightGm());
  11823.                 if ($passStatus != 5)
  11824.                     if ($pikamaster->getStage() < $passStatus)
  11825.                         $pikamaster->setStage($passStatus);
  11826.             }
  11827.             if ($carton)
  11828.                 $carton->setCartonCalculatedWeightGm($total_carton_predicted_weight);
  11829.             if ($passStatus != 5)
  11830.                 $carton->setStage($passStatus);
  11831.             $carton->setColors(implode(','$colorTextList));
  11832.             $carton->setCartonProductByCodeIds(json_encode($cartonProductByCodeIds));
  11833.             $em->flush();
  11834.         }
  11835.         return new JsonResponse(array(
  11836.             'success' => true,
  11837.             'otherData' => $otherData,
  11838.         ));
  11839.     }
  11840.     public
  11841.     function RefreshCartonListAction(Request $request$id)
  11842.     {
  11843.         $em $this->getDoctrine()->getManager();
  11844. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11845.         $cartonListArray = [];
  11846.         $cartonList = [];
  11847.         $assignableCartonList = [];
  11848.         $assignableCartonListArray = [];
  11849.         $assignable 0;
  11850.         $cartonId '';
  11851.         $passStatus 5;
  11852.         $assignProductId '';
  11853.         $assignProductionId '';
  11854.         $assignProductionScheduleId '';
  11855.         if ($request->request->has('productionId'))
  11856.             $assignProductionId $request->request->get('productionId');
  11857.         if ($request->request->has('productionScheduleId'))
  11858.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  11859.         if ($request->request->has('assignable'))
  11860.             $assignable $request->request->get('assignable');
  11861.         $cartonAssignedAlready 0;
  11862.         $otherData = array(
  11863.             'currentCartonBalance' => 0,
  11864.             'currentCartonCapacity' => 0,
  11865.             'currentCartonAssigned' => 0,
  11866.             'currentCartonFull' => 0,
  11867.         );
  11868.         //1st get all cartons for this production id
  11869.         $cartonList $em->getRepository('ApplicationBundle:Carton')
  11870.             ->findBy(
  11871.                 array(
  11872. //                    'productionId' => $assignProductionId,
  11873.                     'productionScheduleId' => $assignProductionScheduleId
  11874.                 )
  11875.             );
  11876.         $foundAssignable 0;
  11877.         $setId 0;
  11878.         $lastdmySer '';
  11879.         foreach ($cartonList as $carton) {
  11880.             $cartonData = array(
  11881.                 'id' => $carton->getId(),
  11882.                 'name' => $carton->getCartonNumber(),
  11883.                 'colors' => $carton->getColors(),
  11884.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  11885.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  11886.             );
  11887.             $cartonListArray[] = $cartonData;
  11888.             $cartonList[$cartonData['id']] = $cartonData;
  11889.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  11890.                 $foundAssignable 1;
  11891.                 $setId $cartonData['id'];
  11892.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  11893.                 $assignableCartonListArray[] = $cartonData;
  11894.             }
  11895.         }
  11896.         if ($assignable == && $foundAssignable == 0) {
  11897. //            $productionData = $em->getRepository('ApplicationBundle:Production')
  11898. //                ->findOneBy(
  11899. //                    array(
  11900. //                        'productionId' => $assignProductionId
  11901. //                    )
  11902. //                );
  11903.             $productionScheduleData $em->getRepository('ApplicationBundle:ProductionSchedule')
  11904.                 ->findOneBy(
  11905.                     array(
  11906.                         'productionScheduleId' => $assignProductionScheduleId
  11907.                     )
  11908.                 );
  11909.             $productId 0;
  11910.             $product = [];
  11911.             $productModel '';
  11912.             if ($productionScheduleData)
  11913.                 $productId $productionScheduleData->getProducedProductId();
  11914. //            $productionItem = $em->getRepository('ApplicationBundle:ProductionEntryItem')
  11915. //                ->findOneBy(
  11916. //                    array(
  11917. //                        'productionId' => $assignProductionId,
  11918. //                        'type' => 1
  11919. //                    )
  11920. //                );
  11921.             if ($productId != 0) {
  11922. //                    $productId = $productionItem->getProductId();
  11923.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  11924.                     ->findOneBy(
  11925.                         array(
  11926.                             'id' => $productId,
  11927.                         )
  11928.                     );
  11929.                 $productModel $product->getModelNo();
  11930.             }
  11931.             $carton = new Carton();
  11932.             $carton_capacity $productionScheduleData->getCartonCapacity();
  11933.             $carton->setProductId($productId);
  11934.             $carton->setProductionId($assignProductionId);
  11935.             $carton->setProductionScheduleId($assignProductionScheduleId);
  11936.             if ($productionScheduleData) {
  11937.                 $carton->setCartonLabelFormatId($productionScheduleData->getCartonLabelFormatId());
  11938.             }
  11939.             $carton->setCartonCapacityCount($carton_capacity == null $carton_capacity);
  11940.             $carton->setCartonAssignedCount(0);
  11941.             $carton->setCompanyId($this->getLoggedUserCompanyId($request));
  11942.             $today = new \DateTime();
  11943.             $dmy $productModel '-' . ($today->format('m')) . '-' . ($today->format('Y')) . '-' $productionScheduleData->getBatchNumber();
  11944.             $ser 0;
  11945.             $carton->setCartonNumberDmy($dmy);
  11946.             $carton->setCartonNumberLastSer(* (($today->format('h')) . '' . ($today->format('i'))));
  11947.             $carton->setCartonNumber($dmy '-' . ($today->format('h')) . '' . ($today->format('i')));
  11948.             $em->persist($carton);
  11949.             $em->flush();
  11950.             $cartonData = array(
  11951.                 'id' => $carton->getId(),
  11952.                 'name' => $carton->getCartonNumber(),
  11953.                 'colors' => $carton->getColors(),
  11954.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  11955.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  11956.             );
  11957.             $cartonListArray[] = $cartonData;
  11958.             $cartonList[$cartonData['id']] = $cartonData;
  11959.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  11960.                 $foundAssignable 1;
  11961.                 $setId $cartonData['id'];
  11962.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  11963.                 $assignableCartonListArray[] = $cartonData;
  11964.             }
  11965.         }
  11966.         return new JsonResponse(array(
  11967.             'success' => true,
  11968.             'cartonList' => $cartonList,
  11969.             'cartonListArray' => $cartonListArray,
  11970.             'assignableCartonList' => $assignableCartonList,
  11971.             'assignableCartonListArray' => $assignableCartonListArray,
  11972.             'setId' => $setId,
  11973.         ));
  11974.     }
  11975.     public
  11976.     function PrintDrBarcodeAction(Request $request$id$item_id)
  11977.     {
  11978.         $em $this->getDoctrine()->getManager();
  11979.         $dt Inventory::GetDrDetails($em$id$item_id);
  11980.         $repeatCount 1;
  11981.         if ($request->query->has('repeatCount'))
  11982.             $repeatCount $request->query->get('repeatCount');
  11983.         $company_data Company::getCompanyData($em1);
  11984.         $document_mark = array(
  11985.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11986.             'copy' => ''
  11987.         );
  11988.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11989.             $html $this->renderView('@Inventory/pages/print/print_dr_barcodes.html.twig',
  11990.                 array(
  11991.                     //full array here
  11992.                     'pdf' => true,
  11993.                     'page_title' => 'Challan Barcodes',
  11994.                     'export' => 'print',
  11995.                     'repeatCount' => $repeatCount,
  11996.                     'item_id' => $item_id,
  11997.                     'data' => $dt,
  11998.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11999.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12000.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12001.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12002.                         $id,
  12003.                         $dt['created_by'],
  12004.                         $dt['edited_by']),
  12005.                     'document_mark_image' => $document_mark['original'],
  12006.                     'company_name' => $company_data->getName(),
  12007.                     'company_data' => $company_data,
  12008.                     'company_address' => $company_data->getAddress(),
  12009.                     'company_image' => $company_data->getImage(),
  12010.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12011.                     'red' => 0
  12012.                 )
  12013.             );
  12014.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12015. //                'orientation' => 'landscape',
  12016.                 'enable-javascript' => true,
  12017. //                'javascript-delay' => 1000,
  12018.                 'no-stop-slow-scripts' => false,
  12019.                 'no-background' => false,
  12020.                 'lowquality' => false,
  12021.                 'encoding' => 'utf-8',
  12022. //            'images' => true,
  12023. //            'cookie' => array(),
  12024.                 'dpi' => 300,
  12025.                 'image-dpi' => 300,
  12026. //                'enable-external-links' => true,
  12027. //                'enable-internal-links' => true
  12028.             ));
  12029.             return new Response(
  12030.                 $pdf_response,
  12031.                 200,
  12032.                 array(
  12033.                     'Content-Type' => 'application/pdf',
  12034.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  12035.                 )
  12036.             );
  12037.         }
  12038.         return $this->render('@Inventory/pages/print/print_dr_barcodes.html.twig',
  12039.             array(
  12040.                 'page_title' => 'Challan barcodes',
  12041. //                'export'=>'pdf,print',
  12042.                 'data' => $dt,
  12043.                 'repeatCount' => $repeatCount,
  12044.                 'item_id' => $item_id,
  12045.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12046.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12047.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12048.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12049.                     $id,
  12050.                     $dt['created_by'],
  12051.                     $dt['edited_by']),
  12052.                 'document_mark_image' => $document_mark['original'],
  12053.                 'company_name' => $company_data->getName(),
  12054.                 'company_data' => $company_data,
  12055.                 'company_address' => $company_data->getAddress(),
  12056.                 'company_image' => $company_data->getImage(),
  12057.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12058.                 'red' => 0
  12059.             )
  12060.         );
  12061.     }
  12062.     public
  12063.     function PrintIrrBarcodeAction(Request $request$id$item_id)
  12064.     {
  12065.         $em $this->getDoctrine()->getManager();
  12066.         $dt Inventory::GetIrrDetails($em$id$item_id);
  12067.         $repeatCount 1;
  12068.         if ($request->query->has('repeatCount'))
  12069.             $repeatCount $request->query->get('repeatCount');
  12070.         $company_data Company::getCompanyData($em1);
  12071.         $document_mark = array(
  12072.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12073.             'copy' => ''
  12074.         );
  12075.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12076.             $html $this->renderView('@Inventory/pages/print/print_irr_barcodes.html.twig',
  12077.                 array(
  12078.                     //full array here
  12079.                     'pdf' => true,
  12080.                     'page_title' => 'Sales Return Barcodes',
  12081.                     'export' => 'print',
  12082.                     'repeatCount' => $repeatCount,
  12083.                     'item_id' => $item_id,
  12084.                     'data' => $dt,
  12085.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12086.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12087.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12088.                         array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12089.                         $id,
  12090.                         $dt['created_by'],
  12091.                         $dt['edited_by']),
  12092.                     'document_mark_image' => $document_mark['original'],
  12093.                     'company_name' => $company_data->getName(),
  12094.                     'company_data' => $company_data,
  12095.                     'company_address' => $company_data->getAddress(),
  12096.                     'company_image' => $company_data->getImage(),
  12097.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12098.                     'red' => 0
  12099.                 )
  12100.             );
  12101.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12102. //                'orientation' => 'landscape',
  12103.                 'enable-javascript' => true,
  12104. //                'javascript-delay' => 1000,
  12105.                 'no-stop-slow-scripts' => false,
  12106.                 'no-background' => false,
  12107.                 'lowquality' => false,
  12108.                 'encoding' => 'utf-8',
  12109. //            'images' => true,
  12110. //            'cookie' => array(),
  12111.                 'dpi' => 300,
  12112.                 'image-dpi' => 300,
  12113. //                'enable-external-links' => true,
  12114. //                'enable-internal-links' => true
  12115.             ));
  12116.             return new Response(
  12117.                 $pdf_response,
  12118.                 200,
  12119.                 array(
  12120.                     'Content-Type' => 'application/pdf',
  12121.                     'Content-Disposition' => 'attachment; filename="irr_barcodes.pdf"'
  12122.                 )
  12123.             );
  12124.         }
  12125.         return $this->render('@Inventory/pages/print/print_irr_barcodes.html.twig',
  12126.             array(
  12127.                 'page_title' => 'Sales Return barcodes',
  12128. //                'export'=>'pdf,print',
  12129.                 'data' => $dt,
  12130.                 'repeatCount' => $repeatCount,
  12131.                 'item_id' => $item_id,
  12132.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12133.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12134.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12135.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12136.                     $id,
  12137.                     $dt['created_by'],
  12138.                     $dt['edited_by']),
  12139.                 'document_mark_image' => $document_mark['original'],
  12140.                 'company_name' => $company_data->getName(),
  12141.                 'company_data' => $company_data,
  12142.                 'company_address' => $company_data->getAddress(),
  12143.                 'company_image' => $company_data->getImage(),
  12144.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12145.                 'red' => 0
  12146.             )
  12147.         );
  12148.     }
  12149.     public
  12150.     function PrintSrcvBarcodeAction(Request $request$id$item_id)
  12151.     {
  12152.         $em $this->getDoctrine()->getManager();
  12153.         $dt Inventory::GetSrcvDetails($em$id$item_id);
  12154.         $repeatCount 1;
  12155.         if ($request->query->has('repeatCount'))
  12156.             $repeatCount $request->query->get('repeatCount');
  12157.         $company_data Company::getCompanyData($em1);
  12158.         $document_mark = array(
  12159.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12160.             'copy' => ''
  12161.         );
  12162.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12163.             $html $this->renderView('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12164.                 array(
  12165.                     //full array here
  12166.                     'pdf' => true,
  12167.                     'page_title' => 'Grn Barcodes',
  12168.                     'export' => 'print',
  12169.                     'repeatCount' => $repeatCount,
  12170.                     'item_id' => $item_id,
  12171.                     'data' => $dt,
  12172.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12173.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12174.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12175.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12176.                         $id,
  12177.                         $dt['created_by'],
  12178.                         $dt['edited_by']),
  12179.                     'document_mark_image' => $document_mark['original'],
  12180.                     'company_name' => $company_data->getName(),
  12181.                     'company_data' => $company_data,
  12182.                     'company_address' => $company_data->getAddress(),
  12183.                     'company_image' => $company_data->getImage(),
  12184.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12185.                     'red' => 0
  12186.                 )
  12187.             );
  12188.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12189. //                'orientation' => 'landscape',
  12190.                 'enable-javascript' => true,
  12191. //                'javascript-delay' => 1000,
  12192.                 'no-stop-slow-scripts' => false,
  12193.                 'no-background' => false,
  12194.                 'lowquality' => false,
  12195.                 'encoding' => 'utf-8',
  12196. //            'images' => true,
  12197. //            'cookie' => array(),
  12198.                 'dpi' => 300,
  12199.                 'image-dpi' => 300,
  12200. //                'enable-external-links' => true,
  12201. //                'enable-internal-links' => true
  12202.             ));
  12203.             return new Response(
  12204.                 $pdf_response,
  12205.                 200,
  12206.                 array(
  12207.                     'Content-Type' => 'application/pdf',
  12208.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  12209.                 )
  12210.             );
  12211.         }
  12212.         return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12213.             array(
  12214.                 'page_title' => 'Srcv barcodes',
  12215. //                'export'=>'pdf,print',
  12216.                 'data' => $dt,
  12217.                 'repeatCount' => $repeatCount,
  12218.                 'item_id' => $item_id,
  12219.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12220.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12221.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12222.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12223.                     $id,
  12224.                     $dt['created_by'],
  12225.                     $dt['edited_by']),
  12226.                 'document_mark_image' => $document_mark['original'],
  12227.                 'company_name' => $company_data->getName(),
  12228.                 'company_data' => $company_data,
  12229.                 'company_address' => $company_data->getAddress(),
  12230.                 'company_image' => $company_data->getImage(),
  12231.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12232.                 'red' => 0
  12233.             )
  12234.         );
  12235.     }
  12236. //product by code
  12237.     public
  12238.     function ImeiListExcelUploadAction(Request $request)
  12239.     {
  12240.         $lastIndex $request->request->get('lastIndex'0);
  12241.         if ($request->isMethod('POST')) {
  12242.             $post $request->request;
  12243.             if ($request->request->has('chunkData')) {
  12244.                 //now getting the relevant checks
  12245.                 $check_list = [];
  12246.                 $csv_data $request->request->get('chunkData', []);
  12247.                 $em $this->getDoctrine()->getManager();
  12248.                 foreach ($csv_data as $ind => $data_row) {
  12249. //                    if ($ind == 1)
  12250. //                        continue;
  12251.                     $np $this->getDoctrine()
  12252.                         ->getRepository('ApplicationBundle:ProductByCode')
  12253.                         ->findOneBy(
  12254.                             array(
  12255.                                 'salesCode' => isset($data_row[4]) ? $data_row[4] : 0,
  12256. //                    'approved' =>  GeneralConstant::APPROVED,
  12257.                             )
  12258.                         );
  12259.                     if (!$np)
  12260.                         $np = new ProductByCode();
  12261. //                    $np = new ProductByCode();
  12262.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  12263.                     if (isset($data_row[1])) $np->setProductId($data_row[1]);
  12264.                     if (isset($data_row[0])) $np->setLcNumber($data_row[0]);
  12265.                     if (isset($data_row[2])) $np->setCartonNumber($data_row[2]);
  12266.                     if (isset($data_row[3])) $np->setSerialNo($data_row[3]);
  12267.                     $np->setSerialAssigned(isset($data_row[10]) ? $data_row[10] : 0);
  12268.                     if (isset($data_row[4])) $np->setImei1($data_row[4]);
  12269.                     if (isset($data_row[5])) $np->setImei2($data_row[5]);
  12270.                     if (isset($data_row[6])) $np->setImei3($data_row[6]);
  12271.                     if (isset($data_row[7])) $np->setImei4($data_row[7]);
  12272.                     if (isset($data_row[8])) $np->setBtMac($data_row[8]);
  12273.                     if (isset($data_row[9])) $np->setWlanMac($data_row[9]);
  12274.                     $np->setWarehouseId(isset($data_row[11]) ? $data_row[11] : 0);
  12275.                     $np->setWarehouseActionId(isset($data_row[12]) ? $data_row[12] : 0);
  12276.                     $np->setPosition(isset($data_row[13]) ? $data_row[13] : 0);//in inventory
  12277.                     $np->setPurchaseOrderId(0);
  12278.                     $np->setGrnId(0);
  12279.                     $np->setStage(0);
  12280.                     if (isset($data_row[3])) $np->setSalesCodeRange(json_encode([$data_row[3]]));
  12281. //                $np->setSalesCode($data_row[3]);
  12282.                     if (isset($data_row[4])) $np->setSalesCode($data_row[4]); //IMEI
  12283.                     $np->setSalesCodeSer(0);
  12284.                     $np->setSalesCodeDmy('');
  12285.                     $np->setPurchaseCodeRange("");
  12286.                     $np->setPurchaseReceiptDate(null);
  12287.                     $np->setLastInDate(null);
  12288.                     $np->setStatus(GeneralConstant::ACTIVE);
  12289.                     $np->setTransactionHistory(json_encode([
  12290.                         ]
  12291.                     ));
  12292.                     $np->setPurchaseWarrantyLastDate(null);
  12293.                     $em->persist($np);
  12294.                     $em->flush();
  12295.                 }
  12296.                 return new JsonResponse(array(
  12297.                     "success" => true,
  12298.                     "lastIndex" => $lastIndex,
  12299.                     "file_path" => '',
  12300.                     "csv_data" => $csv_data,
  12301.                     //                "debug_data"=>System::encryptSignature($r)
  12302.                 ));
  12303.             } else {
  12304.                 $path "";
  12305.                 $file_path "";
  12306.                 //            var_dump($request->files);
  12307.                 //        var_dump($request->getFile());
  12308.                 foreach ($request->files as $uploadedFile) {
  12309.                     //            if($uploadedFile->getImage())
  12310.                     //                var_dump($uploadedFile->getFile());
  12311.                     //                var_dump($uploadedFile);
  12312.                     if ($uploadedFile != null) {
  12313.                         $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  12314.                         $path $fileName;
  12315.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  12316.                         if (!file_exists($upl_dir)) {
  12317.                             mkdir($upl_dir0777true);
  12318.                         }
  12319.                         $file $uploadedFile->move($upl_dir$path);
  12320.                     }
  12321.                 }
  12322.                 //        print_r($file);
  12323.                 if ($path != "")
  12324.                     $file_path 'uploads/FileUploads/' $path;
  12325.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  12326.                 //
  12327.                 //            $img_file = file_get_contents($g_path);
  12328.                 //            $r=base64_encode($img_file);
  12329.                 $row 1;
  12330.                 $csv_data = [];
  12331.                 if (($handle fopen($g_path"r")) !== FALSE) {
  12332.                     while (($data fgetcsv($handle1000",")) !== FALSE) {
  12333.                         $num count($data);
  12334.                         $csv_data[$row] = $data;
  12335.                         //                    echo "<p> $num fields in line $row: <br /></p>\n";
  12336.                         $row++;
  12337.                         //                    for ($c=0; $c < $num; $c++) {
  12338.                         //                        echo $data[$c] . "<br />\n";
  12339.                         //                    }
  12340.                     }
  12341.                     fclose($handle);
  12342.                 }
  12343.                 //now getting the relevant checks
  12344.                 $check_list = [];
  12345.                 $em $this->getDoctrine()->getManager();
  12346.                 foreach ($csv_data as $ind => $data_row) {
  12347.                     if ($ind == 1)
  12348.                         continue;
  12349.                     $np = new ProductByCode();
  12350.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  12351.                     $np->setProductId($data_row[1]);
  12352.                     $np->setLcNumber($data_row[0]);
  12353.                     $np->setCartonNumber($data_row[2]);
  12354.                     $np->setSerialNo($data_row[3]);
  12355.                     $np->setSerialAssigned(0);
  12356.                     $np->setImei1($data_row[4]);
  12357.                     $np->setImei2($data_row[5]);
  12358.                     $np->setImei3($data_row[6]);
  12359.                     $np->setImei4($data_row[7]);
  12360.                     $np->setBtMac($data_row[8]);
  12361.                     $np->setWlanMac($data_row[9]);
  12362.                     $np->setWarehouseId(0);
  12363.                     $np->setWarehouseActionId(0);
  12364.                     $np->setPosition(0);//in inventory
  12365.                     $np->setPurchaseOrderId(0);
  12366.                     $np->setGrnId(0);
  12367.                     $np->setStage(0);
  12368.                     $np->setSalesCodeRange(json_encode([$data_row[3]]));
  12369. //                $np->setSalesCode($data_row[3]);
  12370.                     $np->setSalesCode($data_row[4]); //IMEI
  12371.                     $np->setSalesCodeSer(0);
  12372.                     $np->setSalesCodeDmy('');
  12373.                     $np->setPurchaseCodeRange("");
  12374.                     $np->setPurchaseReceiptDate(null);
  12375.                     $np->setLastInDate(null);
  12376.                     $np->setStatus(GeneralConstant::ACTIVE);
  12377.                     $np->setTransactionHistory(json_encode([
  12378.                         ]
  12379.                     ));
  12380.                     $np->setPurchaseWarrantyLastDate(null);
  12381.                     $em->persist($np);
  12382.                     $em->flush();
  12383.                 }
  12384.                 return new JsonResponse(array(
  12385.                     "success" => true,
  12386.                     "lastIndex" => $lastIndex,
  12387.                     "file_path" => $file_path,
  12388.                     "csv_data" => $csv_data,
  12389.                     //                "debug_data"=>System::encryptSignature($r)
  12390.                 ));
  12391.             }
  12392.         }
  12393.         return new JsonResponse(array(
  12394.             "success" => false,
  12395.             "file_path" => '',
  12396.             "csv_data" => [],
  12397.             "lastIndex" => $lastIndex,
  12398.         ));
  12399.     }
  12400.     public
  12401.     function ProductByCodeListAction(Request $request)
  12402.     {
  12403.         $em $this->getDoctrine()->getManager();
  12404.         $companyId $this->getLoggedUserCompanyId($request);
  12405.         $listData Inventory::GetProductListForProductByCodeListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  12406.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  12407.             if ($request->query->has('dataTableQry')) {
  12408.                 return new JsonResponse(
  12409.                     $listData
  12410.                 );
  12411.             }
  12412.         }
  12413.         $q = [];
  12414. //        $q = $this->getDoctrine()
  12415. //            ->getRepository('ApplicationBundle:ProductByCode')
  12416. //            ->findBy(
  12417. //                array(
  12418. //                    'status' => GeneralConstant::ACTIVE,
  12419. ////                    'approved' =>  GeneralConstant::APPROVED,
  12420. //                )
  12421. //
  12422. //            );
  12423.         //temp start
  12424. //        foreach($q as $np) {
  12425. //            if($np->getPosition()==1) {   /// only starting ones or in warehouse ones
  12426. //                $temp_obj = json_decode($np->getTransactionHistory());
  12427. //                if ($temp_obj != null) {
  12428. //                    $transHistory = [];
  12429. //                    $transHistory[] = $temp_obj;
  12430. //                    $np->setTransactionHistory(json_encode($transHistory));
  12431. //                }
  12432. //            }
  12433. //            $em->flush();
  12434. //        }
  12435.         ///temp end
  12436.         $stage_list = array(
  12437.             => 'Pending',
  12438.             => 'Pending',
  12439.             => 'Complete',
  12440.             => 'Partial',
  12441.         );
  12442.         $data = [];
  12443. //        foreach($q as $entry)
  12444. //        {
  12445. //            $data[]=array(
  12446. //                'doc_date'=>$entry->getStockRequisitionDate(),
  12447. //                'id'=>$entry->getStockRequisitionId(),
  12448. //                'doc_hash'=>$entry->getDocumentHash(),
  12449. //                'approval_status'=>GeneralConstant::$approvalStatus[$entry->getApproved()],
  12450. //                'stage'=>$stage_list[$entry->getStage()]
  12451. //
  12452. //            );
  12453. //        }
  12454.         return $this->render('@Inventory/pages/views/product_by_code_list.html.twig',
  12455.             array(
  12456.                 'page_title' => 'Product List',
  12457.                 'data' => $q,
  12458. //                'listData' => $listData,
  12459.                 'products' => Inventory::ProductList($em),
  12460.                 'warehouseList' => Inventory::WarehouseList($em)
  12461.             )
  12462.         );
  12463.     }
  12464. //SR
  12465.     public
  12466.     function SrListAction(Request $request)
  12467.     {
  12468.         $q $this->getDoctrine()
  12469.             ->getRepository('ApplicationBundle:StockRequisition')
  12470.             ->findBy(
  12471.                 array(
  12472.                     'status' => GeneralConstant::ACTIVE,
  12473. //                    'approved' =>  GeneralConstant::APPROVED,
  12474.                 )
  12475.                 ,
  12476.                 array(
  12477.                     'stockRequisitionDate' => 'DESC'
  12478.                 )
  12479.             );
  12480.         $stage_list = array(
  12481.             => 'Pending',
  12482.             => 'Pending',
  12483.             => 'Complete',
  12484.             => 'Partial',
  12485.         );
  12486.         $data = [];
  12487.         foreach ($q as $entry) {
  12488.             $data[] = array(
  12489.                 'doc_date' => $entry->getStockRequisitionDate(),
  12490.                 'id' => $entry->getStockRequisitionId(),
  12491.                 'doc_hash' => $entry->getDocumentHash(),
  12492.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12493.                 'stage' => $stage_list[$entry->getStage()],
  12494.                 'indentTagged' => $entry->getIndentTagged(),
  12495.                 'srIds' => $entry->getSrIds(),
  12496.                 'irIds' => $entry->getIrIds(),
  12497.                 'prIds' => $entry->getPrIds(),
  12498.                 'poIds' => $entry->getPoIds(),
  12499.             );
  12500.         }
  12501.         return $this->render('@Inventory/pages/views/sr_list.html.twig',
  12502.             array(
  12503.                 'page_title' => 'Stock Requisition List',
  12504.                 'data' => $data
  12505.             )
  12506.         );
  12507.     }
  12508.     public
  12509.     function ViewSrAction(Request $request$id)
  12510.     {
  12511.         $em $this->getDoctrine()->getManager();
  12512.         $dt Inventory::GetSrDetails($em$id);
  12513.         return $this->render('@Inventory/pages/views/view_stock_requisition.html.twig',
  12514.             array(
  12515.                 'page_title' => 'Stock requisition',
  12516.                 'data' => $dt,
  12517.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12518.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12519.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12520.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12521.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12522.                     $id,
  12523.                     $dt['created_by'],
  12524.                     $dt['edited_by'])
  12525.             )
  12526.         );
  12527.     }
  12528.     public
  12529.     function PrintSrAction(Request $request$id)
  12530.     {
  12531.         $em $this->getDoctrine()->getManager();
  12532.         $dt Inventory::GetSrDetails($em$id);
  12533.         $company_data Company::getCompanyData($em1);
  12534.         $document_mark = array(
  12535.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12536.             'copy' => ''
  12537.         );
  12538.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12539.             $html $this->renderView('@Inventory/pages/print/print_sr.html.twig',
  12540.                 array(
  12541.                     //full array here
  12542.                     'pdf' => true,
  12543.                     'page_title' => 'Stock Requisition',
  12544.                     'export' => 'pdf,print',
  12545.                     'data' => $dt,
  12546.                     'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12547.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12548.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12549.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12550.                         array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12551.                         $id,
  12552.                         $dt['created_by'],
  12553.                         $dt['edited_by']),
  12554.                     'document_mark_image' => $document_mark['original'],
  12555.                     'company_name' => $company_data->getName(),
  12556.                     'company_data' => $company_data,
  12557.                     'company_address' => $company_data->getAddress(),
  12558.                     'company_image' => $company_data->getImage(),
  12559.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12560.                     'red' => 0
  12561.                 )
  12562.             );
  12563.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12564. //                'orientation' => 'landscape',
  12565. //                'enable-javascript' => true,
  12566. //                'javascript-delay' => 1000,
  12567.                 'no-stop-slow-scripts' => false,
  12568.                 'no-background' => false,
  12569.                 'lowquality' => false,
  12570.                 'encoding' => 'utf-8',
  12571. //            'images' => true,
  12572. //            'cookie' => array(),
  12573.                 'dpi' => 300,
  12574.                 'image-dpi' => 300,
  12575. //                'enable-external-links' => true,
  12576. //                'enable-internal-links' => true
  12577.             ));
  12578.             return new Response(
  12579.                 $pdf_response,
  12580.                 200,
  12581.                 array(
  12582.                     'Content-Type' => 'application/pdf',
  12583.                     'Content-Disposition' => 'attachment; filename="stock_requisition_' $id '.pdf"'
  12584.                 )
  12585.             );
  12586.         }
  12587.         return $this->render('@Inventory/pages/print/print_sr.html.twig',
  12588.             array(
  12589.                 'page_title' => 'Stock Requisition',
  12590.                 'export' => 'pdf,print',
  12591.                 'data' => $dt,
  12592.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12593.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12594.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12595.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12596.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12597.                     $id,
  12598.                     $dt['created_by'],
  12599.                     $dt['edited_by']),
  12600.                 'document_mark_image' => $document_mark['original'],
  12601.                 'company_name' => $company_data->getName(),
  12602.                 'company_data' => $company_data,
  12603.                 'company_address' => $company_data->getAddress(),
  12604.                 'company_image' => $company_data->getImage(),
  12605.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12606.                 'red' => 0
  12607.             )
  12608.         );
  12609.     }
  12610. //IR
  12611.     public
  12612.     function IrListAction(Request $request)
  12613.     {
  12614.         $q $this->getDoctrine()
  12615.             ->getRepository('ApplicationBundle:StoreRequisition')
  12616.             ->findBy(
  12617.                 array(
  12618.                     'status' => GeneralConstant::ACTIVE,
  12619. //                    'approved' =>  GeneralConstant::APPROVED,
  12620.                 ),
  12621.                 array(
  12622.                     'storeRequisitionDate' => 'DESC'
  12623.                 )
  12624.             );
  12625.         $stage_list = array(
  12626.             => 'Pending',
  12627.             => 'Pending',
  12628.             => 'Complete',
  12629.             => 'Partial',
  12630.         );
  12631.         $data = [];
  12632.         foreach ($q as $entry) {
  12633.             $data[] = array(
  12634.                 'doc_date' => $entry->getStoreRequisitionDate(),
  12635.                 'id' => $entry->getStoreRequisitionId(),
  12636.                 'doc_hash' => $entry->getDocumentHash(),
  12637.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12638.                 'stage' => $stage_list[$entry->getStage()],
  12639.                 'prTagged' => $entry->getIndentTagged(),
  12640.                 'srIds' => $entry->getSrIds(),
  12641.                 'irIds' => $entry->getIrIds(),
  12642.                 'prIds' => $entry->getPrIds(),
  12643.                 'poIds' => $entry->getPoIds(),
  12644.             );
  12645.         }
  12646.         return $this->render('@Inventory/pages/views/ir_list.html.twig',
  12647.             array(
  12648.                 'page_title' => 'Indent Requisition List',
  12649.                 'data' => $data
  12650.             )
  12651.         );
  12652.     }
  12653.     public
  12654.     function ViewIrAction(Request $request$id)
  12655.     {
  12656.         $em $this->getDoctrine()->getManager();
  12657.         $dt Inventory::GetIrDetails($em$id);
  12658.         return $this->render('@Inventory/pages/views/view_indent_requisition.html.twig',
  12659.             array(
  12660.                 'page_title' => 'Indent',
  12661.                 'data' => $dt,
  12662.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12663.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12664.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12665.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12666.                     $id,
  12667.                     $dt['created_by'],
  12668.                     $dt['edited_by'])
  12669.             )
  12670.         );
  12671.     }
  12672.     public
  12673.     function PrintIrAction(Request $request$id)
  12674.     {
  12675.         $em $this->getDoctrine()->getManager();
  12676.         $dt Inventory::GetIrDetails($em$id);
  12677.         $company_data Company::getCompanyData($em1);
  12678.         $document_mark = array(
  12679.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12680.             'copy' => ''
  12681.         );
  12682.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12683.             $html $this->renderView('@Inventory/pages/print/print_ir.html.twig',
  12684.                 array(
  12685.                     //full array here
  12686.                     'pdf' => true,
  12687.                     'page_title' => 'Indent Requisition',
  12688.                     'export' => 'pdf,print',
  12689.                     'data' => $dt,
  12690.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12691.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12692.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12693.                         array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12694.                         $id,
  12695.                         $dt['created_by'],
  12696.                         $dt['edited_by']),
  12697.                     'document_mark_image' => $document_mark['original'],
  12698.                     'company_name' => $company_data->getName(),
  12699.                     'company_data' => $company_data,
  12700.                     'company_address' => $company_data->getAddress(),
  12701.                     'company_image' => $company_data->getImage(),
  12702.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12703.                     'red' => 0
  12704.                 )
  12705.             );
  12706.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12707. //                'orientation' => 'landscape',
  12708. //                'enable-javascript' => true,
  12709. //                'javascript-delay' => 1000,
  12710.                 'no-stop-slow-scripts' => false,
  12711.                 'no-background' => false,
  12712.                 'lowquality' => false,
  12713.                 'encoding' => 'utf-8',
  12714. //            'images' => true,
  12715. //            'cookie' => array(),
  12716.                 'dpi' => 300,
  12717.                 'image-dpi' => 300,
  12718. //                'enable-external-links' => true,
  12719. //                'enable-internal-links' => true
  12720.             ));
  12721.             return new Response(
  12722.                 $pdf_response,
  12723.                 200,
  12724.                 array(
  12725.                     'Content-Type' => 'application/pdf',
  12726.                     'Content-Disposition' => 'attachment; filename="indent_' $id '.pdf"'
  12727.                 )
  12728.             );
  12729.         }
  12730.         return $this->render('@Inventory/pages/print/print_ir.html.twig',
  12731.             array(
  12732.                 'page_title' => 'Indent Requisition',
  12733.                 'export' => 'pdf,print',
  12734.                 'data' => $dt,
  12735.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12736.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12737.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12738.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12739.                     $id,
  12740.                     $dt['created_by'],
  12741.                     $dt['edited_by']),
  12742.                 'document_mark_image' => $document_mark['original'],
  12743.                 'company_name' => $company_data->getName(),
  12744.                 'company_data' => $company_data,
  12745.                 'company_address' => $company_data->getAddress(),
  12746.                 'company_image' => $company_data->getImage(),
  12747.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12748.                 'red' => 0
  12749.             )
  12750.         );
  12751.     }
  12752. //PR
  12753.     public
  12754.     function PrListAction(Request $request)
  12755.     {
  12756.         $q $this->getDoctrine()
  12757.             ->getRepository('ApplicationBundle:PurchaseRequisition')
  12758.             ->findBy(
  12759.                 array(
  12760.                     'status' => GeneralConstant::ACTIVE,
  12761. //                    'approved' =>  GeneralConstant::APPROVED,
  12762.                 ),
  12763.                 array(
  12764.                     'purchaseRequisitionDate' => 'DESC'
  12765.                 )
  12766.             );
  12767.         $stage_list = array(
  12768.             => 'Pending',
  12769.             => 'Pending',
  12770.             => 'Complete',
  12771.             => 'Partial',
  12772.         );
  12773.         $data = [];
  12774.         foreach ($q as $entry) {
  12775.             $data[] = array(
  12776.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  12777.                 'id' => $entry->getPurchaseRequisitionId(),
  12778.                 'doc_hash' => $entry->getDocumentHash(),
  12779.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12780.                 'acquisition_status' => $entry->getAcquisitionStatus(),
  12781.                 'acquisition_start_date' => $entry->getAcquisitionStartDate(),
  12782.                 'acquisition_end_date' => $entry->getAcquisitionEndDate(),
  12783.                 'acquisition_method' => $entry->getquotationAcquisitionMethod(),
  12784.                 'poTagged' => $entry->getPoTagged(),
  12785.                 'typeHash' => $entry->getTypehash(),
  12786.                 'srIds' => $entry->getSrIds(),
  12787.                 'irIds' => $entry->getIrIds(),
  12788.                 'prIds' => $entry->getPrIds(),
  12789.                 'poIds' => $entry->getPoIds(),
  12790.             );
  12791.         }
  12792.         return $this->render('@Inventory/pages/views/pr_list.html.twig',
  12793.             array(
  12794.                 'page_title' => 'Purchase Requisition List',
  12795.                 'data' => $data
  12796.             )
  12797.         );
  12798.     }
  12799.     public
  12800.     function ServiceRequisitionListAction(Request $request)
  12801.     {
  12802.         $q $this->getDoctrine()
  12803.             ->getRepository('ApplicationBundle:PurchaseRequisition')
  12804.             ->findBy(
  12805.                 array(
  12806.                     'status' => GeneralConstant::ACTIVE,
  12807. //                    'approved' =>  GeneralConstant::APPROVED,
  12808.                 ),
  12809.                 array(
  12810.                     'purchaseRequisitionDate' => 'DESC'
  12811.                 )
  12812.             );
  12813.         $stage_list = array(
  12814.             => 'Pending',
  12815.             => 'Pending',
  12816.             => 'Complete',
  12817.             => 'Partial',
  12818.         );
  12819.         $data = [];
  12820.         foreach ($q as $entry) {
  12821.             $data[] = array(
  12822.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  12823.                 'id' => $entry->getPurchaseRequisitionId(),
  12824.                 'doc_hash' => $entry->getDocumentHash(),
  12825.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12826.                 'poTagged' => $entry->getPoTagged(),
  12827.                 'typeHash' => $entry->getTypehash(),
  12828.                 'srIds' => $entry->getSrIds(),
  12829.                 'irIds' => $entry->getIrIds(),
  12830.                 'prIds' => $entry->getPrIds(),
  12831.                 'poIds' => $entry->getPoIds(),
  12832.             );
  12833.         }
  12834.         return $this->render('@Inventory/pages/views/service_requisition_list.html.twig',
  12835.             array(
  12836.                 'page_title' => 'Service Requisition List',
  12837.                 'data' => $data
  12838.             )
  12839.         );
  12840.     }
  12841.     public
  12842.     function ViewPrAction(Request $request$id)
  12843.     {
  12844.         $em $this->getDoctrine()->getManager();
  12845.         $dt Inventory::GetPrDetails($em$id);
  12846.         $companyId $this->getLoggedUserCompanyId($request);
  12847.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  12848.             array(
  12849.                 'page_title' => 'Purchase Requisition',
  12850.                 'data' => $dt,
  12851.                 'branchList' => Client::BranchList($em$companyId),
  12852.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12853.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12854.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12855.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12856.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12857.                     $id,
  12858.                     $dt['created_by'],
  12859.                     $dt['edited_by'])
  12860.             )
  12861.         );
  12862.     }
  12863.     public
  12864.     function ViewServiceRequisitionAction(Request $request$id)
  12865.     {
  12866.         $em $this->getDoctrine()->getManager();
  12867.         $dt Inventory::GetPrDetails($em$id);
  12868.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  12869.             array(
  12870.                 'page_title' => 'Service Requisition',
  12871.                 'data' => $dt,
  12872.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12873.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12874.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12875.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12876.                     $id,
  12877.                     $dt['created_by'],
  12878.                     $dt['edited_by'])
  12879.             )
  12880.         );
  12881.     }
  12882.     public
  12883.     function PrintPrAction(Request $request$id)
  12884.     {
  12885.         $em $this->getDoctrine()->getManager();
  12886.         $dt Inventory::GetPrDetails($em$id);
  12887.         $companyId $this->getLoggedUserCompanyId($request);
  12888.         $company_data Company::getCompanyData($em$companyId);
  12889.         $document_mark = array(
  12890.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12891.             'copy' => ''
  12892.         );
  12893.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12894.             $html $this->renderView('@Inventory/pages/print/print_pr.html.twig',
  12895.                 array(
  12896.                     //full array here
  12897.                     'pdf' => true,
  12898.                     'page_title' => 'Purchase Requisition',
  12899.                     'export' => 'pdf,print',
  12900.                     'data' => $dt,
  12901.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12902.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12903.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12904.                         array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12905.                         $id,
  12906.                         $dt['created_by'],
  12907.                         $dt['edited_by']),
  12908.                     'document_mark_image' => $document_mark['original'],
  12909.                     'branchList' => Client::BranchList($em$companyId),
  12910.                     'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12911.                     'company_name' => $company_data->getName(),
  12912.                     'company_data' => $company_data,
  12913.                     'company_address' => $company_data->getAddress(),
  12914.                     'company_image' => $company_data->getImage(),
  12915.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12916.                     'red' => 0
  12917.                 )
  12918.             );
  12919.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12920. //                'orientation' => 'landscape',
  12921. //                'enable-javascript' => true,
  12922. //                'javascript-delay' => 1000,
  12923.                 'no-stop-slow-scripts' => false,
  12924.                 'no-background' => false,
  12925.                 'lowquality' => false,
  12926.                 'encoding' => 'utf-8',
  12927. //            'images' => true,
  12928. //            'cookie' => array(),
  12929.                 'dpi' => 300,
  12930.                 'image-dpi' => 300,
  12931. //                'enable-external-links' => true,
  12932. //                'enable-internal-links' => true
  12933.             ));
  12934.             return new Response(
  12935.                 $pdf_response,
  12936.                 200,
  12937.                 array(
  12938.                     'Content-Type' => 'application/pdf',
  12939.                     'Content-Disposition' => 'attachment; filename="purchase_requisition_' $id '.pdf"'
  12940.                 )
  12941.             );
  12942.         }
  12943.         return $this->render('@Inventory/pages/print/print_pr.html.twig',
  12944.             array(
  12945.                 'page_title' => 'Purchase Requisition',
  12946.                 'export' => 'pdf,print',
  12947.                 'data' => $dt,
  12948.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12949.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12950.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12951.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12952.                     $id,
  12953.                     $dt['created_by'],
  12954.                     $dt['edited_by']),
  12955.                 'document_mark_image' => $document_mark['original'],
  12956.                 'company_name' => $company_data->getName(),
  12957.                 'company_data' => $company_data,
  12958.                 'branchList' => Client::BranchList($em$companyId),
  12959.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12960.                 'company_address' => $company_data->getAddress(),
  12961.                 'company_image' => $company_data->getImage(),
  12962.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12963.                 'red' => 0
  12964.             )
  12965.         );
  12966.     }
  12967.     public
  12968.     function CreateSecondaryDeliveryReceiptAction(Request $request)
  12969.     {
  12970.         $em $this->getDoctrine()->getManager();
  12971.         $companyId $this->getLoggedUserCompanyId($request);
  12972.         $userBranchIdList $request->getSession()->get('branchIdList');
  12973.         if ($userBranchIdList == null$userBranchIdList = [];
  12974.         $userBranchId $request->getSession()->get('branchId');
  12975.         if ($request->isMethod('POST')) {
  12976.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  12977.             $dochash $request->request->get('docHash'); //change
  12978.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12979.             $approveRole 1;  //created
  12980.             $approveHash $request->request->get('approvalHash');
  12981.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  12982.                 $loginId$approveRole$approveHash)
  12983.             ) {
  12984.                 $this->addFlash(
  12985.                     'error',
  12986.                     'Sorry Couldnot insert Data.'
  12987.                 );
  12988.             } else {
  12989.                 $receiptId SalesOrderM::CreateNewSecondaryDeliveryReceipt($this->getDoctrine()->getManager(), $request->request,
  12990.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  12991.                     $this->getLoggedUserCompanyId($request));
  12992.                 //now add Approval info
  12993.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12994.                 $approveRole 1;  //created
  12995.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12996.                     $receiptId,
  12997.                     $loginId,
  12998.                     $approveRole,
  12999.                     $request->request->get('approvalHash'));
  13000.                 $options = array(
  13001.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  13002.                     'notification_server' => $this->container->getParameter('notification_server'),
  13003.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  13004.                     'url' => $this->generateUrl(
  13005.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  13006.                         ['entity_view_route_path_name']
  13007.                     )
  13008.                 );
  13009.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  13010.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  13011.                     $receiptId,
  13012.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  13013.                 );
  13014.                 $this->addFlash(
  13015.                     'success',
  13016.                     'New Delivery Receipt Created'
  13017.                 );
  13018.                 $url $this->generateUrl(
  13019.                     'view_delivery_receipt'
  13020.                 );
  13021.                 return $this->redirect($url "/" $receiptId);
  13022.             }
  13023.         }
  13024.         $debugData = [];
  13025. //        $dr_data=$em->getRepository('ApplicationBundle:DeliveryReceipt')->findOneBy(
  13026. //            array(
  13027. //                'deliveryReceiptId'=>$dr_id
  13028. //            )
  13029. //        );
  13030.         $new_swld = new \DateTime('2017-07-09');
  13031. //        if ($entry->getWarranty() > 0)
  13032. //            $new_swld->modify('+' . $entry->getWarranty() . ' month');
  13033.         $debugData[] = $new_swld->format('Y-m-d');
  13034.         $debugData[] = $new_swld;
  13035. //        $debugData[]=$dr_data->getDeliveryReceiptDate();
  13036.         $debugData[] = '+' '1' ' month';
  13037.         $branchList Client::BranchList($em$companyId, [], $userBranchIdList);
  13038.         $warehouseIds = [];
  13039.         foreach ($branchList as $br) {
  13040.             $warehouseIds[] = $br['warehouseId'];
  13041.         }
  13042.         return $this->render('@Inventory/pages/input_forms/secondaryDeliveryReceipt.html.twig',
  13043.             array(
  13044.                 'page_title' => 'New Delivery Receipt',
  13045.                 'ExistingClients' => Accounts::getClientLedgerHeads($em),
  13046.                 'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($em),
  13047.                 'ClientList' => SalesOrderM::GetSecondaryClientList($em),
  13048.                 'warehouse' => Inventory::WarehouseList($em$companyId$warehouseIds),
  13049.                 'salesOrders' => SalesOrderM::SecondarySalesOrderListPendingDelivery($em$warehouseIds),
  13050.                 'salesOrdersArray' => SalesOrderM::SecondarySalesOrderListPendingDeliveryArray($em$warehouseIds),
  13051.                 'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
  13052.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
  13053.                 'debugData' => $debugData,
  13054.             )
  13055.         );
  13056.     }
  13057.     public
  13058.     function AddUnitTypeAction(Request $request$id 0)
  13059.     {
  13060.         $em $this->getDoctrine()->getManager();
  13061.         $companyId $this->getLoggedUserCompanyId($request);
  13062.         if ($request->isMethod('POST')) {
  13063.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13064.             $unitType = new UnitType();
  13065.             $unitType->setName($request->request->get('name'));
  13066.             $unitType->setStatus(1);
  13067.             $em->persist($unitType);
  13068.             $em->flush();
  13069.             $this->addFlash(
  13070.                 'success',
  13071.                 'Unit Type Added'
  13072.             );
  13073.         }
  13074.         $unitTypeDeatails $em->getRepository(UnitType::class)->findAll();
  13075.         return $this->render('@Inventory/pages/input_forms/addUnitType.html.twig',
  13076.             array(
  13077.                 'page_title' => 'Add Unit Type',
  13078.                 'unitTypeDeatails' => $unitTypeDeatails
  13079.             )
  13080.         );
  13081.     }
  13082.     public function AddSpecTypeAction(Request $request$id 0)
  13083.     {
  13084.         $em $this->getDoctrine()->getManager();
  13085.         $companyId $this->getLoggedUserCompanyId($request);
  13086.         if ($request->isMethod('POST')) {
  13087.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13088.             $specType = new SpecType();
  13089.             $specType->setName($request->request->get('name'));
  13090.             $specType->setStatus(1);
  13091.             $em->persist($specType);
  13092.             $em->flush();
  13093.             $this->addFlash(
  13094.                 'success',
  13095.                 'Spec Type Added'
  13096.             );
  13097.         }
  13098.         $specTypeDeatails $em->getRepository(SpecType::class)->findAll();
  13099.         return $this->render('@Inventory/pages/input_forms/addSpecType.html.twig',
  13100.             array(
  13101.                 'page_title' => 'Add Spec Type',
  13102.                 'specTypeDeatails' => $specTypeDeatails
  13103.             )
  13104.         );
  13105.     }
  13106.     public
  13107.     function SubcategoryListAction()
  13108.     {
  13109.         return $this->render('@Inventory/pages/input_forms/subCategoryList.html.twig',
  13110.             array(
  13111.                 'page_title' => 'Sub Category List',
  13112.             )
  13113.         );
  13114.     }
  13115.     public function SyncProductAction(Request $request$id)
  13116.     {
  13117.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  13118.         $em_local $this->getDoctrine()->getManager();
  13119.         if ($systemType == '_ERP_') {
  13120.             $product $em_local->getRepository('ApplicationBundle:InvProducts')->find($id);
  13121.             if (!$product) {
  13122.                 return new JsonResponse(['error' => 'Product not found'], 404);
  13123.             }
  13124.             // Get category details
  13125.             $category $em_local->getRepository('ApplicationBundle:InvProductCategories')->find($product->getCategoryId());
  13126.             $brand $em_local -> getRepository('ApplicationBundle:BrandCompany')->find($product->getBrandCompany());
  13127.             $productData = [];
  13128.             $categoryData = [];
  13129.             $brandData = [];
  13130.             // Get product fields
  13131.             $reflectionClass = new \ReflectionClass($product);
  13132.             foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  13133.                 if (strpos($method->getName(), 'get') === 0) {
  13134.                     $property lcfirst(str_replace('get'''$method->getName()));
  13135.                     $productData[$property] = $method->invoke($product);
  13136.                 }
  13137.             }
  13138.             // Get category fields
  13139.             if ($category) {
  13140.                 $categoryReflection = new \ReflectionClass($category);
  13141.                 foreach ($categoryReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  13142.                     if (strpos($method->getName(), 'get') === 0) {
  13143.                         $property lcfirst(str_replace('get'''$method->getName()));
  13144.                         $categoryData[$property] = $method->invoke($category);
  13145.                     }
  13146.                 }
  13147.             }
  13148.             // Brand data
  13149.             if ($brand) {
  13150.                 $brandReflection = new \ReflectionClass($brand);
  13151.                 foreach ($brandReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  13152.                     if (strpos($method->getName(), 'get') === 0) {
  13153.                         $property lcfirst(str_replace('get'''$method->getName()));
  13154.                         $brandData[$property] = $method->invoke($brand);
  13155.                     }
  13156.                 }
  13157.             }
  13158.             // Store product data in pending_data
  13159.             $product->setPendingData(json_encode($productData));
  13160.             $em_local->flush();
  13161.             // Send  product,brand & category to central
  13162.             $syncData = [
  13163.                 'product' => $productData,
  13164.                 'category' => $categoryData,
  13165.                 'brand' => $brandData
  13166.             ];
  13167.             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/product_sync/' $id;
  13168.             $curl curl_init();
  13169.             curl_setopt_array($curl, [
  13170.                 CURLOPT_RETURNTRANSFER => true,
  13171.                 CURLOPT_POST => true,
  13172.                 CURLOPT_URL => $urlToCall,
  13173.                 CURLOPT_CONNECTTIMEOUT => 10,
  13174.                 CURLOPT_SSL_VERIFYPEER => false,
  13175.                 CURLOPT_SSL_VERIFYHOST => false,
  13176.                 CURLOPT_HTTPHEADER => [],
  13177.                 CURLOPT_POSTFIELDS => ['syncData' => json_encode($syncData)]
  13178.             ]);
  13179.             $retData curl_exec($curl);
  13180.             $errData curl_error($curl);
  13181.             curl_close($curl);
  13182.             if ($errData) {
  13183.                 return new JsonResponse(['error' => $errData], 500);
  13184.             }
  13185.             $retDataObj json_decode($retDatatrue);
  13186.             if (isset($retDataObj['globalId'])) {
  13187.                 $product->setGlobalId($retDataObj['globalId']);
  13188.                 $em_local->flush();
  13189.             }
  13190.             return new JsonResponse(['message' => 'Product (pending) and category synced to central server!']);
  13191.         }
  13192.         // CENTRAL SYSTEM PROCESSING
  13193.         else if ($systemType == '_CENTRAL_') {
  13194.             $requestData $request->get('syncData');
  13195.             if (!$requestData) {
  13196.                 return new JsonResponse(['error' => 'Invalid data received'], 400);
  13197.             }
  13198.             $requestData json_decode($requestDatatrue);
  13199.             $productData $requestData['product'] ?? null;
  13200.             $categoryData $requestData['category'] ?? null;
  13201.             $brandData $requestData['brand'] ?? null;
  13202.             if (!$productData) {
  13203.                 return new JsonResponse(['error' => 'Product data missing'], 400);
  13204.             }
  13205.             // Process product (Store in pending_data)
  13206.             $product $em_local->getRepository('ApplicationBundle:InvProducts')->find($productData['id']) ?? new InvProducts();
  13207.             // Store in pending_data until approval
  13208.             $product->setPendingData(json_encode($productData));
  13209.             $this->ApproveProductAction($id);
  13210.             $em_local->persist($product);
  13211.             // Process category (Save directly)
  13212.             if ($categoryData) {
  13213.                 $category $em_local->getRepository('ApplicationBundle:InvProductCategories')->find($categoryData['id']) ?? new InvProductCategories();
  13214.                 foreach ($categoryData as $field => $value) {
  13215.                     if ($field === 'id') continue;
  13216.                     $setterMethod 'set' ucfirst($field);
  13217.                     if (method_exists($category$setterMethod)) {
  13218.                         $category->$setterMethod($value);
  13219.                     }
  13220.                 }
  13221.                 $em_local->persist($category);
  13222.             }
  13223.             // process brand data
  13224.             if($brandData){
  13225.                 $brand $em_local->getRepository('ApplicationBundle:BrandCompany')->find($brandData['id']) ?? new BrandCompany();
  13226.                 foreach ($brandData as $field => $value){
  13227.                     if($field === 'id') continue;
  13228.                     $setterMethod 'set'.ucfirst($field);
  13229.                     if(method_exists($brand,$setterMethod)){
  13230.                         $brand->$setterMethod($value);
  13231.                     }
  13232.                 }
  13233.                 $em_local->persist($brand);
  13234.             }
  13235.             $em_local->flush();
  13236.             return new JsonResponse(['globalId' => $product->getId()]);
  13237.         }
  13238.         return new JsonResponse("Product (pending) and category updated successfully in central!");
  13239.     }
  13240.     public function ApproveProductAction($id)
  13241.     {
  13242.         $em $this->getDoctrine()->getManager();
  13243.         $product $em->getRepository('ApplicationBundle:InvProducts')->find($id);
  13244.         if (!$product) {
  13245.             return new JsonResponse(['error' => 'Product not found'], 404);
  13246.         }
  13247.         $pendingData $product->getPendingData();
  13248.         if (!$pendingData) {
  13249.             return new JsonResponse(['error' => 'No pending data found for this product'], 400);
  13250.         }
  13251.         $data json_decode($pendingDatatrue);
  13252.         if (!$data || !is_array($data)) {
  13253.             return new JsonResponse(['error' => 'Invalid pending data format'], 400);
  13254.         }
  13255.         // Populate actual fields
  13256.         foreach ($data as $field => $value) {
  13257.             if ($field === 'id') continue; // Skip ID
  13258.             $setter 'set' ucfirst($field);
  13259.             if (method_exists($product$setter)) {
  13260.                 $product->$setter($value);
  13261.             }
  13262.         }
  13263.         $product->setPendingData(null); // Clear pending data
  13264.         $em->flush();
  13265.         return new JsonResponse(['message' => 'Product approved and data applied successfully!']);
  13266.     }
  13267. }