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->getPurchaseOrderItemId(),
  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.             $vatAmount 1*$po->getVatAmount();
  4690.             $priceAfterDiscount $po->getSupplierPayableAmount() - $po->getVatAmount();
  4691.             $vatRate = ($vatAmount/$priceAfterDiscount)*100;
  4692.             $po_data = array(
  4693.                 'docHash' => $po->getDocumentHash(),
  4694.                 'docDate' => $po->getPurchaseOrderDate(),
  4695.                 'supplierId' => $po->getSupplierId(),
  4696.                 'supplierName' => $po->getSupplierId(),
  4697.                 'vatRate' => $vatRate,
  4698.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  4699.                 'aitRate' => $po->getAitRate(),
  4700.                 'aitAmount' => $po->getAitAmount(),
  4701.                 'tdsRate' => $po->getTdsRate(),
  4702.                 'tdsAmount' => $po->getTdsAmount(),
  4703.                 'vdsRate' => $po->getVdsRate(),
  4704.                 'vdsAmount' => $po->getVdsAmount(),
  4705.                 'discountRate' => $po->getDiscountRate(),
  4706. //                'discountAmount' => $po->getVatAmount(),
  4707.                 'vatAmount' => $vatAmount,
  4708.                 'discountAmount' => $po->getDiscountAmount(),
  4709.                 'supplierPayableAmount'=> $po->getSupplierPayableAmount(),
  4710.                 'priceAfterDiscount' =>  $priceAfterDiscount
  4711.             );
  4712.             foreach ($Content_obj as $item) {
  4713.                 $Content[] = $item;
  4714.             }
  4715.             foreach ($Content_service_obj as $item) {
  4716.                 $ContentService[] = $item;
  4717.             }
  4718.             if ($Content) {
  4719.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  4720.             }
  4721.             return new JsonResponse(array("success" => false));
  4722.         }
  4723.         return new JsonResponse(array("success" => false));
  4724.     }
  4725.     public function GetPoDetailsForPiAction(Request $request$poId)
  4726.     {
  4727.     }
  4728.     public function GetPoDetailsAction(Request $request$poId)
  4729.     {
  4730.         if ($request->isMethod('POST')) {
  4731.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findBy(
  4732.                 array('purchaseOrderId' => $poId));
  4733.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4734.                 array('purchaseOrderId' => $poId));
  4735.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4736.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4737.             $Content = [];
  4738.             $po_items_list = [];
  4739.             foreach ($po_items as $entry) {
  4740.                 $po_items_list[] = array(
  4741.                     'productId' => $entry->getProductId(),
  4742.                     'productName' => $productList[$entry->getProductId()]['name'],
  4743.                     'price' => $entry->getPrice(),
  4744.                     'unit' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  4745.                     'received' => $entry->getReceived(),
  4746.                     'qty' => $entry->getQty(),
  4747.                     'balance' => $entry->getBalance()
  4748.                 );
  4749.             }
  4750.             $po_data = [];
  4751.             $po_data = array(
  4752.                 'docHash' => $po->getDocumentHash(),
  4753.                 'docDate' => $po->getPurchaseOrderDate(),
  4754.                 'supplierId' => $po->getSupplierId(),
  4755.                 'supplierName' => $po->getSupplierId(),
  4756.             );
  4757.             if ($po_data) {
  4758.                 return new JsonResponse(array("success" => true"content" => $po_data));
  4759.             }
  4760.             return new JsonResponse(array("success" => false));
  4761.         }
  4762.         return new JsonResponse(array("success" => false));
  4763.     }
  4764.     public function CreateSalesReplacementAction(Request $request)
  4765.     {
  4766.         $em $this->getDoctrine()->getManager();
  4767.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4768.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4769.         if ($request->isMethod('POST')) {
  4770.             $em $this->getDoctrine()->getManager();
  4771.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesReplacement']; //change
  4772.             $dochash $request->request->get('voucherNumber'); //change
  4773.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4774.             $approveRole $request->request->get('approvalRole');
  4775.             $approveHash $request->request->get('approvalHash');
  4776.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4777.                 $loginId$approveRole$approveHash)
  4778.             ) {
  4779.                 $this->addFlash(
  4780.                     'error',
  4781.                     'Sorry Couldnot insert Data.'
  4782.                 );
  4783.             } else {
  4784.                 if ($request->request->has('check_allowed'))
  4785.                     $check_allowed 1;
  4786.                 $StID Inventory::CreateNewSalesReplacement(
  4787.                     $this->getDoctrine()->getManager(),
  4788.                     $request->request,
  4789.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  4790.                     $this->getLoggedUserCompanyId($request)
  4791.                 );
  4792.                 //now add Approval info
  4793.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4794.                 $approveRole 1;  //created
  4795.                 $options = array(
  4796.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4797.                     'notification_server' => $this->container->getParameter('notification_server'),
  4798.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4799.                     'url' => $this->generateUrl(
  4800.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesReplacement']]
  4801.                         ['entity_view_route_path_name']
  4802.                     )
  4803.                 );
  4804.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4805.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4806.                     $StID,
  4807.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  4808.                 );
  4809.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesReplacement'], $StID,
  4810.                     $loginId,
  4811.                     $approveRole,
  4812.                     $request->request->get('approvalHash'));
  4813.                 $this->addFlash(
  4814.                     'success',
  4815.                     'Stock Transfer Added.'
  4816.                 );
  4817.                 $url $this->generateUrl(
  4818.                     'view_st'
  4819.                 );
  4820.                 return $this->redirect($url "/" $StID);
  4821.             }
  4822.         }
  4823.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  4824.             array(
  4825.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  4826.             )
  4827.         );
  4828.         $INVLIST = [];
  4829.         foreach ($slotList as $slot) {
  4830.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  4831.         }
  4832.         return $this->render('@Inventory/pages/input_forms/sales_replacement.html.twig',
  4833.             array(
  4834.                 'page_title' => 'Sales Replacement Note',
  4835.                 'warehouseList' => Inventory::WarehouseList($em),
  4836.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  4837.                 'warehouseActionList' => $warehouse_action_list,
  4838.                 'warehouseActionListArray' => $warehouse_action_list_array,
  4839.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  4840.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  4841.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  4842.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  4843.                 'prefix_list' => array(
  4844.                     [
  4845.                         'id' => 1,
  4846.                         'value' => 'GN',
  4847.                         'text' => 'GN'
  4848.                     ]
  4849.                 ),
  4850.                 'assoc_list' => array(
  4851.                     [
  4852.                         'id' => 1,
  4853.                         'value' => 1,
  4854.                         'text' => 'GN'
  4855.                     ]
  4856.                 ),
  4857.                 'INVLIST' => $INVLIST
  4858.             )
  4859.         );
  4860.     }
  4861.     public function SalesReplacementListAction(Request $request)
  4862.     {
  4863.         $q $this->getDoctrine()
  4864.             ->getRepository('ApplicationBundle:SalesReplacement')
  4865.             ->findBy(
  4866.                 array(
  4867.                     'status' => GeneralConstant::ACTIVE,
  4868.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  4869. //                    'approved' =>  GeneralConstant::APPROVED,
  4870.                 )
  4871.             );
  4872.         $stage_list = array(
  4873.             => 'Pending',
  4874.             => 'Pending',
  4875.             => 'Complete',
  4876.             => 'Partial',
  4877.         );
  4878.         $data = [];
  4879.         foreach ($q as $entry) {
  4880.             $data[] = array(
  4881.                 'doc_date' => $entry->getSalesReplacementDate(),
  4882.                 'id' => $entry->getSalesReplacementId(),
  4883.                 'doc_hash' => $entry->getDocumentHash(),
  4884.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  4885.                 'stage' => $stage_list[$entry->getStage()]
  4886.             );
  4887.         }
  4888.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  4889.             array(
  4890.                 'page_title' => 'Stock Transfer List',
  4891.                 'data' => $data
  4892.             )
  4893.         );
  4894.     }
  4895.     public function ViewSalesReplacementAction(Request $request$id)
  4896.     {
  4897.         $em $this->getDoctrine()->getManager();
  4898.         $dt Inventory::GetSalesReplacementDetails($em$id);
  4899.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  4900.             array(
  4901.                 'page_title' => 'Stock Transfer',
  4902.                 'data' => $dt,
  4903.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4904.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  4905.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  4906.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4907.                     $id,
  4908.                     $dt['created_by'],
  4909.                     $dt['edited_by'])
  4910.             )
  4911.         );
  4912.     }
  4913.     public function PrintSalesReplacementAction(Request $request$id)
  4914.     {
  4915.         $em $this->getDoctrine()->getManager();
  4916.         $dt Inventory::GetSalesReplacementDetails($em$id);
  4917.         $company_data Company::getCompanyData($em1);
  4918.         $document_mark = array(
  4919.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4920.             'copy' => ''
  4921.         );
  4922.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  4923.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  4924.                 array(
  4925.                     //full array here
  4926.                     'pdf' => true,
  4927.                     'page_title' => 'Stock Transfer',
  4928.                     'export' => 'pdf,print',
  4929.                     'data' => $dt,
  4930.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4931.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  4932.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  4933.                         array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4934.                         $id,
  4935.                         $dt['created_by'],
  4936.                         $dt['edited_by']),
  4937.                     'document_mark_image' => $document_mark['original'],
  4938.                     'company_name' => $company_data->getName(),
  4939.                     'company_data' => $company_data,
  4940.                     'company_address' => $company_data->getAddress(),
  4941.                     'company_image' => $company_data->getImage(),
  4942.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  4943.                     'red' => 0
  4944.                 )
  4945.             );
  4946.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  4947. //                'orientation' => 'landscape',
  4948. //                'enable-javascript' => true,
  4949. //                'javascript-delay' => 1000,
  4950.                 'no-stop-slow-scripts' => false,
  4951.                 'no-background' => false,
  4952.                 'lowquality' => false,
  4953.                 'encoding' => 'utf-8',
  4954. //            'images' => true,
  4955. //            'cookie' => array(),
  4956.                 'dpi' => 300,
  4957.                 'image-dpi' => 300,
  4958. //                'enable-external-links' => true,
  4959. //                'enable-internal-links' => true
  4960.             ));
  4961.             return new Response(
  4962.                 $pdf_response,
  4963.                 200,
  4964.                 array(
  4965.                     'Content-Type' => 'application/pdf',
  4966.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  4967.                 )
  4968.             );
  4969.         }
  4970.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  4971.             array(
  4972.                 'page_title' => 'Stock Transfer',
  4973.                 'export' => 'pdf,print',
  4974.                 'data' => $dt,
  4975.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4976.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  4977.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  4978.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  4979.                     $id,
  4980.                     $dt['created_by'],
  4981.                     $dt['edited_by']),
  4982.                 'document_mark_image' => $document_mark['original'],
  4983.                 'company_name' => $company_data->getName(),
  4984.                 'company_data' => $company_data,
  4985.                 'company_address' => $company_data->getAddress(),
  4986.                 'company_image' => $company_data->getImage(),
  4987.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  4988.                 'red' => 0
  4989.             )
  4990.         );
  4991.     }
  4992.     public function CreateStockTransferAction(Request $request)
  4993.     {
  4994.         $em $this->getDoctrine()->getManager();
  4995.         $companyId $this->getLoggedUserCompanyId($request);
  4996.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4997.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4998.         if ($request->isMethod('POST')) {
  4999.             $em $this->getDoctrine()->getManager();
  5000.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  5001.             $dochash $request->request->get('docHash'); //change
  5002.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5003.             $approveRole $request->request->get('approvalRole');
  5004.             $approveHash $request->request->get('approvalHash');
  5005.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5006.                 $loginId$approveRole$approveHash)
  5007.             ) {
  5008.                 $this->addFlash(
  5009.                     'error',
  5010.                     'Sorry Could Not insert Data.'
  5011.                 );
  5012.             } else {
  5013.                 if ($request->request->has('check_allowed'))
  5014.                     $check_allowed 1;
  5015.                 $StID Inventory::CreateNewStockTransfer(
  5016.                     $this->getDoctrine()->getManager(),
  5017.                     $request->request,
  5018.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5019.                     $this->getLoggedUserCompanyId($request)
  5020.                 );
  5021.                 //now add Approval info
  5022.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5023.                 $approveRole 1;  //created
  5024.                 $options = array(
  5025.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5026.                     'notification_server' => $this->container->getParameter('notification_server'),
  5027.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5028.                     'url' => $this->generateUrl(
  5029.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  5030.                         ['entity_view_route_path_name']
  5031.                     )
  5032.                 );
  5033.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5034.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5035.                     $StID,
  5036.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  5037.                 );
  5038.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  5039.                     $loginId,
  5040.                     $approveRole,
  5041.                     $request->request->get('approvalHash'));
  5042.                 $this->addFlash(
  5043.                     'success',
  5044.                     'Stock Transfer Added.'
  5045.                 );
  5046.                 $url $this->generateUrl(
  5047.                     'view_st'
  5048.                 );
  5049.                 return $this->redirect($url "/" $StID);
  5050.             }
  5051.         }
  5052.         $INVLIST = [];
  5053.         return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  5054.             array(
  5055.                 'page_title' => 'Stock Transfer Note',
  5056.                 'warehouseList' => Inventory::WarehouseList($em),
  5057.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5058.                 'colorList' => Inventory::GetColorList($em),
  5059.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  5060.                 'srList' => [],
  5061.                 'warehouseActionList' => $warehouse_action_list,
  5062.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5063.                 'item_list' => Inventory::ItemGroupList($em),
  5064.                 'item_list_array' => Inventory::ItemGroupListArray($em),
  5065.                 'category_list_array' => Inventory::ProductCategoryListArray($em),
  5066.                 'product_list_array' => Inventory::ProductListDetailedArray($em),
  5067. //                'product_list_array' => [],
  5068.                 'product_list' => Inventory::ProductList($em$companyId),
  5069. //                'product_list' => [],
  5070.                 'prefix_list' => array(
  5071.                     [
  5072.                         'id' => 1,
  5073.                         'value' => 'GN',
  5074.                         'text' => 'GN'
  5075.                     ]
  5076.                 ),
  5077.                 'assoc_list' => array(
  5078.                     [
  5079.                         'id' => 1,
  5080.                         'value' => 1,
  5081.                         'text' => 'GN'
  5082.                     ]
  5083.                 ),
  5084.                 'INVLIST' => $INVLIST
  5085.             )
  5086.         );
  5087.     }
  5088.     public function GetSrItemForTransferAction(Request $request)
  5089.     {
  5090.         $em $this->getDoctrine()->getManager();
  5091.         $search_query = [];
  5092.         $res_data_by_so_item_id = [];
  5093.         $Content = [];
  5094.         $productionProcessSettings = array(
  5095.             'id' => 0
  5096.         );
  5097.         if ($request->query->has('srId'))
  5098.             $search_query['stockRequisitionId'] = $request->query->get('srId');
  5099.         $DT $this->getDoctrine()
  5100.             ->getRepository('ApplicationBundle:StockRequisitionItem')
  5101.             ->findBy(
  5102.                 $search_query
  5103.             );
  5104.         $Content = array(
  5105.             'requisitioned_product_item_id' => [],
  5106.             'requisitioned_products' => [],
  5107.             'requisitioned_product_fdm' => [],
  5108.             'requisitioned_product_name' => [],
  5109.             'requisitioned_product_units' => [],
  5110.             'requisitioned_product_unit_type' => [],
  5111.             'requisitioned_product_balance' => [],
  5112.         );
  5113.         foreach ($DT as $dt) {
  5114. //            $data=json_decode($DT->getData(),true);
  5115.             $Content['requisitioned_products'][] = $dt->getProductId();
  5116.             $Content['requisitioned_product_item_id'][] = $dt->getId();
  5117.             $Content['requisitioned_product_fdm'][] = $dt->getProductFdm();
  5118.             $Content['requisitioned_product_name'][] = $dt->getProductNameFdm();
  5119.             $Content['requisitioned_product_units'][] = $dt->getQty();
  5120.             $Content['requisitioned_product_balance'][] = $dt->getAlottmentPendingAmount();
  5121.         }
  5122.         $INVLIST = [];
  5123.         if (!empty($Content)) {
  5124.             return new JsonResponse(array("success" => true"content" => $Content"INVLIST" => $INVLIST));
  5125.         } else {
  5126.             return new JsonResponse(array("success" => false"content" => $Content"INVLIST" => $INVLIST));
  5127.         }
  5128.     }
  5129.     public function StockTransferListAction(Request $request)
  5130.     {
  5131.         $q $this->getDoctrine()
  5132.             ->getRepository('ApplicationBundle:StockTransfer')
  5133.             ->findBy(
  5134.                 array(
  5135.                     'status' => GeneralConstant::ACTIVE,
  5136.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5137. //                    'approved' =>  GeneralConstant::APPROVED,
  5138.                 )
  5139.             );
  5140.         $stage_list = array(
  5141.             => 'Pending',
  5142.             => 'Pending',
  5143.             => 'Complete',
  5144.             => 'Partial',
  5145.         );
  5146.         $data = [];
  5147.         foreach ($q as $entry) {
  5148.             $data[] = array(
  5149.                 'doc_date' => $entry->getStockTransferDate(),
  5150.                 'id' => $entry->getStockTransferId(),
  5151.                 'doc_hash' => $entry->getDocumentHash(),
  5152.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5153.                 'stage' => $stage_list[$entry->getStage()]
  5154.             );
  5155.         }
  5156.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5157.             array(
  5158.                 'page_title' => 'Stock Transfer List',
  5159.                 'data' => $data
  5160.             )
  5161.         );
  5162.     }
  5163.     public function ViewStockTransferAction(Request $request$id)
  5164.     {
  5165.         $em $this->getDoctrine()->getManager();
  5166.         $dt Inventory::GetStockTransferDetails($em$id);
  5167.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  5168.             array(
  5169.                 'page_title' => 'Stock Transfer',
  5170.                 'data' => $dt,
  5171.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5172.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5173.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5174.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5175.                     $id,
  5176.                     $dt['created_by'],
  5177.                     $dt['edited_by'])
  5178.             )
  5179.         );
  5180.     }
  5181.     public function PrintStockTransferAction(Request $request$id)
  5182.     {
  5183.         $em $this->getDoctrine()->getManager();
  5184.         $dt Inventory::GetStockTransferDetails($em$id);
  5185.         $company_data Company::getCompanyData($em1);
  5186.         $document_mark = array(
  5187.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5188.             'copy' => ''
  5189.         );
  5190.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5191.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5192.                 array(
  5193.                     //full array here
  5194.                     'pdf' => true,
  5195.                     'page_title' => 'Stock Transfer',
  5196.                     'export' => 'pdf,print',
  5197.                     'data' => $dt,
  5198.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5199.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5200.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5201.                         array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5202.                         $id,
  5203.                         $dt['created_by'],
  5204.                         $dt['edited_by']),
  5205.                     'document_mark_image' => $document_mark['original'],
  5206.                     'company_name' => $company_data->getName(),
  5207.                     'company_data' => $company_data,
  5208.                     'company_address' => $company_data->getAddress(),
  5209.                     'company_image' => $company_data->getImage(),
  5210.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5211.                     'red' => 0
  5212.                 )
  5213.             );
  5214.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5215. //                'orientation' => 'landscape',
  5216. //                'enable-javascript' => true,
  5217. //                'javascript-delay' => 1000,
  5218.                 'no-stop-slow-scripts' => false,
  5219.                 'no-background' => false,
  5220.                 'lowquality' => false,
  5221.                 'encoding' => 'utf-8',
  5222. //            'images' => true,
  5223. //            'cookie' => array(),
  5224.                 'dpi' => 300,
  5225.                 'image-dpi' => 300,
  5226. //                'enable-external-links' => true,
  5227. //                'enable-internal-links' => true
  5228.             ));
  5229.             return new Response(
  5230.                 $pdf_response,
  5231.                 200,
  5232.                 array(
  5233.                     'Content-Type' => 'application/pdf',
  5234.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5235.                 )
  5236.             );
  5237.         }
  5238.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5239.             array(
  5240.                 'page_title' => 'Stock Transfer',
  5241.                 'export' => 'pdf,print',
  5242.                 'data' => $dt,
  5243.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5244.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5245.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5246.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5247.                     $id,
  5248.                     $dt['created_by'],
  5249.                     $dt['edited_by']),
  5250.                 'document_mark_image' => $document_mark['original'],
  5251.                 'company_name' => $company_data->getName(),
  5252.                 'company_data' => $company_data,
  5253.                 'company_address' => $company_data->getAddress(),
  5254.                 'company_image' => $company_data->getImage(),
  5255.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5256.                 'red' => 0
  5257.             )
  5258.         );
  5259.     }
  5260.     public function CreateStockConsumptionNoteAction(Request $request)
  5261.     {
  5262.         $em $this->getDoctrine()->getManager();
  5263.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5264.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5265.         if ($request->isMethod('POST')) {
  5266.             $em $this->getDoctrine()->getManager();
  5267.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']; //change
  5268.             $dochash $request->request->get('voucherNumber'); //change
  5269.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5270.             $approveRole $request->request->get('approvalRole');
  5271.             $approveHash $request->request->get('approvalHash');
  5272.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5273.                 $loginId$approveRole$approveHash)
  5274.             ) {
  5275.                 $this->addFlash(
  5276.                     'error',
  5277.                     'Sorry Could not insert Data.'
  5278.                 );
  5279.             } else {
  5280.                 if ($request->request->has('check_allowed'))
  5281.                     $check_allowed 1;
  5282.                 $StID Inventory::CreateNewStockConsumptionNote(
  5283.                     $this->getDoctrine()->getManager(),
  5284.                     $request->request,
  5285.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5286.                     $this->getLoggedUserCompanyId($request)
  5287.                 );
  5288.                 //now add Approval info
  5289.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5290.                 $approveRole 1;  //created
  5291.                 $options = array(
  5292.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5293.                     'notification_server' => $this->container->getParameter('notification_server'),
  5294.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5295.                     'url' => $this->generateUrl(
  5296.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']]
  5297.                         ['entity_view_route_path_name']
  5298.                     )
  5299.                 );
  5300.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5301.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5302.                     $StID,
  5303.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5304.                 );
  5305.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'], $StID,
  5306.                     $loginId,
  5307.                     $approveRole,
  5308.                     $request->request->get('approvalHash'));
  5309.                 $this->addFlash(
  5310.                     'success',
  5311.                     'Stock Consumption Added.'
  5312.                 );
  5313.                 $url $this->generateUrl(
  5314.                     'view_stock_consumption_note'
  5315.                 );
  5316.                 return $this->redirect($url "/" $StID);
  5317.             }
  5318.         }
  5319.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5320.             array(
  5321.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5322.             )
  5323.         );
  5324.         $INVLIST = [];
  5325.         foreach ($slotList as $slot) {
  5326.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5327.         }
  5328.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5329.             array(
  5330.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5331.             )
  5332.         );
  5333.         $consumptionTypeList = [];
  5334.         $consumptionTypeListArray = [];
  5335.         foreach ($consumptionTypeQry as $entry) {
  5336.             $p = array(
  5337.                 'name' => $entry->getName(),
  5338.                 'id' => $entry->getConsumptionTypeId(),
  5339.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5340.                 'cost_center_id' => $entry->getCostCenterId(),
  5341.             );
  5342.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5343.             $consumptionTypeListArray[] = $p;
  5344.         }
  5345.         //add bill list
  5346.         $service_purchase_bill_query $this->getDoctrine()
  5347.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5348.             ->findBy(
  5349.                 array(
  5350.                     'typeHash' => 'SPB',
  5351.                     'approved' => GeneralConstant::APPROVED
  5352.                 )
  5353.             );
  5354.         $service_purchase_bill_list = [];
  5355.         $service_purchase_bill_list_array = [];
  5356.         $bill = array(
  5357.             'id' => 0,
  5358.             'type' => 'SPB',
  5359.             'name' => 'New Expense',
  5360.             'text' => 'New Expense',
  5361.             'amount' => 0,
  5362.         );
  5363.         $service_purchase_bill_list[0] = $bill;
  5364.         $service_purchase_bill_list_array[] = $bill;
  5365.         foreach ($service_purchase_bill_query as $d) {
  5366.             $bill = array(
  5367.                 'id' => $d->getPurchaseInvoiceId(),
  5368.                 'type' => 'SPB',
  5369.                 'name' => $d->getDocumentHash(),
  5370.                 'text' => $d->getDocumentHash(),
  5371.                 'amount' => $d->getInvoiceAmount(),
  5372.             );
  5373.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5374.             $service_purchase_bill_list_array[] = $bill;
  5375.         }
  5376.         return $this->render('@Inventory/pages/input_forms/stock_consumption_note.html.twig',
  5377.             array(
  5378.                 'page_title' => 'Stock Consumption Note',
  5379.                 'warehouseList' => Inventory::WarehouseList($em),
  5380.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5381.                 'consumptionTypeList' => $consumptionTypeList,
  5382.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5383.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5384.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5385.                 'warehouseActionList' => $warehouse_action_list,
  5386.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5387.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5388.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5389.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5390.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5391.                 'product_list' => Inventory::ProductListDetailed($this->getDoctrine()->getManager()),
  5392.                 'prefix_list' => array(
  5393.                     [
  5394.                         'id' => 1,
  5395.                         'value' => 'GN',
  5396.                         'text' => 'GN'
  5397.                     ]
  5398.                 ),
  5399.                 'assoc_list' => array(
  5400.                     [
  5401.                         'id' => 1,
  5402.                         'value' => 1,
  5403.                         'text' => 'GN'
  5404.                     ]
  5405.                 ),
  5406.                 'INVLIST' => $INVLIST
  5407.             )
  5408.         );
  5409.     }
  5410.     public function StockConsumptionNoteListAction(Request $request)
  5411.     {
  5412.         $q $this->getDoctrine()
  5413.             ->getRepository('ApplicationBundle:StockConsumptionNote')
  5414.             ->findBy(
  5415.                 array(
  5416.                     'status' => GeneralConstant::ACTIVE,
  5417.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5418. //                    'approved' =>  GeneralConstant::APPROVED,
  5419.                 )
  5420.             );
  5421.         $stage_list = array(
  5422.             => 'Pending',
  5423.             => 'Pending',
  5424.             => 'Complete',
  5425.             => 'Partial',
  5426.         );
  5427.         $data = [];
  5428.         foreach ($q as $entry) {
  5429.             $data[] = array(
  5430.                 'doc_date' => $entry->getStockConsumptionNoteDate(),
  5431.                 'id' => $entry->getStockConsumptionNoteId(),
  5432.                 'doc_hash' => $entry->getDocumentHash(),
  5433.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5434.                 'stage' => $stage_list[$entry->getStage()]
  5435.             );
  5436.         }
  5437.         return $this->render('@Inventory/pages/views/stock_consumption_note_list.html.twig',
  5438.             array(
  5439.                 'page_title' => 'Stock Consumption Note List',
  5440.                 'data' => $data
  5441.             )
  5442.         );
  5443.     }
  5444.     public function ViewStockConsumptionNoteAction(Request $request$id)
  5445.     {
  5446.         $em $this->getDoctrine()->getManager();
  5447.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5448.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5449.             array(
  5450.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5451.             )
  5452.         );
  5453.         $consumptionTypeList = [];
  5454.         $consumptionTypeListArray = [];
  5455.         foreach ($consumptionTypeQry as $entry) {
  5456.             $p = array(
  5457.                 'name' => $entry->getName(),
  5458.                 'id' => $entry->getConsumptionTypeId(),
  5459.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5460.                 'cost_center_id' => $entry->getCostCenterId(),
  5461.             );
  5462.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5463.             $consumptionTypeListArray[] = $p;
  5464.         }
  5465.         //add bill list
  5466.         $service_purchase_bill_query $this->getDoctrine()
  5467.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5468.             ->findBy(
  5469.                 array(
  5470.                     'typeHash' => 'SPB',
  5471.                     'approved' => GeneralConstant::APPROVED
  5472.                 )
  5473.             );
  5474.         $service_purchase_bill_list = [];
  5475.         $service_purchase_bill_list_array = [];
  5476.         $bill = array(
  5477.             'id' => 0,
  5478.             'type' => 'SPB',
  5479.             'name' => 'New Expense',
  5480.             'text' => 'New Expense',
  5481.             'amount' => 0,
  5482.         );
  5483.         $service_purchase_bill_list[0] = $bill;
  5484.         $service_purchase_bill_list_array[] = $bill;
  5485.         foreach ($service_purchase_bill_query as $d) {
  5486.             $bill = array(
  5487.                 'id' => $d->getPurchaseInvoiceId(),
  5488.                 'type' => 'SPB',
  5489.                 'name' => $d->getDocumentHash(),
  5490.                 'text' => $d->getDocumentHash(),
  5491.                 'amount' => $d->getInvoiceAmount(),
  5492.             );
  5493.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5494.             $service_purchase_bill_list_array[] = $bill;
  5495.         }
  5496.         return $this->render('@Inventory/pages/views/view_stock_consumption_note.html.twig',
  5497.             array(
  5498.                 'page_title' => 'Stock Transfer',
  5499.                 'data' => $dt,
  5500.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5501.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5502.                 'consumptionTypeList' => $consumptionTypeList,
  5503.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5504.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5505.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5506.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5507.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5508.                     $id,
  5509.                     $dt['created_by'],
  5510.                     $dt['edited_by'])
  5511.             )
  5512.         );
  5513.     }
  5514.     public function PrintStockConsumptionNoteAction(Request $request$id)
  5515.     {
  5516.         $em $this->getDoctrine()->getManager();
  5517.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5518.         $company_data Company::getCompanyData($em1);
  5519.         $document_mark = array(
  5520.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5521.             'copy' => ''
  5522.         );
  5523.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5524.             array(
  5525.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5526.             )
  5527.         );
  5528.         $consumptionTypeList = [];
  5529.         $consumptionTypeListArray = [];
  5530.         foreach ($consumptionTypeQry as $entry) {
  5531.             $p = array(
  5532.                 'name' => $entry->getName(),
  5533.                 'id' => $entry->getConsumptionTypeId(),
  5534.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5535.                 'cost_center_id' => $entry->getCostCenterId(),
  5536.             );
  5537.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5538.             $consumptionTypeListArray[] = $p;
  5539.         }
  5540.         //add bill list
  5541.         $service_purchase_bill_query $this->getDoctrine()
  5542.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5543.             ->findBy(
  5544.                 array(
  5545.                     'typeHash' => 'SPB',
  5546.                     'approved' => GeneralConstant::APPROVED
  5547.                 )
  5548.             );
  5549.         $service_purchase_bill_list = [];
  5550.         $service_purchase_bill_list_array = [];
  5551.         $bill = array(
  5552.             'id' => 0,
  5553.             'type' => 'SPB',
  5554.             'name' => 'New Expense',
  5555.             'text' => 'New Expense',
  5556.             'amount' => 0,
  5557.         );
  5558.         $service_purchase_bill_list[0] = $bill;
  5559.         $service_purchase_bill_list_array[] = $bill;
  5560.         foreach ($service_purchase_bill_query as $d) {
  5561.             $bill = array(
  5562.                 'id' => $d->getPurchaseInvoiceId(),
  5563.                 'type' => 'SPB',
  5564.                 'name' => $d->getDocumentHash(),
  5565.                 'text' => $d->getDocumentHash(),
  5566.                 'amount' => $d->getInvoiceAmount(),
  5567.             );
  5568.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5569.             $service_purchase_bill_list_array[] = $bill;
  5570.         }
  5571.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5572.             $html $this->renderView('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  5573.                 array(
  5574.                     //full array here
  5575.                     'pdf' => true,
  5576.                     'page_title' => 'Stock Consumption',
  5577.                     'export' => 'pdf,print',
  5578.                     'data' => $dt,
  5579.                     'service_purchase_bill_list' => $service_purchase_bill_list,
  5580.                     'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5581.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5582.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5583.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5584.                         array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5585.                         $id,
  5586.                         $dt['created_by'],
  5587.                         $dt['edited_by']),
  5588.                     'document_mark_image' => $document_mark['original'],
  5589.                     'consumptionTypeList' => $consumptionTypeList,
  5590.                     'consumptionTypeListArray' => $consumptionTypeListArray,
  5591.                     'company_name' => $company_data->getName(),
  5592.                     'company_data' => $company_data,
  5593.                     'company_address' => $company_data->getAddress(),
  5594.                     'company_image' => $company_data->getImage(),
  5595.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5596.                     'red' => 0
  5597.                 )
  5598.             );
  5599.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5600. //                'orientation' => 'landscape',
  5601. //                'enable-javascript' => true,
  5602. //                'javascript-delay' => 1000,
  5603.                 'no-stop-slow-scripts' => false,
  5604.                 'no-background' => false,
  5605.                 'lowquality' => false,
  5606.                 'encoding' => 'utf-8',
  5607. //            'images' => true,
  5608. //            'cookie' => array(),
  5609.                 'dpi' => 300,
  5610.                 'image-dpi' => 300,
  5611. //                'enable-external-links' => true,
  5612. //                'enable-internal-links' => true
  5613.             ));
  5614.             return new Response(
  5615.                 $pdf_response,
  5616.                 200,
  5617.                 array(
  5618.                     'Content-Type' => 'application/pdf',
  5619.                     'Content-Disposition' => 'attachment; filename="stock_consumption_note_' $id '.pdf"'
  5620.                 )
  5621.             );
  5622.         }
  5623.         return $this->render('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  5624.             array(
  5625.                 'page_title' => 'Stock Consumption',
  5626.                 'export' => 'pdf,print',
  5627.                 'data' => $dt,
  5628.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5629.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5630.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5631.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5632.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5633.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5634.                     $id,
  5635.                     $dt['created_by'],
  5636.                     $dt['edited_by']),
  5637.                 'document_mark_image' => $document_mark['original'],
  5638.                 'consumptionTypeList' => $consumptionTypeList,
  5639.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5640.                 'company_name' => $company_data->getName(),
  5641.                 'company_data' => $company_data,
  5642.                 'company_address' => $company_data->getAddress(),
  5643.                 'company_image' => $company_data->getImage(),
  5644.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5645.                 'red' => 0
  5646.             )
  5647.         );
  5648.     }
  5649.     public function CreateStockReceivedNoteAction(Request $request$id 0)
  5650.     {
  5651.         $em $this->getDoctrine()->getManager();
  5652.         $companyId $this->getLoggedUserCompanyId($request);
  5653.         $extDocData = [];
  5654.         $userId $request->getSession()->get(UserConstants::USER_ID);
  5655.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  5656.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  5657.         $userBranchIdList $request->getSession()->get('branchIdList');
  5658.         if ($userBranchIdList == null$userBranchIdList = [];
  5659.         $userBranchId $request->getSession()->get('branchId');
  5660.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  5661.             $em $this->getDoctrine()->getManager();
  5662.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'];
  5663.             $dochash $request->request->get('docHash');
  5664.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5665.             $approveRole $request->request->get('approvalRole');
  5666.             $approveHash $request->request->get('approvalHash');
  5667.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5668.                 $loginId$approveRole$approveHash$id)
  5669.             ) {
  5670.                 if ($request->request->has('returnJson')) {
  5671.                     return new JsonResponse(array(
  5672.                         'success' => false,
  5673.                         'documentHash' => 0,
  5674.                         'documentId' => 0,
  5675.                         'billIds' => [],
  5676.                         'drIds' => [],
  5677.                         'pmntTransIds' => [],
  5678.                         'viewUrl' => '',
  5679.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  5680.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  5681.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  5682.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  5683.                     ));
  5684.                 } else
  5685.                     $this->addFlash(
  5686.                         'error',
  5687.                         'Sorry Could not insert Data.'
  5688.                     );
  5689.             } else {
  5690.                 if ($request->request->has('check_allowed'))
  5691.                     $check_allowed 1;
  5692.                 $StID Inventory::CreateNewStockReceivedNote(
  5693.                     $this->getDoctrine()->getManager(),
  5694.                     $request->request,
  5695.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5696.                     $this->getLoggedUserCompanyId($request)
  5697.                 );
  5698.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5699.                 $approveRole 1;
  5700.                 $options = array(
  5701.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5702.                     'notification_server' => $this->container->getParameter('notification_server'),
  5703.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5704.                     'url' => $this->generateUrl(
  5705.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  5706.                         ['entity_view_route_path_name']
  5707.                     )
  5708.                 );
  5709.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5710.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5711.                     $StID,
  5712.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5713.                 );
  5714.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  5715.                     $loginId,
  5716.                     $approveRole,
  5717.                     $request->request->get('approvalHash'));
  5718.                 $url $this->generateUrl(
  5719.                     'view_srcv'
  5720.                 );
  5721.                 if ($request->request->has('returnJson')) {
  5722.                     return new JsonResponse(array(
  5723.                         'success' => true,
  5724.                         'documentHash' => $dochash,
  5725.                         'documentId' => $StID,
  5726.                         'viewUrl' => $url "/" $StID,
  5727.                     ));
  5728.                 } else {
  5729.                     $this->addFlash(
  5730.                         'success',
  5731.                         'Stock Received Note Added.'
  5732.                     );
  5733.                     return $this->redirect($url "/" $StID);
  5734.                 }
  5735.             }
  5736.         }
  5737.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5738.             array(
  5739.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5740.             )
  5741.         );
  5742.         if ($id == 0) {
  5743.         } else {
  5744.             $extDoc $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  5745.                 array(
  5746.                     'salesOrderId' => $id,
  5747.                 )
  5748.             );
  5749.             if ($extDoc) {
  5750.                 if ($extDoc->getEditFlag() != 1) {
  5751.                     $url $this->generateUrl(
  5752.                         'view_srcv'
  5753.                     );
  5754.                     return $this->redirect($url "/" $id);
  5755.                 } else {
  5756.                     $extDocData $extDoc;
  5757.                     $extDocDataDetails $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findOneBy(
  5758.                         array(
  5759.                             'stockReceivedNoteId' => $id,
  5760.                         )
  5761.                     );
  5762.                 }
  5763.             } else {
  5764.             }
  5765.         }
  5766.         $INVLIST = [];
  5767.         foreach ($slotList as $slot) {
  5768.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5769.         }
  5770.         $dataArray = array(
  5771.             'page_title' => 'Stock Received Note',
  5772. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  5773.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  5774.             'users' => Users::getUserListById($em),
  5775.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  5776.             'warehouseList' => Inventory::WarehouseList($em),
  5777.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  5778.             'warehouseActionList' => $warehouse_action_list,
  5779.             'warehouseActionListArray' => $warehouse_action_list_array,
  5780.             'extDocData' => $extDocData,
  5781.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  5782.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5783.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5784.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5785. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5786. //            'product_list' => Inventory::ProductList($em, $companyId),
  5787.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  5788.             'prefix_list' => array(
  5789.                 [
  5790.                     'id' => 1,
  5791.                     'value' => 'GN',
  5792.                     'text' => 'GN'
  5793.                 ]
  5794.             ),
  5795.             'assoc_list' => array(
  5796.                 [
  5797.                     'id' => 1,
  5798.                     'value' => 1,
  5799.                     'text' => 'GN'
  5800.                 ]
  5801.             ),
  5802.             'INVLIST' => $INVLIST,
  5803.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  5804.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  5805.             'userBranchIdList' => $userBranchIdList,
  5806.             'userBranchId' => $userBranchId,
  5807. //            'headList' => Accounts::HeadList($em),
  5808.         );
  5809.         //json
  5810.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  5811.         {
  5812.             $dataArray['success'] = true;
  5813.             return new JsonResponse(
  5814.                 $dataArray
  5815.             );
  5816.         }
  5817.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  5818.             $dataArray
  5819.         );
  5820.     }
  5821.     public function GetItemListForStockReceivedAction(Request $request)
  5822.     {
  5823.         if ($request->isMethod('POST')) {
  5824.             $em $this->getDoctrine();
  5825.             $receiveType 1;//transfer
  5826.             if ($request->request->has('receiveType'))
  5827.                 $receiveType $request->request->get('receiveType');
  5828.             $QD = [];
  5829.             if ($receiveType == 1)
  5830.                 $QD $this->getDoctrine()
  5831.                     ->getRepository('ApplicationBundle:StockTransferItem')
  5832.                     ->findBy(
  5833.                         array(
  5834. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  5835.                             'stockTransferId' => $request->request->get('stId')
  5836.                         ),
  5837.                         array()
  5838.                     );
  5839.             if ($receiveType == 2)
  5840.                 $QD $this->getDoctrine()
  5841.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  5842.                     ->findBy(
  5843.                         array(
  5844. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  5845.                             'salesOrderId' => $request->request->get('soId')
  5846.                         ),
  5847.                         array()
  5848.                     );
  5849. //            if($request->request->get('wareHouseId')!='')
  5850. //
  5851. //            $DO=$this->getDoctrine()
  5852. //                ->getRepository('ApplicationBundle:DeliveryOrder')
  5853. //                ->findOneBy(
  5854. //                    $find_array,
  5855. //                    array(
  5856. //
  5857. //                    )
  5858. //                );
  5859.             $sendData = array(
  5860. //                'salesType'=>$SO->getSalesType(),
  5861. //                'packageData'=>[],
  5862.                 'productList' => [],
  5863. //                'productListByPackage'=>[],
  5864.             );
  5865.             $productList Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request));
  5866.             $pckg_item_cross_match_data = [];
  5867.             foreach ($QD as $product) {
  5868. //                $b_code=json_decode($product->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  5869.                 $b_code = [];
  5870.                 $newProductId $product->getProductId();
  5871.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  5872.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  5873.                     if ($to_analyze_codes_str != null)
  5874.                         $b_code json_decode($to_analyze_codes_strtrue512JSON_BIGINT_AS_STRING);
  5875.                     else
  5876.                         $b_code = [];
  5877.                 } else {
  5878.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  5879.                     if ($to_analyze_codes_str != null) {
  5880.                         $max_int_length strlen((string)PHP_INT_MAX) - 1;
  5881.                         $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$to_analyze_codes_str);
  5882.                         $b_code json_decode($json_without_bigintstrue);
  5883.                     } else {
  5884.                         $b_code = [];
  5885.                     }
  5886.                 }
  5887.                 $b_code_data = [];
  5888.                 foreach ($b_code as $d) {
  5889.                     $b_code_data[] = array(
  5890.                         'id' => $d,
  5891.                         'name' => str_pad($d13'0'STR_PAD_LEFT),
  5892.                     );
  5893.                 }
  5894.                 $p_data = array(
  5895.                     'details_id' => $product->getId(),
  5896.                     'productId' => $product->getProductId(),
  5897.                     'product_name' => isset($productList[$product->getProductId()]) ? $productList[$product->getProductId()]['name'] : 'Unknown Product',
  5898.                     'product_barcodes' => $b_code_data,
  5899. //                    'available_inventory'=>$inventory_by_warehouse?$inventory_by_warehouse->getQty():0,
  5900. //                        'package_id'=>$product->getPackageId(),
  5901.                     'qty' => $receiveType == $product->getQty() : $product->getToBeReceived(),
  5902.                     'unit_price' => $receiveType == $product->getPrice() : $productList[$product->getProductId()]['purchase_price'],
  5903.                     'balance' => $receiveType == $product->getBalance() : ($product->getToBeReceived() - $product->getReceived()),
  5904. //                        'delivered'=>$product->getDelivered(),
  5905.                 );
  5906.                 $sendData['productList'][] = $p_data;
  5907.             }
  5908.             //now package data
  5909.             if ($sendData) {
  5910.                 return new JsonResponse(array("success" => true"content" => $sendData));
  5911.             }
  5912.             return new JsonResponse(array("success" => false));
  5913.         }
  5914.         return new JsonResponse(array("success" => false));
  5915.     }
  5916.     public function StockReceivedNoteListAction(Request $request)
  5917.     {
  5918.         $q $this->getDoctrine()
  5919.             ->getRepository('ApplicationBundle:StockReceivedNote')
  5920.             ->findBy(
  5921.                 array(
  5922.                     'status' => GeneralConstant::ACTIVE,
  5923.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5924. //                    'approved' =>  GeneralConstant::APPROVED,
  5925.                 )
  5926.             );
  5927.         $stage_list = array(
  5928.             => 'Pending',
  5929.             => 'Pending',
  5930.             => 'Complete',
  5931.             => 'Partial',
  5932.         );
  5933.         $data = [];
  5934.         foreach ($q as $entry) {
  5935.             $data[] = array(
  5936.                 'doc_date' => $entry->getStockReceivedNoteDate(),
  5937.                 'id' => $entry->getStockReceivedNoteId(),
  5938.                 'doc_hash' => $entry->getDocumentHash(),
  5939.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5940.                 'stage' => $stage_list[$entry->getStage()]
  5941.             );
  5942.         }
  5943.         return $this->render('@Inventory/pages/views/stock_received_note_list.html.twig',
  5944.             array(
  5945.                 'page_title' => 'Stock Received List',
  5946.                 'data' => $data
  5947.             )
  5948.         );
  5949.     }
  5950.     public function ViewStockReceivedNoteAction(Request $request$id)
  5951.     {
  5952.         $em $this->getDoctrine()->getManager();
  5953.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  5954.         return $this->render('@Inventory/pages/views/view_stock_received_note.html.twig',
  5955.             array(
  5956.                 'page_title' => 'Stock Received Note',
  5957.                 'data' => $dt,
  5958.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  5959.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5960.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5961.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5962.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5963.                     $id,
  5964.                     $dt['created_by'],
  5965.                     $dt['edited_by'])
  5966.             )
  5967.         );
  5968.     }
  5969.     public function PrintStockReceivedNoteAction(Request $request$id)
  5970.     {
  5971.         $em $this->getDoctrine()->getManager();
  5972.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  5973.         $company_data Company::getCompanyData($em1);
  5974.         $document_mark = array(
  5975.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5976.             'copy' => ''
  5977.         );
  5978.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5979.             $html $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
  5980.                 array(
  5981.                     //full array here
  5982.                     'pdf' => true,
  5983.                     'page_title' => 'Stock Received Note',
  5984.                     'export' => 'pdf,print',
  5985.                     'data' => $dt,
  5986.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5987.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5988.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5989.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5990.                         $id,
  5991.                         $dt['created_by'],
  5992.                         $dt['edited_by']),
  5993.                     'document_mark_image' => $document_mark['original'],
  5994.                     'company_name' => $company_data->getName(),
  5995.                     'company_data' => $company_data,
  5996.                     'company_address' => $company_data->getAddress(),
  5997.                     'company_image' => $company_data->getImage(),
  5998.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5999.                     'red' => 0
  6000.                 )
  6001.             );
  6002.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6003. //                'orientation' => 'landscape',
  6004. //                'enable-javascript' => true,
  6005. //                'javascript-delay' => 1000,
  6006.                 'no-stop-slow-scripts' => false,
  6007.                 'no-background' => false,
  6008.                 'lowquality' => false,
  6009.                 'encoding' => 'utf-8',
  6010. //            'images' => true,
  6011. //            'cookie' => array(),
  6012.                 'dpi' => 300,
  6013.                 'image-dpi' => 300,
  6014. //                'enable-external-links' => true,
  6015. //                'enable-internal-links' => true
  6016.             ));
  6017.             return new Response(
  6018.                 $pdf_response,
  6019.                 200,
  6020.                 array(
  6021.                     'Content-Type' => 'application/pdf',
  6022.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  6023.                 )
  6024.             );
  6025.         }
  6026.         return $this->render('@Inventory/pages/print/print_stock_received_note.html.twig',
  6027.             array(
  6028.                 'page_title' => 'Stock Received Note',
  6029.                 'export' => 'pdf,print',
  6030.                 'data' => $dt,
  6031.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6032.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6033.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6034.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6035.                     $id,
  6036.                     $dt['created_by'],
  6037.                     $dt['edited_by']),
  6038.                 'document_mark_image' => $document_mark['original'],
  6039.                 'company_name' => $company_data->getName(),
  6040.                 'company_data' => $company_data,
  6041.                 'company_address' => $company_data->getAddress(),
  6042.                 'company_image' => $company_data->getImage(),
  6043.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6044.                 'red' => 0
  6045.             )
  6046.         );
  6047.     }
  6048.     public function CreateStoreRequisitionSlipAction(Request $request$id 0)
  6049.     {
  6050.         $em $this->getDoctrine()->getManager();
  6051. //        $id;
  6052.         if ($request->isMethod('POST')) {
  6053.             $em $this->getDoctrine()->getManager();
  6054.             $entity_id array_flip(GeneralConstant::$Entity_list)['StoreRequisition']; //change
  6055.             $dochash $request->request->get('voucherNumber'); //change
  6056.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6057.             $approveRole $request->request->get('approvalRole');
  6058.             $approveHash $request->request->get('approvalHash');
  6059.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6060.                 $loginId$approveRole$approveHash$id)
  6061.             ) {
  6062.                 $this->addFlash(
  6063.                     'error',
  6064.                     'Sorry, could not insert Data.'
  6065.                 );
  6066.             } else {
  6067.                 if ($request->request->has('check_allowed'))
  6068.                     $check_allowed 1;
  6069.                 $IrID Inventory::CreateNewStoreRequisition($id,
  6070.                     $this->getDoctrine()->getManager(),
  6071.                     $request->request,
  6072.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6073.                     $this->getLoggedUserCompanyId($request)
  6074.                 );
  6075.                 //now add Approval info
  6076.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6077.                 $approveRole $request->request->get('approvalRole');
  6078.                 $options = array(
  6079.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6080.                     'notification_server' => $this->container->getParameter('notification_server'),
  6081.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6082.                     'url' => $this->generateUrl(
  6083.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StoreRequisition']]
  6084.                         ['entity_view_route_path_name']
  6085.                     )
  6086.                 );
  6087.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6088.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  6089.                     $IrID,
  6090.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6091.                 );
  6092.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StoreRequisition'], $IrID,
  6093.                     $loginId,
  6094.                     $approveRole,
  6095.                     $request->request->get('approvalHash'));
  6096.                 $this->addFlash(
  6097.                     'success',
  6098.                     'New Indent Added.'
  6099.                 );
  6100.                 $url $this->generateUrl(
  6101.                     'view_ir'
  6102.                 );
  6103.                 return $this->redirect($url "/" $IrID);
  6104.             }
  6105.         }
  6106.         $extDocData = [];
  6107.         $extDocDetailsData = [];
  6108.         if ($id == 0) {
  6109.         } else {
  6110.             $extDoc $em->getRepository('ApplicationBundle:StoreRequisition')->findOneBy(
  6111.                 array(
  6112.                     'storeRequisitionId' => $id///material
  6113.                 )
  6114.             );
  6115.             //now if its not editable, redirect to view
  6116.             if ($extDoc) {
  6117.                 if ($extDoc->getEditFlag() != 1) {
  6118.                     $url $this->generateUrl(
  6119.                         'view_ir'
  6120.                     );
  6121.                     return $this->redirect($url "/" $id);
  6122.                 } else {
  6123.                     $extDocData $extDoc;
  6124.                     $extDocDetailsData $em->getRepository('ApplicationBundle:StoreRequisitionItem')->findBy(
  6125.                         array(
  6126.                             'storeRequisitionId' => $id///material
  6127.                         )
  6128.                     );;
  6129.                 }
  6130.             } else {
  6131.             }
  6132.         }
  6133.         $companyId $this->getLoggedUserCompanyId($request);
  6134.         $productListArray = [];
  6135.         $subCategoryListArray = [];
  6136.         $categoryListArray = [];
  6137.         $igListArray = [];
  6138.         $unitListArray = [];
  6139.         $brandListArray = [];
  6140.         $productList Inventory::ProductList($em$companyId);
  6141.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6142.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6143.         $igList Inventory::ItemGroupList($em$companyId);
  6144.         $unitList Inventory::UnitTypeList($em);
  6145.         $brandList Inventory::GetBrandList($em$companyId);
  6146.         foreach ($productList as $product$productListArray[] = $product;
  6147.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6148.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6149.         foreach ($igList as $product$igListArray[] = $product;
  6150.         foreach ($unitList as $product$unitListArray[] = $product;
  6151.         foreach ($brandList as $product$brandListArray[] = $product;
  6152.         $sr_list = [];
  6153.         $QD $this->getDoctrine()
  6154.             ->getRepository('ApplicationBundle:StockRequisition')
  6155.             ->findBy(
  6156.                 array(
  6157.                     'indentTagged' => 0,
  6158.                     'approved' => 1
  6159.                 )
  6160.             );
  6161.         foreach ($QD as $dt) {
  6162.             $sr_list[$dt->getStockRequisitionId()] = array(
  6163.                 'id' => $dt->getStockRequisitionId(),
  6164.                 'name' => $dt->getDocumentHash(),
  6165.                 'text' => $dt->getDocumentHash(),
  6166.             );
  6167.         }
  6168.         return $this->render('@Inventory/pages/input_forms/store_requisition.html.twig',
  6169.             array(
  6170.                 'page_title' => 'Indent Requisition Slip',
  6171.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6172.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6173.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6174.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6175.                 'sr_list' => $sr_list,
  6176.                 'productList' => $productList,
  6177.                 'subCategoryList' => $subCategoryList,
  6178.                 'categoryList' => $categoryList,
  6179.                 'igList' => $igList,
  6180.                 'extId' => $id,
  6181.                 'extDocDetailsData' => $extDocDetailsData,
  6182.                 'extDocData' => $extDocData,
  6183.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6184.                 'unitList' => $unitList,
  6185.                 'brandList' => $brandList,
  6186.                 'brandListArray' => $brandListArray,
  6187.                 'productListArray' => $productListArray,
  6188.                 'subCategoryListArray' => $subCategoryListArray,
  6189.                 'categoryListArray' => $categoryListArray,
  6190.                 'igListArray' => $igListArray,
  6191.                 'unitListArray' => $unitListArray,
  6192.                 'prefix_list' => array(
  6193.                     [
  6194.                         'id' => 1,
  6195.                         'value' => 'GN',
  6196.                         'text' => 'General'
  6197.                     ],
  6198.                     [
  6199.                         'id' => 1,
  6200.                         'value' => 'SD',
  6201.                         'text' => 'For Sales Demand'
  6202.                     ]
  6203.                 ),
  6204.                 'assoc_list' => array(
  6205.                     [
  6206.                         'id' => 1,
  6207.                         'value' => 1,
  6208.                         'text' => 'GN'
  6209.                     ]
  6210.                 )
  6211.             )
  6212.         );
  6213.     }
  6214.     public function CreateStockRequisitionSlipAction(Request $request$id 0)
  6215.     {
  6216.         $em $this->getDoctrine()->getManager();
  6217.         if ($request->isMethod('POST')) {
  6218.             $em $this->getDoctrine()->getManager();
  6219.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockRequisition']; //change
  6220.             $dochash $request->request->get('voucherNumber'); //change
  6221.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6222.             $approveRole $request->request->get('approvalRole');
  6223.             $approveHash $request->request->get('approvalHash');
  6224.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6225.                 $loginId$approveRole$approveHash$id)
  6226.             ) {
  6227.                 $this->addFlash(
  6228.                     'error',
  6229.                     'Sorry, could not insert Data.'
  6230.                 );
  6231.             } else {
  6232.                 if ($request->request->has('check_allowed'))
  6233.                     $check_allowed 1;
  6234.                 $SrID Inventory::CreateNewStockRequisition($id,
  6235.                     $this->getDoctrine()->getManager(),
  6236.                     $request->request,
  6237.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6238.                     $this->getLoggedUserCompanyId($request)
  6239.                 );
  6240.                 //now add Approval info
  6241.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6242.                 $approveRole $request->request->get('approvalRole');
  6243.                 $options = array(
  6244.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6245.                     'notification_server' => $this->container->getParameter('notification_server'),
  6246.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6247.                     'url' => $this->generateUrl(
  6248.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockRequisition']]
  6249.                         ['entity_view_route_path_name']
  6250.                     )
  6251.                 );
  6252.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6253.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  6254.                     $SrID,
  6255.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6256.                 );
  6257.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockRequisition'], $SrID,
  6258.                     $loginId,
  6259.                     $approveRole,
  6260.                     $request->request->get('approvalHash'));
  6261.                 $this->addFlash(
  6262.                     'success',
  6263.                     'New Requisition Added.'
  6264.                 );
  6265.                 $url $this->generateUrl(
  6266.                     'view_sr'
  6267.                 );
  6268. //                return $this->redirect($url . "/" . $SrID);
  6269.             }
  6270.         }
  6271.         $extDocData = [];
  6272.         $extDocDetailsData = [];
  6273.         if ($id == 0) {
  6274.         } else {
  6275.             $extDoc $em->getRepository('ApplicationBundle:StockRequisition')->findOneBy(
  6276.                 array(
  6277.                     'stockRequisitionId' => $id///material
  6278.                 )
  6279.             );
  6280.             //now if its not editable, redirect to view
  6281.             if ($extDoc) {
  6282.                 if ($extDoc->getEditFlag() != 1) {
  6283.                     $url $this->generateUrl(
  6284.                         'view_sr'
  6285.                     );
  6286.                     return $this->redirect($url "/" $id);
  6287.                 } else {
  6288.                     $extDocData $extDoc;
  6289.                     $extDocDetailsData $em->getRepository('ApplicationBundle:StockRequisitionItem')->findBy(
  6290.                         array(
  6291.                             'stockRequisitionId' => $id///material
  6292.                         )
  6293.                     );;
  6294.                 }
  6295.             } else {
  6296.             }
  6297.         }
  6298.         $companyId $this->getLoggedUserCompanyId($request);
  6299.         $productListArray = [];
  6300.         $subCategoryListArray = [];
  6301.         $categoryListArray = [];
  6302.         $igListArray = [];
  6303.         $unitListArray = [];
  6304.         $brandListArray = [];
  6305.         $productList Inventory::ProductList($em$companyId);
  6306.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6307.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6308.         $igList Inventory::ItemGroupList($em$companyId);
  6309.         $unitList Inventory::UnitTypeList($em);
  6310.         $brandList Inventory::GetBrandList($em$companyId);
  6311.         foreach ($productList as $product$productListArray[] = $product;
  6312.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6313.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6314.         foreach ($igList as $product$igListArray[] = $product;
  6315.         foreach ($unitList as $product$unitListArray[] = $product;
  6316.         foreach ($brandList as $product$brandListArray[] = $product;
  6317.         return $this->render('@Inventory/pages/input_forms/stock_requisition_slip.html.twig',
  6318.             array(
  6319.                 'page_title' => 'Stock Requisition Slip',
  6320.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6321.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6322.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6323.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6324.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  6325.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6326.                 'productList' => $productList,
  6327.                 'extId' => $id,
  6328.                 'extDocDetailsData' => $extDocDetailsData,
  6329.                 'extDocData' => $extDocData,
  6330.                 'subCategoryList' => $subCategoryList,
  6331.                 'categoryList' => $categoryList,
  6332.                 'igList' => $igList,
  6333.                 'unitList' => $unitList,
  6334.                 'brandList' => $brandList,
  6335.                 'brandListArray' => $brandListArray,
  6336.                 'productListArray' => $productListArray,
  6337.                 'subCategoryListArray' => $subCategoryListArray,
  6338.                 'categoryListArray' => $categoryListArray,
  6339.                 'igListArray' => $igListArray,
  6340.                 'unitListArray' => $unitListArray,
  6341.                 'productionBomList' => ProductionM::ProductionBomList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6342.                 'productionScheduleList' => ProductionM::ProductionScheduleList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6343.                 'prefix_list' => array(
  6344.                     [
  6345.                         'id' => 1,
  6346.                         'value' => 'GN',
  6347.                         'text' => 'General'
  6348.                     ],
  6349.                     [
  6350.                         'id' => 1,
  6351.                         'value' => 'SD',
  6352.                         'text' => 'For Sales Demand'
  6353.                     ]
  6354.                 ),
  6355.                 'projectList' => $em->getRepository('ApplicationBundle:Project')->findBy(
  6356.                     array(
  6357.                         'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  6358.                     ), array('projectDate' => 'desc')
  6359.                 ),
  6360.                 'salesOrderList' => SalesOrderM::SalesOrderListPendingDelivery($em),
  6361.                 'assoc_list' => array(
  6362.                     [
  6363.                         'id' => 1,
  6364.                         'value' => 'GN',
  6365.                         'text' => 'General'
  6366.                     ]
  6367.                 )
  6368.             )
  6369.         );
  6370.     }
  6371.     public function CreateStockReturnAction(Request $request)
  6372.     {
  6373.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  6374.             array(
  6375.                 'page_title' => 'Stock Return',
  6376. //                'dataList'=>$dta_list
  6377.             )
  6378.         );
  6379.     }
  6380.     public function MaterialInwardAction(Request $request)
  6381.     {
  6382.         $data = [];
  6383.         if ($request->isMethod('POST')) {
  6384.             //first of all resolve the transport costs
  6385.             $total_price_value 0;
  6386.             $data_list $dt $this->getDoctrine()
  6387.                 ->getRepository('ApplicationBundle:PurchaseOrderItem')
  6388.                 ->findBy(
  6389.                     array(
  6390.                         'purchaseOrderId' => $request->request->get('poId'),
  6391.                         'productId' => $request->request->get('products')
  6392.                     )
  6393.                 );
  6394.             $purchase_items = [];
  6395.             foreach ($data_list as $key => $value) {
  6396.                 $purchase_items[$value->getProductId()] = $value;
  6397.             }
  6398.             foreach ($request->request->get('products') as $key => $entry) {
  6399.                 $total_price_value $total_price_value + ($request->request->get('receivedQty')[$key]) * ($purchase_items[$entry]->getPrice());
  6400.             }
  6401.             $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$request->request->get('poId')];
  6402.             $supplier_id $po_data['supplier_id'];
  6403.             $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6404.             foreach ($request->request->get('products') as $key => $entry) {
  6405.                 if ($request->request->get('receivedQty')[$key] > 0)
  6406.                     Inventory::NewMaterialInward($this->getDoctrine()->getManager(),
  6407.                         $request->request,
  6408.                         $key,
  6409.                         $request->request->get('poId'),
  6410.                         $request->request->get('purchaseOrderItemId'),
  6411.                         $supplier_id,
  6412.                         $request->request->get('warehouseId'),
  6413.                         $request->request->get('lotNumber'),
  6414.                         $request->request->get('type_hash'),
  6415.                         $request->request->get('prefix_hash'),
  6416.                         $request->request->get('assoc_hash'),
  6417.                         $request->request->get('number_hash'),
  6418.                         $request->request->get('docHash'),
  6419.                         $request->request->get('docDate'),
  6420.                         $purchase_items[$entry],
  6421.                         $total_price_value,
  6422.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6423.             }
  6424.             $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$request->request->get('warehouseId')]['name'];
  6425. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6426.             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),
  6427.                 "A stack of material Has Arrived at The " $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6428.                 'all',
  6429.                 "",
  6430.                 'information',
  6431.                 "",
  6432.                 "Inbound Material"
  6433.             );
  6434. //                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);
  6435.         }
  6436.         return $this->render('@Inventory/pages/input_forms/material_inward.html.twig',
  6437.             array(
  6438.                 'page_title' => 'Material Inward',
  6439.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6440.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  6441.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  6442.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  6443.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  6444.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  6445.                 "unitList" => Inventory::UnitTypeList($this->getDoctrine()->getManager())
  6446. //                'po'=>Inventory::getPurchaseOrderList
  6447.             )
  6448.         );
  6449.     }
  6450.     public function QualityControlAction(Request $request)
  6451.     {
  6452.         $checked_qc_list_flag 0;
  6453.         if ($request->query->has('checked_qc_list_flag'))
  6454.             $checked_qc_list_flag $request->query->has('checked_qc_list_flag');
  6455.         if ($request->isMethod('POST')) {
  6456.             foreach ($request->request->get('qc_checked', []) as $key => $entry) {
  6457.                 $em $this->getDoctrine()->getManager();
  6458.                 $data $this->getDoctrine()
  6459.                     ->getRepository('ApplicationBundle:MaterialInward')
  6460.                     ->findOneBy(
  6461.                         array(
  6462.                             'qcId' => $entry
  6463.                         )
  6464.                     );
  6465.                 if ($request->request->get('approvedQty')[$entry] <= 0) {
  6466.                     $em->remove($data);
  6467.                     $em->flush();
  6468.                 } else {
  6469.                     $data->setApprovedQty($request->request->get('approvedQty')[$entry]);
  6470.                     $data->setRejectedQty($data->getInwardQty() - $request->request->get('approvedQty')[$entry]);
  6471.                     $data->setQcDate(new \DateTime($request->request->get('qcDate')));
  6472.                     $data->setStage(GeneralConstant::STAGE_PENDING_TAG);
  6473.                     $em->flush();
  6474.                 }
  6475.                 //notification
  6476.                 $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$data->getPurchaseOrderId()];
  6477.                 $supplier_id $po_data['supplier_id'];
  6478.                 $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6479.                 $product_name Inventory::ProductList($this->getDoctrine()->getManager())[$data->getProductId()]['name'];
  6480.                 $qty $request->request->get('approvedQty')[$entry];
  6481.                 $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$data->getWarehouseId()]['name'];
  6482. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6483.                 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),
  6484.                     $qty " among " $data->getInwardQty() . " units of " $product_name " has passed the Quality Control in " .
  6485.                     $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6486.                     'all',
  6487.                     "",
  6488.                     'success',
  6489.                     "",
  6490.                     "Quality Control"
  6491.                 );
  6492.             }
  6493.         }
  6494.         return $this->render('@Inventory/pages/input_forms/qc.html.twig',
  6495.             array(
  6496.                 'page_title' => 'Quality Control',
  6497.                 'checked_qc_list_flag' => $checked_qc_list_flag,
  6498.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6499.                 'warehouse_indexed' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6500.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  6501.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  6502.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  6503.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  6504.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6505.                 'material_inward' => $this->getDoctrine()
  6506.                     ->getRepository('ApplicationBundle:MaterialInward')
  6507.                     ->findBy(
  6508.                         array(
  6509.                             'stage' => $checked_qc_list_flag == GeneralConstant::STAGE_PENDING GeneralConstant::STAGE_PENDING_TAG
  6510.                         )
  6511.                     )
  6512. //                'po'=>Inventory::getPurchaseOrderList
  6513.             )
  6514.         );
  6515.     }
  6516.     public function InventoryTransactionViewAction(Request $request)
  6517.     {
  6518.         $em $this->getDoctrine()->getManager();
  6519.         $qry_data = array(
  6520.             'warehouseId' => [0],
  6521.             'igId' => [0],
  6522.             'brandId' => [0],
  6523.             'categoryId' => [0],
  6524.             'actionTagId' => [0],
  6525.         );
  6526.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6527.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6528.         $data_searched = [];
  6529.         $em $this->getDoctrine()->getManager();
  6530.         $companyId $this->getLoggedUserCompanyId($request);
  6531.         $company_data Company::getCompanyData($em$companyId);
  6532.         $data = [];
  6533.         $print_title "Inventory Report";
  6534.         $document_mark = array(
  6535.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6536.             'copy' => ''
  6537.         );
  6538.         if ($request->isMethod('POST'))
  6539.             $method 'POST';
  6540.         else
  6541.             $method 'GET';
  6542.         {
  6543.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  6544.                 $request->request$method,
  6545.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6546.                 $companyId);
  6547.             if ($request->query->has('returnJson') || $request->request->has('returnJson')) {
  6548.                 return new JsonResponse(
  6549.                     array(
  6550.                         'success' => true,
  6551. //                    'page_title' => 'Product Details',
  6552. //                    'company_data' => $company_data,
  6553.                         'page_title' => 'Inventory Transactions',
  6554.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6555.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6556.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6557.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6558.                         'data_products' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6559.                         'action_tag' => $warehouse_action_list,
  6560.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6561.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6562.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6563.                         'data_searched' => $data_searched
  6564.                     )
  6565.                 );
  6566.             } else if ($request->request->get('print_data_enabled') == 1) {
  6567.                 $print_sub_title "";
  6568.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  6569.                     array(
  6570.                         'page_title' => 'Inventory Report',
  6571.                         'page_header' => 'Report',
  6572.                         'print_title' => $print_title,
  6573.                         'document_type' => 'Journal voucher',
  6574.                         'document_mark_image' => $document_mark['original'],
  6575.                         'page_header_sub' => 'Add',
  6576.                         'item_data' => [],
  6577.                         'received' => 2,
  6578.                         'return' => 1,
  6579.                         'total_w_vat' => 1,
  6580.                         'total_vat' => 1,
  6581.                         'total_wo_vat' => 1,
  6582.                         'invoice_id' => 'abcd1234',
  6583.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6584.                         'created_by' => 'created by',
  6585.                         'created_at' => '',
  6586.                         'red' => 0,
  6587.                         'company_name' => $company_data->getName(),
  6588.                         'company_data' => $company_data,
  6589.                         'company_address' => $company_data->getAddress(),
  6590.                         'company_image' => $company_data->getImage(),
  6591.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6592.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6593.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6594.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6595.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6596.                         'action_tag' => $warehouse_action_list,
  6597.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6598.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6599.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6600.                         'data_searched' => $data_searched
  6601.                     )
  6602.                 );
  6603.             }
  6604.         }
  6605.         return $this->render('@Inventory/pages/report/inventory_transaction_view.html.twig',
  6606.             array(
  6607.                 'page_title' => 'Inventory Transactions',
  6608.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6609.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6610.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6611.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6612.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6613.                 'action_tag' => $warehouse_action_list,
  6614.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6615.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6616.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6617.                 'data_searched' => $data_searched
  6618.             )
  6619.         );
  6620.     }
  6621.     public function StockConsumptionViewAction(Request $request)
  6622.     {
  6623.         $em $this->getDoctrine()->getManager();
  6624.         $start_date $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
  6625.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : new \DateTime();
  6626.         $qry_data = array(
  6627.             'warehouseId' => [0],
  6628.             'igId' => [0],
  6629.             'brandId' => [0],
  6630.             'categoryId' => [0],
  6631.             'actionTagId' => [0],
  6632.         );
  6633.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6634.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6635.         $data_searched = [];
  6636.         $em $this->getDoctrine()->getManager();
  6637.         $company_data Company::getCompanyData($em1);
  6638.         $data = [];
  6639.         $print_title "Inventory Report";
  6640.         $document_mark = array(
  6641.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6642.             'copy' => ''
  6643.         );
  6644.         if ($request->isMethod('POST'))
  6645.             $method 'POST';
  6646.         else
  6647.             $method 'GET';
  6648.         $post_data $method == 'POST' $request->request $request->query;
  6649.         $data_searched Inventory::GetStockConsumptionData($this->getDoctrine()->getManager(),
  6650.             $post_data,
  6651.             $method,
  6652.             $start_date,
  6653.             $end_date,
  6654.             $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6655.         if ($post_data->get('print_data_enabled') == 1) {
  6656.             $print_sub_title "";
  6657.             if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6658.                 $html $this->renderView('@Inventory/pages/print/print_stock_consumption.html.twig',
  6659.                     array(
  6660.                         'pdf' => 'true',
  6661.                         'page_title' => 'Inventory Report',
  6662.                         'page_header' => 'Report',
  6663.                         'print_title' => $print_title,
  6664.                         'document_type' => 'Journal voucher',
  6665.                         'document_mark_image' => $document_mark['original'],
  6666.                         'page_header_sub' => 'Add',
  6667.                         'item_data' => [],
  6668.                         'received' => 2,
  6669.                         'return' => 1,
  6670.                         'total_w_vat' => 1,
  6671.                         'total_vat' => 1,
  6672.                         'total_wo_vat' => 1,
  6673.                         'invoice_id' => 'abcd1234',
  6674.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6675.                         'created_by' => 'created by',
  6676.                         'created_at' => '',
  6677.                         'red' => 0,
  6678.                         'start_date' => $start_date,
  6679.                         'end_date' => $end_date,
  6680.                         'openFilter' => empty($post_data->keys()) ? 0,
  6681.                         'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6682.                         'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6683.                         'company_name' => $company_data->getName(),
  6684.                         'company_data' => $company_data,
  6685.                         'company_address' => $company_data->getAddress(),
  6686.                         'company_image' => $company_data->getImage(),
  6687.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6688.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6689.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6690.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6691.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6692.                         'action_tag' => $warehouse_action_list,
  6693.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6694.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6695.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6696.                         'data_searched' => $data_searched,
  6697.                         'export' => 'all'
  6698.                     )
  6699.                 );
  6700.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6701.                     'orientation' => count($data_searched['query_columns_filter']) > 'landscape' 'portrait',
  6702.                     'no-stop-slow-scripts' => true,
  6703.                     'no-background' => false,
  6704.                     'lowquality' => false,
  6705.                     'encoding' => 'utf-8',
  6706.                     'dpi' => 300,
  6707.                     'image-dpi' => 300,
  6708.                 ));
  6709.                 return new Response(
  6710.                     $pdf_response,
  6711.                     200,
  6712.                     array(
  6713.                         'Content-Type' => 'application/pdf',
  6714.                         'Content-Disposition' => 'attachment; filename="Stock_Consumption.pdf"'
  6715.                     )
  6716.                 );
  6717.             }
  6718.             return $this->render('@Inventory/pages/print/print_stock_consumption.html.twig',
  6719.                 array(
  6720.                     'page_title' => 'Inventory Report',
  6721.                     'page_header' => 'Report',
  6722.                     'print_title' => $print_title,
  6723.                     'document_type' => 'Journal voucher',
  6724.                     'document_mark_image' => $document_mark['original'],
  6725.                     'page_header_sub' => 'Add',
  6726.                     'item_data' => [],
  6727.                     'received' => 2,
  6728.                     'return' => 1,
  6729.                     'total_w_vat' => 1,
  6730.                     'total_vat' => 1,
  6731.                     'total_wo_vat' => 1,
  6732.                     'invoice_id' => 'abcd1234',
  6733.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6734.                     'created_by' => 'created by',
  6735.                     'created_at' => '',
  6736.                     'red' => 0,
  6737.                     'start_date' => $start_date,
  6738.                     'end_date' => $end_date,
  6739.                     'openFilter' => empty($post_data->keys()) ? 0,
  6740.                     'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6741.                     'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6742.                     'company_name' => $company_data->getName(),
  6743.                     'company_data' => $company_data,
  6744.                     'company_address' => $company_data->getAddress(),
  6745.                     'company_image' => $company_data->getImage(),
  6746.                     'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6747.                     'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6748.                     'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6749.                     'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6750.                     'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6751.                     'action_tag' => $warehouse_action_list,
  6752.                     'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6753.                     'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6754.                     'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6755.                     'data_searched' => $data_searched,
  6756.                     'export' => 'all'
  6757.                 )
  6758.             );
  6759.         }
  6760.         return $this->render('@Inventory/pages/report/stock_consumption.html.twig',
  6761.             array(
  6762.                 'page_title' => 'Stock Consumption',
  6763.                 'start_date' => $start_date,
  6764.                 'end_date' => $end_date,
  6765.                 'openFilter' => empty($post_data->keys()) ? 0,
  6766.                 'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6767.                 'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6768.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6769.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6770.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6771.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6772.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6773.                 'action_tag' => $warehouse_action_list,
  6774.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6775.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6776.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6777.                 'data_searched' => $data_searched
  6778.             )
  6779.         );
  6780.     }
  6781.     public function ItemViewAction(Request $request)
  6782.     {
  6783.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  6784.             array(
  6785.                 'page_title' => 'Stock Return'
  6786.             )
  6787.         );
  6788.     }
  6789.     public function ProductViewAction(Request $request$id 0)
  6790.     {
  6791.         $em $this->getDoctrine()->getManager();
  6792.         $companyId $this->getLoggedUserCompanyId($request);
  6793.         $company_data Company::getCompanyData($em$companyId);
  6794.         $data = [];
  6795.         $productData $em->getRepository('ApplicationBundle:InvProducts')
  6796.             ->findOneBy(
  6797.                 array(
  6798.                     'id' => $id
  6799.                 )
  6800.             );
  6801.         $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  6802.             ->findBy(
  6803.                 array(
  6804.                     'productId' => $id
  6805.                 )
  6806.             );
  6807.         $trans_history $em->getRepository('ApplicationBundle:InvItemTransaction')
  6808.             ->findBy(
  6809.                 array(
  6810.                     'productId' => $id
  6811.                 ), array(
  6812.                     'transactionDate' => 'ASC',
  6813.                     'id' => 'ASC'
  6814.                 )
  6815.             );
  6816.         $productDataObj = array();
  6817.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  6818.             $getters array_filter(get_class_methods($productData), function ($method) {
  6819.                 return 'get' === substr($method03);
  6820.             });
  6821.             foreach ($getters as $getter) {
  6822.                 if ($getter == 'getGlobalId')
  6823.                     continue;
  6824.         //                    if ($getter == 'getId')
  6825.         //                        continue;
  6826.                 $Fieldname str_replace('get'''$getter);
  6827.                 $productDataObj[$Fieldname] = $productData->{$getter}(); // `foo!`
  6828.             }
  6829.             if ($request->request->has('genInfoOnly') && $request->request->get('genInfoOnly') == 1) {
  6830.                 $dataArray = array(
  6831.                     'success' => true,
  6832.                     'page_title' => 'Product Details',
  6833.                     'company_data' => $company_data,
  6834.                     'productData' => $productData,
  6835.                     'productDataObj' => $productDataObj,
  6836.                     'defaultImageAppendUrl' => '/uploads/Products/',
  6837.                 );
  6838.             } else {
  6839.                 $dataArray = array(
  6840.                     'success' => true,
  6841.                     'page_title' => 'Product Details',
  6842.                     'company_data' => $company_data,
  6843.                     'productData' => $productData,
  6844.                     'productDataObj' => $productDataObj,
  6845.                     'currInvList' => $currInvList,
  6846.                     'trans_history' => $trans_history,
  6847.                     'entityList' => GeneralConstant::$Entity_list_details,
  6848.         //                    'productList' => Inventory::ProductList($em, $companyId),
  6849.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  6850.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  6851.                     'igList' => Inventory::ItemGroupList($em$companyId),
  6852.                     'unitList' => Inventory::UnitTypeList($em),
  6853.                     'brandList' => Inventory::GetBrandList($em$companyId),
  6854.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  6855.                     'warehouseList' => Inventory::WarehouseList($em),
  6856.                     'defaultImageAppendUrl' => '/uploads/Products/',
  6857.                 );
  6858.             }
  6859.             return new JsonResponse(
  6860.                 $dataArray
  6861.             );
  6862.         }
  6863.         $dataArray = array(
  6864.             'page_title' => 'Product Details',
  6865.             'company_data' => $company_data,
  6866.             'productData' => $productData,
  6867.             'currInvList' => $currInvList,
  6868.             'trans_history' => $trans_history,
  6869.             'entityList' => GeneralConstant::$Entity_list_details,
  6870.         //            'productList' => Inventory::ProductList($em, $companyId),
  6871.             'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  6872.             'categoryList' => Inventory::ProductCategoryList($em$companyId),
  6873.             'igList' => Inventory::ItemGroupList($em$companyId),
  6874.             'unitList' => Inventory::UnitTypeList($em),
  6875.             'brandList' => Inventory::GetBrandList($em$companyId),
  6876.             'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  6877.             'warehouseList' => Inventory::WarehouseList($em),
  6878.         );
  6879.         return $this->render('@Inventory/pages/views/product_view.html.twig'$dataArray
  6880.         );
  6881.     }
  6882.     public function CheckForProductInWarehouseAction(Request $request$queryStr '')
  6883.     {
  6884.         $em $this->getDoctrine()->getManager();
  6885.         $companyId $this->getLoggedUserCompanyId($request);
  6886.         $data = [
  6887.             'availableQty' => 0,
  6888.             'productByCodesArray' => [],
  6889.             'indRowId' => 0
  6890.         ];
  6891.         $html '';
  6892.         $productByCodeData = [];
  6893.         if ($request->isMethod('POST')) {
  6894.             $warehouseId $request->request->get('warehouseId'0);
  6895.             $warehouseActionId $request->request->get('warehouseActionId'0);
  6896.             $productId $request->request->get('productId'0);
  6897.             $indRowId $request->request->get('indRowId'0);
  6898.             $data['indRowId'] = $indRowId;
  6899.             $inStorage $em->getRepository('ApplicationBundle:InventoryStorage')
  6900.                 ->findBy(
  6901.                     array(
  6902.                         'productId' => $productId,
  6903.                         'warehouseId' => $warehouseId,
  6904.                         'actionTagId' => $warehouseActionId,
  6905.                         'CompanyId' => $companyId,
  6906.                     )
  6907.                 );
  6908.             foreach ($inStorage as $strg) {
  6909.                 $data['availableQty'] += $strg->getQty();
  6910.             }
  6911.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  6912.                 ->findBy(
  6913.                     array(
  6914.                         'productId' => $productId,
  6915.                         'warehouseId' => $warehouseId,
  6916.                         'warehouseActionId' => $warehouseActionId,
  6917.                         'CompanyId' => $companyId,
  6918.                     )
  6919.                 );
  6920.             foreach ($productByCodeData as $pbc) {
  6921.                 $data['productByCodesArray'][] = array(
  6922.                     'id' => $pbc->getProductByCodeId(),
  6923.                     'productId' => $pbc->getProductId(),
  6924.                     'warehouseId' => $pbc->getWarehouseId(),
  6925.                     'warehouseActionId' => $pbc->getWarehouseActionId(),
  6926. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  6927.                     'sales_code' => str_pad($pbc->getSalesCode(), 13'0'STR_PAD_LEFT),
  6928. //                'sales_code'=>$d['sales_code'],
  6929.                 );
  6930.             }
  6931.             return new JsonResponse(array(
  6932.                     'success' => true,
  6933.                     'data' => $data,
  6934.                 )
  6935.             );
  6936.         }
  6937.         return new JsonResponse(
  6938.             array(
  6939.                 'success' => false,
  6940.                 'data' => $data,
  6941.             )
  6942.         );
  6943.     }
  6944.     public function ProductByCodeListAjaxAction(Request $request$queryStr '')
  6945.     {
  6946.         $em $this->getDoctrine()->getManager();
  6947.         $companyId $this->getLoggedUserCompanyId($request);
  6948.         $company_data Company::getCompanyData($em$companyId);
  6949.         $data = [];
  6950.         $html '';
  6951.         $productByCodeData = [];
  6952.         if ($request->request->has('query') && $queryStr == '')
  6953.             $queryStr $request->request->get('queryStr');
  6954.         $get_kids_sql "select product_by_code_id id, product_id, warehouse_id, warehouse_action_id,
  6955.                             sales_code ,
  6956.                             serial_no,
  6957.                             imei1,
  6958.                             imei2,
  6959.                             imei3,
  6960.                             imei4
  6961.                             from product_by_code
  6962.                             where ( CONVERT(sales_code,char)  like '%" $queryStr "%'
  6963.                                     or  CONVERT(serial_no,char)  like '%" $queryStr "%'
  6964.                                     or  CONVERT(imei1,char)  like '%" $queryStr "%'
  6965.                                     or  CONVERT(imei2,char)  like '%" $queryStr "%'
  6966.                                     or  CONVERT(imei3,char)  like '%" $queryStr "%'
  6967.                                     or  CONVERT(imei4,char)  like '%" $queryStr "%'
  6968.                                     ) ";
  6969.         if ($request->query->has('warehouseId'))
  6970.             $get_kids_sql .= " and warehouse_id=" $request->query->get('warehouseId') . " ";
  6971.         if ($request->query->has('position'))
  6972.             $get_kids_sql .= " and position=" $request->query->get('position') . " ";
  6973.         if ($request->query->has('deliveryReceiptId'))
  6974.             $get_kids_sql .= " and deliveryReceiptId=" $request->query->get('deliveryReceiptId') . " ";
  6975.         if ($request->query->has('warehouseActionId'))
  6976.             $get_kids_sql .= " and warehouse_action_id=" $request->query->get('warehouseActionId') . " ";
  6977.         if ($request->query->has('productId'))
  6978.             $get_kids_sql .= " and product_id=" $request->query->get('productId') . " ";
  6979.         $get_kids_sql .= " and company_id=" $companyId " limit 25";
  6980.         $stmt $em->getConnection()->prepare($get_kids_sql);
  6981.         $stmt->execute();
  6982.         $get_kids $stmt->fetchAll();
  6983.         if (!empty($get_kids)) {
  6984.             foreach ($get_kids as $d) {
  6985.                 $dt = array(
  6986.                     'id' => $d['id'],
  6987.                     'productId' => $d['product_id'],
  6988.                     'warehouseId' => $d['warehouse_id'],
  6989.                     'warehouseActionId' => $d['warehouse_action_id'],
  6990. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  6991.                     'sales_code' => str_pad($d['sales_code'], 13'0'STR_PAD_LEFT),
  6992.                     'serial_no' => str_pad($d['serial_no'], 13'0'STR_PAD_LEFT),
  6993.                     'imei1' => str_pad($d['imei1'], 13'0'STR_PAD_LEFT),
  6994.                     'imei2' => str_pad($d['imei2'], 13'0'STR_PAD_LEFT),
  6995.                     'imei3' => str_pad($d['imei3'], 13'0'STR_PAD_LEFT),
  6996.                     'imei4' => str_pad($d['imei4'], 13'0'STR_PAD_LEFT),
  6997. //                'sales_code'=>$d['sales_code'],
  6998.                 );
  6999.                 $data[] = $dt;
  7000.             }
  7001.         }
  7002. //        if($request->query->has('returnJson'))
  7003.         {
  7004.             return new JsonResponse(
  7005.                 array(
  7006.                     'success' => true,
  7007. //                    'page_title' => 'Product Details',
  7008. //                    'company_data' => $company_data,
  7009.                     'data' => $data,
  7010. //                    'exId'=>$id,
  7011. //                'productByCodeData' => $productByCodeData,
  7012. //                'productData' => $productData,
  7013. //                'currInvList' => $currInvList,
  7014. //                'productList' => Inventory::ProductList($em, $companyId),
  7015. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  7016. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  7017. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  7018. //                'unitList' => Inventory::UnitTypeList($em),
  7019. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  7020. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  7021. //                'warehouseList' => Inventory::WarehouseList($em),
  7022.                 )
  7023.             );
  7024.         }
  7025.     }
  7026.     public function selectDataAjaxAction(Request $request$queryStr '',
  7027.                                                  $version 'latest',
  7028.                                                  $identifier '_default_',
  7029.                                                  $apiKey '_ignore_'
  7030.     )
  7031.     {
  7032.         $em $this->getDoctrine()->getManager();
  7033.         $em_goc $this->getDoctrine()->getManager('company_group');
  7034.         $companyId 0;
  7035.         $skipCurrentUserIdRestriction $request->get('skipCurrentUserIdRestriction'0);
  7036.         $dataOnly $request->get('dataOnly'0);
  7037.         $skipCurrentEmployeeIdRestriction $request->get('skipCurrentEmployeeIdRestriction'0);
  7038.         $skipCurrentUserLoginIdRestriction $request->get('skipCurrentUserLoginIdRestriction'0);
  7039.         $currentUserId $request->getSession()->get(UserConstants::USER_ID0);
  7040.         $currentEmployeeId $request->getSession()->get(UserConstants::USER_EMPLOYEE_ID0);
  7041.         $currentUserLoginIds = [];
  7042.         if ($request->request->get('entity_group'0)) {
  7043.             $companyId 0;
  7044.             $em $this->getDoctrine()->getManager('company_group');
  7045.         } else {
  7046.             if ($request->request->get('appId'0) != 0) {
  7047.                 $gocEnabled 0;
  7048.                 if ($this->container->hasParameter('entity_group_enabled'))
  7049.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7050.                 else
  7051.                     $gocEnabled 1;
  7052.                 if ($gocEnabled == 1) {
  7053.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7054.                         $this->getDoctrine()->getManager('company_group'),
  7055.                         $gocEnabled,
  7056.                         $request->request->get('appId'0)
  7057.                     );
  7058.                     if (!empty($dataToConnect)) {
  7059.                         $connector $this->container->get('application_connector');
  7060.                         $connector->resetConnection(
  7061.                             'default',
  7062.                             $dataToConnect['dbName'],
  7063.                             $dataToConnect['dbUser'],
  7064.                             $dataToConnect['dbPass'],
  7065.                             $dataToConnect['dbHost'],
  7066.                             $reset true
  7067.                         );
  7068.                         $em $this->getDoctrine()->getManager();
  7069.                     }
  7070.                 }
  7071.             } else if ($request->getSession()->get(UserConstants::USER_APP_ID) != && $request->getSession()->get(UserConstants::USER_APP_ID) != null) {
  7072.                 $gocEnabled 0;
  7073.                 if ($this->container->hasParameter('entity_group_enabled'))
  7074.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7075.                 else
  7076.                     $gocEnabled 1;
  7077.                 if ($gocEnabled == 1) {
  7078.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7079.                         $this->getDoctrine()->getManager('company_group'),
  7080.                         $gocEnabled,
  7081.                         $request->getSession()->get(UserConstants::USER_APP_ID)
  7082.                     );
  7083.                     if (!empty($dataToConnect)) {
  7084.                         $connector $this->container->get('application_connector');
  7085.                         $connector->resetConnection(
  7086.                             'default',
  7087.                             $dataToConnect['dbName'],
  7088.                             $dataToConnect['dbUser'],
  7089.                             $dataToConnect['dbPass'],
  7090.                             $dataToConnect['dbHost'],
  7091.                             $reset true
  7092.                         );
  7093.                         $em $this->getDoctrine()->getManager();
  7094.                     }
  7095.                 }
  7096.             }
  7097.             $companyId $this->getLoggedUserCompanyId($request);
  7098.         }
  7099.         $configData = [];
  7100.         $isSingleDataset 1;
  7101.         $dataSet $request->request->has('dataset') ? $request->request->get('dataset') : [];
  7102.         if (is_string($dataSet)) $dataSet json_decode($dataSettrue);
  7103.         $valuePairs $request->get('valuePairs', []);
  7104.         if (is_string($valuePairs)) $valuePairs json_decode($valuePairstrue);
  7105.         $allResult = [];
  7106.         $datasetFromConfig = [];
  7107.         if ($identifier != '_default_') {
  7108.             $config_file $this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' $identifier 'Config.json';
  7109.             if (!file_exists($config_file)) {
  7110.             } else {
  7111.                 $fileText file_get_contents($config_file);
  7112.                 //now replace any value pairs
  7113.                 foreach ($valuePairs as $kkeeyy => $vvaalluuee) {
  7114.                     if (is_array($vvaalluuee)) {
  7115.                         if (isset($vvaalluuee['value']) && isset($vvaalluuee['type'])) {
  7116.                             if ($vvaalluuee['type'] == 'array'$fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee['value']), $fileText);
  7117.                             if ($vvaalluuee['type'] == 'value'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7118.                             if ($vvaalluuee['type'] == 'text'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7119.                         } else {
  7120.                             $fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee), $fileText);
  7121.                         }
  7122.                     }
  7123.                     $fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee$fileText);
  7124.                 }
  7125.                 $fileText str_ireplace('_query_'$request->get('query'$queryStr), $fileText);
  7126.                 $fileText str_ireplace('_itemLimit_'$request->get('itemLimit''_all_'), $fileText);
  7127.                 $fileText str_ireplace('_offset_'$request->get('offset', ($request->get('itemLimit'10))*($request->get('page'1)-1)), $fileText);
  7128.                 if (!(strpos($fileText'_CURRENT_USER_LOGIN_IDS_') === false) && $skipCurrentUserLoginIdRestriction == 0) {
  7129.                     $userInfo = [];
  7130.                     if ($request->getSession()->get(UserConstants::USER_TYPE0) == UserConstants::USER_TYPE_APPLICANT) {
  7131.                         $userInfo $em_goc->getRepository('CompanyGroupBundle:EntityLoginLog')->findBy(
  7132.                             array('userId' => $currentUserId)
  7133.                         );
  7134.                     } else {
  7135.                         $userInfo $em->getRepository('ApplicationBundle:SysLoginLog')->findBy(
  7136.                             array('userId' => $currentUserId)
  7137.                         );
  7138.                     }
  7139.                     foreach ($userInfo as $uLogininfo) {
  7140.                         $currentUserLoginIds[] = $uLogininfo->getLoginId();
  7141.                     }
  7142.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_'json_encode($currentUserLoginIds), $fileText);
  7143.                 } else {
  7144.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_''_EMPTY_'$fileText);
  7145.                 }
  7146.                 if (!(strpos($fileText'_CURRENT_USER_ID_') === false) && $skipCurrentUserIdRestriction == 0) {
  7147.                     $fileText str_ireplace('_CURRENT_USER_ID_'$currentUserId$fileText);
  7148.                 } else {
  7149.                     $fileText str_ireplace('_CURRENT_USER_ID_''_EMPTY_'$fileText);
  7150.                 }
  7151.                 if (!(strpos($fileText'_CURRENT_USER_EMPLOYEE_ID_') === false) && $skipCurrentEmployeeIdRestriction == 0) {
  7152.                     if ((strpos($fileText'skipCurrentEmployeeIdRestriction') === false)) {
  7153.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_'$currentEmployeeId$fileText);
  7154.                     } else {
  7155.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  7156.                     }
  7157.                 } else {
  7158.                     $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  7159.                 }
  7160.                 if ($fileText)
  7161.                     $datasetFromConfig json_decode($fileTexttrue);
  7162.                 $skipCurrentUserIdRestriction = isset($datasetFromConfig['skipCurrentUserIdRestriction']) ? $datasetFromConfig['skipCurrentUserIdRestriction'] : $skipCurrentUserIdRestriction;
  7163.                 $skipCurrentEmployeeIdRestriction = isset($datasetFromConfig['skipCurrentEmployeeIdRestriction']) ? $datasetFromConfig['skipCurrentEmployeeIdRestriction'] : $skipCurrentEmployeeIdRestriction;
  7164.                 $skipCurrentUserLoginIdRestriction = isset($datasetFromConfig['skipCurrentUserLoginIdRestriction']) ? $datasetFromConfig['skipCurrentUserLoginIdRestriction'] : $skipCurrentUserLoginIdRestriction;
  7165.             }
  7166.         }
  7167.         if ($dataSet == null$dataSet = [];
  7168. //        return new JsonResponse(array(
  7169. //            'queryStr'=>$queryStr
  7170. //        ));
  7171.         if (!empty($datasetFromConfig)) {
  7172.             if (isset($datasetFromConfig['tableName'])) {
  7173.                 $isSingleDataset 1;
  7174.                 $dataSet[] = $datasetFromConfig;
  7175.             } else {
  7176.                 if (count($datasetFromConfig) == 1)
  7177.                     $isSingleDataset 1;
  7178.                 $dataSet $datasetFromConfig;
  7179.             }
  7180.         }
  7181.         if (empty($dataSet)) {
  7182.             $isSingleDataset 1;
  7183.             $singleDataSet = array(
  7184.                 "valueField" => $request->request->has('valueField') ? $request->request->get('valueField') : 'id',
  7185.                 "query" => $request->get('query'$queryStr),
  7186.                 "headMarkers" => $request->get('headMarkers'''),
  7187.                 "headMarkersStrictMatch" => $request->get('headMarkersStrictMatch'0),
  7188.                 "itemLimit" => $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25,
  7189.                 "selectorId" => $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_',
  7190.                 "textField" => $request->request->has('textField') ? $request->request->get('textField') : 'name',
  7191.                 "tableName" => $request->request->has('tableName') ? $request->request->get('tableName') : '',
  7192.                 "isMultiple" => $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0,
  7193.                 "orConditions" => $request->request->has('orConditions') ? $request->request->get('orConditions') : [],
  7194.                 "andConditions" => $request->request->has('andConditions') ? $request->request->get('andConditions') : [],
  7195.                 "andOrConditions" => $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [],
  7196.                 "mustConditions" => $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [],
  7197.                 "joinTableData" => $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [],
  7198.                 "renderTextFormat" => $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '',
  7199.                 "setDataForSingle" => $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0,
  7200.                 "dataId" => $request->request->has('dataId') ? $request->request->get('dataId') : 0,
  7201.                 "lastChildrenOnly" => $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0,
  7202.                 "parentOnly" => $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0,
  7203.                 "parentIdField" => $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id',
  7204.                 "skipDefaultCompanyId" => $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1,
  7205.                 "offset" => $request->request->has('offset') ? $request->request->get('offset') : 0,
  7206.                 "returnTotalMatchedEntriesFlag" => $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0,
  7207.                 "nextOffset" => 0,
  7208.                 "totalMatchedEntries" => 0,
  7209.                 "convertToObject" => $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [],
  7210.                 "convertDateToStringFieldList" => $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [],
  7211.                 "orderByConditions" => $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [],
  7212.                 "convertToUrl" => $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [],
  7213.                 "fullPathList" => $request->request->has('fullPathList') ? $request->request->get('fullPathList') : [],
  7214.                 "ret_data" => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  7215.             );
  7216.             $dataSet[] = $singleDataSet;
  7217.         }
  7218. //        $lastResult = [
  7219. //            'identifier' => $identifier,
  7220. //            'dataSet' => $dataSet,
  7221. //        ];
  7222. //        return new JsonResponse($lastResult);
  7223.         $userId $request->getSession()->get(UserConstants::USER_ID);
  7224. //        public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [],$userId=0)
  7225.         foreach ($dataSet as $dsIndex => $dataConfig) {
  7226.             $companyId 0;
  7227.             $queryStringIndividual $queryStr;
  7228.             $data = [];
  7229.             $data_by_id = [];
  7230.             $setValueArray = [];
  7231.             $silentChangeSelectize 0;
  7232.             $setValue 0;
  7233.             $setValueType 0;// 0 for id , 1 for query
  7234.             $selectAll 0;
  7235.             if ($queryStringIndividual == '_EMPTY_')
  7236.                 $queryStringIndividual '';
  7237.             if (isset($dataConfig['query']))
  7238.                 $queryStringIndividual $dataConfig['query'];
  7239.             if ($queryStringIndividual == '_EMPTY_')
  7240.                 $queryStringIndividual '';
  7241.             $queryStringIndividual str_replace('_FSLASH_''/'$queryStringIndividual);
  7242.             if ($queryStringIndividual === '#setValue:') {
  7243.                 $queryStringIndividual '';
  7244.             }
  7245.             if (!(strpos($queryStringIndividual'_silent_change_') === false)) {
  7246.                 $silentChangeSelectize 1;
  7247.                 $queryStringIndividual str_ireplace('_silent_change_'''$queryStringIndividual);
  7248.             }
  7249.             if (!(strpos($queryStringIndividual'#setValue:') === false)) {
  7250.                 $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStringIndividual));
  7251.                 foreach ($setValueArrayBeforeFilter as $svf) {
  7252.                     if ($svf == '_ALL_') {
  7253.                         $selectAll 1;
  7254.                         $setValueArray = [];
  7255.                         continue;
  7256.                     }
  7257.                     if (is_numeric($svf)) {
  7258.                         $setValueArray[] = ($svf 1);
  7259.                         $setValue $svf 1;
  7260.                     }
  7261.                 }
  7262.                 $queryStringIndividual '';
  7263.             }
  7264.             $valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
  7265.             $headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''//Special Field
  7266.             $headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0//Special Field
  7267.             $itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
  7268.             $selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
  7269.             $textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
  7270.             $table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
  7271.             $isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
  7272.             $orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
  7273.             $andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
  7274.             $andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
  7275.             $mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
  7276.             $joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
  7277.             $renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
  7278.             $setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
  7279.             $dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
  7280.             $lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
  7281.             $parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
  7282.             $parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
  7283.             $skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
  7284.             $offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
  7285.             $returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
  7286.             $nextOffset 0;
  7287.             $totalMatchedEntries 0;
  7288.             $convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
  7289.             $convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
  7290.             $orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
  7291.             $convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
  7292.             $fullPathList = isset($dataConfig['fullPathList']) ? $dataConfig['fullPathList'] : [];
  7293.             if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  7294.             if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  7295.             if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  7296.             if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  7297.             if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  7298.             if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  7299.             if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  7300.             if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  7301.             if (is_string($fullPathList)) $fullPathList json_decode($fullPathListtrue);
  7302. //            return new JsonResponse(array(
  7303. //                'dataSet'=>$dataSet,
  7304. //                'dataConfig'=>$dataConfig,
  7305. //                'hi'=>$this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json',
  7306. //                'hiD'=>file_get_contents($this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json')
  7307. //            ));
  7308.             if ($table == '') {
  7309.                 $lastResult = array(
  7310.                     'success' => false,
  7311.                     'currentTs' => (new \Datetime())->format('U'),
  7312.                     'isMultiple' => $isMultiple,
  7313.                     'setValueArray' => $setValueArray,
  7314.                     'setValue' => $setValue,
  7315.                     'data' => $data,
  7316.                     'dataId' => $dataId,
  7317.                     'selectorId' => $selectorId,
  7318.                     'dataById' => $data_by_id,
  7319.                     'selectedId' => 0,
  7320.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  7321.                 );
  7322.             } else {
  7323.                 $restrictionData = array(
  7324. //            'table'=>'relevantField in restriction'
  7325.                     'warehouse_action' => 'warehouseActionIds',
  7326.                     'branch' => 'branchIds',
  7327.                     'warehouse' => 'warehouseIds',
  7328.                     'production_process_settings' => 'productionProcessIds',
  7329.                 );
  7330.                 $restrictionIdList = [];
  7331.                 $filterQryForCriteria "select ";
  7332.                 $selectQry "";
  7333. //        $selectQry=" `$table`.* ";
  7334.                 $selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
  7335.                 $selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
  7336.                 if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  7337.                 foreach ($selectFieldList as $selField) {
  7338.                     if ($selectQry != '')
  7339.                         $selectQry .= ", ";
  7340.                     if ($selField == '*')
  7341.                         $selectQry .= " `$table`.$selField ";
  7342.                     else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7343.                         if ($selectPrefix == '')
  7344.                             $selectQry .= " count(*)  ";
  7345.                         else
  7346.                             $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  7347.                     } else {
  7348.                         if ($selectPrefix == '')
  7349.                             $selectQry .= " `$table`.`$selField` ";
  7350.                         else
  7351.                             $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  7352.                     }
  7353.                 }
  7354.                 $joinQry " from $table ";
  7355. //        $filterQryForCriteria = "select * from $table ";
  7356.                 foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  7357. //            $conditionStr.=' 1=1 ';
  7358.                     $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  7359.                     $joinTableAlias $joinTableName '_' $joinIndex;
  7360.                     $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  7361.                     $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  7362.                     $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  7363.                     $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  7364.                     $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  7365.                     $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  7366.                     $joinMustConditions = isset($joinTableDatum['joinMustConditions']) ? $joinTableDatum['joinMustConditions'] : [];
  7367.                     $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  7368.                     $joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
  7369.                     $joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
  7370.                     if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  7371.                     if (is_string($joinMustConditions)) $joinMustConditions json_decode($joinMustConditionstrue);
  7372.                     if (is_string($joinAndOrConditions)) $joinAndOrConditions json_decode($joinAndOrConditionstrue);
  7373.                     if (is_string($joinOrConditions)) $joinOrConditions json_decode($joinOrConditionstrue);
  7374.                     foreach ($selectFieldList as $selField) {
  7375.                         if ($selField == '*')
  7376.                             $selectQry .= ", `$joinTableAlias`.$selField ";
  7377.                         else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7378.                             if ($selectPrefix == '')
  7379.                                 $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  7380.                             else
  7381.                                 $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  7382.                         } else {
  7383.                             if ($selectPrefix == '')
  7384.                                 $selectQry .= ", `$joinTableAlias`.`$selField`  ";
  7385.                             else
  7386.                                 $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  7387.                         }
  7388.                     }
  7389.                     $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  7390. //            if($joinTablePrimaryField!='')
  7391. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7392. //            $joinAndString = '';
  7393.                     $joinMustString '';
  7394.                     if ($joinTablePrimaryField != '')
  7395.                         $joinQry .= "  `$joinTableAlias`.`$joinTableOnField$fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7396.                     foreach ($joinMustConditions as $mustCondition) {
  7397. //            $conditionStr.=' 1=1 ';
  7398.                         $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  7399.                         $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  7400.                         $aliasInCondition $table;
  7401.                         if (!(strpos($cfield'.') === false)) {
  7402.                             $fullCfieldArray explode('.'$cfield);
  7403.                             $aliasInCondition $fullCfieldArray[0];
  7404.                             $cfield $fullCfieldArray[1];
  7405.                         }
  7406.                         $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  7407.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7408.                             if ($joinMustString != '')
  7409.                                 $joinMustString .= " and ";
  7410.                             if ($ctype == 'like') {
  7411.                                 $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7412.                                 $wordsBySpaces explode(' '$cvalue);
  7413.                                 foreach ($wordsBySpaces as $word) {
  7414.                                     if ($joinMustString != '')
  7415.                                         $joinMustString .= " and ";
  7416.                                     $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7417.                                 }
  7418.                             } else if ($ctype == 'not like') {
  7419.                                 $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7420.                                 $wordsBySpaces explode(' '$cvalue);
  7421.                                 foreach ($wordsBySpaces as $word) {
  7422.                                     if ($joinMustString != '')
  7423.                                         $joinMustString .= " and ";
  7424.                                     $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7425.                                 }
  7426.                             } else if ($ctype == 'not_in') {
  7427.                                 $joinMustString .= " ( ";
  7428.                                 if (in_array('null'$cvalue)) {
  7429.                                     $joinMustString .= " `$joinTableAlias`.$cfield is not null";
  7430.                                     $cvalue array_diff($cvalue, ['null']);
  7431.                                     if (!empty($cvalue))
  7432.                                         $joinMustString .= " and ";
  7433.                                 }
  7434.                                 if (in_array(''$cvalue)) {
  7435.                                     $joinMustString .= "`$joinTableAlias`.$cfield != '' ";
  7436.                                     $cvalue array_diff($cvalue, ['']);
  7437.                                     if (!empty($cvalue))
  7438.                                         $joinMustString .= " and ";
  7439.                                 }
  7440.                                 $joinMustString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7441.                             } else if ($ctype == 'in') {
  7442.                                 if (in_array('null'$cvalue)) {
  7443.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null";
  7444.                                     $cvalue array_diff($cvalue, ['null']);
  7445.                                     if (!empty($cvalue))
  7446.                                         $joinMustString .= " and ";
  7447.                                 }
  7448.                                 if (in_array(''$cvalue)) {
  7449.                                     $joinMustString .= "`$joinTableAlias`.$cfield = '' ";
  7450.                                     $cvalue array_diff($cvalue, ['']);
  7451.                                     if (!empty($cvalue))
  7452.                                         $joinMustString .= " and ";
  7453.                                 }
  7454.                                 $joinMustString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7455.                             } else if ($ctype == '=') {
  7456. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7457. //                            $fullCfieldArray = explode('.', $cfield);
  7458. //                            $aliasInCondition = $fullCfieldArray[0];
  7459. //                            $cfield = $fullCfieldArray[1];
  7460. //                        }
  7461.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7462.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null ";
  7463.                                 else
  7464.                                     $joinMustString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7465.                             } else if ($ctype == '!=') {
  7466.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7467.                                     $joinMustString .= "`$joinTableAlias`.$cfield is not null ";
  7468.                                 else
  7469.                                     $joinMustString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7470.                             } else {
  7471.                                 if (is_string($cvalue))
  7472.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7473.                                 else
  7474.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7475.                             }
  7476.                         }
  7477.                     }
  7478. //            if ($joinMustString != '') {
  7479. //                if ($conditionStr != '')
  7480. //                    $conditionStr .= (" and (" . $joinMustString . ") ");
  7481. //                else
  7482. //                    $conditionStr .= ("  (" . $joinMustString . ") ");
  7483. //            }
  7484.                     if ($joinMustString != '') {
  7485.                         $joinQry .= (' and ' $joinMustString);
  7486. //                        $joinQry.=' and (';
  7487.                     }
  7488.                     $mustBracketDone 0;
  7489.                     $joinAndString '';
  7490. //                    if ($joinTablePrimaryField != '')
  7491. //                        $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7492.                     foreach ($joinAndConditions as $andCondition) {
  7493. //            $conditionStr.=' 1=1 ';
  7494.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  7495.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  7496.                         $aliasInCondition $table;
  7497.                         if (!(strpos($cfield'.') === false)) {
  7498.                             $fullCfieldArray explode('.'$cfield);
  7499.                             $aliasInCondition $fullCfieldArray[0];
  7500.                             $cfield $fullCfieldArray[1];
  7501.                         }
  7502.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  7503.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7504.                             if ($joinAndString != '')
  7505.                                 $joinAndString .= " and ";
  7506.                             if ($ctype == 'like') {
  7507.                                 $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7508.                                 $wordsBySpaces explode(' '$cvalue);
  7509.                                 foreach ($wordsBySpaces as $word) {
  7510.                                     if ($joinAndString != '')
  7511.                                         $joinAndString .= " and ";
  7512.                                     $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7513.                                 }
  7514.                             } else if ($ctype == 'not like') {
  7515.                                 $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7516.                                 $wordsBySpaces explode(' '$cvalue);
  7517.                                 foreach ($wordsBySpaces as $word) {
  7518.                                     if ($joinAndString != '')
  7519.                                         $joinAndString .= " and ";
  7520.                                     $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7521.                                 }
  7522.                             } else if ($ctype == 'not_in') {
  7523.                                 $joinAndString .= " ( ";
  7524.                                 if (in_array('null'$cvalue)) {
  7525.                                     $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  7526.                                     $cvalue array_diff($cvalue, ['null']);
  7527.                                     if (!empty($cvalue))
  7528.                                         $joinAndString .= " and ";
  7529.                                 }
  7530.                                 if (in_array(''$cvalue)) {
  7531.                                     $joinAndString .= "`$joinTableAlias`.$cfield != '' ";
  7532.                                     $cvalue array_diff($cvalue, ['']);
  7533.                                     if (!empty($cvalue))
  7534.                                         $joinAndString .= " and ";
  7535.                                 }
  7536.                                 $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7537.                             } else if ($ctype == 'in') {
  7538.                                 if (in_array('null'$cvalue)) {
  7539.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null";
  7540.                                     $cvalue array_diff($cvalue, ['null']);
  7541.                                     if (!empty($cvalue))
  7542.                                         $joinAndString .= " and ";
  7543.                                 }
  7544.                                 if (in_array(''$cvalue)) {
  7545.                                     $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  7546.                                     $cvalue array_diff($cvalue, ['']);
  7547.                                     if (!empty($cvalue))
  7548.                                         $joinAndString .= " and ";
  7549.                                 }
  7550.                                 $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7551.                             } else if ($ctype == '=') {
  7552. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7553. //                            $fullCfieldArray = explode('.', $cfield);
  7554. //                            $aliasInCondition = $fullCfieldArray[0];
  7555. //                            $cfield = $fullCfieldArray[1];
  7556. //                        }
  7557.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7558.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  7559.                                 else
  7560.                                     $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7561.                             } else if ($ctype == '!=') {
  7562.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7563.                                     $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  7564.                                 else
  7565.                                     $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7566.                             } else {
  7567.                                 if (is_string($cvalue))
  7568.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7569.                                 else
  7570.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7571.                             }
  7572.                         }
  7573.                     }
  7574. //            if ($joinAndString != '') {
  7575. //                if ($conditionStr != '')
  7576. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  7577. //                else
  7578. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  7579. //            }
  7580.                     if ($joinAndString != '') {
  7581.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7582.                             $joinQry .= ' and (';
  7583.                             $mustBracketDone 1;
  7584.                         }
  7585.                         if ($joinQry != '')
  7586.                             $joinQry .= (" and (" $joinAndString ") ");
  7587.                         else
  7588.                             $joinQry .= ("  (" $joinAndString ") ");
  7589.                     }
  7590.                     $joinAndOrString "";
  7591.                     foreach ($joinAndOrConditions as $andOrCondition) {
  7592. //            $conditionStr.=' 1=1 ';
  7593.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  7594.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  7595.                         $aliasInCondition $table;
  7596.                         if (!(strpos($cfield'.') === false)) {
  7597.                             $fullCfieldArray explode('.'$cfield);
  7598.                             $aliasInCondition $fullCfieldArray[0];
  7599.                             $cfield $fullCfieldArray[1];
  7600.                         }
  7601.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  7602.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7603.                             if ($joinAndOrString != '')
  7604.                                 $joinAndOrString .= " or ";
  7605.                             if ($ctype == 'like') {
  7606.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7607.                                 $wordsBySpaces explode(' '$cvalue);
  7608.                                 foreach ($wordsBySpaces as $word) {
  7609.                                     if ($joinAndOrString != '')
  7610.                                         $joinAndOrString .= " or ";
  7611.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7612.                                 }
  7613.                             } else if ($ctype == 'not like') {
  7614.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7615.                                 $wordsBySpaces explode(' '$cvalue);
  7616.                                 foreach ($wordsBySpaces as $word) {
  7617.                                     if ($joinAndOrString != '')
  7618.                                         $joinAndOrString .= " or ";
  7619.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7620.                                 }
  7621.                             } else if ($ctype == 'not_in') {
  7622.                                 $joinAndOrString .= " ( ";
  7623.                                 if (in_array('null'$cvalue)) {
  7624.                                     $joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
  7625.                                     $cvalue array_diff($cvalue, ['null']);
  7626.                                     if (!empty($cvalue))
  7627.                                         $joinAndOrString .= " or ";
  7628.                                 }
  7629.                                 if (in_array(''$cvalue)) {
  7630.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != '' ";
  7631.                                     $cvalue array_diff($cvalue, ['']);
  7632.                                     if (!empty($cvalue))
  7633.                                         $joinAndOrString .= " or ";
  7634.                                 }
  7635.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7636.                             } else if ($ctype == 'in') {
  7637.                                 if (in_array('null'$cvalue)) {
  7638.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null";
  7639.                                     $cvalue array_diff($cvalue, ['null']);
  7640.                                     if (!empty($cvalue))
  7641.                                         $joinAndOrString .= " or ";
  7642.                                 }
  7643.                                 if (in_array(''$cvalue)) {
  7644.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  7645.                                     $cvalue array_diff($cvalue, ['']);
  7646.                                     if (!empty($cvalue))
  7647.                                         $joinAndOrString .= " or ";
  7648.                                 }
  7649.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7650.                             } else if ($ctype == '=') {
  7651. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7652. //                            $fullCfieldArray = explode('.', $cfield);
  7653. //                            $aliasInCondition = $fullCfieldArray[0];
  7654. //                            $cfield = $fullCfieldArray[1];
  7655. //                        }
  7656.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7657.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
  7658.                                 else
  7659.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7660.                             } else if ($ctype == '!=') {
  7661.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7662.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
  7663.                                 else
  7664.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7665.                             } else {
  7666.                                 if (is_string($cvalue))
  7667.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7668.                                 else
  7669.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7670.                             }
  7671.                         }
  7672.                     }
  7673. //            if ($joinAndOrString != '')
  7674. //                $joinQry .= $joinAndOrString;
  7675.                     if ($joinAndOrString != '') {
  7676.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7677.                             $joinQry .= ' and (';
  7678.                             $mustBracketDone 1;
  7679.                         }
  7680.                         if ($joinQry != '')
  7681.                             $joinQry .= (" and (" $joinAndOrString ") ");
  7682.                         else
  7683.                             $joinQry .= ("  (" $joinAndOrString ") ");
  7684.                     }
  7685.                     //pika
  7686.                     $joinOrString "";
  7687.                     foreach ($joinOrConditions as $orCondition) {
  7688. //            $conditionStr.=' 1=1 ';
  7689.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  7690.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  7691.                         $aliasInCondition $table;
  7692.                         if (!(strpos($cfield'.') === false)) {
  7693.                             $fullCfieldArray explode('.'$cfield);
  7694.                             $aliasInCondition $fullCfieldArray[0];
  7695.                             $cfield $fullCfieldArray[1];
  7696.                         }
  7697.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  7698.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7699.                             if ($joinOrString != '' || $joinAndString != '' || $joinMustString != '')
  7700.                                 $joinOrString .= " or ";
  7701.                             if ($ctype == 'like') {
  7702.                                 $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7703.                                 $wordsBySpaces explode(' '$cvalue);
  7704.                                 foreach ($wordsBySpaces as $word) {
  7705.                                     if ($joinOrString != '')
  7706.                                         $joinOrString .= " or ";
  7707.                                     $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7708.                                 }
  7709.                             } else if ($ctype == 'not like') {
  7710.                                 $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7711.                                 $wordsBySpaces explode(' '$cvalue);
  7712.                                 foreach ($wordsBySpaces as $word) {
  7713.                                     if ($joinOrString != '')
  7714.                                         $joinOrString .= " or ";
  7715.                                     $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7716.                                 }
  7717.                             } else if ($ctype == 'not_in') {
  7718.                                 $joinOrString .= " ( ";
  7719.                                 if (in_array('null'$cvalue)) {
  7720.                                     $joinOrString .= " `$joinTableAlias`.$cfield is not null";
  7721.                                     $cvalue array_diff($cvalue, ['null']);
  7722.                                     if (!empty($cvalue))
  7723.                                         $joinOrString .= " or ";
  7724.                                 }
  7725.                                 if (in_array(''$cvalue)) {
  7726.                                     $joinOrString .= "`$joinTableAlias`.$cfield != '' ";
  7727.                                     $cvalue array_diff($cvalue, ['']);
  7728.                                     if (!empty($cvalue))
  7729.                                         $joinOrString .= " or ";
  7730.                                 }
  7731.                                 $joinOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7732.                             } else if ($ctype == 'in') {
  7733.                                 if (in_array('null'$cvalue)) {
  7734.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null";
  7735.                                     $cvalue array_diff($cvalue, ['null']);
  7736.                                     if (!empty($cvalue))
  7737.                                         $joinOrString .= " or ";
  7738.                                 }
  7739.                                 if (in_array(''$cvalue)) {
  7740.                                     $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  7741.                                     $cvalue array_diff($cvalue, ['']);
  7742.                                     if (!empty($cvalue))
  7743.                                         $joinOrString .= " or ";
  7744.                                 }
  7745.                                 $joinOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7746.                             } else if ($ctype == '=') {
  7747. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7748. //                            $fullCfieldArray = explode('.', $cfield);
  7749. //                            $aliasInCondition = $fullCfieldArray[0];
  7750. //                            $cfield = $fullCfieldArray[1];
  7751. //                        }
  7752.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7753.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null ";
  7754.                                 else
  7755.                                     $joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7756.                             } else if ($ctype == '!=') {
  7757.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7758.                                     $joinOrString .= "`$joinTableAlias`.$cfield is not null ";
  7759.                                 else
  7760.                                     $joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7761.                             } else {
  7762.                                 if (is_string($cvalue))
  7763.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7764.                                 else
  7765.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7766.                             }
  7767.                         }
  7768.                     }
  7769. //            if ($joinOrString != '')
  7770. //                $joinQry .= $joinOrString;
  7771.                     if ($joinOrString != '') {
  7772.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  7773.                             $joinQry .= ' and (';
  7774.                             $mustBracketDone 1;
  7775.                         }
  7776.                         if ($joinQry != '')
  7777.                             $joinQry .= (" or (" $joinOrString ") ");
  7778.                         else
  7779.                             $joinQry .= ("  (" $joinOrString ") ");
  7780.                     }
  7781.                     if ($joinMustString != '' && $mustBracketDone == 1) {
  7782.                         $joinQry .= ' ) ';
  7783.                     }
  7784. //
  7785. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7786.                 }
  7787.                 $filterQryForCriteria .= $selectQry;
  7788.                 $filterQryForCriteria .= $joinQry;
  7789.                 if ($skipDefaultCompanyId == && $companyId != && !isset($dataConfig['entity_group']))
  7790.                     $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  7791.                 else
  7792.                     $filterQryForCriteria .= " where 1=1 ";
  7793.                 $conditionStr "";
  7794.                 $aliasInCondition $table;
  7795.                 if ($headMarkers != '' && $table == 'acc_accounts_head') {
  7796.                     $markerList explode(','$headMarkers);
  7797.                     $spMarkerQry "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
  7798.                     $markerPassedHeads = [];
  7799.                     foreach ($markerList as $mrkr) {
  7800.                         $spMarkerQry .= " and marker_hash like '%" $mrkr "%'";
  7801.                     }
  7802.                     $spStmt $em->getConnection()->prepare($spMarkerQry);
  7803.                     $spStmt->execute();
  7804.                     $spStmtResults $spStmt->fetchAll();
  7805.                     foreach ($spStmtResults as $ggres) {
  7806.                         $markerPassedHeads[] = $ggres['accounts_head_id'];
  7807.                     }
  7808.                     if (!empty($markerPassedHeads)) {
  7809.                         if ($conditionStr != '')
  7810.                             $conditionStr .= " and (";
  7811.                         else
  7812.                             $conditionStr .= " (";
  7813.                         if ($headMarkersStrictMatch != 1) {
  7814.                             foreach ($markerPassedHeads as $mh) {
  7815.                                 $conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" $mh "/%' or ";
  7816.                             }
  7817.                         }
  7818.                         $conditionStr .= "  `$aliasInCondition`.`accounts_head_id` in (" implode(','$markerPassedHeads) . ") ";
  7819.                         $conditionStr .= " )";
  7820.                     }
  7821.                 }
  7822.                 if (isset($restrictionData[$table])) {
  7823.                     $userRestrictionData Users::getUserApplicationAccessSettings($em$userId)['options'];
  7824.                     if (isset($userRestrictionData[$restrictionData[$table]])) {
  7825.                         $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  7826.                         if ($restrictionIdList == null)
  7827.                             $restrictionIdList = [];
  7828.                     }
  7829.                     if (!empty($restrictionIdList)) {
  7830.                         if ($conditionStr != '')
  7831.                             $conditionStr .= " and ";
  7832.                         $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  7833.                     }
  7834.                 }
  7835. //        $aliasInCondition = $table;
  7836.                 if (!empty($setValueArray) || $selectAll == 1) {
  7837.                     if (!empty($setValueArray)) {
  7838.                         if ($conditionStr != '')
  7839.                             $conditionStr .= " and ";
  7840.                         $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  7841.                     }
  7842.                 } else {
  7843.                     $andString '';
  7844.                     foreach ($andConditions as $andCondition) {
  7845. //            $conditionStr.=' 1=1 ';
  7846.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  7847.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  7848.                         $aliasInCondition $table;
  7849.                         if (!(strpos($cfield'.') === false)) {
  7850.                             $fullCfieldArray explode('.'$cfield);
  7851.                             $aliasInCondition $fullCfieldArray[0];
  7852.                             $cfield $fullCfieldArray[1];
  7853.                         }
  7854.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  7855.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7856.                             if ($andString != '')
  7857.                                 $andString .= " and ";
  7858.                             if ($ctype == 'like') {
  7859.                                 $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7860.                                 $wordsBySpaces explode(' '$cvalue);
  7861.                                 foreach ($wordsBySpaces as $word) {
  7862.                                     if ($andString != '')
  7863.                                         $andString .= " and ";
  7864.                                     $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7865.                                 }
  7866.                             } else if ($ctype == 'not like') {
  7867.                                 $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7868.                                 $wordsBySpaces explode(' '$cvalue);
  7869.                                 foreach ($wordsBySpaces as $word) {
  7870.                                     if ($andString != '')
  7871.                                         $andString .= " and ";
  7872.                                     $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7873.                                 }
  7874.                             } else if ($ctype == 'not_in') {
  7875.                                 $andString .= " ( ";
  7876.                                 if (in_array('null'$cvalue)) {
  7877.                                     $andString .= " `$aliasInCondition`.$cfield is not null";
  7878.                                     $cvalue array_diff($cvalue, ['null']);
  7879.                                     if (!empty($cvalue))
  7880.                                         $andString .= " and ";
  7881.                                 }
  7882.                                 if (in_array(''$cvalue)) {
  7883.                                     $andString .= "`$aliasInCondition`.$cfield != '' ";
  7884.                                     $cvalue array_diff($cvalue, ['']);
  7885.                                     if (!empty($cvalue))
  7886.                                         $andString .= " and ";
  7887.                                 }
  7888.                                 $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7889.                             } else if ($ctype == 'in') {
  7890.                                 if (in_array('null'$cvalue)) {
  7891.                                     $andString .= "`$aliasInCondition`.$cfield is null";
  7892.                                     $cvalue array_diff($cvalue, ['null']);
  7893.                                     if (!empty($cvalue))
  7894.                                         $andString .= " and ";
  7895.                                 }
  7896.                                 if (in_array(''$cvalue)) {
  7897.                                     $andString .= "`$aliasInCondition`.$cfield = '' ";
  7898.                                     $cvalue array_diff($cvalue, ['']);
  7899.                                     if (!empty($cvalue))
  7900.                                         $andString .= " and ";
  7901.                                 }
  7902.                                 $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  7903.                             } else if ($ctype == '=') {
  7904.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7905.                                     $andString .= "`$aliasInCondition`.$cfield is null ";
  7906.                                 else
  7907.                                     $andString .= "`$aliasInCondition`.$cfield = $cvalue ";
  7908.                             } else if ($ctype == '!=') {
  7909.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7910.                                     $andString .= "`$aliasInCondition`.$cfield is not null ";
  7911.                                 else
  7912.                                     $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  7913.                             } else {
  7914.                                 if (is_string($cvalue))
  7915.                                     $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  7916.                                 else
  7917.                                     $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  7918.                             }
  7919.                         }
  7920.                     }
  7921.                     if ($andString != '') {
  7922.                         if ($conditionStr != '')
  7923.                             $conditionStr .= (" and (" $andString ") ");
  7924.                         else
  7925.                             $conditionStr .= ("  (" $andString ") ");
  7926.                     }
  7927.                     $orString '';
  7928.                     foreach ($orConditions as $orCondition) {
  7929.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  7930.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  7931.                         $aliasInCondition $table;
  7932.                         if (!(strpos($cfield'.') === false)) {
  7933.                             $fullCfieldArray explode('.'$cfield);
  7934.                             $aliasInCondition $fullCfieldArray[0];
  7935.                             $cfield $fullCfieldArray[1];
  7936.                         }
  7937.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  7938.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7939.                             if ($orString != '')
  7940.                                 $orString .= " or ";
  7941.                             if ($ctype == 'like') {
  7942.                                 $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7943.                                 $wordsBySpaces explode(' '$cvalue);
  7944.                                 foreach ($wordsBySpaces as $word) {
  7945.                                     if ($orString != '')
  7946.                                         $orString .= " or ";
  7947.                                     $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7948.                                 }
  7949.                             } else if ($ctype == 'not like') {
  7950.                                 $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7951.                                 $wordsBySpaces explode(' '$cvalue);
  7952.                                 foreach ($wordsBySpaces as $word) {
  7953.                                     if ($orString != '')
  7954.                                         $orString .= " or ";
  7955.                                     $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7956.                                 }
  7957.                             } else if ($ctype == 'not_in') {
  7958.                                 $orString .= " ( ";
  7959.                                 if (in_array('null'$cvalue)) {
  7960.                                     $orString .= " `$aliasInCondition`.$cfield is not null";
  7961.                                     $cvalue array_diff($cvalue, ['null']);
  7962.                                     if (!empty($cvalue))
  7963.                                         $orString .= " or ";
  7964.                                 }
  7965.                                 if (in_array(''$cvalue)) {
  7966.                                     $orString .= "`$aliasInCondition`.$cfield != '' ";
  7967.                                     $cvalue array_diff($cvalue, ['']);
  7968.                                     if (!empty($cvalue))
  7969.                                         $orString .= " or ";
  7970.                                 }
  7971.                                 $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7972.                             } else if ($ctype == 'in') {
  7973.                                 $orString .= " ( ";
  7974.                                 if (in_array('null'$cvalue)) {
  7975.                                     $orString .= " `$aliasInCondition`.$cfield is null";
  7976.                                     $cvalue array_diff($cvalue, ['null']);
  7977.                                     if (!empty($cvalue))
  7978.                                         $orString .= " or ";
  7979.                                 }
  7980.                                 if (in_array(''$cvalue)) {
  7981.                                     $orString .= "`$aliasInCondition`.$cfield = '' ";
  7982.                                     $cvalue array_diff($cvalue, ['']);
  7983.                                     if (!empty($cvalue))
  7984.                                         $orString .= " or ";
  7985.                                 }
  7986.                                 $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  7987.                             } else if ($ctype == '=') {
  7988.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7989.                                     $orString .= "`$aliasInCondition`.$cfield is null ";
  7990.                                 else
  7991.                                     $orString .= "`$aliasInCondition`.$cfield = $cvalue ";
  7992.                             } else if ($ctype == '!=') {
  7993.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  7994.                                     $orString .= "`$aliasInCondition`.$cfield is not null ";
  7995.                                 else
  7996.                                     $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  7997.                             } else {
  7998.                                 if (is_string($cvalue))
  7999.                                     $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8000.                                 else
  8001.                                     $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8002.                             }
  8003.                         }
  8004.                     }
  8005.                     if ($orString != '') {
  8006.                         if ($conditionStr != '')
  8007.                             $conditionStr .= (" or (" $orString ") ");
  8008.                         else
  8009.                             $conditionStr .= ("  (" $orString ") ");
  8010.                     }
  8011.                     $andOrString '';
  8012.                     foreach ($andOrConditions as $andOrCondition) {
  8013.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  8014.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  8015.                         $aliasInCondition $table;
  8016.                         if (!(strpos($cfield'.') === false)) {
  8017.                             $fullCfieldArray explode('.'$cfield);
  8018.                             $aliasInCondition $fullCfieldArray[0];
  8019.                             $cfield $fullCfieldArray[1];
  8020.                         }
  8021.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  8022.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8023.                             if ($andOrString != '')
  8024.                                 $andOrString .= " or ";
  8025.                             if ($ctype == 'like') {
  8026.                                 $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8027.                                 $wordsBySpaces explode(' '$cvalue);
  8028.                                 foreach ($wordsBySpaces as $word) {
  8029.                                     if ($andOrString != '')
  8030.                                         $andOrString .= " or ";
  8031.                                     $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8032.                                 }
  8033.                             } else if ($ctype == 'not like') {
  8034.                                 $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8035.                                 $wordsBySpaces explode(' '$cvalue);
  8036.                                 foreach ($wordsBySpaces as $word) {
  8037.                                     if ($andOrString != '')
  8038.                                         $andOrString .= " or ";
  8039.                                     $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8040.                                 }
  8041.                             } else if ($ctype == 'in') {
  8042.                                 $andOrString .= " ( ";
  8043.                                 if (in_array('null'$cvalue)) {
  8044.                                     $andOrString .= " `$aliasInCondition`.$cfield is null";
  8045.                                     $cvalue array_diff($cvalue, ['null']);
  8046.                                     if (!empty($cvalue))
  8047.                                         $andOrString .= " or ";
  8048.                                 }
  8049.                                 if (in_array(''$cvalue)) {
  8050.                                     $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  8051.                                     $cvalue array_diff($cvalue, ['']);
  8052.                                     if (!empty($cvalue))
  8053.                                         $andOrString .= " or ";
  8054.                                 }
  8055.                                 if (!empty($cvalue))
  8056.                                     $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8057.                                 else
  8058.                                     $andOrString .= "  ) ";
  8059.                             } else if ($ctype == 'not_in') {
  8060.                                 $andOrString .= " ( ";
  8061.                                 if (in_array('null'$cvalue)) {
  8062.                                     $andOrString .= " `$aliasInCondition`.$cfield is not null";
  8063.                                     $cvalue array_diff($cvalue, ['null']);
  8064.                                     if (!empty($cvalue))
  8065.                                         $andOrString .= " or ";
  8066.                                 }
  8067.                                 if (in_array(''$cvalue)) {
  8068.                                     $andOrString .= "`$aliasInCondition`.$cfield != '' ";
  8069.                                     $cvalue array_diff($cvalue, ['']);
  8070.                                     if (!empty($cvalue))
  8071.                                         $andOrString .= " or ";
  8072.                                 }
  8073.                                 if (!empty($cvalue))
  8074.                                     $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8075.                                 else
  8076.                                     $andOrString .= "  ) ";
  8077.                             } else if ($ctype == '=') {
  8078.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8079.                                     $andOrString .= "`$aliasInCondition`.$cfield is null ";
  8080.                                 else
  8081.                                     $andOrString .= "`$aliasInCondition`.$cfield = $cvalue ";
  8082.                             } else if ($ctype == '!=') {
  8083.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8084.                                     $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  8085.                                 else
  8086.                                     $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8087.                             } else {
  8088.                                 if (is_string($cvalue))
  8089.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8090.                                 else
  8091.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8092.                             }
  8093.                         }
  8094.                     }
  8095.                     if ($andOrString != '') {
  8096.                         if ($conditionStr != '')
  8097.                             $conditionStr .= (" and (" $andOrString ") ");
  8098.                         else
  8099.                             $conditionStr .= ("  (" $andOrString ") ");
  8100.                     }
  8101.                 }
  8102.                 $mustStr '';
  8103. ///now must conditions
  8104.                 foreach ($mustConditions as $mustCondition) {
  8105. //            $conditionStr.=' 1=1 ';
  8106.                     $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  8107.                     $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  8108.                     $aliasInCondition $table;
  8109.                     if (!(strpos($cfield'.') === false)) {
  8110.                         $fullCfieldArray explode('.'$cfield);
  8111.                         $aliasInCondition $fullCfieldArray[0];
  8112.                         $cfield $fullCfieldArray[1];
  8113.                     }
  8114.                     $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  8115.                     if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8116.                         if ($mustStr != '')
  8117.                             $mustStr .= " and ";
  8118.                         if ($ctype == 'like') {
  8119.                             $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8120.                             $wordsBySpaces explode(' '$cvalue);
  8121.                             foreach ($wordsBySpaces as $word) {
  8122.                                 if ($mustStr != '')
  8123.                                     $mustStr .= " or ";
  8124.                                 $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8125.                             }
  8126.                             $mustStr .= " )";
  8127.                         } else if ($ctype == 'not like') {
  8128.                             $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8129.                             $wordsBySpaces explode(' '$cvalue);
  8130.                             foreach ($wordsBySpaces as $word) {
  8131.                                 if ($mustStr != '')
  8132.                                     $mustStr .= " and ";
  8133.                                 $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8134.                             }
  8135.                         } else if ($ctype == 'in') {
  8136.                             $mustStr .= " ( ";
  8137.                             if (in_array('null'$cvalue)) {
  8138.                                 $mustStr .= " `$aliasInCondition`.$cfield is null";
  8139.                                 $cvalue array_diff($cvalue, ['null']);
  8140.                                 if (!empty($cvalue))
  8141.                                     $mustStr .= " or ";
  8142.                             }
  8143.                             if (in_array(''$cvalue)) {
  8144.                                 $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  8145.                                 $cvalue array_diff($cvalue, ['']);
  8146.                                 if (!empty($cvalue))
  8147.                                     $mustStr .= " or ";
  8148.                             }
  8149.                             $mustStr .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8150.                         } else if ($ctype == 'not_in') {
  8151.                             $mustStr .= " ( ";
  8152.                             if (in_array('null'$cvalue)) {
  8153.                                 $mustStr .= " `$aliasInCondition`.$cfield is not null";
  8154.                                 $cvalue array_diff($cvalue, ['null']);
  8155.                                 if (!empty($cvalue))
  8156.                                     $mustStr .= " and ";
  8157.                             }
  8158.                             if (in_array(''$cvalue)) {
  8159.                                 $mustStr .= "`$aliasInCondition`.$cfield != '' ";
  8160.                                 $cvalue array_diff($cvalue, ['']);
  8161.                                 if (!empty($cvalue))
  8162.                                     $mustStr .= " and ";
  8163.                             }
  8164.                             $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8165.                         } else if ($ctype == '=') {
  8166.                             if ($cvalue == 'null' || $cvalue == 'Null')
  8167.                                 $mustStr .= "`$aliasInCondition`.$cfield is null ";
  8168.                             else
  8169.                                 $mustStr .= "`$aliasInCondition`.$cfield = $cvalue ";
  8170.                         } else if ($ctype == '!=') {
  8171.                             if ($cvalue == 'null' || $cvalue == 'Null')
  8172.                                 $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  8173.                             else
  8174.                                 $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  8175.                         } else {
  8176.                             if (is_string($cvalue))
  8177.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8178.                             else
  8179.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8180.                         }
  8181.                     }
  8182.                 }
  8183.                 if ($mustStr != '') {
  8184.                     if ($conditionStr != '')
  8185.                         $conditionStr .= (" and (" $mustStr ") ");
  8186.                     else
  8187.                         $conditionStr .= ("  (" $mustStr ") ");
  8188.                 }
  8189.                 if ($conditionStr != '')
  8190.                     $filterQryForCriteria .= (" and (" $conditionStr ") ");
  8191.                 if ($lastChildrenOnly == 1) {
  8192.                     if ($filterQryForCriteria != '')
  8193.                         $filterQryForCriteria .= ' and';
  8194.                     $filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  8195.                 } else if ($parentOnly == 1) {
  8196.                     if ($filterQryForCriteria != '')
  8197.                         $filterQryForCriteria .= ' and';
  8198.                     $filterQryForCriteria .= "`$table`.`$valueField`  in ( select distinct $parentIdField from  $table)";
  8199.                 }
  8200.                 if (!empty($orderByConditions)) {
  8201.                     $filterQryForCriteria .= "  order by ";
  8202.                     $fone 1;
  8203.                     foreach ($orderByConditions as $orderByCondition) {
  8204.                         if ($fone != 1) {
  8205.                             $filterQryForCriteria .= " , ";
  8206.                         }
  8207.                         if (isset($orderByCondition['valueList'])) {
  8208.                             if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  8209.                             if ($orderByCondition['valueList'] == null)
  8210.                                 $orderByCondition['valueList'] = [];
  8211.                             $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  8212.                         } else
  8213.                             $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  8214.                         $fone 0;
  8215.                     }
  8216.                 }
  8217.                 if ($returnTotalMatchedEntriesFlag == 1) {
  8218. //            $stmt = $em->getConnection()->prepare($get_kids_sql);
  8219. //            $stmt->execute();
  8220. //            $get_kids = $stmt->fetchAll();
  8221.                 }
  8222.                 if ($filterQryForCriteria != '')
  8223.                     if (!empty($setValueArray) || $selectAll == 1) {
  8224.                     } else {
  8225.                         if ($itemLimit != '_ALL_')
  8226.                             $filterQryForCriteria .= "  limit $offset$itemLimit ";
  8227.                         else
  8228.                             $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  8229.                     }
  8230.                 $get_kids_sql $filterQryForCriteria;
  8231.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  8232.                 $stmt->execute();
  8233.                 $get_kids $stmt->fetchAll();
  8234.                 $selectedId 0;
  8235.                 if ($table == 'warehouse_action') {
  8236.                     if (empty($get_kids)) {
  8237.                         $get_kids_sql_2 "select * from warehouse_action";
  8238.                         $stmt $em->getConnection()->prepare($get_kids_sql_2);
  8239.                         $stmt->execute();
  8240.                         $get_kids2 $stmt->fetchAll();
  8241.                         if (empty($get_kids2))
  8242.                             $get_kids GeneralConstant::$warehouse_action_list;
  8243.                     }
  8244.                 }
  8245.                 if (!empty($get_kids)) {
  8246.                     $nextOffset $offset count($get_kids);
  8247.                     $nextOffset++;
  8248.                     foreach ($get_kids as $pa) {
  8249.                         if (!empty($setValueArray) && $selectAll == 0) {
  8250.                             if (!in_array($pa[$valueField], $setValueArray))
  8251.                                 continue;
  8252.                         }
  8253.                         if (!empty($restrictionIdList)) {
  8254.                             if (!in_array($pa[$valueField], $restrictionIdList))
  8255.                                 continue;
  8256.                         }
  8257.                         if ($selectAll == 1) {
  8258.                             $setValueArray[] = $pa[$valueField];
  8259.                             $setValue $pa[$valueField];
  8260.                         } else if (count($get_kids) == && $setDataForSingle == 1) {
  8261.                             $setValueArray[] = $pa[$valueField];
  8262.                             $setValue $pa[$valueField];
  8263.                         }
  8264.                         if ($valueField != '')
  8265.                             $pa['value'] = $pa[$valueField];
  8266.                         $renderedText $renderTextFormat;
  8267.                         $compare_array = [];
  8268.                         if ($renderTextFormat != '') {
  8269.                             $renderedText $renderTextFormat;
  8270.                             $compare_arrayFull = [];
  8271.                             $compare_array = [];
  8272.                             $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  8273.                             );
  8274.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  8275.                             if (isset($compare_arrayFull[0]))
  8276.                                 $compare_array $compare_arrayFull[0];
  8277. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  8278.                             foreach ($compare_array as $cmpdt) {
  8279.                                 $tbr str_replace("__"""$cmpdt);
  8280.                                 if ($tbr != '') {
  8281.                                     if (isset($pa[$tbr])) {
  8282.                                         if ($pa[$tbr] == null)
  8283.                                             $renderedText str_replace($cmpdt''$renderedText);
  8284.                                         else
  8285.                                             $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  8286.                                     } else {
  8287.                                         $renderedText str_replace($cmpdt''$renderedText);
  8288.                                     }
  8289.                                 }
  8290.                             }
  8291.                         }
  8292.                         $pa['rendered_text'] = $renderedText;
  8293.                         $pa['text'] = ($textField != '' $pa[$textField] : '');
  8294. //                $pa['compare_array'] = $compare_array;
  8295.                         foreach ($convertToObjectFieldList as $convField) {
  8296.                             if (isset($pa[$convField])) {
  8297.                                 $taA json_decode($pa[$convField], true);
  8298.                                 if ($taA == null$taA = [];
  8299.                                 $pa[$convField] = $taA;
  8300.                             } else {
  8301.                                 $pa[$convField] = [];
  8302.                             }
  8303.                         }
  8304.                         foreach ($convertDateToStringFieldList as $convField) {
  8305.                             if (is_array($convField)) {
  8306.                                 $fld $convField['field'];
  8307.                                 $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  8308.                             } else {
  8309.                                 $fld $convField;
  8310.                                 $frmt 'Y-m-d H:i:s';
  8311.                             }
  8312.                             if (isset($pa[$fld])) {
  8313.                                 $taA = new \DateTime($pa[$fld]);
  8314.                                 $pa[$fld] = $taA->format($frmt);
  8315.                             }
  8316.                         }
  8317.                         foreach ($convertToUrl as $convField) {
  8318. //
  8319. //                            $fld = $convField;
  8320. //
  8321. //
  8322. //                            if (isset($pa[$fld])) {
  8323. //
  8324. //
  8325. //                                $pa[$fld] =
  8326. //                                    $this->generateUrl(
  8327. //                                        'dashboard', [
  8328. //
  8329. //                                    ], UrlGenerator::ABSOLUTE_URL
  8330. //                                    ).'/'.$pa[$fld];
  8331. //
  8332. //                            }
  8333.                         }
  8334.                         foreach ($fullPathList as $pathField) {
  8335.                             $fld $pathField;
  8336.                             if (isset($pa[$fld])) {
  8337.                             if ($pa[$fld] !='' && $pa[$fld] !=null) {
  8338.                                 $pa[$fld]=($this->generateUrl(
  8339.                                     'dashboard', [
  8340.                                 ], UrlGenerator::ABSOLUTE_URL
  8341.                                 ).$pa[$fld]);
  8342.                             }
  8343.                             }
  8344.                         }
  8345.                         $pa['currentTs'] = (new \Datetime())->format('U');
  8346.                         $data[] = $pa;
  8347.                         if ($valueField != '') {
  8348.                             $data_by_id[$pa[$valueField]] = $pa;
  8349.                             $selectedId $pa[$valueField];
  8350.                         }
  8351.                     }
  8352.                 }
  8353.                 if ($dataOnly == 1)
  8354.                     $lastResult = array(
  8355.                         'success' => true,
  8356.                         'data' => $data,
  8357.                         'currentTs' => (new \Datetime())->format('U'),
  8358.                         'restrictionIdList' => $restrictionIdList,
  8359.                         'nextOffset' => $nextOffset,
  8360.                         'totalMatchedEntries' => $totalMatchedEntries,
  8361.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8362.                     );
  8363.                 else
  8364.                     $lastResult = array(
  8365.                     'success' => true,
  8366.                     'data' => $data,
  8367.                     'tableName' => $table,
  8368.                     'setValue' => $setValue,
  8369.                     'currentTs' => (new \Datetime())->format('U'),
  8370.                     'restrictionIdList' => $restrictionIdList,
  8371.                     'andConditions' => $andConditions,
  8372.                     'queryStr' => $queryStringIndividual,
  8373.                     'isMultiple' => $isMultiple,
  8374.                     'nextOffset' => $nextOffset,
  8375.                     'totalMatchedEntries' => $totalMatchedEntries,
  8376.                     'selectorId' => $selectorId,
  8377.                     'setValueArray' => $setValueArray,
  8378.                     'silentChangeSelectize' => $silentChangeSelectize,
  8379.                     'convertToObjectFieldList' => $convertToObjectFieldList,
  8380.                     'conditionStr' => $conditionStr,
  8381. //                    'andStr' => $andString,
  8382. //                    'andOrStr' => $andOrString,
  8383.                     'dataById' => $data_by_id,
  8384.                     'selectedId' => $selectedId,
  8385.                     'dataId' => $dataId,
  8386.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8387.                 );
  8388.             }
  8389.             $allResult[] = $lastResult;
  8390.         }
  8391.         if ($isSingleDataset == 1)
  8392.             return new JsonResponse($lastResult);
  8393.         else
  8394.             return new JsonResponse($allResult);
  8395.     }
  8396.     public function updatePlanningItemSequenceAction(Request $request$queryStr '')
  8397.     {
  8398.         $em $this->getDoctrine()->getManager();
  8399.         $stmt $em->getConnection()->prepare("select  `id` , parent_id, sequence from planning_item where sequence is null 
  8400.             ORDER BY parent_id ASC, id ASC
  8401.                         ");
  8402.         $stmt->execute();
  8403.         $query_output $stmt->fetchAll();
  8404.         foreach ($query_output as $dupe) {
  8405.             System::updatePlanningItemSequence($em$dupe["id"]);
  8406.         }
  8407.         System::updatePlanningItemSequence(
  8408.             $em,
  8409.             $request->request->get('planningItemId'0),
  8410.             $request->request->get('assignType''_ASSIGN_')   ///can be _MOVE_UP_ or _MOVE_DOWN_
  8411.         );
  8412. //        if($request->query->has('returnJson'))
  8413.         return new JsonResponse(
  8414.             array(
  8415.                 'success' => true,
  8416.                 'data' => [],
  8417.             )
  8418.         );
  8419.     }
  8420.     public function insertDataAjaxAction(Request $request$queryStr '')
  8421.     {
  8422.         $em $this->getDoctrine()->getManager();
  8423. //        if($request->query->has('big_data_test'))
  8424. //        {
  8425. //            for($t=0;$t<$request->request->get('big_data_test',10000);$t++) {
  8426. //                $em = $this->getDoctrine()->getManager('company_group');
  8427. //                $NOTIFICATION = new EntityNotification();
  8428. //                $NOTIFICATION->setAppId(1);
  8429. //                $NOTIFICATION->setCompanyId(0);
  8430. //                $NOTIFICATION->setCompanyId(0);
  8431. //                $NOTIFICATION->setBody('Test Description'.$t);
  8432. //                $NOTIFICATION->setTitle('Test Title'.$t);
  8433. //                $NOTIFICATION->setExpireTs(0);
  8434. //                $NOTIFICATION->setIsBuddybee(0);
  8435. //                $NOTIFICATION->setType(0);
  8436. //                $em->persist($NOTIFICATION);
  8437. //                $em->flush();
  8438. //            }
  8439. //
  8440. //            return new JsonResponse(
  8441. //                array(
  8442. //                    'success' => true,
  8443. //                    'data' => [],
  8444. //
  8445. //
  8446. //                )
  8447. //            );
  8448. //
  8449. //
  8450. //        }
  8451.         if ($request->request->get('entity_group'0)) {
  8452.             $companyId 0;
  8453.             $em $this->getDoctrine()->getManager('company_group');
  8454.         } else
  8455.             $companyId $this->getLoggedUserCompanyId($request);
  8456.         if ($companyId) {
  8457.             $company_data = [];
  8458. //            $company_data = Company::getCompanyData($em, $companyId);
  8459.         } else {
  8460.             $companyId 0;
  8461.             $company_data = [];
  8462.         }
  8463. //        $theEntity= new EntityNotification();
  8464. //        $entityName = 'EntityNotification';
  8465. //
  8466. //        $className='\\CompanyGroupBundle\\Entity\\'.$entityName;
  8467. //
  8468. //
  8469. //            $theEntity= new $className();
  8470.         $dataToAdd $request->request->has('dataToAdd') ? $request->request->get('dataToAdd') : [];
  8471.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8472.         if ($dataToAdd == null$dataToAdd = [];
  8473.         $dataToRemove $request->request->has('dataToRemove') ? $request->request->get('dataToRemove') : [];
  8474.         if (is_string($dataToRemove)) $dataToAdd json_decode($dataToRemovetrue);
  8475.         if ($dataToRemove == null$dataToRemove = [];
  8476.         $relData = [];
  8477.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8478.         $updatedDataList = [];
  8479.         foreach ($dataToAdd as $dataInd => $dat) {
  8480.             $entityName $dat['entityName'];
  8481.             $idField $dat['idField'];
  8482.             $findByField = isset($dat['findByField']) ? $dat['findByField'] : '';
  8483.             $findByValue = isset($dat['findByValue']) ? $dat['findByValue'] : '';
  8484.             $returnRefIndex $dat['returnRefIndex'];
  8485.             $findById $dat['findId'];
  8486.             $dataFields = isset($dat['dataFields']) ? $dat['dataFields'] : [];
  8487.             $noCreation = isset($dat['noCreation']) ? $dat['noCreation'] : 0;
  8488.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  8489.             $preAdditionalSql = isset($dat['preAdditionalSql']) ? $dat['preAdditionalSql'] : '';
  8490.             if ($preAdditionalSql != '') {
  8491. //            if ($entityName == 'PlanningItem') {
  8492. //
  8493. //                $stmt='select disctinct parent_id from planning_item;';
  8494. //                $stmt->execute();
  8495. //                $get_kids = $stmt->fetchAll();
  8496. //                $p_ids=[];
  8497. //                foreach($get_kids as $g)
  8498. //                {
  8499. //                    $p_ids[]=$g['parent_id'];
  8500. //                }
  8501. //
  8502. //
  8503. //
  8504.                 $stmt $em->getConnection()->prepare($preAdditionalSql);
  8505.                 $stmt->execute();
  8506.                 $stmt->closeCursor();
  8507. //
  8508. //
  8509.             }
  8510.             if ($entityName == 'PlanningItem') {
  8511.                 $stmt $em->getConnection()->prepare("select  `id` , parent_id, sequence from planning_item where sequence is null
  8512.             ORDER BY parent_id ASC, id ASC
  8513.                         ");
  8514.                 $stmt->execute();
  8515.                 $query_output $stmt->fetchAll();
  8516.                 foreach ($query_output as $dupe) {
  8517.                     System::updatePlanningItemSequence($em$dupe["id"]);
  8518.                 }
  8519.             }
  8520.             $className = ($request->request->get('entity_group'0) ? '\\CompanyGroupBundle\\Entity\\' '\\ApplicationBundle\\Entity\\') . $entityName;
  8521.             if (
  8522.                 ($findById == || $findById == '_NA_') && $findByField == '' && $noCreation == 0
  8523.             ) {
  8524.                 $theEntity = new $className();
  8525. //                $theEntity= new EntityNotification();
  8526.             } else {
  8527.                 if ($findByField != '') {
  8528.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findOneBy(
  8529.                         array
  8530.                         (
  8531.                             $findByField => $findByValue,
  8532.                         )
  8533.                     );
  8534.                 } else {
  8535.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findOneBy(
  8536.                         array
  8537.                         (
  8538.                             $idField => $findById,
  8539.                         )
  8540.                     );
  8541.                 }
  8542.             }
  8543.             if (!$theEntity && $noCreation == 0)
  8544.                 $theEntity = new $className();
  8545.             foreach ($dataFields as $dt) {
  8546.                 $setMethod 'set' ucfirst($dt['field']);
  8547.                 $getMethod 'get' ucfirst($dt['field']);
  8548.                 $type = isset($dt['type']) ? $dt['type'] : '_VALUE_';
  8549.                 $action = isset($dt['action']) ? $dt['action'] : '_REPLACE_';
  8550.                 if (method_exists($theEntity$setMethod)) {
  8551.                     $oldValue $theEntity->{$getMethod}();
  8552.                     $newValue $oldValue;
  8553.                     if ($type == '_VALUE_') {
  8554.                         $newValue $dt['value'];
  8555.                     }
  8556.                     if ($type == '_DECIMAL_') {
  8557.                         $newValue $dt['value'];
  8558.                     }
  8559.                     if ($type == '_DATE_') {
  8560.                         $newValue = new \DateTime($dt['value']);
  8561.                     }
  8562.                     if ($type == '_ARRAY_') {
  8563.                         $oldValue json_decode($oldValue);
  8564.                         if ($oldValue == null$oldValue = [];
  8565.                         if ($action == '_REPLACE_') {
  8566.                             $newValue json_encode($dt['value']);
  8567.                         }
  8568.                         if ($action == '_APPEND_') {
  8569.                             $newValue array_merge($oldValuearray_values(array_diff([$dt['value']], $oldValue)));
  8570.                         }
  8571.                         if ($action == '_MERGE_') {
  8572.                             $newValue array_merge($oldValuearray_values(array_diff($dt['value'], $oldValue)));
  8573.                         }
  8574.                         if ($action == '_EXCLUDE_') {
  8575.                             $newValue array_values(array_diff($oldValue, [$dt['value']]));
  8576.                         }
  8577.                         if ($action == '_EXCLUDE_ARRAY_') {
  8578.                             $newValue array_values(array_diff($oldValue$dt['value']));
  8579.                         }
  8580.                         $newValue json_encode($newValue);
  8581.                     }
  8582.                     $theEntity->{$setMethod}($newValue); // `foo!`
  8583. //                    $theEntity->setCompletionPercentage(78); // `foo!`
  8584.                 }
  8585.             }
  8586.             if ($additionalSql != '') {
  8587. //            if ($entityName == 'PlanningItem') {
  8588. //
  8589. //                $stmt='select disctinct parent_id from planning_item;';
  8590. //                $stmt->execute();
  8591. //                $get_kids = $stmt->fetchAll();
  8592. //                $p_ids=[];
  8593. //                foreach($get_kids as $g)
  8594. //                {
  8595. //                    $p_ids[]=$g['parent_id'];
  8596. //                }
  8597. //
  8598. //
  8599. //
  8600.                 $stmt $em->getConnection()->prepare($additionalSql);
  8601.                 $stmt->execute();
  8602.                 $stmt->closeCursor();
  8603. //
  8604. //
  8605.             }
  8606.             if (($findById == || $findById == '_NA_') && $noCreation == 0) {
  8607.                 $em->persist($theEntity);
  8608.                 $em->flush();
  8609.                 $getMethod 'get' ucfirst($idField);
  8610.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8611.             } else if ($theEntity) {
  8612.                 $em->flush();
  8613.                 $getMethod 'get' ucfirst($idField);
  8614.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8615.             }
  8616.             if ($entityName == 'PlanningItem') {
  8617.                 $stmt $em->getConnection()->prepare('select distinct parent_id from planning_item;');
  8618.                 $stmt->execute();
  8619.                 $get_kids $stmt->fetchAll();
  8620.                 $p_ids = [];
  8621.                 foreach ($get_kids as $g) {
  8622.                     $p_ids[] = $g['parent_id'];
  8623.                 }
  8624.                 $stmt $em->getConnection()->prepare('UPDATE planning_item d SET d.`has_child` =0 WHERE d.id NOT IN (' implode(','$p_ids) . '); 
  8625.                           UPDATE planning_item d SET d.`has_child` =1 WHERE d.id  IN (' implode(','$p_ids) . ')');
  8626.                 $stmt->execute();
  8627.                 $stmt->closeCursor();
  8628.                 $updatedData System::updatePlanningItemSequence($em$theEntity->getId());
  8629.                 $theEntity $updatedData['primaryOne'];
  8630.                 $theEntityUpdated $theEntity;
  8631.                 if ($theEntityUpdated->getEntryType() == 4)///cashflow
  8632.                 {
  8633.                     MiscActions::AddCashFlowProjection($em0, [
  8634.                         'planningItemId' => $theEntityUpdated->getId(),
  8635.                         'fundRequisitionId' => 0,
  8636.                         'concernedPersonId' => 0,
  8637.                         'type' => 1//exp
  8638.                         'subType' => 1//1== khoroch hobe 2: ashbe
  8639.                         'cashFlowType' => 1//2== RCV /in  1: Payment/out
  8640.                         'creationType' => 1//auto
  8641.                         'amountType' => 1//fund
  8642.                         'cashFlowAmount' => 0,
  8643.                         'expAstAmount' => 0,
  8644.                         'accumulatedCashFlowAmount' => 0,
  8645.                         'accumulatedCashFlowBalance' => 0,
  8646.                         'accumulatedExpAstAmount' => 0,
  8647.                         'relevantExpAstHeadId' => 0,
  8648.                         'balancingHeadId' => 0,
  8649.                         'cashFlowHeadId' => 0,
  8650.                         'cashFlowHeadType' => 1,
  8651.                         'relevantProductIds' => [],
  8652.                         'reminderDateTs' => 0,
  8653.                         'cashFlowDateTs' => 0,
  8654.                         'expAstRealizationDateTs' => 0,
  8655.                     ]);
  8656.                 }
  8657.             } else if ($entityName == 'TaskLog') {
  8658.                 $session $request->getSession();
  8659.                 if ($theEntity) {
  8660.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  8661.                     $currTime = new \DateTime();
  8662.                     $options = array(
  8663.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8664.                         'notification_server' => $this->container->getParameter('notification_server'),
  8665.                     );
  8666.                     $positionsArray = [
  8667.                         array(
  8668.                             'employeeId' => $empId,
  8669.                             'userId' => $session->get(UserConstants::USER_ID0),
  8670.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  8671.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  8672.                             'lat' => 23.8623834,
  8673.                             'lng' => 90.3979294,
  8674.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING,
  8675. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  8676.                         )
  8677.                     ];
  8678.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  8679.                     if ($positionsArray == null$positionsArray = [];
  8680.                     $dataByAttId = [];
  8681.                     $workPlaceType '_UNSET_';
  8682.                     foreach ($positionsArray as $findex => $d) {
  8683.                         $sysUserId 0;
  8684.                         $userId 0;
  8685.                         $empId 0;
  8686.                         $dtTs 0;
  8687.                         $timeZoneStr '+0000';
  8688.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  8689.                         if (isset($d['userId'])) $userId $d['userId'];
  8690.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  8691.                         if (isset($d['tsMilSec'])) {
  8692.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  8693.                         }
  8694.                         if ($dtTs == 0) {
  8695.                             $currTsTime = new \DateTime();
  8696.                             $dtTs $currTsTime->format('U');
  8697.                         } else {
  8698.                             $currTsTime = new \DateTime('@' $dtTs);
  8699.                         }
  8700.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  8701.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  8702.                         $EmployeeAttendance $this->getDoctrine()
  8703.                             ->getRepository(EmployeeAttendance::class)
  8704.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  8705.                         if (!$EmployeeAttendance) {
  8706.                             $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8707.                             $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8708.                             $EmployeeAttendance = new EmployeeAttendance;
  8709.                         } else {
  8710.                             if ($EmployeeAttendance->getCurrentLocation() == 'out') {
  8711.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8712.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8713.                             } else {
  8714.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8715.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8716.                             }
  8717.                         }
  8718.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  8719.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  8720.                             $workPlaceType '_STATIC_';
  8721.                         }
  8722.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  8723.                             $dataByAttId[$attendanceInfo->getId()] = array(
  8724.                                 'attendanceInfo' => $attendanceInfo,
  8725.                                 'empId' => $empId,
  8726.                                 'lat' => 0,
  8727.                                 'lng' => 0,
  8728.                                 'address' => 0,
  8729.                                 'sysUserId' => $sysUserId,
  8730.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8731.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8732.                                 'positionArray' => []
  8733.                             );
  8734.                         $posData = array(
  8735.                             'ts' => $dtTs,
  8736.                             'lat' => $d['lat'],
  8737.                             'lng' => $d['lng'],
  8738.                             'marker' => $d['markerId'],
  8739.                             'src' => 2,
  8740.                         );
  8741.                         $posDataArray = array(
  8742.                             $dtTs,
  8743.                             $d['lat'],
  8744.                             $d['lng'],
  8745.                             $d['markerId'],
  8746.                             2
  8747.                         );
  8748.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  8749.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  8750.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  8751.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  8752.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  8753.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  8754.                         if (isset($d['address']))
  8755.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  8756. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  8757.                     }
  8758.                     $response = array(
  8759.                         'success' => true,
  8760.                     );
  8761.                     foreach ($dataByAttId as $attInfoId => $d) {
  8762.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  8763.                             $d['empId'],
  8764.                             $d['sysUserId'],
  8765.                             $d['companyId'],
  8766.                             $d['appId'],
  8767.                             $request,
  8768.                             $d['attendanceInfo'],
  8769.                             $options,
  8770.                             $d['positionArray'],
  8771.                             $d['lat'],
  8772.                             $d['lng'],
  8773.                             $d['address'],
  8774.                             $d['markerId']
  8775.                         );
  8776.                     }
  8777.                     $session->set(UserConstants::USER_CURRENT_TASK_ID$theEntity->getId());
  8778.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$theEntity->getPlanningItemId());
  8779.                 } else {
  8780.                     $session->set(UserConstants::USER_CURRENT_TASK_ID0);
  8781.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID0);
  8782.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  8783.                     $currTime = new \DateTime();
  8784.                     $options = array(
  8785.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8786.                         'notification_server' => $this->container->getParameter('notification_server'),
  8787.                     );
  8788.                     $positionsArray = [
  8789.                         array(
  8790.                             'employeeId' => $empId,
  8791.                             'userId' => $session->get(UserConstants::USER_ID0),
  8792.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  8793.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  8794.                             'lat' => 23.8623834,
  8795.                             'lng' => 90.3979294,
  8796.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT,
  8797. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  8798.                         )
  8799.                     ];
  8800.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  8801.                     if ($positionsArray == null$positionsArray = [];
  8802.                     $dataByAttId = [];
  8803.                     $workPlaceType '_UNSET_';
  8804.                     foreach ($positionsArray as $findex => $d) {
  8805.                         $sysUserId 0;
  8806.                         $userId 0;
  8807.                         $empId 0;
  8808.                         $dtTs 0;
  8809.                         $timeZoneStr '+0000';
  8810.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  8811.                         if (isset($d['userId'])) $userId $d['userId'];
  8812.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  8813.                         if (isset($d['tsMilSec'])) {
  8814.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  8815.                         }
  8816.                         if ($dtTs == 0) {
  8817.                             $currTsTime = new \DateTime();
  8818.                             $dtTs $currTsTime->format('U');
  8819.                         } else {
  8820.                             $currTsTime = new \DateTime('@' $dtTs);
  8821.                         }
  8822.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  8823.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  8824.                         $EmployeeAttendance $this->getDoctrine()
  8825.                             ->getRepository(EmployeeAttendance::class)
  8826.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  8827.                         if (!$EmployeeAttendance) {
  8828.                             continue;
  8829.                         } else {
  8830.                         }
  8831.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  8832.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT) {
  8833.                             $workPlaceType '_STATIC_';
  8834.                         }
  8835.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  8836.                             $dataByAttId[$attendanceInfo->getId()] = array(
  8837.                                 'attendanceInfo' => $attendanceInfo,
  8838.                                 'empId' => $empId,
  8839.                                 'lat' => 0,
  8840.                                 'lng' => 0,
  8841.                                 'address' => 0,
  8842.                                 'sysUserId' => $sysUserId,
  8843.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8844.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8845.                                 'positionArray' => []
  8846.                             );
  8847.                         $posData = array(
  8848.                             'ts' => $dtTs,
  8849.                             'lat' => $d['lat'],
  8850.                             'lng' => $d['lng'],
  8851.                             'marker' => $d['markerId'],
  8852.                             'src' => 2,
  8853.                         );
  8854.                         $posDataArray = array(
  8855.                             $dtTs,
  8856.                             $d['lat'],
  8857.                             $d['lng'],
  8858.                             $d['markerId'],
  8859.                             2
  8860.                         );
  8861.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  8862.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  8863.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  8864.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  8865.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  8866.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  8867.                         if (isset($d['address']))
  8868.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  8869. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  8870.                     }
  8871.                     $response = array(
  8872.                         'success' => true,
  8873.                     );
  8874.                     foreach ($dataByAttId as $attInfoId => $d) {
  8875.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  8876.                             $d['empId'],
  8877.                             $d['sysUserId'],
  8878.                             $d['companyId'],
  8879.                             $d['appId'],
  8880.                             $request,
  8881.                             $d['attendanceInfo'],
  8882.                             $options,
  8883.                             $d['positionArray'],
  8884.                             $d['lat'],
  8885.                             $d['lng'],
  8886.                             $d['address'],
  8887.                             $d['markerId']
  8888.                         );
  8889.                     }
  8890.                 }
  8891.                 $theEntityUpdated $theEntity;
  8892.             } else
  8893.                 $theEntityUpdated $theEntity;
  8894. //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  8895.             $getters = [];
  8896.             if ($theEntityUpdated)
  8897.                 $getters array_filter(get_class_methods($theEntityUpdated), function ($method) {
  8898.                     return 'get' === substr($method03);
  8899.                 });
  8900.             $updatedData = [];
  8901.             foreach ($getters as $getter) {
  8902.                 $indForThis str_replace('get'''$getter);
  8903.                 $indForThis lcfirst($indForThis);
  8904.                 $updatedData[$indForThis] = $theEntityUpdated->{$getter}();
  8905.             }
  8906.             $updatedDataList[$dataInd] = $updatedData;
  8907.         }
  8908.         foreach ($dataToRemove as $dataInd => $dat) {
  8909.             $entityName $dat['entityName'];
  8910.             $idField $dat['idField'];
  8911.             $findById $dat['findId'];
  8912.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  8913.             $theEntityList $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findBy(
  8914.                 array
  8915.                 (
  8916.                     $idField => $findById,
  8917.                 )
  8918.             );
  8919.             foreach ($theEntityList as $dt) {
  8920.                 $em->remove($dt);
  8921.                 $em->flush();
  8922.             }
  8923.             if ($additionalSql != '') {
  8924. //            if ($entityName == 'PlanningItem') {
  8925. //
  8926. //                $stmt='select disctinct parent_id from planning_item;';
  8927. //                $stmt->execute();
  8928. //                $get_kids = $stmt->fetchAll();
  8929. //                $p_ids=[];
  8930. //                foreach($get_kids as $g)
  8931. //                {
  8932. //                    $p_ids[]=$g['parent_id'];
  8933. //                }
  8934. //
  8935. //
  8936. //
  8937.                 $stmt $em->getConnection()->prepare($additionalSql);
  8938.                 $stmt->execute();
  8939.                 $stmt->closeCursor();
  8940. //
  8941. //
  8942.             }
  8943.             $updatedDataList[$dataInd] = [];
  8944.         }
  8945. //        if ($table == '') {
  8946. //            return new JsonResponse(
  8947. //                array(
  8948. //                    'success' => false,
  8949. ////                    'page_title' => 'Product Details',
  8950. ////                    'company_data' => $company_data,
  8951. //                    'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8952. //
  8953. //                )
  8954. //            );
  8955. //        }
  8956. //        if($request->query->has('returnJson'))
  8957.         return new JsonResponse(
  8958.             array(
  8959.                 'success' => true,
  8960.                 'data' => $relData,
  8961.                 'updatedDataList' => $updatedDataList,
  8962.             )
  8963.         );
  8964.     }
  8965.     public function GetAvailableQtyAction(Request $request$id 0)
  8966.     {
  8967.         $em $this->getDoctrine()->getManager();
  8968.         $productId $request->request->has('productId') ? $request->request->get('productId') : 0;
  8969.         $colorId $request->request->has('colorId') ? $request->request->get('colorId') : 0;
  8970.         $dataId $request->request->has('dataId') ? $request->request->get('dataId') : 0;
  8971.         $allowedWarehouseIds $request->request->has('warehouseId') ? [$request->request->get('warehouseId')] : [];
  8972.         $allowedWarehouseActionIds $request->request->has('warehouseActionId') ? [$request->request->get('warehouseActionId')] : [];
  8973.         $qty Inventory::getProductQty($em$productId$allowedWarehouseIds$allowedWarehouseActionIds$colorId);
  8974.         return new JsonResponse(array("success" => true,
  8975.             "qty" => $qty,
  8976.             "dataId" => $dataId,
  8977.         ));
  8978.     }
  8979.     public
  8980.     function labelFormatSelectAjaxAction(Request $request$queryStr '')
  8981.     {
  8982.         $em $this->getDoctrine()->getManager();
  8983.         $companyId $this->getLoggedUserCompanyId($request);
  8984.         $company_data Company::getCompanyData($em$companyId);
  8985.         $data = [];
  8986.         $data_by_id = [];
  8987.         $html '';
  8988.         $productByCodeData = [];
  8989.         if ($queryStr == '_EMPTY_')
  8990.             $queryStr '';
  8991.         if ($request->request->has('query') && $queryStr == '')
  8992.             $queryStr $request->request->get('queryStr');
  8993.         if ($queryStr == '_EMPTY_')
  8994.             $queryStr '';
  8995.         $filterQryForCriteria "select * from label_format where company_id=" $companyId " ";
  8996.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  8997.             $filterQryForCriteria .= " and label_type=" $request->request->get('dataType');
  8998.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  8999.             $filterQryForCriteria .= " and format_id=" $request->request->get('formatId');
  9000.         else if ($queryStr != '')
  9001.             $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' or `format_code` like '%" $queryStr "%') ";
  9002.         if ($filterQryForCriteria != '')
  9003.             $filterQryForCriteria .= "  limit 25";
  9004.         $get_kids_sql $filterQryForCriteria;
  9005. //        if ($request->request->has('productIds'))
  9006. //
  9007. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9008. //        else if ($request->request->has('productCode'))
  9009. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9010. //        else if ($filterQryForCriteria!='')
  9011. //            $get_kids_sql = $filterQryForCriteria;
  9012. //
  9013. //        else
  9014. //               $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";
  9015.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9016.         $stmt->execute();
  9017.         $get_kids $stmt->fetchAll();
  9018.         $productId 0;
  9019.         if (!empty($get_kids)) {
  9020.             foreach ($get_kids as $product) {
  9021.                 $pa = array();
  9022.                 $pa['id'] = $product['format_id'];
  9023.                 $pa['name'] = $product['name'];
  9024.                 $pa['format_code'] = $product['format_code'] . '. ' $product['name'];
  9025.                 $pa['id_code_name'] = $product['format_id'] . '. ' $product['format_code'] . ' - ' $product['name'] . ' ';
  9026.                 $pa['text'] = $product['name'];
  9027.                 $pa['value'] = $product['format_id'];
  9028.                 $data[] = $pa;
  9029.                 $data_by_id[$product['format_id']] = $pa;
  9030.                 $productId $product['format_id'];
  9031.             }
  9032.         }
  9033. //        if($request->query->has('returnJson'))
  9034.         {
  9035.             return new JsonResponse(
  9036.                 array(
  9037.                     'success' => true,
  9038. //                    'page_title' => 'Product Details',
  9039. //                    'company_data' => $company_data,
  9040.                     'data' => $data,
  9041.                     'dataById' => $data_by_id,
  9042.                     'productId' => $productId,
  9043.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9044. //                    'exId'=>$id,
  9045. //                'productByCodeData' => $productByCodeData,
  9046. //                'productData' => $productData,
  9047. //                'currInvList' => $currInvList,
  9048. //                'productList' => Inventory::ProductList($em, $companyId),
  9049. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9050. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9051. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9052. //                'unitList' => Inventory::UnitTypeList($em),
  9053. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9054. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9055. //                'warehouseList' => Inventory::WarehouseList($em),
  9056.                 )
  9057.             );
  9058.         }
  9059.     }
  9060.     public
  9061.     function CategoryListSelectAjaxAction(Request $request$queryStr '')
  9062.     {
  9063.         $em $this->getDoctrine()->getManager();
  9064.         $companyId $this->getLoggedUserCompanyId($request);
  9065.         $company_data Company::getCompanyData($em$companyId);
  9066.         $data = [];
  9067.         $data_by_id = [];
  9068.         $html '';
  9069.         $productByCodeData = [];
  9070.         if ($queryStr == '_EMPTY_')
  9071.             $queryStr '';
  9072.         if ($request->request->has('query') && $queryStr == '')
  9073.             $queryStr $request->request->get('queryStr');
  9074.         if ($queryStr == '_EMPTY_')
  9075.             $queryStr '';
  9076.         $filterQryForCriteria "select * from inv_product_categories where company_id=" $companyId " ";
  9077.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  9078.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  9079.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  9080.         if ($filterQryForCriteria != '')
  9081.             $filterQryForCriteria .= "  limit 25";
  9082.         $get_kids_sql $filterQryForCriteria;
  9083. //        if ($request->request->has('productIds'))
  9084. //
  9085. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9086. //        else if ($request->request->has('productCode'))
  9087. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9088. //        else if ($filterQryForCriteria!='')
  9089. //            $get_kids_sql = $filterQryForCriteria;
  9090. //
  9091. //        else
  9092. //               $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";
  9093.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9094.         $stmt->execute();
  9095.         $get_kids $stmt->fetchAll();
  9096.         $productId 0;
  9097.         if (!empty($get_kids)) {
  9098.             foreach ($get_kids as $product) {
  9099.                 $pa = array();
  9100.                 $pa['id'] = $product['id'];
  9101.                 $pa['name'] = $product['name'];
  9102.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  9103.                 $pa['globalId'] = $product['global_id'];
  9104.                 $pa['text'] = $product['name'];
  9105.                 $pa['value'] = $product['id'];
  9106.                 $pa['igId'] = $product['ig_id'];
  9107. //                $pa['categoryId'] = $product['category_id'];
  9108. //                $pa['subCategoryId'] = $product['sub_category_id'];
  9109.                 $data[] = $pa;
  9110.                 $data_by_id[$product['id']] = $pa;
  9111.                 $productId $product['id'];
  9112.             }
  9113.         }
  9114. //        if($request->query->has('returnJson'))
  9115.         {
  9116.             return new JsonResponse(
  9117.                 array(
  9118.                     'success' => true,
  9119. //                    'page_title' => 'Product Details',
  9120. //                    'company_data' => $company_data,
  9121.                     'data' => $data,
  9122.                     'dataById' => $data_by_id,
  9123.                     'productId' => $productId,
  9124.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9125. //                    'exId'=>$id,
  9126. //                'productByCodeData' => $productByCodeData,
  9127. //                'productData' => $productData,
  9128. //                'currInvList' => $currInvList,
  9129. //                'productList' => Inventory::ProductList($em, $companyId),
  9130. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9131. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9132. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9133. //                'unitList' => Inventory::UnitTypeList($em),
  9134. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9135. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9136. //                'warehouseList' => Inventory::WarehouseList($em),
  9137.                 )
  9138.             );
  9139.         }
  9140.     }
  9141.     public
  9142.     function SubCategoryListSelectAjaxAction(Request $request$queryStr '')
  9143.     {
  9144.         $em $this->getDoctrine()->getManager();
  9145.         $companyId $this->getLoggedUserCompanyId($request);
  9146.         $company_data Company::getCompanyData($em$companyId);
  9147.         $data = [];
  9148.         $data_by_id = [];
  9149.         $html '';
  9150.         $productByCodeData = [];
  9151.         if ($queryStr == '_EMPTY_')
  9152.             $queryStr '';
  9153.         if ($request->request->has('query') && $queryStr == '')
  9154.             $queryStr $request->request->get('queryStr');
  9155.         if ($queryStr == '_EMPTY_')
  9156.             $queryStr '';
  9157.         $filterQryForCriteria "select * from inv_product_sub_categories where company_id=" $companyId " ";
  9158.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9159.             $filterQryForCriteria .= " and sub_category_id=" $request->request->get('subCategoryId');
  9160.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  9161.             $filterQryForCriteria .= " and category_id=" $request->request->get('categoryId');
  9162.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  9163.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  9164.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  9165.             if ($request->request->get('parentId') != 0)
  9166.                 $filterQryForCriteria .= " and  parent_id=" $request->request->get('parentId');
  9167.             else
  9168.                 $filterQryForCriteria .= " and ( parent_id =0 or parent_id is null ) ";
  9169.         if ($request->request->has('level') && $request->request->get('level') != '')
  9170.             if ($request->request->get('level') != 0)
  9171.                 $filterQryForCriteria .= " and level=" $request->request->get('level');
  9172.             else
  9173.                 $filterQryForCriteria .= " and ( level =0 or level is null) ";
  9174.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  9175.         if ($filterQryForCriteria != '')
  9176.             $filterQryForCriteria .= "  limit 25";
  9177.         $get_kids_sql $filterQryForCriteria;
  9178. //        if ($request->request->has('productIds'))
  9179. //
  9180. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9181. //        else if ($request->request->has('productCode'))
  9182. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9183. //        else if ($filterQryForCriteria!='')
  9184. //            $get_kids_sql = $filterQryForCriteria;
  9185. //
  9186. //        else
  9187. //               $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";
  9188.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9189.         $stmt->execute();
  9190.         $get_kids $stmt->fetchAll();
  9191.         $productId 0;
  9192.         if (!empty($get_kids)) {
  9193.             foreach ($get_kids as $product) {
  9194.                 $pa = array();
  9195.                 $pa['id'] = $product['id'];
  9196.                 $pa['name'] = $product['name'];
  9197.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  9198.                 $pa['globalId'] = $product['global_id'];
  9199.                 $pa['parentId'] = $product['parent_id'];
  9200.                 $pa['text'] = $product['name'];
  9201.                 $pa['value'] = $product['id'];
  9202.                 $pa['igId'] = $product['ig_id'];
  9203.                 $pa['categoryId'] = $product['category_id'];
  9204. //                $pa['subCategoryId'] = $product['sub_category_id'];
  9205.                 $data[] = $pa;
  9206.                 $data_by_id[$product['id']] = $pa;
  9207.                 $productId $product['id'];
  9208.             }
  9209.         }
  9210. //        if($request->query->has('returnJson'))
  9211.         {
  9212.             return new JsonResponse(
  9213.                 array(
  9214.                     'success' => true,
  9215. //                    'page_title' => 'Product Details',
  9216. //                    'company_data' => $company_data,
  9217.                     'data' => $data,
  9218.                     'dataById' => $data_by_id,
  9219.                     'productId' => $productId,
  9220.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9221. //                    'exId'=>$id,
  9222. //                'productByCodeData' => $productByCodeData,
  9223. //                'productData' => $productData,
  9224. //                'currInvList' => $currInvList,
  9225. //                'productList' => Inventory::ProductList($em, $companyId),
  9226. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9227. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9228. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9229. //                'unitList' => Inventory::UnitTypeList($em),
  9230. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9231. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9232. //                'warehouseList' => Inventory::WarehouseList($em),
  9233.                 )
  9234.             );
  9235.         }
  9236.     }
  9237.     public
  9238.     function ProductByCodeViewAction(Request $request$id 0)
  9239.     {
  9240.         $em $this->getDoctrine()->getManager();
  9241.         $companyId $this->getLoggedUserCompanyId($request);
  9242.         $company_data Company::getCompanyData($em$companyId);
  9243.         $data = [];
  9244.         $html '';
  9245.         $productByCodeData = [];
  9246.         if ($id != 0) {
  9247.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9248.                 ->findOneBy(
  9249.                     array(
  9250.                         'productByCodeId' => $id
  9251.                     )
  9252.                 );
  9253.         } else {
  9254.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9255.                 ->findOneBy(
  9256.                     array(
  9257. //                        'productByCodeId' => $id,
  9258.                         'CompanyId' => $companyId
  9259.                     ), array(
  9260.                         'productByCodeId' => 'DESC'
  9261.                     )
  9262.                 );
  9263.             if ($productByCodeData)
  9264.                 $id $productByCodeData->getProductByCodeId();
  9265.         }
  9266.         if ($id != 0) {
  9267.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9268.                 ->findOneBy(
  9269.                     array(
  9270.                         'id' => $productByCodeData->getProductId()
  9271.                     )
  9272.                 );
  9273.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9274.                 ->findBy(
  9275.                     array(
  9276.                         'productId' => $id
  9277.                     )
  9278.                 );
  9279.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  9280.                 array(
  9281.                     'page_title' => 'Product Details',
  9282.                     'company_data' => $company_data,
  9283.                     'productByCodeData' => $productByCodeData,
  9284.                     'productData' => $productData,
  9285.                     'currInvList' => $currInvList,
  9286.                     'exId' => $id,
  9287.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9288.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9289.                     'productList' => Inventory::ProductList($em$companyId),
  9290.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9291.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9292.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9293.                     'unitList' => Inventory::UnitTypeList($em),
  9294.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9295.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9296.                     'warehouseList' => Inventory::WarehouseList($em),
  9297.                 )
  9298.             );
  9299.         } else {
  9300.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  9301.                 array(
  9302.                     'exId' => $id,
  9303.                 )
  9304.             );
  9305.         }
  9306.         if ($request->query->has('returnJson')) {
  9307.             return new JsonResponse(
  9308.                 array(
  9309.                     'success' => true,
  9310.                     'page_title' => 'Product Details',
  9311.                     'company_data' => $company_data,
  9312.                     'renderedHtml' => $html,
  9313.                     'exId' => $id,
  9314. //                'productByCodeData' => $productByCodeData,
  9315. //                'productData' => $productData,
  9316. //                'currInvList' => $currInvList,
  9317. //                'productList' => Inventory::ProductList($em, $companyId),
  9318. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9319. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9320. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9321. //                'unitList' => Inventory::UnitTypeList($em),
  9322. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9323. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9324. //                'warehouseList' => Inventory::WarehouseList($em),
  9325.                 )
  9326.             );
  9327.         } else {
  9328. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9329. //                ->findBy(
  9330. //                    array(
  9331. ////                        'productByCodeId' => $id,
  9332. //                    'CompanyId'=>$companyId
  9333. //                    )
  9334. //                );
  9335.             $productByCodeList = []; //called by ajax
  9336.             return $this->render('@Inventory/pages/views/product_by_code_view.html.twig',
  9337.                 array(
  9338.                     'page_title' => 'Product Details',
  9339.                     'company_data' => $company_data,
  9340.                     'renderedHtml' => $html,
  9341.                     'exId' => $id,
  9342.                     'productByCodeList' => $productByCodeList,
  9343. //                'productByCodeData' => $productByCodeData,
  9344. //                'productData' => $productData,
  9345. //                'currInvList' => $currInvList,
  9346. //                'productList' => Inventory::ProductList($em, $companyId),
  9347. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9348. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9349. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9350. //                'unitList' => Inventory::UnitTypeList($em),
  9351. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9352. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9353. //                'warehouseList' => Inventory::WarehouseList($em),
  9354.                 )
  9355.             );
  9356.         }
  9357.     }
  9358.     public
  9359.     function ConsumptionSettingsAction(Request $request$id)
  9360.     {
  9361.         $cc_id '';
  9362.         $cc_name '';
  9363.         $em $this->getDoctrine()->getManager();
  9364.         $companyId $this->getLoggedUserCompanyId($request);
  9365.         $consumptionTypeId 0;
  9366.         if ($request->isMethod('POST')) {
  9367.             $new_cc = [];
  9368.             if ($request->request->get('consumptionTypeId') != '' && $request->request->get('consumptionTypeId') != 0) {
  9369.                 $em $this->getDoctrine()->getManager();
  9370.                 $new_cc $this->getDoctrine()
  9371.                     ->getRepository('ApplicationBundle:ConsumptionType')
  9372.                     ->findOneBy(
  9373.                         array(
  9374.                             'consumptionTypeId' => $request->request->get('consumptionTypeId'),
  9375.                         )
  9376.                     );
  9377.                 $new_cc->setName($request->request->get('name'));
  9378.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9379.                 $new_cc->setCompanyId($companyId);
  9380.                 $em->flush();
  9381.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9382.                 $this->addFlash(
  9383.                     'success',
  9384.                     'Consumption Information Updated'
  9385.                 );
  9386.             } else {
  9387.                 $new_cc = new ConsumptionType();
  9388.                 $new_cc->setName($request->request->get('name'));
  9389.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9390.                 $new_cc->setCompanyId($companyId);
  9391.                 $em->persist($new_cc);
  9392.                 $em->flush();
  9393.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9394.                 $em->flush();
  9395.                 $this->addFlash(
  9396.                     'success',
  9397.                     'New Consumption Type Added'
  9398.                 );
  9399.             }
  9400.         }
  9401.         $extData = [];
  9402.         if ($id != 0) {
  9403.             $extData $this->getDoctrine()
  9404.                 ->getRepository('ApplicationBundle:ConsumptionType')
  9405.                 ->findOneBy(
  9406.                     array(
  9407.                         'consumptionTypeId' => $id
  9408.                     )
  9409.                 );
  9410. //            $cc_data_list = [];
  9411. //            foreach ($cc_data as $value) {
  9412. //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  9413. //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  9414. //
  9415. //                if ($value->getSupplierCategoryId() == $id) {
  9416. //                    $cc_id = $value->getSupplierCategoryId();
  9417. //                    $cc_name = $value->getName();
  9418. //                }
  9419. //            }
  9420.         }
  9421.         return $this->render('@Inventory/pages/input_forms/consumption_settings.html.twig',
  9422.             array(
  9423.                 'page_title' => 'Consumption Settings',
  9424.                 'consumptionTypeList' => $this->getDoctrine()
  9425.                     ->getRepository('ApplicationBundle:ConsumptionType')
  9426.                     ->findBy(
  9427.                         array(
  9428.                             'CompanyId' => $companyId
  9429.                         )
  9430.                     ),
  9431.                 'extData' => $extData,
  9432.                 'headList' => Accounts::getParentLedgerHeads($em),
  9433. //                'countryList'=>SalesOrderM::Co
  9434.             )
  9435.         );
  9436.     }
  9437.     public
  9438.     function ProductByCodeCheckAssignPrintAction(Request $request$id 0)
  9439.     {
  9440.         $em $this->getDoctrine()->getManager();
  9441.         $companyId $this->getLoggedUserCompanyId($request);
  9442.         $company_data Company::getCompanyData($em$companyId);
  9443.         $data = [];
  9444.         $html '';
  9445.         $productByCodeData = [];
  9446.         $productDataWeightPackageGm '';
  9447.         $productDataWeightVarianceValue 0;
  9448.         $productDataWeightVarianceType 0;
  9449.         $productByCodeDataObj = [];
  9450.         $dr_id 0;//for dr_id
  9451.         $skipRenderData 0;
  9452.         if ($request->query->has('skipRenderData'))
  9453.             $skipRenderData $request->query->get('skipRenderData');
  9454.         if ($id != 0) {
  9455.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9456.                 ->findOneBy(
  9457.                     array(
  9458.                         'productByCodeId' => $id
  9459.                     )
  9460.                 );
  9461.         } else {
  9462.             if ($request->query->has('scanCode')) {
  9463.                 $query $em->getRepository('ApplicationBundle:ProductByCode')
  9464.                     ->createQueryBuilder('p');
  9465.                 if ($request->query->has('assigned')) {
  9466.                     $query->where('p.assigned > :av')
  9467.                         ->setParameter('av'$request->query->get('assigned'));
  9468.                 } else
  9469.                     $query->where("1=0");
  9470.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  9471.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  9472.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  9473.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  9474.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  9475.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  9476.                 $query->setMaxResults(1);
  9477.                 $results $query->getQuery()->getResult();
  9478.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  9479.             } else
  9480.                 $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9481.                     ->findOneBy(
  9482.                         array(
  9483. //                        'productByCodeId' => $id,
  9484.                             'CompanyId' => $companyId
  9485.                         ), array(
  9486.                             'productByCodeId' => 'DESC'
  9487.                         )
  9488.                     );
  9489.             if ($productByCodeData)
  9490.                 $id $productByCodeData->getProductByCodeId();
  9491.         }
  9492.         if ($id != 0) {
  9493.             $productByCodeDataObj = array(
  9494.                 'salesCode' => $productByCodeData->getSalesCode(),
  9495.                 'sales_code' => $productByCodeData->getSalesCode(),
  9496.                 'sn' => $productByCodeData->getSerialNo(),
  9497.                 'serialNo' => $productByCodeData->getSerialNo(),
  9498.                 'imei1' => $productByCodeData->getImei1(),
  9499.                 'imei2' => $productByCodeData->getImei2(),
  9500.                 'soId' => $productByCodeData->getSalesOrderId(),
  9501.                 'poId' => $productByCodeData->getPurchaseOrderId(),
  9502.                 'irrId' => $productByCodeData->getIrrId(),
  9503.                 'productId' => $productByCodeData->getProductId(),
  9504.                 'productByCodeId' => $productByCodeData->getProductByCodeId(),
  9505.                 'warehouseId' => $productByCodeData->getWarehouseId(),
  9506.                 'warehouseActionId' => $productByCodeData->getWarehouseActionId(),
  9507.                 'stId' => $productByCodeData->getStockTransferId(),
  9508.                 'srId' => $productByCodeData->getStockReceivedNoteId(),
  9509.                 'scmpId' => $productByCodeData->getStockConsumptionNoteId(),
  9510.                 'clientId' => $productByCodeData->getClientId(),
  9511.                 'supplierId' => $productByCodeData->getSupplierId(),
  9512.                 'drId' => $productByCodeData->getDeliveryReceiptId(),
  9513.                 'consumerName' => $productByCodeData->getConsumerName(),
  9514.                 'drItemData' => [],
  9515. //                'salesCodes' => $productByCodeData->getDeliveryReceiptId(),
  9516.             );
  9517.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9518.                 ->findOneBy(
  9519.                     array(
  9520.                         'id' => $productByCodeData->getProductId()
  9521.                     )
  9522.                 );
  9523.             if ($productByCodeData->getProductionId() != null) {
  9524.                 $productionDataHere $em->getRepository('ApplicationBundle:Production')
  9525.                     ->findOneBy(
  9526.                         array(
  9527.                             'productionId' => $productByCodeData->getProductionId()
  9528.                         )
  9529.                     );
  9530.                 if ($productionDataHere) {
  9531.                     $productDataWeightPackageGm $productionDataHere->getPackageWeight();
  9532.                     $productDataWeightVarianceValue $productionDataHere->getPackageWeightVarianceValue();
  9533.                     $productDataWeightVarianceType $productionDataHere->getPackageWeightVarianceType();
  9534.                 }
  9535.             } else {
  9536.                 if ($productData) {
  9537.                     $productDataWeightPackageGm $productData->getWeight();
  9538.                     $productDataWeightVarianceValue $productData->getWeightVarianceValue();
  9539.                     $productDataWeightVarianceType $productData->getWeightVarianceType();
  9540.                 }
  9541.             }
  9542.             if ($productData) {
  9543.                 $productByCodeDataObj['unitTypeId'] = $productData->getUnitTypeId();
  9544.                 $productByCodeDataObj['purchasePrice'] = $productData->getPurchasePrice();
  9545.                 $productByCodeDataObj['productFdm'] = $productData->getProductFdm();
  9546.                 $productByCodeDataObj['productName'] = $productData->getName();
  9547.                 if ($request->request->has('forSalesReturn') || $request->query->has('forSalesReturn')) {
  9548.                     $QD $this->getDoctrine()
  9549.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  9550.                         ->findOneBy(
  9551.                             array(
  9552.                                 'deliveryReceiptId' => $productByCodeData->getDeliveryReceiptId(),
  9553.                                 'productId' => $productByCodeData->getProductId(),
  9554.                             )
  9555.                         );
  9556. //            if($request->request->get('wareHouseId')!='')
  9557.                     if ($QD) {
  9558.                         $new_pid $QD->getProductId();
  9559.                         $sales_code_range = [];
  9560.                         if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  9561.                             $sales_code_range json_decode($QD->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  9562.                         } else {
  9563.                             $max_int_length strlen((string)PHP_INT_MAX) - 1;
  9564.                             $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$QD->getSalesCodeRange());
  9565.                             $sales_code_range json_decode($json_without_bigintstrue);
  9566.                         }
  9567.                         $p_data = array(
  9568.                             'details_id' => $QD->getId(),
  9569.                             'productId' => $new_pid,
  9570.                             'dr_id' => $productByCodeData->getDeliveryReceiptId(),
  9571.                             'product_name' => $productData->getName(),
  9572.                             'qty' => $QD->getQty(),
  9573.                             'delivered' => $QD->getDelivered(),
  9574.                             'unitTypeId' => $QD->getUnitTypeId(),
  9575.                             'deliverable' => $QD->getDeliverable(),
  9576.                             'balance' => $QD->getBalance(),
  9577.                             'salesCodeRangeStr' => $QD->getSalesCodeRange(),
  9578.                             'salesCodeRange' => $sales_code_range,
  9579.                             'sales_codes' => $sales_code_range,
  9580.                             'sales_price' => $QD->getPrice(),
  9581.                             'purchase_price' => $QD->getCurrentPurchasePrice()
  9582. //                        'delivered'=>$product->getDelivered(),
  9583.                         );
  9584.                         $productByCodeDataObj['drItemData'][] = $p_data;
  9585.                     }
  9586.                 }
  9587.             }
  9588.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9589.                 ->findBy(
  9590.                     array(
  9591.                         'productId' => $id
  9592.                     )
  9593.                 );
  9594.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  9595.                 array(
  9596.                     'page_title' => 'Details',
  9597.                     'company_data' => $company_data,
  9598.                     'productByCodeData' => $productByCodeData,
  9599.                     'productByCodeDataObj' => $productByCodeDataObj,
  9600.                     'productData' => $productData,
  9601.                     'currInvList' => $currInvList,
  9602.                     'productDataWeightPackageGm' => $productDataWeightPackageGm,
  9603.                     'productDataWeightVarianceValue' => $productDataWeightVarianceValue,
  9604.                     'productDataWeightVarianceType' => $productDataWeightVarianceType,
  9605.                     'exId' => $id,
  9606.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9607.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9608.                     'productList' => Inventory::ProductList($em$companyId),
  9609.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9610.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9611.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9612.                     'unitList' => Inventory::UnitTypeList($em),
  9613.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9614.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9615.                     'warehouseList' => Inventory::WarehouseList($em),
  9616.                 )
  9617.             ));
  9618.         } else {
  9619.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  9620.                 array(
  9621.                     'exId' => $id,
  9622.                 )
  9623.             ));
  9624.         }
  9625.         if ($request->query->has('returnJson')) {
  9626.             return new JsonResponse(
  9627.                 array(
  9628.                     'success' => true,
  9629.                     'page_title' => 'Product Details',
  9630.                     'company_data' => $company_data,
  9631.                     'renderedHtml' => $html,
  9632.                     'exId' => $id,
  9633.                     'productByCodeDataObj' => $productByCodeDataObj,
  9634. //                'productData' => $productData,
  9635. //                'currInvList' => $currInvList,
  9636. //                'productList' => Inventory::ProductList($em, $companyId),
  9637. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9638. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9639. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9640. //                'unitList' => Inventory::UnitTypeList($em),
  9641. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9642. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9643. //                'warehouseList' => Inventory::WarehouseList($em),
  9644.                 )
  9645.             );
  9646.         } else {
  9647. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9648. //                ->findBy(
  9649. //                    array(
  9650. ////                        'productByCodeId' => $id,
  9651. //                    'CompanyId'=>$companyId
  9652. //                    )
  9653. //                );
  9654.             $productByCodeList = []; //called by ajax
  9655.             return $this->render('@Inventory/pages/views/product_by_code_assign_check_print.html.twig',
  9656.                 array(
  9657.                     'page_title' => 'Serial Manager',
  9658.                     'company_data' => $company_data,
  9659.                     'renderedHtml' => $html,
  9660.                     'exId' => $id,
  9661.                     'productByCodeList' => $productByCodeList,
  9662.                     'productByCodeDataObj' => $productByCodeDataObj,
  9663. //                'productByCodeData' => $productByCodeData,
  9664. //                'productData' => $productData,
  9665. //                'currInvList' => $currInvList,
  9666. //                'productList' => Inventory::ProductList($em, $companyId),
  9667. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9668. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9669. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9670. //                'unitList' => Inventory::UnitTypeList($em),
  9671. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9672. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9673. //                'warehouseList' => Inventory::WarehouseList($em),
  9674.                 )
  9675.             );
  9676.         }
  9677.     }
  9678.     public
  9679.     function TestProductByCodeCheckAssignPrintAction(Request $request$id 0)
  9680.     {
  9681.         $em $this->getDoctrine()->getManager();
  9682.         $companyId $this->getLoggedUserCompanyId($request);
  9683.         $company_data Company::getCompanyData($em$companyId);
  9684.         $data = [];
  9685.         $html '';
  9686.         $productByCodeData = [];
  9687.         $productByCodeDataObj = [];
  9688.         if ($id != 0) {
  9689.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9690.                 ->findOneBy(
  9691.                     array(
  9692.                         'productByCodeId' => $id
  9693.                     )
  9694.                 );
  9695.         } else {
  9696.             if ($request->query->has('scanCode')) {
  9697.                 $query $em->getRepository('ApplicationBundle:ProductByCode')
  9698.                     ->createQueryBuilder('p');
  9699.                 if ($request->query->has('assigned')) {
  9700.                     $query->where('p.assigned > :av')
  9701.                         ->setParameter('av'$request->query->get('assigned'));
  9702.                 } else
  9703.                     $query->where("1=0");
  9704.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  9705.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  9706.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  9707.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  9708.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  9709.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  9710.                 $query->setMaxResults(1);
  9711.                 $results $query->getQuery()->getResult();
  9712.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  9713.             } else
  9714.                 $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9715.                     ->findOneBy(
  9716.                         array(
  9717. //                        'productByCodeId' => $id,
  9718.                             'CompanyId' => $companyId
  9719.                         ), array(
  9720.                             'productByCodeId' => 'DESC'
  9721.                         )
  9722.                     );
  9723.             if ($productByCodeData)
  9724.                 $id $productByCodeData->getProductByCodeId();
  9725.         }
  9726.         if ($id != 0) {
  9727.             $productByCodeDataObj = array(
  9728.                 'sn' => $productByCodeData->getSalesCode(),
  9729.                 'imei1' => $productByCodeData->getImei1(),
  9730.                 'imei2' => $productByCodeData->getImei2(),
  9731.                 'colorId' => $productByCodeData->getColorId(),
  9732.             );
  9733.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9734.                 ->findOneBy(
  9735.                     array(
  9736.                         'id' => $productByCodeData->getProductId()
  9737.                     )
  9738.                 );
  9739.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9740.                 ->findBy(
  9741.                     array(
  9742.                         'productId' => $id
  9743.                     )
  9744.                 );
  9745.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  9746.                 array(
  9747.                     'page_title' => 'Details',
  9748.                     'company_data' => $company_data,
  9749.                     'productByCodeData' => $productByCodeData,
  9750.                     'productData' => $productData,
  9751.                     'currInvList' => $currInvList,
  9752.                     'exId' => $id,
  9753.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9754.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9755.                     'productList' => Inventory::ProductList($em$companyId),
  9756.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9757.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9758.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9759.                     'unitList' => Inventory::UnitTypeList($em),
  9760.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9761.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9762.                     'warehouseList' => Inventory::WarehouseList($em),
  9763.                 )
  9764.             );
  9765.         } else {
  9766.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  9767.                 array(
  9768.                     'exId' => $id,
  9769.                 )
  9770.             );
  9771.         }
  9772.         if ($request->query->has('returnJson')) {
  9773.             return new JsonResponse(
  9774.                 array(
  9775.                     'success' => true,
  9776.                     'page_title' => 'Product Details',
  9777.                     'company_data' => $company_data,
  9778.                     'renderedHtml' => $html,
  9779.                     'exId' => $id,
  9780.                     'productByCodeDataObj' => $productByCodeDataObj,
  9781. //                'productData' => $productData,
  9782. //                'currInvList' => $currInvList,
  9783. //                'productList' => Inventory::ProductList($em, $companyId),
  9784. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9785. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9786. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9787. //                'unitList' => Inventory::UnitTypeList($em),
  9788. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9789. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9790. //                'warehouseList' => Inventory::WarehouseList($em),
  9791.                 )
  9792.             );
  9793.         } else {
  9794. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9795. //                ->findBy(
  9796. //                    array(
  9797. ////                        'productByCodeId' => $id,
  9798. //                    'CompanyId'=>$companyId
  9799. //                    )
  9800. //                );
  9801.             $productByCodeList = []; //called by ajax
  9802.             return $this->render('@Inventory/pages/views/test_product_by_code_assign_check_print.html.twig',
  9803.                 array(
  9804.                     'page_title' => ' Test Serial Manager',
  9805.                     'company_data' => $company_data,
  9806.                     'renderedHtml' => $html,
  9807.                     'exId' => $id,
  9808.                     'productByCodeList' => $productByCodeList,
  9809.                     'productByCodeDataObj' => $productByCodeDataObj,
  9810. //                'productByCodeData' => $productByCodeData,
  9811. //                'productData' => $productData,
  9812. //                'currInvList' => $currInvList,
  9813. //                'productList' => Inventory::ProductList($em, $companyId),
  9814. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9815. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9816. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9817. //                'unitList' => Inventory::UnitTypeList($em),
  9818. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9819. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9820. //                'warehouseList' => Inventory::WarehouseList($em),
  9821.                 )
  9822.             );
  9823.         }
  9824.     }
  9825.     public
  9826.     function DeleteProductAction(Request $request$id '')
  9827.     {
  9828.         $em $this->getDoctrine()->getManager();
  9829.         $idListArray = [];
  9830.         if ($request->isMethod('POST')) {
  9831.             if ($id == 0)
  9832.                 $id $request->request->get('productId');
  9833.             //now check the product closing , if nothing then we cna remove it
  9834.             $query_here $this->getDoctrine()
  9835.                 ->getRepository('ApplicationBundle:InvClosingBalance')
  9836.                 ->findBy(
  9837.                     array(
  9838.                         'productId' => $request->request->get('productId')
  9839.                     )
  9840.                 );
  9841.             if (!empty($query_here)) {
  9842.                 return new JsonResponse(
  9843.                     array(
  9844.                         'success' => false,
  9845.                     )
  9846.                 );
  9847.             } else {
  9848.                 $qry $em->getRepository('ApplicationBundle:ProductByCode')->findBy(array(
  9849.                     'productId' => $id
  9850.                 ));
  9851.                 foreach ($qry as $det) {
  9852.                     //remove any barcoded products
  9853.                     $em->remove($det);
  9854.                     $em->flush();
  9855.                 }
  9856.                 $qry $em->getRepository('ApplicationBundle:InvProducts')->findBy(array(
  9857.                     'id' => $id
  9858.                 ));
  9859.                 foreach ($qry as $det) {
  9860.                     //remove any barcoded products
  9861.                     $em->remove($det);
  9862.                     $em->flush();
  9863.                 }
  9864.                 $qry $em->getRepository('ApplicationBundle:InvItemTransaction')->findBy(array(
  9865.                     'productId' => $id
  9866.                 ));
  9867.                 foreach ($qry as $det) {
  9868.                     //remove any barcoded products
  9869.                     $em->remove($det);
  9870.                     $em->flush();
  9871.                 }
  9872.                 return new JsonResponse(
  9873.                     array(
  9874.                         'success' => true,
  9875.                     )
  9876.                 );
  9877.             }
  9878.         }
  9879.         return new JsonResponse(
  9880.             array(
  9881.                 'success' => false,
  9882.             )
  9883.         );
  9884.     }
  9885.     public
  9886.     function RegisterProductAction(Request $request$idListStr '')
  9887.     {
  9888.         $em $this->getDoctrine()->getManager();
  9889.         $companyId $this->getLoggedUserCompanyId($request);
  9890.         $company_data Company::getCompanyData($em$companyId);
  9891.         $session $request->getSession();
  9892. //        System::setSessionForUser($session );
  9893.         $idListArray = [];
  9894.         if ($idListStr != '')
  9895.             $idListArray explode(','$idListStr);
  9896.         $data = [];
  9897. //        if ($request->isMethod('POST')) {
  9898. //            $post = $request->request;
  9899. //            if ($request->request->get('formatId') != '') {
  9900. //                $query_here = $this->getDoctrine()
  9901. //                    ->getRepository('ApplicationBundle:CheckFormat')
  9902. //                    ->findOneBy(
  9903. //                        array(
  9904. //                            'formatId' => $request->request->get('formatId')
  9905. //                        )
  9906. //                    );
  9907. //                if (!empty($query_here))
  9908. //                    $new = $query_here;
  9909. //            } else
  9910. //                $new = new CheckFormat();
  9911. //            $new->setName($request->request->get('name'));
  9912. //            $new->setWidth($request->request->get('width'));
  9913. //            $new->setHeight($request->request->get('height'));
  9914. //            $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
  9915. //            $new->setCheckPayToTop($request->request->get('checkPayToTop'));
  9916. //            $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
  9917. //            $new->setCheckAmountTop($request->request->get('checkAmountTop'));
  9918. //            $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
  9919. //            $new->setCheckAiWTop($request->request->get('checkAiWTop'));
  9920. //            $new->setCheckDateLeft($request->request->get('checkDateLeft'));
  9921. //            $new->setCheckDateTop($request->request->get('checkDateTop'));
  9922. //            $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
  9923. //            $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
  9924. //            $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
  9925. //            $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
  9926. //            $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
  9927. //            $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
  9928. //            $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
  9929. //            $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
  9930. //            $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
  9931. //            $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
  9932. //            $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 1 : 0);
  9933. //            $new->setCheckImage($request->request->get('checkImage'));
  9934. //
  9935. //            $em = $this->getDoctrine()->getManager();
  9936. //            $em->persist($new);
  9937. //            $em->flush();
  9938. //
  9939. //        }
  9940. //        if (!empty($idListArray)) {
  9941. //            $query_here = $this->getDoctrine()
  9942. //                ->getRepository('ApplicationBundle:ProductByCode')
  9943. //                ->findBy(
  9944. //                    array(
  9945. //                        'productByCodeId' => $idListArray
  9946. //                    )
  9947. //                );
  9948. //            if (!empty($query_here))
  9949. //                $data = $query_here;
  9950. //
  9951. //        }
  9952. //        else if ($request->query->has('formatId')) {
  9953. //            $query_here = $this->getDoctrine()
  9954. //                ->getRepository('ApplicationBundle:CheckFormat')
  9955. //                ->findOneBy(
  9956. //                    array(
  9957. //                        'formatId' => $request->query->get('formatId')
  9958. //                    )
  9959. //                );
  9960. //            if (!empty($query_here))
  9961. //                $data = $query_here;
  9962. //        }
  9963.         $data = [];
  9964.         $html '';
  9965.         $productByCodeData = [];
  9966.         if ($request->query->has('returnJson')) {
  9967.             return new JsonResponse(
  9968.                 array(
  9969.                     'success' => true,
  9970.                     'page_title' => 'Product Details',
  9971.                     'company_data' => $company_data,
  9972.                     'renderedHtml' => $html,
  9973.                     'data' => $data,
  9974.                     'idListArray' => $idListArray,
  9975. //                    'exId'=>$id,
  9976. //                'productByCodeData' => $productByCodeData,
  9977. //                'productData' => $productData,
  9978. //                'currInvList' => $currInvList,
  9979. //                'productList' => Inventory::ProductList($em, $companyId),
  9980. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9981. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9982. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9983. //                'unitList' => Inventory::UnitTypeList($em),
  9984. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9985. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9986. //                'warehouseList' => Inventory::WarehouseList($em),
  9987.                 )
  9988.             );
  9989.         } else {
  9990.             return $this->render('@Inventory/pages/input_forms/register_product.html.twig',
  9991.                 array(
  9992.                     'page_title' => 'Register Product',
  9993.                     'company_data' => $company_data,
  9994.                     'renderedHtml' => $html,
  9995. //                    'exIdList'=>$i,
  9996.                     'idListArray' => $idListArray,
  9997.                     'data' => $data,
  9998.                     'productByCodeList' => [],
  9999.                     'productByCodeData' => [],
  10000.                     'productList' => Inventory::ProductList($em$companyId),
  10001.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10002.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10003.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10004.                     'unitList' => Inventory::UnitTypeList($em),
  10005.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10006.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10007.                     'warehouseList' => Inventory::WarehouseList($em),
  10008.                 )
  10009.             );
  10010.         }
  10011.     }
  10012.     public
  10013.     function BrandViewAction(Request $request)
  10014.     {
  10015.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  10016.             array(
  10017.                 'page_title' => 'Stock Return'
  10018.             )
  10019.         );
  10020.     }
  10021.     public
  10022.     function PrintTableDataAction(Request $request)
  10023.     {
  10024.         $em $this->getDoctrine()->getManager();
  10025.         $company_data Company::getCompanyData($em1);
  10026.         $data = [];
  10027.         $print_title "test";
  10028.         $document_mark = array(
  10029.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10030.             'copy' => ''
  10031.         );
  10032.         $mis_data = [];
  10033.         $p 1;
  10034.         return $this->render('@Inventory/pages/print/print_table_data.html.twig',
  10035.             array(
  10036.                 'page_title' => 'Data Report',
  10037.                 'data' => $data,
  10038.                 'page_header' => 'Report',
  10039.                 'print_title' => $print_title,
  10040.                 'document_type' => 'Journal voucher',
  10041.                 'document_mark_image' => $document_mark['original'],
  10042.                 'page_header_sub' => 'Add',
  10043. //                'type_list'=>$type_list,
  10044.                 'mis_data' => $mis_data,
  10045.                 'item_data' => [],
  10046.                 'received' => 2,
  10047.                 'return' => 1,
  10048.                 'total_w_vat' => 1,
  10049.                 'total_vat' => 1,
  10050.                 'total_wo_vat' => 1,
  10051.                 'invoice_id' => 'abcd1234',
  10052.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10053.                 'created_by' => 'created by',
  10054.                 'created_at' => '',
  10055.                 'red' => 0,
  10056.                 'company_name' => $company_data->getName(),
  10057.                 'company_data' => $company_data,
  10058.                 'company_address' => $company_data->getAddress(),
  10059.                 'company_image' => $company_data->getImage(),
  10060.                 'p' => $p
  10061.             )
  10062.         );
  10063.     }
  10064.     public
  10065.     function ReplacementReportAction(Request $request)
  10066.     {
  10067.         $qry_data = array(
  10068.             'warehouseId' => [0],
  10069.             'igId' => [0],
  10070.             'brandId' => [0],
  10071.             'categoryId' => [0],
  10072.             'actionTagId' => [0],
  10073.         );
  10074.         $em $this->getDoctrine()->getManager();
  10075.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  10076.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  10077.         $data_searched = [];
  10078.         $companyId $this->getLoggedUserCompanyId($request);
  10079.         $company_data Company::getCompanyData($em$companyId);
  10080.         $data = [];
  10081.         $print_title "Inventory Report";
  10082.         $document_mark = array(
  10083.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10084.             'copy' => ''
  10085.         );
  10086.         $post_data $request->request;
  10087.         $start_date $post_data->has('start_date') ? $post_data->get('start_date') : '';
  10088.         $end_date $post_data->has('end_date') ? $post_data->get('end_date') : '';
  10089.         if ($request->isMethod('POST'))
  10090.             $method 'POST';
  10091.         else
  10092.             $method 'GET';
  10093.         {
  10094. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  10095.             $data_searched Inventory::GetReplacementReportData($this->getDoctrine()->getManager(),
  10096.                 $request->request$method,
  10097.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  10098.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  10099.                 return new JsonResponse(
  10100.                     array(
  10101.                         'page_title' => 'Inventory ',
  10102.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10103.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10104.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10105.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10106.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10107.                         'action_tag' => $warehouse_action_list,
  10108.                         'start_date' => $start_date,
  10109.                         'end_date' => $end_date,
  10110.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10111.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10112.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10113.                         'data_searched' => $data_searched,
  10114.                         'success' => empty($data_searched['query_result']) ? false true
  10115.                     )
  10116.                 );
  10117.             }
  10118.             if ($request->request->get('print_data_enabled') == 1) {
  10119.                 $print_sub_title "";
  10120.                 return $this->render('@Inventory/pages/print/print_replacement_report.html.twig',
  10121.                     array(
  10122.                         'page_title' => 'Replacement Report',
  10123.                         'page_header' => 'Report',
  10124.                         'print_title' => $print_title,
  10125.                         'document_type' => 'Journal voucher',
  10126.                         'document_mark_image' => $document_mark['original'],
  10127.                         'page_header_sub' => 'Add',
  10128.                         'item_data' => [],
  10129.                         'received' => 2,
  10130.                         'return' => 1,
  10131.                         'total_w_vat' => 1,
  10132.                         'total_vat' => 1,
  10133.                         'total_wo_vat' => 1,
  10134.                         'invoice_id' => 'abcd1234',
  10135.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  10136.                         'created_by' => 'created by',
  10137.                         'created_at' => '',
  10138.                         'red' => 0,
  10139.                         'company_name' => $company_data->getName(),
  10140.                         'company_data' => $company_data,
  10141.                         'company_address' => $company_data->getAddress(),
  10142.                         'company_image' => $company_data->getImage(),
  10143.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10144.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10145.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10146.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10147.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10148.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10149.                         'action_tag' => $warehouse_action_list,
  10150.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10151.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10152.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10153.                         'start_date' => $start_date,
  10154.                         'end_date' => $end_date,
  10155.                         'data_searched' => $data_searched
  10156.                     )
  10157.                 );
  10158.             }
  10159.         }
  10160.         return $this->render('@Inventory/pages/report/replacement_report.html.twig',
  10161.             array(
  10162.                 'page_title' => 'Replacement Report',
  10163.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10164.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10165.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10166.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10167.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10168. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10169.                 'action_tag' => $warehouse_action_list,
  10170.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10171.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10172.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10173.                 'start_date' => $start_date,
  10174.                 'end_date' => $end_date,
  10175.                 'data_searched' => $data_searched,
  10176.                 'success' => empty($data_searched['query_result']) ? false true
  10177.             )
  10178.         );
  10179.     }
  10180.     public
  10181.     function InventoryViewAction(Request $request)
  10182.     {
  10183.         $qry_data = array(
  10184.             'warehouseId' => [0],
  10185.             'igId' => [0],
  10186.             'brandId' => [0],
  10187.             'categoryId' => [0],
  10188.             'actionTagId' => [0],
  10189.         );
  10190.         $em $this->getDoctrine()->getManager();
  10191.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  10192.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  10193.         $data_searched = [];
  10194.         $companyId $this->getLoggedUserCompanyId($request);
  10195.         $company_data Company::getCompanyData($em$companyId);
  10196.         $data = [];
  10197.         $print_title "Inventory Report";
  10198.         $document_mark = array(
  10199.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10200.             'copy' => ''
  10201.         );
  10202.         if ($request->isMethod('POST'))
  10203.             $method 'POST';
  10204.         else
  10205.             $method 'GET';
  10206.         {
  10207. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  10208.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  10209.                 $request->request$method,
  10210.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  10211.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  10212.                 return new JsonResponse(
  10213.                     array(
  10214.                         'page_title' => 'Inventory ',
  10215.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10216.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10217.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10218.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10219.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10220.                         'action_tag' => $warehouse_action_list,
  10221.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10222.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10223.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10224.                         'data_searched' => $data_searched,
  10225.                         'success' => empty($data_searched['query_result']) ? false true
  10226.                     )
  10227.                 );
  10228.             }
  10229.             if ($request->request->get('print_data_enabled') == 1) {
  10230.                 $print_sub_title "";
  10231.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  10232.                     array(
  10233.                         'page_title' => 'Inventory Report',
  10234.                         'page_header' => 'Report',
  10235.                         'print_title' => $print_title,
  10236.                         'document_type' => 'Journal voucher',
  10237.                         'document_mark_image' => $document_mark['original'],
  10238.                         'page_header_sub' => 'Add',
  10239.                         'item_data' => [],
  10240.                         'received' => 2,
  10241.                         'return' => 1,
  10242.                         'total_w_vat' => 1,
  10243.                         'total_vat' => 1,
  10244.                         'total_wo_vat' => 1,
  10245.                         'invoice_id' => 'abcd1234',
  10246.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  10247.                         'created_by' => 'created by',
  10248.                         'created_at' => '',
  10249.                         'red' => 0,
  10250.                         'company_name' => $company_data->getName(),
  10251.                         'company_data' => $company_data,
  10252.                         'company_address' => $company_data->getAddress(),
  10253.                         'company_image' => $company_data->getImage(),
  10254.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10255.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10256.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10257.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10258.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10259.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10260.                         'action_tag' => $warehouse_action_list,
  10261.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10262.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10263.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10264.                         'data_searched' => $data_searched
  10265.                     )
  10266.                 );
  10267.             }
  10268.         }
  10269.         return $this->render('@Inventory/pages/report/inventory_view.html.twig',
  10270.             array(
  10271.                 'page_title' => 'Inventory',
  10272.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10273.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10274.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10275.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10276.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10277. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10278.                 'action_tag' => $warehouse_action_list,
  10279.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10280.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10281.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10282.                 'data_searched' => $data_searched
  10283.             )
  10284.         );
  10285.     }
  10286.     public
  10287.     function GrnListAction(Request $request)
  10288.     {
  10289.         $q $this->getDoctrine()
  10290.             ->getRepository('ApplicationBundle:Grn')
  10291.             ->findBy(
  10292.                 array(
  10293.                     'status' => GeneralConstant::ACTIVE,
  10294. //                    'approved' =>  GeneralConstant::APPROVED,
  10295.                 )
  10296.             );
  10297.         $stage_list = array(
  10298.             => 'Pending',
  10299.             => 'Pending',
  10300.             => 'Complete',
  10301.             => 'Partial',
  10302.         );
  10303.         $data = [];
  10304.         foreach ($q as $entry) {
  10305.             $data[] = array(
  10306.                 'doc_date' => $entry->getGrnDate(),
  10307.                 'id' => $entry->getGrnId(),
  10308.                 'doc_hash' => $entry->getDocumentHash(),
  10309.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  10310.                 'stage' => $stage_list[$entry->getStage()]
  10311.             );
  10312.         }
  10313.         return $this->render('@Inventory/pages/views/grn_list.html.twig',
  10314.             array(
  10315.                 'page_title' => 'Grn List',
  10316.                 'data' => $data
  10317.             )
  10318.         );
  10319.     }
  10320.     public
  10321.     function ViewGrnAction(Request $request$id)
  10322.     {
  10323.         $em $this->getDoctrine()->getManager();
  10324.         $dt Inventory::GetGrnDetails($em$id);
  10325.         return $this->render('@Inventory/pages/views/view_grn.html.twig',
  10326.             array(
  10327.                 'page_title' => 'View',
  10328.                 'data' => $dt,
  10329.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  10330.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10331.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10332.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10333.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10334.                     $id,
  10335.                     $dt['created_by'],
  10336.                     $dt['edited_by'])
  10337.             )
  10338.         );
  10339.     }
  10340.     public
  10341.     function PrintGrnAction(Request $request$id)
  10342.     {
  10343.         $em $this->getDoctrine()->getManager();
  10344.         $dt Inventory::GetGrnDetails($em$id);
  10345.         $company_data Company::getCompanyData($em1);
  10346.         $document_mark = array(
  10347.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10348.             'copy' => ''
  10349.         );
  10350.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10351.             $html $this->renderView('@Inventory/pages/print/print_received_note.html.twig',
  10352.                 array(
  10353.                     //full array here
  10354.                     'pdf' => true,
  10355.                     'page_title' => 'Grn',
  10356.                     'export' => 'pdf,print',
  10357.                     'data' => $dt,
  10358.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10359.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10360.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10361.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10362.                         $id,
  10363.                         $dt['created_by'],
  10364.                         $dt['edited_by']),
  10365.                     'document_mark_image' => $document_mark['original'],
  10366.                     'company_name' => $company_data->getName(),
  10367.                     'company_data' => $company_data,
  10368.                     'company_address' => $company_data->getAddress(),
  10369.                     'company_image' => $company_data->getImage(),
  10370.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10371.                     'red' => 0
  10372.                 )
  10373.             );
  10374.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10375. //                'orientation' => 'landscape',
  10376. //                'enable-javascript' => true,
  10377. //                'javascript-delay' => 1000,
  10378.                 'no-stop-slow-scripts' => false,
  10379.                 'no-background' => false,
  10380.                 'lowquality' => false,
  10381.                 'encoding' => 'utf-8',
  10382. //            'images' => true,
  10383. //            'cookie' => array(),
  10384.                 'dpi' => 300,
  10385.                 'image-dpi' => 300,
  10386. //                'enable-external-links' => true,
  10387. //                'enable-internal-links' => true
  10388.             ));
  10389.             return new Response(
  10390.                 $pdf_response,
  10391.                 200,
  10392.                 array(
  10393.                     'Content-Type' => 'application/pdf',
  10394.                     'Content-Disposition' => 'attachment; filename="grn.pdf"'
  10395.                 )
  10396.             );
  10397.         }
  10398.         return $this->render('@Inventory/pages/print/print_received_note.html.twig',
  10399.             array(
  10400.                 'page_title' => 'Grn',
  10401.                 'export' => 'pdf,print',
  10402.                 'data' => $dt,
  10403.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10404.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10405.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10406.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10407.                     $id,
  10408.                     $dt['created_by'],
  10409.                     $dt['edited_by']),
  10410.                 'document_mark_image' => $document_mark['original'],
  10411.                 'company_name' => $company_data->getName(),
  10412.                 'company_data' => $company_data,
  10413.                 'company_address' => $company_data->getAddress(),
  10414.                 'company_image' => $company_data->getImage(),
  10415.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10416.                 'red' => 0
  10417.             )
  10418.         );
  10419.     }
  10420.     public
  10421.     function PrintGrnBarcodeAction(Request $request$id)
  10422.     {
  10423.         $em $this->getDoctrine()->getManager();
  10424.         $dt Inventory::GetGrnDetails($em$id);
  10425.         $company_data Company::getCompanyData($em1);
  10426.         $repeatCount 1;
  10427.         if ($request->query->has('repeatCount'))
  10428.             $repeatCount $request->query->get('repeatCount');
  10429.         $document_mark = array(
  10430.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10431.             'copy' => ''
  10432.         );
  10433.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10434.             $html $this->renderView('@Inventory/pages/print/print_grn_barcodes.html.twig',
  10435.                 array(
  10436.                     //full array here
  10437.                     'pdf' => true,
  10438.                     'page_title' => 'Grn Barcodes',
  10439.                     'export' => 'print',
  10440.                     'data' => $dt,
  10441.                     'repeatCount' => $repeatCount,
  10442.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10443.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10444.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10445.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10446.                         $id,
  10447.                         $dt['created_by'],
  10448.                         $dt['edited_by']),
  10449.                     'document_mark_image' => $document_mark['original'],
  10450.                     'company_name' => $company_data->getName(),
  10451.                     'company_data' => $company_data,
  10452.                     'company_address' => $company_data->getAddress(),
  10453.                     'company_image' => $company_data->getImage(),
  10454.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10455.                     'red' => 0
  10456.                 )
  10457.             );
  10458.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10459. //                'orientation' => 'landscape',
  10460.                 'enable-javascript' => true,
  10461. //                'javascript-delay' => 1000,
  10462.                 'no-stop-slow-scripts' => false,
  10463.                 'no-background' => false,
  10464.                 'lowquality' => false,
  10465.                 'encoding' => 'utf-8',
  10466. //            'images' => true,
  10467. //            'cookie' => array(),
  10468.                 'dpi' => 300,
  10469.                 'image-dpi' => 300,
  10470. //                'enable-external-links' => true,
  10471. //                'enable-internal-links' => true
  10472.             ));
  10473.             return new Response(
  10474.                 $pdf_response,
  10475.                 200,
  10476.                 array(
  10477.                     'Content-Type' => 'application/pdf',
  10478.                     'Content-Disposition' => 'attachment; filename="grn_barcodes.pdf"'
  10479.                 )
  10480.             );
  10481.         }
  10482.         return $this->render('@Inventory/pages/print/print_grn_barcodes.html.twig',
  10483.             array(
  10484.                 'page_title' => 'Grn barcodes',
  10485. //                'export'=>'pdf,print',
  10486.                 'data' => $dt,
  10487.                 'repeatCount' => $repeatCount,
  10488.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10489.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10490.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10491.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10492.                     $id,
  10493.                     $dt['created_by'],
  10494.                     $dt['edited_by']),
  10495.                 'document_mark_image' => $document_mark['original'],
  10496.                 'company_name' => $company_data->getName(),
  10497.                 'company_data' => $company_data,
  10498.                 'company_address' => $company_data->getAddress(),
  10499.                 'company_image' => $company_data->getImage(),
  10500.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10501.                 'red' => 0
  10502.             )
  10503.         );
  10504.     }
  10505.     public
  10506.     function GenerateBarcodeAction(Request $request$type$id$item_id)
  10507.     {
  10508.         $em $this->getDoctrine()->getManager();
  10509.         $repeatCount 1;
  10510.         $spec_item_id 0;
  10511.         $skip_ids = [];
  10512.         $clearUnnecessaryOnly 0;
  10513.         if ($request->query->has('skipIds'))
  10514.             $skip_ids $request->query->get('skipIds');
  10515.         if ($request->query->has('clearUnnecessaryOnly'))
  10516.             $clearUnnecessaryOnly $request->query->get('clearUnnecessaryOnly');
  10517.         if ($type == 'srcv') {
  10518.             $doc_data $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  10519.                 array(
  10520.                     'stockReceivedNoteId' => $id
  10521.                 )
  10522.             );
  10523.             if ($item_id == '_single_') {
  10524.                 $doc_item_data $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
  10525.                     array(
  10526.                         'stockReceivedNoteId' => $id,
  10527. //                        'id' => $item_id
  10528.                     )
  10529.                 );
  10530.             } else {
  10531.                 $doc_item_data $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
  10532.                     array(
  10533.                         'stockReceivedNoteId' => $id,
  10534.                         'id' => $item_id
  10535.                     )
  10536.                 );
  10537.             }
  10538.             $inv_acc_data = [
  10539.                 'fa_amount' => 0,
  10540.                 'tg_amount' => 0,
  10541.             ];
  10542.             $inv_acc_data_by_head = [
  10543.             ];
  10544.             $new_non_delivered_sales_code_range = [];
  10545.             foreach ($doc_item_data as $entry) {
  10546.                 //adding transaction
  10547.                 $sales_code_range_ser = [];
  10548.                 if (in_array($entry->getId(), $skip_ids))
  10549.                     continue;
  10550.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10551.                     ->findOneBy(
  10552.                         array(
  10553.                             'id' => $entry->getProductId()
  10554.                         )
  10555.                     );
  10556.                 $stitem $em->getRepository('ApplicationBundle:StockTransferItem')
  10557.                     ->findOneBy(
  10558.                         array(
  10559.                             'id' => $entry->getStockTransferItemId(),
  10560.                             'productId' => $entry->getProductId()
  10561.                         )
  10562.                     );
  10563.                 if ($product) {
  10564.                     if ($product->getHasSerial() == 1) {
  10565.                         //clear if exists
  10566.                         if ($clearUnnecessaryOnly == 1) {
  10567.                             $get_kids_sql "DELETE FROM product_by_code
  10568.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10569. //                $get_kids_sql .=' ORDER BY name ASC';
  10570.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  10571.                             $stmt->execute();
  10572.                             $em->flush();
  10573.                         } else {
  10574.                             $get_kids_sql "DELETE FROM product_by_code
  10575.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10576. //                $get_kids_sql .=' ORDER BY name ASC';
  10577.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  10578.                             $stmt->execute();
  10579.                             $em->flush();
  10580.                         }
  10581. //                        $check_here = $stmt->fetchAll();
  10582.                         //now addng product by code
  10583.                         $sales_code_range = [];
  10584.                         if ($doc_data->getType() == || $doc_data->getType() == 4) {
  10585. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10586. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10587.                             $product_action_tag_id $entry->getWarehouseActionId();
  10588.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getQty(),
  10589.                                 $doc_data->getStockReceivedNoteDate(), $entry->getWarrantyMon(), 0$doc_data->getCompanyId(), $entry->getWarehouseId(),
  10590.                                 $entry->getWarehouseActionId(), $entry->getPurchaseCodeRange(), nullnullnullnull$doc_data->getStockReceivedNoteId()
  10591.                             );
  10592.                             $sales_code_range $barcodeData['sales_code_range'];
  10593.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  10594.                             $em->flush();
  10595.                         }
  10596. //                        else {
  10597. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10598. //
  10599. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10600. //                            } else {
  10601. //
  10602. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10603. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10604. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10605. //                            }
  10606. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10607. //
  10608. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10609. //                            } else {
  10610. //
  10611. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10612. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10613. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10614. //                            }
  10615. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10616. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10617. //                            $new_non_delivered_sales_code_range = [];
  10618. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10619. //                                if (!(in_array($ndsc, $sales_code_range)))
  10620. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10621. //                            }
  10622. //                            if ($sales_code_range != null) {
  10623. //                                foreach ($sales_code_range as $ind => $dt) {
  10624. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  10625. //                                        ->findOneBy(
  10626. //                                            array(
  10627. //                                                'salesCode' => [$dt],
  10628. //                                                'productId' => $entry->getProductId()
  10629. //                                            )
  10630. //                                        );
  10631. //
  10632. //                                    if ($np) {
  10633. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10634. //                                        $np->setProductId($entry->getProductId());
  10635. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10636. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10637. //                                        $np->setPosition(1);//in warehouse
  10638. //                                        $np->setStockReceivedNoteId($id);
  10639. //
  10640. //
  10641. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10642. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10643. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10644. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10645. //                                            'direction' => 'in',
  10646. //                                            'warehouseId' => $entry->getWarehouseId(),
  10647. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10648. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10649. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10650. //                                        );
  10651. //                                        $np->setTransactionHistory(json_encode(
  10652. //                                            $trans_history
  10653. //                                        ));
  10654. //
  10655. //
  10656. //                                        $em->persist($np);
  10657. //                                        $em->flush();
  10658. //                                    }
  10659. //                                }
  10660. //                            }
  10661. //                        }
  10662.                     }
  10663.                 }
  10664.                 //adding transaction
  10665.                 if ($stitem) {
  10666.                     $stitem->setNonDeliveredSalesCodeRange(json_encode($new_non_delivered_sales_code_range));
  10667.                 }
  10668.                 $spec_item_id $entry->getId();
  10669.                 if ($item_id == '_single_') {
  10670.                     break;
  10671.                 }
  10672.             }
  10673.         }
  10674.         if ($type == 'irr') {
  10675.             $doc_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacement')->findOneBy(
  10676.                 array(
  10677.                     'itemReceivedAndReplacementId' => $id
  10678.                 )
  10679.             );
  10680.             if ($item_id == '_single_') {
  10681.                 $doc_item_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
  10682.                     array(
  10683.                         'itemReceivedAndReplacementId' => $id,
  10684. //                        'id' => $item_id
  10685.                     )
  10686.                 );
  10687.             } else {
  10688.                 $doc_item_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
  10689.                     array(
  10690.                         'itemReceivedAndReplacementId' => $id,
  10691.                         'id' => $item_id
  10692.                     )
  10693.                 );
  10694.             }
  10695.             $inv_acc_data = [
  10696.                 'fa_amount' => 0,
  10697.                 'tg_amount' => 0,
  10698.             ];
  10699.             $inv_acc_data_by_head = [
  10700.             ];
  10701.             $new_non_delivered_sales_code_range = [];
  10702.             foreach ($doc_item_data as $entry) {
  10703.                 //adding transaction
  10704.                 $sales_code_range_ser = [];
  10705.                 if (in_array($entry->getId(), $skip_ids))
  10706.                     continue;
  10707.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10708.                     ->findOneBy(
  10709.                         array(
  10710.                             'id' => $entry->getReceivedProductId()
  10711.                         )
  10712.                     );
  10713.                 if ($product) {
  10714.                     if ($product->getHasSerial() == 1) {
  10715.                         //clear if exists
  10716. //                        if($clearUnnecessaryOnly==1) {
  10717. //                            $get_kids_sql = "DELETE FROM product_by_code
  10718. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10719. ////                $get_kids_sql .=' ORDER BY name ASC';
  10720. //
  10721. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10722. //                            $stmt->execute();
  10723. //                            $em->flush();
  10724. //                        }
  10725. //                        else{
  10726. //                            $get_kids_sql = "DELETE FROM product_by_code
  10727. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10728. ////                $get_kids_sql .=' ORDER BY name ASC';
  10729. //
  10730. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10731. //                            $stmt->execute();
  10732. //                            $em->flush();
  10733. //                        }
  10734. //                        $check_here = $stmt->fetchAll();
  10735.                         //now addng product by code
  10736.                         $sales_code_range = [];
  10737.                         if ($entry->getReceivedQty() > 0) {
  10738. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10739. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10740. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  10741.                             $barcodeData Inventory::GenerateBarcode($em$entry->getReceivedProductId(), $entry->getReceivedQty(),
  10742.                                 $doc_data->getItemReceivedAndReplacementDate(), 00$doc_data->getCompanyId(), $entry->getReceivedWarehouseId(),
  10743.                                 $entry->getReceivedWarehouseActionId(), nullnullnullnullnullnullnullnull$doc_data->getItemReceivedAndReplacementId()
  10744.                             );
  10745.                             $sales_code_range $barcodeData['sales_code_range'];
  10746.                             $entry->setReceivedCodeRange(json_encode($sales_code_range));
  10747.                             $em->flush();
  10748.                         }
  10749. //                        else {
  10750. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10751. //
  10752. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10753. //                            } else {
  10754. //
  10755. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10756. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10757. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10758. //                            }
  10759. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10760. //
  10761. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10762. //                            } else {
  10763. //
  10764. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10765. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10766. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10767. //                            }
  10768. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10769. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10770. //                            $new_non_delivered_sales_code_range = [];
  10771. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10772. //                                if (!(in_array($ndsc, $sales_code_range)))
  10773. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10774. //                            }
  10775. //                            if ($sales_code_range != null) {
  10776. //                                foreach ($sales_code_range as $ind => $dt) {
  10777. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  10778. //                                        ->findOneBy(
  10779. //                                            array(
  10780. //                                                'salesCode' => [$dt],
  10781. //                                                'productId' => $entry->getProductId()
  10782. //                                            )
  10783. //                                        );
  10784. //
  10785. //                                    if ($np) {
  10786. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10787. //                                        $np->setProductId($entry->getProductId());
  10788. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10789. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10790. //                                        $np->setPosition(1);//in warehouse
  10791. //                                        $np->setStockReceivedNoteId($id);
  10792. //
  10793. //
  10794. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10795. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10796. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10797. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10798. //                                            'direction' => 'in',
  10799. //                                            'warehouseId' => $entry->getWarehouseId(),
  10800. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10801. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10802. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10803. //                                        );
  10804. //                                        $np->setTransactionHistory(json_encode(
  10805. //                                            $trans_history
  10806. //                                        ));
  10807. //
  10808. //
  10809. //                                        $em->persist($np);
  10810. //                                        $em->flush();
  10811. //                                    }
  10812. //                                }
  10813. //                            }
  10814. //                        }
  10815.                     }
  10816.                 }
  10817.                 //adding transaction
  10818.                 $spec_item_id $entry->getId();
  10819.                 if ($item_id == '_single_') {
  10820.                     break;
  10821.                 }
  10822.             }
  10823.         }
  10824.         if ($type == 'prdcn') {
  10825.             $doc_data $em->getRepository('ApplicationBundle:Production')->findOneBy(
  10826.                 array(
  10827.                     'productionId' => $id
  10828.                 )
  10829.             );
  10830.             if ($item_id == '_single_') {
  10831.                 $doc_item_data $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
  10832.                     array(
  10833.                         'productionId' => $id,
  10834. //                        'id' => $item_id
  10835.                     )
  10836.                 );
  10837.             } else {
  10838.                 $doc_item_data $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
  10839.                     array(
  10840.                         'productionId' => $id,
  10841.                         'id' => $item_id
  10842.                     )
  10843.                 );
  10844.             }
  10845.             $inv_acc_data = [
  10846.                 'fa_amount' => 0,
  10847.                 'tg_amount' => 0,
  10848.             ];
  10849.             $inv_acc_data_by_head = [
  10850.             ];
  10851.             $new_non_delivered_sales_code_range = [];
  10852.             foreach ($doc_item_data as $entry) {
  10853.                 //adding transaction
  10854.                 $sales_code_range_ser = [];
  10855.                 if (in_array($entry->getId(), $skip_ids))
  10856.                     continue;
  10857.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10858.                     ->findOneBy(
  10859.                         array(
  10860.                             'id' => $entry->getProductId()
  10861.                         )
  10862.                     );
  10863.                 if ($product) {
  10864.                     if ($product->getHasSerial() == 1) {
  10865.                         //clear if exists
  10866. //                        if($clearUnnecessaryOnly==1) {
  10867. //                            $get_kids_sql = "DELETE FROM product_by_code
  10868. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10869. ////                $get_kids_sql .=' ORDER BY name ASC';
  10870. //
  10871. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10872. //                            $stmt->execute();
  10873. //                            $em->flush();
  10874. //                        }
  10875. //                        else{
  10876. //                            $get_kids_sql = "DELETE FROM product_by_code
  10877. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10878. ////                $get_kids_sql .=' ORDER BY name ASC';
  10879. //
  10880. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10881. //                            $stmt->execute();
  10882. //                            $em->flush();
  10883. //                        }
  10884. //                        $check_here = $stmt->fetchAll();
  10885.                         //now addng product by code
  10886.                         $sales_code_range = [];
  10887.                         if ($entry->getProducedQty() > 0) {
  10888. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10889. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10890. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  10891.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getProducedQty(),
  10892.                                 $doc_data->getProductionDate(), 00$doc_data->getCompanyId(), $entry->getWarehouseId(),
  10893.                                 $entry->getProducedItemActionTagId(), nullnullnullnullnullnullnull$doc_data->getProductionId(), null
  10894.                             );
  10895.                             $sales_code_range $barcodeData['sales_code_range'];
  10896.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  10897.                             $em->flush();
  10898.                         }
  10899. //                        else {
  10900. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10901. //
  10902. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10903. //                            } else {
  10904. //
  10905. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10906. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10907. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10908. //                            }
  10909. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10910. //
  10911. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10912. //                            } else {
  10913. //
  10914. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10915. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10916. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10917. //                            }
  10918. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10919. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10920. //                            $new_non_delivered_sales_code_range = [];
  10921. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10922. //                                if (!(in_array($ndsc, $sales_code_range)))
  10923. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10924. //                            }
  10925. //                            if ($sales_code_range != null) {
  10926. //                                foreach ($sales_code_range as $ind => $dt) {
  10927. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  10928. //                                        ->findOneBy(
  10929. //                                            array(
  10930. //                                                'salesCode' => [$dt],
  10931. //                                                'productId' => $entry->getProductId()
  10932. //                                            )
  10933. //                                        );
  10934. //
  10935. //                                    if ($np) {
  10936. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10937. //                                        $np->setProductId($entry->getProductId());
  10938. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10939. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10940. //                                        $np->setPosition(1);//in warehouse
  10941. //                                        $np->setStockReceivedNoteId($id);
  10942. //
  10943. //
  10944. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10945. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10946. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10947. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10948. //                                            'direction' => 'in',
  10949. //                                            'warehouseId' => $entry->getWarehouseId(),
  10950. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10951. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10952. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10953. //                                        );
  10954. //                                        $np->setTransactionHistory(json_encode(
  10955. //                                            $trans_history
  10956. //                                        ));
  10957. //
  10958. //
  10959. //                                        $em->persist($np);
  10960. //                                        $em->flush();
  10961. //                                    }
  10962. //                                }
  10963. //                            }
  10964. //                        }
  10965.                     }
  10966.                 }
  10967.                 //adding transaction
  10968.                 $spec_item_id $entry->getId();
  10969.                 if ($item_id == '_single_') {
  10970.                     break;
  10971.                 }
  10972.             }
  10973.         }
  10974.         return new JsonResponse(array(
  10975.             'success' => $spec_item_id != true false,
  10976.             'skipIds' => [],
  10977.             'spec_item_id' => $spec_item_id
  10978.         ));
  10979. //        return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  10980. //            array(
  10981. //                'page_title' => 'Srcv barcodes',
  10982. ////                'export'=>'pdf,print',
  10983. //                'data' => $dt,
  10984. //                'repeatCount' => $repeatCount,
  10985. //                'item_id' => $item_id,
  10986. //                'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  10987. //                    $id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10988. //                'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10989. //                    array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  10990. //                    $id,
  10991. //                    $dt['created_by'],
  10992. //                    $dt['edited_by']),
  10993. //                'document_mark_image' => $document_mark['original'],
  10994. //                                    'company_name' => $company_data->getName(),
  10995. //                    'company_data'=>$company_data,
  10996. //                'company_address' => $company_data->getAddress(),
  10997. //                'company_image' => $company_data->getImage(),
  10998. //                'invoice_footer' => $company_data->getInvoiceFooter(),
  10999. //                'red' => 0
  11000. //
  11001. //            )
  11002. //        );
  11003.     }
  11004.     public
  11005.     function PrintLabelAction(Request $request$id)
  11006.     {
  11007.         $em $this->getDoctrine()->getManager();
  11008. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11009.         $repeatCount 1;
  11010.         $assignProductId '';
  11011.         $productByCodeIds = [];
  11012.         $print_selection_type 1;
  11013.         $print_selection_string 1;
  11014.         $assignLabelFormatId 0;
  11015.         $assignColorId 0;
  11016.         $assignProductionScheduleId 0;
  11017.         $warehouseId '';
  11018.         $warehouseActionId '';
  11019.         $toAssignPosition '';
  11020.         $printFlag $request->request->has('printFlag') ? $request->request->get('printFlag') : 1;
  11021.         $returnJson $request->request->has('returnJson') ? $request->request->get('returnJson') : 0;
  11022.         if ($returnJson == 1)
  11023.             $printFlag 0;
  11024.         $companyId $this->getLoggedUserCompanyId($request);
  11025.         if ($request->query->has('repeatCount'))
  11026.             $repeatCount $request->query->get('repeatCount');
  11027.         if ($request->request->has('print_selection_type'))
  11028.             $print_selection_type $request->request->get('print_selection_type');
  11029.         if ($request->request->has('print_selection_string'))
  11030.             $print_selection_string $request->request->get('print_selection_string');
  11031.         if ($request->request->has('productByCodeIds'))
  11032.             $productByCodeIds json_decode($request->request->get('productByCodeIds'), true);
  11033.         if ($request->request->has('formatId'))
  11034.             $assignLabelFormatId $request->request->get('formatId');
  11035.         if ($printFlag == 0) {
  11036.             if ($request->request->has('productSelector'))
  11037.                 $assignProductId $request->request->get('productSelector');
  11038.             if ($request->request->has('colorId'))
  11039.                 $assignColorId $request->request->get('colorId');
  11040.             if ($request->request->has('productionScheduleId'))
  11041.                 $assignProductionScheduleId $request->request->get('productionScheduleId');
  11042.             if ($request->request->has('warehouseId'))
  11043.                 $warehouseId $request->request->get('warehouseId');
  11044.             if ($request->request->has('warehouseActionId'))
  11045.                 $warehouseActionId $request->request->get('warehouseActionId');
  11046.             if ($request->request->has('position'))
  11047.                 $toAssignPosition $request->request->get('position');
  11048.             if ($assignColorId == '')
  11049.                 $assignColorId 0;
  11050.         }
  11051.         if ($productByCodeIds == null)
  11052.             $productByCodeIds = [];
  11053.         $productByCodeData = [];
  11054.         $productList = [];
  11055.         $productIds = [];
  11056.         if ($print_selection_type == 2) {
  11057.             //range
  11058.             $productByCodeIds Inventory::getIdsFromIdSelectionStr($print_selection_string);
  11059.         }
  11060.         $labelData = [
  11061.             'formatId' => 0
  11062.         ];
  11063.         $formatId 0;
  11064.         if (!empty($productByCodeIds)) {
  11065.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11066.                 ->findBy(
  11067.                     array(
  11068.                         'productByCodeId' => $productByCodeIds
  11069.                     )
  11070.                 );
  11071.             foreach ($productByCodeData as $d) {
  11072.                 if ($d->getStage() < 10$d->setStage(11);
  11073.                 if ($assignProductId != '') {
  11074.                     $d->setProductId($assignProductId);
  11075.                 }
  11076.                 if ($assignColorId != 0) {
  11077.                     $d->setColorId($assignColorId);
  11078.                 } else {
  11079.                     $productData $em->getRepository('ApplicationBundle:InvProducts')
  11080.                         ->findOneBy(
  11081.                             array(
  11082.                                 'id' => $assignProductId
  11083.                             )
  11084.                         );
  11085.                     if ($productData) {
  11086.                         $d->setColorId($productData->getDefaultColorId());
  11087.                     }
  11088.                 }
  11089.                 if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  11090.                     $d->setDefaultLabelFormatId($assignLabelFormatId);
  11091.                     $d->setDeviceLabelFormatId($assignLabelFormatId);
  11092.                 }
  11093.                 $toAssignPosition != '' $d->setPosition($toAssignPosition) : '';
  11094.                 $warehouseId != '' $d->setWarehouseId($warehouseId) : '';
  11095.                 $warehouseActionId != '' $d->setWarehouseActionId($warehouseActionId) : '';
  11096.                 if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  11097.                     $d->setProductionScheduleId($assignProductionScheduleId);
  11098.                     $productionSchedule $em->getRepository('ApplicationBundle:ProductionSchedule')
  11099.                         ->findOneBy(
  11100.                             array(
  11101.                                 'productionScheduleId' => $assignProductionScheduleId
  11102.                             )
  11103.                         );
  11104.                     if ($productionSchedule) {
  11105.                         if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  11106.                             //becuase it will assigned at previous lines
  11107.                         } else {
  11108.                             $d->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  11109.                             $d->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  11110.                         }
  11111.                         $d->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  11112.                         $d->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  11113.                     }
  11114.                 }
  11115.                 $em->flush();
  11116.                 if ($d->getProductId() != '' || $d->getProductId() != null)
  11117.                     $productIds[] = $d->getProductId();
  11118.                 $formatId $d->getDeviceLabelFormatId();
  11119.             }
  11120.         }
  11121.         $labelFormatHere $em->getRepository('ApplicationBundle:LabelFormat')
  11122.             ->findOneBy(
  11123.                 array(
  11124.                     'formatId' => $formatId,
  11125. //                        'CompanyId' => $companyId
  11126.                 )
  11127.             );
  11128.         if ($labelFormatHere) {
  11129.             $formatData json_decode($labelFormatHere->getFormatData(), true);
  11130.             if ($formatData == null$formatData = [];
  11131.             $labelData = array(
  11132.                 'id' => $labelFormatHere->getFormatId(),
  11133.                 'formatId' => $labelFormatHere->getFormatId(),
  11134.                 'labelType' => $labelFormatHere->getLabelType(),
  11135.                 'name' => $labelFormatHere->getName(),
  11136.                 'width' => $labelFormatHere->getWidth(),
  11137.                 'pageWidth' => $labelFormatHere->getPageWidth(),
  11138.                 'height' => $labelFormatHere->getheight(),
  11139.                 'pageHeight' => $labelFormatHere->getPageHeight(),
  11140.                 'formatData' => $formatData,
  11141.             );
  11142.         }
  11143.         $productList Inventory::ProductList($em$this->getLoggedUserCompanyId($request), 10''$productIds);
  11144.         $company_data Company::getCompanyData($em1);
  11145.         $document_mark = array(
  11146.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11147.             'copy' => ''
  11148.         );
  11149.         $dt $productByCodeData;
  11150.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11151.             $html $this->renderView('@Inventory/pages/print/print_label.html.twig',
  11152.                 array(
  11153.                     //full array here
  11154.                     'pdf' => true,
  11155.                     'page_title' => 'Device Labels',
  11156.                     'export' => 'print',
  11157.                     'repeatCount' => $repeatCount,
  11158.                     'labelData' => $labelData,
  11159.                     'brandList' => Inventory::GetBrandList($em$companyId),
  11160. //                    'item_id' => $item_id,
  11161.                     'data' => $dt,
  11162.                     'productList' => $productList,
  11163.                     'approval_data' => [],
  11164.                     'document_log' => [],
  11165.                     'document_mark_image' => $document_mark['original'],
  11166.                     'company_name' => $company_data->getName(),
  11167.                     'company_data' => $company_data,
  11168.                     'company_address' => $company_data->getAddress(),
  11169.                     'company_image' => $company_data->getImage(),
  11170.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11171.                     'red' => 0
  11172.                 )
  11173.             );
  11174.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11175. //                'orientation' => 'landscape',
  11176.                 'enable-javascript' => true,
  11177. //                'javascript-delay' => 1000,
  11178.                 'no-stop-slow-scripts' => false,
  11179.                 'no-background' => false,
  11180.                 'lowquality' => false,
  11181.                 'encoding' => 'utf-8',
  11182. //            'images' => true,
  11183. //            'cookie' => array(),
  11184.                 'dpi' => 300,
  11185.                 'image-dpi' => 300,
  11186. //                'enable-external-links' => true,
  11187. //                'enable-internal-links' => true
  11188.             ));
  11189.             return new Response(
  11190.                 $pdf_response,
  11191.                 200,
  11192.                 array(
  11193.                     'Content-Type' => 'application/pdf',
  11194.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11195.                 )
  11196.             );
  11197.         }
  11198.         $url $this->generateUrl(
  11199.             'print_label'
  11200.         );
  11201.         if ($returnJson == && $printFlag == 0) {
  11202. //                    $dr = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  11203. //                        array(
  11204. //                            'salesOrderId' => $orderId, ///material
  11205. //
  11206. //                        )
  11207. //                    );
  11208.             return new JsonResponse(array(
  11209.                 'success' => true,
  11210. //                        'documentHash' => $order->getDocumentHash(),
  11211. //                'documentId' => $receiptId,
  11212. //                'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
  11213. //
  11214. //                'viewUrl' => $url . "/" . $receiptId,
  11215.             ));
  11216.         } else return $this->render('@Inventory/pages/print/print_label.html.twig',
  11217.             array(
  11218.                 'page_title' => 'Product Labels',
  11219. //                'export'=>'pdf,print',
  11220.                 'data' => $dt,
  11221.                 'productList' => $productList,
  11222.                 'repeatCount' => $repeatCount,
  11223. //                'item_id' => $item_id,
  11224.                 'labelData' => $labelData,
  11225.                 'brandList' => Inventory::GetBrandList($em$companyId),
  11226.                 'approval_data' => [],
  11227.                 'document_log' => [],
  11228.                 'document_mark_image' => $document_mark['original'],
  11229.                 'company_name' => $company_data->getName(),
  11230.                 'company_data' => $company_data,
  11231.                 'company_address' => $company_data->getAddress(),
  11232.                 'company_image' => $company_data->getImage(),
  11233.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11234.                 'red' => 0
  11235.             )
  11236.         );
  11237.     }
  11238.     public
  11239.     function PrintCartonLabelAction(Request $request$id)
  11240.     {
  11241.         $em $this->getDoctrine()->getManager();
  11242. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11243.         $repeatCount 1;
  11244.         $assignProductId '';
  11245.         $productByCodeIds = [];
  11246.         $cartonId 0;
  11247.         if ($id != 0)
  11248.             $cartonId $id;
  11249.         $colorText '';
  11250.         $weightText '';
  11251.         if ($request->query->has('repeatCount'))
  11252.             $repeatCount $request->query->get('repeatCount');
  11253.         if ($request->request->has('printCartonId'))
  11254.             $cartonId $request->request->get('printCartonId');
  11255.         if ($request->request->has('printCartonColorText'))
  11256.             $colorText $request->request->get('printCartonColorText');
  11257.         if ($request->request->has('printCartonWeightText'))
  11258.             $weightText $request->request->get('printCartonWeightText');
  11259.         $labelData = [
  11260.             'formatId' => 0
  11261.         ];
  11262.         if ($productByCodeIds == null)
  11263.             $productByCodeIds = [];
  11264.         $productByCodeData = [];
  11265.         $cartonData = [];
  11266.         $product = [];
  11267.         if ($cartonId != 0) {
  11268.             $cartonData $em->getRepository('ApplicationBundle:Carton')
  11269.                 ->findOneBy(
  11270.                     array(
  11271.                         'id' => $cartonId
  11272.                     )
  11273.                 );
  11274.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11275.                 ->findBy(
  11276.                     array(
  11277.                         'cartonId' => $cartonId
  11278.                     )
  11279.                 );
  11280. //            if(!empty($productByCodeData))
  11281. //                $product = $em->getRepository('ApplicationBundle:InvProducts')
  11282. //                ->findOneBy(
  11283. //                    array(
  11284. //                        'id' => $productByCodeData[0]->getProductId()
  11285. //                    )
  11286. //                );
  11287. //            else
  11288.             $product $em->getRepository('ApplicationBundle:InvProducts')
  11289.                 ->findOneBy(
  11290.                     array(
  11291.                         'id' => $cartonData->getProductId()
  11292.                     )
  11293.                 );
  11294.             $formatId $cartonData->getCartonLabelFormatId();
  11295.             $labelFormatHere $em->getRepository('ApplicationBundle:LabelFormat')
  11296.                 ->findOneBy(
  11297.                     array(
  11298.                         'formatId' => $formatId,
  11299. //                        'CompanyId' => $companyId
  11300.                     )
  11301.                 );
  11302.             if ($labelFormatHere) {
  11303.                 $formatData json_decode($labelFormatHere->getFormatData(), true);
  11304.                 if ($formatData == null$formatData = [];
  11305.                 $labelData = array(
  11306.                     'id' => $labelFormatHere->getFormatId(),
  11307.                     'formatId' => $labelFormatHere->getFormatId(),
  11308.                     'labelType' => $labelFormatHere->getLabelType(),
  11309.                     'name' => $labelFormatHere->getName(),
  11310.                     'width' => $labelFormatHere->getWidth(),
  11311.                     'pageWidth' => $labelFormatHere->getPageWidth(),
  11312.                     'height' => $labelFormatHere->getheight(),
  11313.                     'pageHeight' => $labelFormatHere->getPageHeight(),
  11314.                     'formatData' => $formatData,
  11315.                 );
  11316.             }
  11317.         }
  11318.         $company_data Company::getCompanyData($em1);
  11319.         $document_mark = array(
  11320.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11321.             'copy' => ''
  11322.         );
  11323.         $dt $productByCodeData;
  11324.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11325.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  11326.                 array(
  11327.                     //full array here
  11328.                     'pdf' => true,
  11329.                     'page_title' => 'Carton Labels',
  11330.                     'export' => 'print',
  11331.                     'labelData' => $labelData,
  11332.                     'repeatCount' => $repeatCount,
  11333. //                    'item_id' => $item_id,
  11334.                     'data' => $dt,
  11335.                     'cartonData' => $cartonData,
  11336.                     'product' => $product,
  11337.                     'colorText' => $colorText,
  11338.                     'weightText' => $weightText,
  11339.                     'approval_data' => [],
  11340.                     'document_log' => [],
  11341.                     'document_mark_image' => $document_mark['original'],
  11342.                     'company_name' => $company_data->getName(),
  11343.                     'company_data' => $company_data,
  11344.                     'company_address' => $company_data->getAddress(),
  11345.                     'company_image' => $company_data->getImage(),
  11346.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11347.                     'red' => 0
  11348.                 )
  11349.             );
  11350.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11351. //                'orientation' => 'landscape',
  11352.                 'enable-javascript' => true,
  11353. //                'javascript-delay' => 1000,
  11354.                 'no-stop-slow-scripts' => false,
  11355.                 'no-background' => false,
  11356.                 'lowquality' => false,
  11357.                 'encoding' => 'utf-8',
  11358. //            'images' => true,
  11359. //            'cookie' => array(),
  11360.                 'dpi' => 300,
  11361.                 'image-dpi' => 300,
  11362. //                'enable-external-links' => true,
  11363. //                'enable-internal-links' => true
  11364.             ));
  11365.             return new Response(
  11366.                 $pdf_response,
  11367.                 200,
  11368.                 array(
  11369.                     'Content-Type' => 'application/pdf',
  11370.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11371.                 )
  11372.             );
  11373.         }
  11374.         if ($request->query->has('previewOnly')) {
  11375.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  11376.                 array(
  11377.                     'page_title' => 'Carton Labels',
  11378. //                'export'=>'pdf,print',
  11379.                     'data' => $dt,
  11380.                     'skip_parameters' => 1,
  11381.                     'labelData' => $labelData,
  11382.                     'cartonData' => $cartonData,
  11383.                     'product' => $product,
  11384.                     'colorText' => $colorText,
  11385.                     'weightText' => $weightText,
  11386.                     'repeatCount' => $repeatCount,
  11387. //                'item_id' => $item_id,
  11388.                     'approval_data' => [],
  11389.                     'document_log' => [],
  11390.                     'document_mark_image' => $document_mark['original'],
  11391.                     'company_name' => $company_data->getName(),
  11392.                     'company_data' => $company_data,
  11393.                     'company_address' => $company_data->getAddress(),
  11394.                     'company_image' => $company_data->getImage(),
  11395.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11396.                     'red' => 0
  11397.                 )
  11398.             );
  11399.             if ($request->query->has('returnJson')) {
  11400.                 return new JsonResponse(
  11401.                     array(
  11402.                         'success' => true,
  11403.                         'page_title' => 'Product Details',
  11404.                         'company_data' => $company_data,
  11405.                         'renderedHtml' => $html,
  11406. //                'productData' => $productData,
  11407. //                'currInvList' => $currInvList,
  11408. //                'productList' => Inventory::ProductList($em, $companyId),
  11409. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11410. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11411. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11412. //                'unitList' => Inventory::UnitTypeList($em),
  11413. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11414. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11415. //                'warehouseList' => Inventory::WarehouseList($em),
  11416.                     )
  11417.                 );
  11418.             }
  11419.         }
  11420.         return $this->render('@Inventory/pages/print/print_carton_label.html.twig',
  11421.             array(
  11422.                 'page_title' => 'Carton Labels',
  11423. //                'export'=>'pdf,print',
  11424.                 'data' => $dt,
  11425.                 'cartonData' => $cartonData,
  11426.                 'product' => $product,
  11427. //                'productByCodeData' => $productByCodeData,
  11428.                 'colorText' => $colorText,
  11429.                 'weightText' => $weightText,
  11430.                 'repeatCount' => $repeatCount,
  11431.                 'labelData' => $labelData,
  11432. //                'item_id' => $item_id,
  11433.                 'approval_data' => [],
  11434.                 'document_log' => [],
  11435.                 'document_mark_image' => $document_mark['original'],
  11436.                 'company_name' => $company_data->getName(),
  11437.                 'company_data' => $company_data,
  11438.                 'company_address' => $company_data->getAddress(),
  11439.                 'company_image' => $company_data->getImage(),
  11440.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11441.                 'red' => 0
  11442.             )
  11443.         );
  11444.     }
  11445.     public
  11446.     function AssignInfoToProductByCodeAction(Request $request$id)
  11447.     {
  11448.         $em $this->getDoctrine()->getManager();
  11449.         $companyId $this->getLoggedUserCompanyId($request);
  11450. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11451.         $cartonId '';
  11452.         $passStatus 5;
  11453.         $assignProductId '';
  11454.         $assignProductionId '';
  11455.         $assignProductionScheduleId '';
  11456.         $gbWeightGm '';
  11457.         $dvWeightGm '';
  11458.         $cartonWeightGm '';
  11459.         if ($request->request->has('cartonId'))
  11460.             $cartonId $request->request->get('cartonId');
  11461.         if ($request->request->has('passStatus'))
  11462.             $passStatus $request->request->get('passStatus');
  11463.         if ($request->request->has('productByCodeId'))
  11464.             $id $request->request->get('productByCodeId');
  11465.         if ($request->request->has('productId'))
  11466.             $assignProductId $request->request->get('productId');
  11467.         if ($request->request->has('productionId'))
  11468.             $assignProductionId $request->request->get('productionId');
  11469.         if ($request->request->has('productionScheduleId'))
  11470.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  11471.         if ($request->request->has('gbWeightGm'))
  11472.             $gbWeightGm $request->request->get('gbWeightGm');
  11473.         if ($request->request->has('dvWeightGm'))
  11474.             $dvWeightGm $request->request->get('dvWeightGm');
  11475.         if ($request->request->has('cartonWeightGm'))
  11476.             $cartonWeightGm $request->request->get('cartonWeightGm');
  11477.         $cartonAssignedAlready 0;
  11478.         $otherData = array(
  11479.             'currentCartonBalance' => 0,
  11480.             'currentCartonCapacity' => 0,
  11481.             'currentCartonAssigned' => 0,
  11482.             'currentCartonFull' => 0,
  11483.         );
  11484.         if ($id != && $id != '') {
  11485.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11486.                 ->findOneBy(
  11487.                     array(
  11488.                         'productByCodeId' => $id
  11489.                     )
  11490.                 );
  11491.             if ($assignProductId != ''$productByCodeData->setProductId($assignProductId);
  11492.             if ($productByCodeData->getCartonId() != '' || $productByCodeData->getCartonId() != null)
  11493.                 $cartonAssignedAlready 1;
  11494.             else if ($cartonId != ''$productByCodeData->setCartonId($cartonId);
  11495.             if ($dvWeightGm != ''$productByCodeData->setSingleWeightGm($dvWeightGm);
  11496.             if ($gbWeightGm != '') {
  11497.                 $productByCodeData->setPackagedWeightGm($gbWeightGm);
  11498.             }
  11499.             $colorText '_NA_';
  11500.             if ($passStatus != 5$productByCodeData->setStage($passStatus);
  11501.             $productByCodeData->setCompanyId($companyId);
  11502.             if ($assignProductionId != '') {
  11503.                 $productByCodeData->setProductionId($assignProductionId);
  11504.                 $productionData $em->getRepository('ApplicationBundle:Production')
  11505.                     ->findOneBy(
  11506.                         array(
  11507.                             'productionId' => $assignProductionId
  11508.                         )
  11509.                     );
  11510.                 if ($assignProductId != '' && $assignProductId != null && $assignProductId != 0)
  11511.                     $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11512.                         array(
  11513.                             'productionId' => $assignProductionId,
  11514.                             'productId' => $assignProductId,
  11515.                             'type' => 1,
  11516.                         )
  11517.                     );
  11518.                 else
  11519.                     $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11520.                         array(
  11521.                             'productionId' => $assignProductionId,
  11522. //                            'productId' => $assignProductId,
  11523.                             'type' => 1,
  11524.                         )
  11525.                     );
  11526.                 $assignProductionScheduleId $productionData->getProductionScheduleId();
  11527.                 if ($productionItemData) {
  11528.                     $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11529.                     $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11530.                     $productByCodeData->setPosition(1);//in inventory
  11531.                     $productByCodeData->setSerialAssigned(1);
  11532.                     $productByCodeData->setColorId($productionItemData->getColorId());
  11533.                     $productByCodeData->setColorText($productionItemData->getColorText());
  11534.                     $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11535.                     $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11536.                     if ($passStatus == 1)//passed
  11537.                     {
  11538. //                    $transDate = new \DateTime();
  11539. //                    Inventory::addItemToInventoryCompact($em,
  11540. //                        $productionItemData->getProductId(),
  11541. //                        $productionItemData->getWarehouseId(),
  11542. //                        $productionItemData->getWarehouseId(),
  11543. //                        $productionData->getProducedItemActionTagId(),
  11544. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11545. //                        $transDate,
  11546. //                        1,
  11547. //                        1,
  11548. //                        $entry['valueAdd'],
  11549. //                        $entry['valueSub'],
  11550. //                        $entry['price'],
  11551. //                        $this->getLoggedUserCompanyId($request),
  11552. //                        0,
  11553. //                        $entry['entity'],
  11554. //                        $entry['entityId'],
  11555. //                        $entry['entityDocHash']
  11556. //                    );
  11557.                     }
  11558.                     $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  11559.                     if ($transHistory == null)
  11560.                         $transHistory = [];
  11561.                     $transHistory[] = array(
  11562.                         'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  11563.                         'direction' => 'in',
  11564.                         'warehouseId' => $productionItemData->getWarehouseId(),
  11565.                         'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  11566.                         'fromWarehouseId' => 0,
  11567.                         'fromWarehouseActionId' => //stock of goods
  11568.                     );
  11569.                     $productByCodeData->setTransactionHistory(json_encode($transHistory));
  11570.                 }
  11571.             }
  11572.             if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  11573.                 $productByCodeData->setProductionScheduleId($assignProductionScheduleId);
  11574.                 $productionSchedule $em->getRepository('ApplicationBundle:ProductionSchedule')
  11575.                     ->findOneBy(
  11576.                         array(
  11577.                             'productionScheduleId' => $assignProductionScheduleId
  11578.                         )
  11579.                     );
  11580.                 if ($productionSchedule) {
  11581.                     $productByCodeData->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  11582.                     $productByCodeData->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  11583.                     $productByCodeData->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  11584.                     $productByCodeData->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  11585.                     if ($productByCodeData->getProductionId() == null || $productByCodeData->getProductionId() == '' || $productByCodeData->getProductionId() == 0) {
  11586.                         $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11587.                             array(
  11588.                                 'productionScheduleId' => $assignProductionScheduleId,
  11589.                                 'productId' => $productionSchedule->getProducedProductId(),
  11590.                                 'type' => 1,
  11591.                             )
  11592.                         );
  11593. //                        $assignProductionScheduleId=$productionData->getProductionScheduleId();
  11594.                         if ($productionItemData) {
  11595.                             $productByCodeData->setProductionId($productionItemData->getProductionId());
  11596.                             $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11597.                             $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11598.                             $productByCodeData->setPosition(1);//in inventory
  11599.                             $productByCodeData->setSerialAssigned(1);
  11600.                             $productByCodeData->setColorId($productionItemData->getColorId());
  11601.                             $productByCodeData->setColorText($productionItemData->getColorText());
  11602.                             $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11603.                             $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11604.                             if ($passStatus == 1)//passed
  11605.                             {
  11606. //                    $transDate = new \DateTime();
  11607. //                    Inventory::addItemToInventoryCompact($em,
  11608. //                        $productionItemData->getProductId(),
  11609. //                        $productionItemData->getWarehouseId(),
  11610. //                        $productionItemData->getWarehouseId(),
  11611. //                        $productionData->getProducedItemActionTagId(),
  11612. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11613. //                        $transDate,
  11614. //                        1,
  11615. //                        1,
  11616. //                        $entry['valueAdd'],
  11617. //                        $entry['valueSub'],
  11618. //                        $entry['price'],
  11619. //                        $this->getLoggedUserCompanyId($request),
  11620. //                        0,
  11621. //                        $entry['entity'],
  11622. //                        $entry['entityId'],
  11623. //                        $entry['entityDocHash']
  11624. //                    );
  11625.                             }
  11626.                             $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  11627.                             if ($transHistory == null)
  11628.                                 $transHistory = [];
  11629.                             $transHistory[] = array(
  11630.                                 'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  11631.                                 'direction' => 'in',
  11632.                                 'warehouseId' => $productionItemData->getWarehouseId(),
  11633.                                 'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  11634.                                 'fromWarehouseId' => 0,
  11635.                                 'fromWarehouseActionId' => //stock of goods
  11636.                             );
  11637.                             $productByCodeData->setTransactionHistory(json_encode($transHistory));
  11638.                         }
  11639.                     }
  11640.                 }
  11641.             }
  11642. //                $productByCodeData->setPurchaseWarrantyLastDate($new_pwld);
  11643.             $em->flush();
  11644.             //now adding carton
  11645.         }
  11646.         if ($cartonId != '') {
  11647.             $carton $em->getRepository('ApplicationBundle:Carton')
  11648.                 ->findOneBy(
  11649.                     array(
  11650.                         'id' => $cartonId
  11651.                     )
  11652.                 );
  11653.             if ($cartonWeightGm != ''$carton->setCartonWeightGm($cartonWeightGm);
  11654.             $otherData['currentCartonCapacity'] = $carton->getCartonCapacityCount();
  11655.             if ($cartonAssignedAlready == 0)
  11656.                 $carton->setCartonAssignedCount(($carton->getCartonAssignedCount()) + 1);
  11657.             $otherData['currentCartonAssigned'] = $carton->getCartonAssignedCount();
  11658.             $otherData['currentCartonBalance'] = $otherData['currentCartonCapacity'] - $otherData['currentCartonAssigned'];
  11659.             if ($otherData['currentCartonAssigned'] >= $otherData['currentCartonCapacity'])
  11660.                 $otherData['currentCartonFull'] = 1;
  11661.             $em->flush();
  11662.         }
  11663.         if ($cartonId != '') {
  11664. //                    if($cartonAssignedAlready==1)
  11665. //                    {
  11666.             $productByCodeDataListForThisCarton $em->getRepository('ApplicationBundle:ProductByCode')
  11667.                 ->findBy(
  11668.                     array(
  11669.                         'cartonId' => $cartonId
  11670.                     )
  11671.                 );
  11672.             $carton $em->getRepository('ApplicationBundle:Carton')
  11673.                 ->findOneBy(
  11674.                     array(
  11675.                         'id' => $cartonId
  11676.                     )
  11677.                 );
  11678.             $total_carton_predicted_weight 0;
  11679.             $colorTextList = [];
  11680.             $cartonProductByCodeIds = [];
  11681.             foreach ($productByCodeDataListForThisCarton as $pikamaster) {
  11682.                 if (!in_array($pikamaster->getProductByCodeId(), $cartonProductByCodeIds))
  11683.                     $cartonProductByCodeIds[] = $pikamaster->getProductByCodeId();
  11684.                 if (!in_array($pikamaster->getColorText(), $colorTextList) && $pikamaster->getColorText() != null)
  11685.                     $colorTextList[] = $pikamaster->getColorText();
  11686.                 $total_carton_predicted_weight += ($pikamaster->getPackagedWeightGm());
  11687.                 if ($passStatus != 5)
  11688.                     if ($pikamaster->getStage() < $passStatus)
  11689.                         $pikamaster->setStage($passStatus);
  11690.             }
  11691.             if ($carton)
  11692.                 $carton->setCartonCalculatedWeightGm($total_carton_predicted_weight);
  11693.             if ($passStatus != 5)
  11694.                 $carton->setStage($passStatus);
  11695.             $carton->setColors(implode(','$colorTextList));
  11696.             $carton->setCartonProductByCodeIds(json_encode($cartonProductByCodeIds));
  11697.             $em->flush();
  11698.         }
  11699.         return new JsonResponse(array(
  11700.             'success' => true,
  11701.             'otherData' => $otherData,
  11702.         ));
  11703.     }
  11704.     public
  11705.     function RefreshCartonListAction(Request $request$id)
  11706.     {
  11707.         $em $this->getDoctrine()->getManager();
  11708. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11709.         $cartonListArray = [];
  11710.         $cartonList = [];
  11711.         $assignableCartonList = [];
  11712.         $assignableCartonListArray = [];
  11713.         $assignable 0;
  11714.         $cartonId '';
  11715.         $passStatus 5;
  11716.         $assignProductId '';
  11717.         $assignProductionId '';
  11718.         $assignProductionScheduleId '';
  11719.         if ($request->request->has('productionId'))
  11720.             $assignProductionId $request->request->get('productionId');
  11721.         if ($request->request->has('productionScheduleId'))
  11722.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  11723.         if ($request->request->has('assignable'))
  11724.             $assignable $request->request->get('assignable');
  11725.         $cartonAssignedAlready 0;
  11726.         $otherData = array(
  11727.             'currentCartonBalance' => 0,
  11728.             'currentCartonCapacity' => 0,
  11729.             'currentCartonAssigned' => 0,
  11730.             'currentCartonFull' => 0,
  11731.         );
  11732.         //1st get all cartons for this production id
  11733.         $cartonList $em->getRepository('ApplicationBundle:Carton')
  11734.             ->findBy(
  11735.                 array(
  11736. //                    'productionId' => $assignProductionId,
  11737.                     'productionScheduleId' => $assignProductionScheduleId
  11738.                 )
  11739.             );
  11740.         $foundAssignable 0;
  11741.         $setId 0;
  11742.         $lastdmySer '';
  11743.         foreach ($cartonList as $carton) {
  11744.             $cartonData = array(
  11745.                 'id' => $carton->getId(),
  11746.                 'name' => $carton->getCartonNumber(),
  11747.                 'colors' => $carton->getColors(),
  11748.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  11749.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  11750.             );
  11751.             $cartonListArray[] = $cartonData;
  11752.             $cartonList[$cartonData['id']] = $cartonData;
  11753.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  11754.                 $foundAssignable 1;
  11755.                 $setId $cartonData['id'];
  11756.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  11757.                 $assignableCartonListArray[] = $cartonData;
  11758.             }
  11759.         }
  11760.         if ($assignable == && $foundAssignable == 0) {
  11761. //            $productionData = $em->getRepository('ApplicationBundle:Production')
  11762. //                ->findOneBy(
  11763. //                    array(
  11764. //                        'productionId' => $assignProductionId
  11765. //                    )
  11766. //                );
  11767.             $productionScheduleData $em->getRepository('ApplicationBundle:ProductionSchedule')
  11768.                 ->findOneBy(
  11769.                     array(
  11770.                         'productionScheduleId' => $assignProductionScheduleId
  11771.                     )
  11772.                 );
  11773.             $productId 0;
  11774.             $product = [];
  11775.             $productModel '';
  11776.             if ($productionScheduleData)
  11777.                 $productId $productionScheduleData->getProducedProductId();
  11778. //            $productionItem = $em->getRepository('ApplicationBundle:ProductionEntryItem')
  11779. //                ->findOneBy(
  11780. //                    array(
  11781. //                        'productionId' => $assignProductionId,
  11782. //                        'type' => 1
  11783. //                    )
  11784. //                );
  11785.             if ($productId != 0) {
  11786. //                    $productId = $productionItem->getProductId();
  11787.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  11788.                     ->findOneBy(
  11789.                         array(
  11790.                             'id' => $productId,
  11791.                         )
  11792.                     );
  11793.                 $productModel $product->getModelNo();
  11794.             }
  11795.             $carton = new Carton();
  11796.             $carton_capacity $productionScheduleData->getCartonCapacity();
  11797.             $carton->setProductId($productId);
  11798.             $carton->setProductionId($assignProductionId);
  11799.             $carton->setProductionScheduleId($assignProductionScheduleId);
  11800.             if ($productionScheduleData) {
  11801.                 $carton->setCartonLabelFormatId($productionScheduleData->getCartonLabelFormatId());
  11802.             }
  11803.             $carton->setCartonCapacityCount($carton_capacity == null $carton_capacity);
  11804.             $carton->setCartonAssignedCount(0);
  11805.             $carton->setCompanyId($this->getLoggedUserCompanyId($request));
  11806.             $today = new \DateTime();
  11807.             $dmy $productModel '-' . ($today->format('m')) . '-' . ($today->format('Y')) . '-' $productionScheduleData->getBatchNumber();
  11808.             $ser 0;
  11809.             $carton->setCartonNumberDmy($dmy);
  11810.             $carton->setCartonNumberLastSer(* (($today->format('h')) . '' . ($today->format('i'))));
  11811.             $carton->setCartonNumber($dmy '-' . ($today->format('h')) . '' . ($today->format('i')));
  11812.             $em->persist($carton);
  11813.             $em->flush();
  11814.             $cartonData = array(
  11815.                 'id' => $carton->getId(),
  11816.                 'name' => $carton->getCartonNumber(),
  11817.                 'colors' => $carton->getColors(),
  11818.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  11819.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  11820.             );
  11821.             $cartonListArray[] = $cartonData;
  11822.             $cartonList[$cartonData['id']] = $cartonData;
  11823.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  11824.                 $foundAssignable 1;
  11825.                 $setId $cartonData['id'];
  11826.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  11827.                 $assignableCartonListArray[] = $cartonData;
  11828.             }
  11829.         }
  11830.         return new JsonResponse(array(
  11831.             'success' => true,
  11832.             'cartonList' => $cartonList,
  11833.             'cartonListArray' => $cartonListArray,
  11834.             'assignableCartonList' => $assignableCartonList,
  11835.             'assignableCartonListArray' => $assignableCartonListArray,
  11836.             'setId' => $setId,
  11837.         ));
  11838.     }
  11839.     public
  11840.     function PrintDrBarcodeAction(Request $request$id$item_id)
  11841.     {
  11842.         $em $this->getDoctrine()->getManager();
  11843.         $dt Inventory::GetDrDetails($em$id$item_id);
  11844.         $repeatCount 1;
  11845.         if ($request->query->has('repeatCount'))
  11846.             $repeatCount $request->query->get('repeatCount');
  11847.         $company_data Company::getCompanyData($em1);
  11848.         $document_mark = array(
  11849.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11850.             'copy' => ''
  11851.         );
  11852.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11853.             $html $this->renderView('@Inventory/pages/print/print_dr_barcodes.html.twig',
  11854.                 array(
  11855.                     //full array here
  11856.                     'pdf' => true,
  11857.                     'page_title' => 'Challan Barcodes',
  11858.                     'export' => 'print',
  11859.                     'repeatCount' => $repeatCount,
  11860.                     'item_id' => $item_id,
  11861.                     'data' => $dt,
  11862.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11863.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11864.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11865.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  11866.                         $id,
  11867.                         $dt['created_by'],
  11868.                         $dt['edited_by']),
  11869.                     'document_mark_image' => $document_mark['original'],
  11870.                     'company_name' => $company_data->getName(),
  11871.                     'company_data' => $company_data,
  11872.                     'company_address' => $company_data->getAddress(),
  11873.                     'company_image' => $company_data->getImage(),
  11874.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11875.                     'red' => 0
  11876.                 )
  11877.             );
  11878.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11879. //                'orientation' => 'landscape',
  11880.                 'enable-javascript' => true,
  11881. //                'javascript-delay' => 1000,
  11882.                 'no-stop-slow-scripts' => false,
  11883.                 'no-background' => false,
  11884.                 'lowquality' => false,
  11885.                 'encoding' => 'utf-8',
  11886. //            'images' => true,
  11887. //            'cookie' => array(),
  11888.                 'dpi' => 300,
  11889.                 'image-dpi' => 300,
  11890. //                'enable-external-links' => true,
  11891. //                'enable-internal-links' => true
  11892.             ));
  11893.             return new Response(
  11894.                 $pdf_response,
  11895.                 200,
  11896.                 array(
  11897.                     'Content-Type' => 'application/pdf',
  11898.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  11899.                 )
  11900.             );
  11901.         }
  11902.         return $this->render('@Inventory/pages/print/print_dr_barcodes.html.twig',
  11903.             array(
  11904.                 'page_title' => 'Challan barcodes',
  11905. //                'export'=>'pdf,print',
  11906.                 'data' => $dt,
  11907.                 'repeatCount' => $repeatCount,
  11908.                 'item_id' => $item_id,
  11909.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11910.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11911.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11912.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  11913.                     $id,
  11914.                     $dt['created_by'],
  11915.                     $dt['edited_by']),
  11916.                 'document_mark_image' => $document_mark['original'],
  11917.                 'company_name' => $company_data->getName(),
  11918.                 'company_data' => $company_data,
  11919.                 'company_address' => $company_data->getAddress(),
  11920.                 'company_image' => $company_data->getImage(),
  11921.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11922.                 'red' => 0
  11923.             )
  11924.         );
  11925.     }
  11926.     public
  11927.     function PrintIrrBarcodeAction(Request $request$id$item_id)
  11928.     {
  11929.         $em $this->getDoctrine()->getManager();
  11930.         $dt Inventory::GetIrrDetails($em$id$item_id);
  11931.         $repeatCount 1;
  11932.         if ($request->query->has('repeatCount'))
  11933.             $repeatCount $request->query->get('repeatCount');
  11934.         $company_data Company::getCompanyData($em1);
  11935.         $document_mark = array(
  11936.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11937.             'copy' => ''
  11938.         );
  11939.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11940.             $html $this->renderView('@Inventory/pages/print/print_irr_barcodes.html.twig',
  11941.                 array(
  11942.                     //full array here
  11943.                     'pdf' => true,
  11944.                     'page_title' => 'Sales Return Barcodes',
  11945.                     'export' => 'print',
  11946.                     'repeatCount' => $repeatCount,
  11947.                     'item_id' => $item_id,
  11948.                     'data' => $dt,
  11949.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  11950.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11951.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11952.                         array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  11953.                         $id,
  11954.                         $dt['created_by'],
  11955.                         $dt['edited_by']),
  11956.                     'document_mark_image' => $document_mark['original'],
  11957.                     'company_name' => $company_data->getName(),
  11958.                     'company_data' => $company_data,
  11959.                     'company_address' => $company_data->getAddress(),
  11960.                     'company_image' => $company_data->getImage(),
  11961.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11962.                     'red' => 0
  11963.                 )
  11964.             );
  11965.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11966. //                'orientation' => 'landscape',
  11967.                 'enable-javascript' => true,
  11968. //                'javascript-delay' => 1000,
  11969.                 'no-stop-slow-scripts' => false,
  11970.                 'no-background' => false,
  11971.                 'lowquality' => false,
  11972.                 'encoding' => 'utf-8',
  11973. //            'images' => true,
  11974. //            'cookie' => array(),
  11975.                 'dpi' => 300,
  11976.                 'image-dpi' => 300,
  11977. //                'enable-external-links' => true,
  11978. //                'enable-internal-links' => true
  11979.             ));
  11980.             return new Response(
  11981.                 $pdf_response,
  11982.                 200,
  11983.                 array(
  11984.                     'Content-Type' => 'application/pdf',
  11985.                     'Content-Disposition' => 'attachment; filename="irr_barcodes.pdf"'
  11986.                 )
  11987.             );
  11988.         }
  11989.         return $this->render('@Inventory/pages/print/print_irr_barcodes.html.twig',
  11990.             array(
  11991.                 'page_title' => 'Sales Return barcodes',
  11992. //                'export'=>'pdf,print',
  11993.                 'data' => $dt,
  11994.                 'repeatCount' => $repeatCount,
  11995.                 'item_id' => $item_id,
  11996.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  11997.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11998.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11999.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  12000.                     $id,
  12001.                     $dt['created_by'],
  12002.                     $dt['edited_by']),
  12003.                 'document_mark_image' => $document_mark['original'],
  12004.                 'company_name' => $company_data->getName(),
  12005.                 'company_data' => $company_data,
  12006.                 'company_address' => $company_data->getAddress(),
  12007.                 'company_image' => $company_data->getImage(),
  12008.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12009.                 'red' => 0
  12010.             )
  12011.         );
  12012.     }
  12013.     public
  12014.     function PrintSrcvBarcodeAction(Request $request$id$item_id)
  12015.     {
  12016.         $em $this->getDoctrine()->getManager();
  12017.         $dt Inventory::GetSrcvDetails($em$id$item_id);
  12018.         $repeatCount 1;
  12019.         if ($request->query->has('repeatCount'))
  12020.             $repeatCount $request->query->get('repeatCount');
  12021.         $company_data Company::getCompanyData($em1);
  12022.         $document_mark = array(
  12023.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12024.             'copy' => ''
  12025.         );
  12026.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12027.             $html $this->renderView('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12028.                 array(
  12029.                     //full array here
  12030.                     'pdf' => true,
  12031.                     'page_title' => 'Grn Barcodes',
  12032.                     'export' => 'print',
  12033.                     'repeatCount' => $repeatCount,
  12034.                     'item_id' => $item_id,
  12035.                     'data' => $dt,
  12036.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12037.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12038.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12039.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12040.                         $id,
  12041.                         $dt['created_by'],
  12042.                         $dt['edited_by']),
  12043.                     'document_mark_image' => $document_mark['original'],
  12044.                     'company_name' => $company_data->getName(),
  12045.                     'company_data' => $company_data,
  12046.                     'company_address' => $company_data->getAddress(),
  12047.                     'company_image' => $company_data->getImage(),
  12048.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12049.                     'red' => 0
  12050.                 )
  12051.             );
  12052.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12053. //                'orientation' => 'landscape',
  12054.                 'enable-javascript' => true,
  12055. //                'javascript-delay' => 1000,
  12056.                 'no-stop-slow-scripts' => false,
  12057.                 'no-background' => false,
  12058.                 'lowquality' => false,
  12059.                 'encoding' => 'utf-8',
  12060. //            'images' => true,
  12061. //            'cookie' => array(),
  12062.                 'dpi' => 300,
  12063.                 'image-dpi' => 300,
  12064. //                'enable-external-links' => true,
  12065. //                'enable-internal-links' => true
  12066.             ));
  12067.             return new Response(
  12068.                 $pdf_response,
  12069.                 200,
  12070.                 array(
  12071.                     'Content-Type' => 'application/pdf',
  12072.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  12073.                 )
  12074.             );
  12075.         }
  12076.         return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12077.             array(
  12078.                 'page_title' => 'Srcv barcodes',
  12079. //                'export'=>'pdf,print',
  12080.                 'data' => $dt,
  12081.                 'repeatCount' => $repeatCount,
  12082.                 'item_id' => $item_id,
  12083.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12084.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12085.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12086.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12087.                     $id,
  12088.                     $dt['created_by'],
  12089.                     $dt['edited_by']),
  12090.                 'document_mark_image' => $document_mark['original'],
  12091.                 'company_name' => $company_data->getName(),
  12092.                 'company_data' => $company_data,
  12093.                 'company_address' => $company_data->getAddress(),
  12094.                 'company_image' => $company_data->getImage(),
  12095.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12096.                 'red' => 0
  12097.             )
  12098.         );
  12099.     }
  12100. //product by code
  12101.     public
  12102.     function ImeiListExcelUploadAction(Request $request)
  12103.     {
  12104.         $lastIndex $request->request->get('lastIndex'0);
  12105.         if ($request->isMethod('POST')) {
  12106.             $post $request->request;
  12107.             if ($request->request->has('chunkData')) {
  12108.                 //now getting the relevant checks
  12109.                 $check_list = [];
  12110.                 $csv_data $request->request->get('chunkData', []);
  12111.                 $em $this->getDoctrine()->getManager();
  12112.                 foreach ($csv_data as $ind => $data_row) {
  12113. //                    if ($ind == 1)
  12114. //                        continue;
  12115.                     $np $this->getDoctrine()
  12116.                         ->getRepository('ApplicationBundle:ProductByCode')
  12117.                         ->findOneBy(
  12118.                             array(
  12119.                                 'salesCode' => isset($data_row[4]) ? $data_row[4] : 0,
  12120. //                    'approved' =>  GeneralConstant::APPROVED,
  12121.                             )
  12122.                         );
  12123.                     if (!$np)
  12124.                         $np = new ProductByCode();
  12125. //                    $np = new ProductByCode();
  12126.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  12127.                     if (isset($data_row[1])) $np->setProductId($data_row[1]);
  12128.                     if (isset($data_row[0])) $np->setLcNumber($data_row[0]);
  12129.                     if (isset($data_row[2])) $np->setCartonNumber($data_row[2]);
  12130.                     if (isset($data_row[3])) $np->setSerialNo($data_row[3]);
  12131.                     $np->setSerialAssigned(isset($data_row[10]) ? $data_row[10] : 0);
  12132.                     if (isset($data_row[4])) $np->setImei1($data_row[4]);
  12133.                     if (isset($data_row[5])) $np->setImei2($data_row[5]);
  12134.                     if (isset($data_row[6])) $np->setImei3($data_row[6]);
  12135.                     if (isset($data_row[7])) $np->setImei4($data_row[7]);
  12136.                     if (isset($data_row[8])) $np->setBtMac($data_row[8]);
  12137.                     if (isset($data_row[9])) $np->setWlanMac($data_row[9]);
  12138.                     $np->setWarehouseId(isset($data_row[11]) ? $data_row[11] : 0);
  12139.                     $np->setWarehouseActionId(isset($data_row[12]) ? $data_row[12] : 0);
  12140.                     $np->setPosition(isset($data_row[13]) ? $data_row[13] : 0);//in inventory
  12141.                     $np->setPurchaseOrderId(0);
  12142.                     $np->setGrnId(0);
  12143.                     $np->setStage(0);
  12144.                     if (isset($data_row[3])) $np->setSalesCodeRange(json_encode([$data_row[3]]));
  12145. //                $np->setSalesCode($data_row[3]);
  12146.                     if (isset($data_row[4])) $np->setSalesCode($data_row[4]); //IMEI
  12147.                     $np->setSalesCodeSer(0);
  12148.                     $np->setSalesCodeDmy('');
  12149.                     $np->setPurchaseCodeRange("");
  12150.                     $np->setPurchaseReceiptDate(null);
  12151.                     $np->setLastInDate(null);
  12152.                     $np->setStatus(GeneralConstant::ACTIVE);
  12153.                     $np->setTransactionHistory(json_encode([
  12154.                         ]
  12155.                     ));
  12156.                     $np->setPurchaseWarrantyLastDate(null);
  12157.                     $em->persist($np);
  12158.                     $em->flush();
  12159.                 }
  12160.                 return new JsonResponse(array(
  12161.                     "success" => true,
  12162.                     "lastIndex" => $lastIndex,
  12163.                     "file_path" => '',
  12164.                     "csv_data" => $csv_data,
  12165.                     //                "debug_data"=>System::encryptSignature($r)
  12166.                 ));
  12167.             } else {
  12168.                 $path "";
  12169.                 $file_path "";
  12170.                 //            var_dump($request->files);
  12171.                 //        var_dump($request->getFile());
  12172.                 foreach ($request->files as $uploadedFile) {
  12173.                     //            if($uploadedFile->getImage())
  12174.                     //                var_dump($uploadedFile->getFile());
  12175.                     //                var_dump($uploadedFile);
  12176.                     if ($uploadedFile != null) {
  12177.                         $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  12178.                         $path $fileName;
  12179.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  12180.                         if (!file_exists($upl_dir)) {
  12181.                             mkdir($upl_dir0777true);
  12182.                         }
  12183.                         $file $uploadedFile->move($upl_dir$path);
  12184.                     }
  12185.                 }
  12186.                 //        print_r($file);
  12187.                 if ($path != "")
  12188.                     $file_path 'uploads/FileUploads/' $path;
  12189.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  12190.                 //
  12191.                 //            $img_file = file_get_contents($g_path);
  12192.                 //            $r=base64_encode($img_file);
  12193.                 $row 1;
  12194.                 $csv_data = [];
  12195.                 if (($handle fopen($g_path"r")) !== FALSE) {
  12196.                     while (($data fgetcsv($handle1000",")) !== FALSE) {
  12197.                         $num count($data);
  12198.                         $csv_data[$row] = $data;
  12199.                         //                    echo "<p> $num fields in line $row: <br /></p>\n";
  12200.                         $row++;
  12201.                         //                    for ($c=0; $c < $num; $c++) {
  12202.                         //                        echo $data[$c] . "<br />\n";
  12203.                         //                    }
  12204.                     }
  12205.                     fclose($handle);
  12206.                 }
  12207.                 //now getting the relevant checks
  12208.                 $check_list = [];
  12209.                 $em $this->getDoctrine()->getManager();
  12210.                 foreach ($csv_data as $ind => $data_row) {
  12211.                     if ($ind == 1)
  12212.                         continue;
  12213.                     $np = new ProductByCode();
  12214.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  12215.                     $np->setProductId($data_row[1]);
  12216.                     $np->setLcNumber($data_row[0]);
  12217.                     $np->setCartonNumber($data_row[2]);
  12218.                     $np->setSerialNo($data_row[3]);
  12219.                     $np->setSerialAssigned(0);
  12220.                     $np->setImei1($data_row[4]);
  12221.                     $np->setImei2($data_row[5]);
  12222.                     $np->setImei3($data_row[6]);
  12223.                     $np->setImei4($data_row[7]);
  12224.                     $np->setBtMac($data_row[8]);
  12225.                     $np->setWlanMac($data_row[9]);
  12226.                     $np->setWarehouseId(0);
  12227.                     $np->setWarehouseActionId(0);
  12228.                     $np->setPosition(0);//in inventory
  12229.                     $np->setPurchaseOrderId(0);
  12230.                     $np->setGrnId(0);
  12231.                     $np->setStage(0);
  12232.                     $np->setSalesCodeRange(json_encode([$data_row[3]]));
  12233. //                $np->setSalesCode($data_row[3]);
  12234.                     $np->setSalesCode($data_row[4]); //IMEI
  12235.                     $np->setSalesCodeSer(0);
  12236.                     $np->setSalesCodeDmy('');
  12237.                     $np->setPurchaseCodeRange("");
  12238.                     $np->setPurchaseReceiptDate(null);
  12239.                     $np->setLastInDate(null);
  12240.                     $np->setStatus(GeneralConstant::ACTIVE);
  12241.                     $np->setTransactionHistory(json_encode([
  12242.                         ]
  12243.                     ));
  12244.                     $np->setPurchaseWarrantyLastDate(null);
  12245.                     $em->persist($np);
  12246.                     $em->flush();
  12247.                 }
  12248.                 return new JsonResponse(array(
  12249.                     "success" => true,
  12250.                     "lastIndex" => $lastIndex,
  12251.                     "file_path" => $file_path,
  12252.                     "csv_data" => $csv_data,
  12253.                     //                "debug_data"=>System::encryptSignature($r)
  12254.                 ));
  12255.             }
  12256.         }
  12257.         return new JsonResponse(array(
  12258.             "success" => false,
  12259.             "file_path" => '',
  12260.             "csv_data" => [],
  12261.             "lastIndex" => $lastIndex,
  12262.         ));
  12263.     }
  12264.     public
  12265.     function ProductByCodeListAction(Request $request)
  12266.     {
  12267.         $em $this->getDoctrine()->getManager();
  12268.         $companyId $this->getLoggedUserCompanyId($request);
  12269.         $listData Inventory::GetProductListForProductByCodeListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  12270.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  12271.             if ($request->query->has('dataTableQry')) {
  12272.                 return new JsonResponse(
  12273.                     $listData
  12274.                 );
  12275.             }
  12276.         }
  12277.         $q = [];
  12278. //        $q = $this->getDoctrine()
  12279. //            ->getRepository('ApplicationBundle:ProductByCode')
  12280. //            ->findBy(
  12281. //                array(
  12282. //                    'status' => GeneralConstant::ACTIVE,
  12283. ////                    'approved' =>  GeneralConstant::APPROVED,
  12284. //                )
  12285. //
  12286. //            );
  12287.         //temp start
  12288. //        foreach($q as $np) {
  12289. //            if($np->getPosition()==1) {   /// only starting ones or in warehouse ones
  12290. //                $temp_obj = json_decode($np->getTransactionHistory());
  12291. //                if ($temp_obj != null) {
  12292. //                    $transHistory = [];
  12293. //                    $transHistory[] = $temp_obj;
  12294. //                    $np->setTransactionHistory(json_encode($transHistory));
  12295. //                }
  12296. //            }
  12297. //            $em->flush();
  12298. //        }
  12299.         ///temp end
  12300.         $stage_list = array(
  12301.             => 'Pending',
  12302.             => 'Pending',
  12303.             => 'Complete',
  12304.             => 'Partial',
  12305.         );
  12306.         $data = [];
  12307. //        foreach($q as $entry)
  12308. //        {
  12309. //            $data[]=array(
  12310. //                'doc_date'=>$entry->getStockRequisitionDate(),
  12311. //                'id'=>$entry->getStockRequisitionId(),
  12312. //                'doc_hash'=>$entry->getDocumentHash(),
  12313. //                'approval_status'=>GeneralConstant::$approvalStatus[$entry->getApproved()],
  12314. //                'stage'=>$stage_list[$entry->getStage()]
  12315. //
  12316. //            );
  12317. //        }
  12318.         return $this->render('@Inventory/pages/views/product_by_code_list.html.twig',
  12319.             array(
  12320.                 'page_title' => 'Product List',
  12321.                 'data' => $q,
  12322. //                'listData' => $listData,
  12323.                 'products' => Inventory::ProductList($em),
  12324.                 'warehouseList' => Inventory::WarehouseList($em)
  12325.             )
  12326.         );
  12327.     }
  12328. //SR
  12329.     public
  12330.     function SrListAction(Request $request)
  12331.     {
  12332.         $q $this->getDoctrine()
  12333.             ->getRepository('ApplicationBundle:StockRequisition')
  12334.             ->findBy(
  12335.                 array(
  12336.                     'status' => GeneralConstant::ACTIVE,
  12337. //                    'approved' =>  GeneralConstant::APPROVED,
  12338.                 )
  12339.                 ,
  12340.                 array(
  12341.                     'stockRequisitionDate' => 'DESC'
  12342.                 )
  12343.             );
  12344.         $stage_list = array(
  12345.             => 'Pending',
  12346.             => 'Pending',
  12347.             => 'Complete',
  12348.             => 'Partial',
  12349.         );
  12350.         $data = [];
  12351.         foreach ($q as $entry) {
  12352.             $data[] = array(
  12353.                 'doc_date' => $entry->getStockRequisitionDate(),
  12354.                 'id' => $entry->getStockRequisitionId(),
  12355.                 'doc_hash' => $entry->getDocumentHash(),
  12356.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12357.                 'stage' => $stage_list[$entry->getStage()],
  12358.                 'indentTagged' => $entry->getIndentTagged(),
  12359.                 'srIds' => $entry->getSrIds(),
  12360.                 'irIds' => $entry->getIrIds(),
  12361.                 'prIds' => $entry->getPrIds(),
  12362.                 'poIds' => $entry->getPoIds(),
  12363.             );
  12364.         }
  12365.         return $this->render('@Inventory/pages/views/sr_list.html.twig',
  12366.             array(
  12367.                 'page_title' => 'Stock Requisition List',
  12368.                 'data' => $data
  12369.             )
  12370.         );
  12371.     }
  12372.     public
  12373.     function ViewSrAction(Request $request$id)
  12374.     {
  12375.         $em $this->getDoctrine()->getManager();
  12376.         $dt Inventory::GetSrDetails($em$id);
  12377.         return $this->render('@Inventory/pages/views/view_stock_requisition.html.twig',
  12378.             array(
  12379.                 'page_title' => 'Stock requisition',
  12380.                 'data' => $dt,
  12381.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12382.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12383.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12384.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12385.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12386.                     $id,
  12387.                     $dt['created_by'],
  12388.                     $dt['edited_by'])
  12389.             )
  12390.         );
  12391.     }
  12392.     public
  12393.     function PrintSrAction(Request $request$id)
  12394.     {
  12395.         $em $this->getDoctrine()->getManager();
  12396.         $dt Inventory::GetSrDetails($em$id);
  12397.         $company_data Company::getCompanyData($em1);
  12398.         $document_mark = array(
  12399.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12400.             'copy' => ''
  12401.         );
  12402.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12403.             $html $this->renderView('@Inventory/pages/print/print_sr.html.twig',
  12404.                 array(
  12405.                     //full array here
  12406.                     'pdf' => true,
  12407.                     'page_title' => 'Stock Requisition',
  12408.                     'export' => 'pdf,print',
  12409.                     'data' => $dt,
  12410.                     'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12411.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12412.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12413.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12414.                         array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12415.                         $id,
  12416.                         $dt['created_by'],
  12417.                         $dt['edited_by']),
  12418.                     'document_mark_image' => $document_mark['original'],
  12419.                     'company_name' => $company_data->getName(),
  12420.                     'company_data' => $company_data,
  12421.                     'company_address' => $company_data->getAddress(),
  12422.                     'company_image' => $company_data->getImage(),
  12423.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12424.                     'red' => 0
  12425.                 )
  12426.             );
  12427.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12428. //                'orientation' => 'landscape',
  12429. //                'enable-javascript' => true,
  12430. //                'javascript-delay' => 1000,
  12431.                 'no-stop-slow-scripts' => false,
  12432.                 'no-background' => false,
  12433.                 'lowquality' => false,
  12434.                 'encoding' => 'utf-8',
  12435. //            'images' => true,
  12436. //            'cookie' => array(),
  12437.                 'dpi' => 300,
  12438.                 'image-dpi' => 300,
  12439. //                'enable-external-links' => true,
  12440. //                'enable-internal-links' => true
  12441.             ));
  12442.             return new Response(
  12443.                 $pdf_response,
  12444.                 200,
  12445.                 array(
  12446.                     'Content-Type' => 'application/pdf',
  12447.                     'Content-Disposition' => 'attachment; filename="stock_requisition_' $id '.pdf"'
  12448.                 )
  12449.             );
  12450.         }
  12451.         return $this->render('@Inventory/pages/print/print_sr.html.twig',
  12452.             array(
  12453.                 'page_title' => 'Stock Requisition',
  12454.                 'export' => 'pdf,print',
  12455.                 'data' => $dt,
  12456.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12457.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12458.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12459.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12460.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12461.                     $id,
  12462.                     $dt['created_by'],
  12463.                     $dt['edited_by']),
  12464.                 'document_mark_image' => $document_mark['original'],
  12465.                 'company_name' => $company_data->getName(),
  12466.                 'company_data' => $company_data,
  12467.                 'company_address' => $company_data->getAddress(),
  12468.                 'company_image' => $company_data->getImage(),
  12469.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12470.                 'red' => 0
  12471.             )
  12472.         );
  12473.     }
  12474. //IR
  12475.     public
  12476.     function IrListAction(Request $request)
  12477.     {
  12478.         $q $this->getDoctrine()
  12479.             ->getRepository('ApplicationBundle:StoreRequisition')
  12480.             ->findBy(
  12481.                 array(
  12482.                     'status' => GeneralConstant::ACTIVE,
  12483. //                    'approved' =>  GeneralConstant::APPROVED,
  12484.                 ),
  12485.                 array(
  12486.                     'storeRequisitionDate' => 'DESC'
  12487.                 )
  12488.             );
  12489.         $stage_list = array(
  12490.             => 'Pending',
  12491.             => 'Pending',
  12492.             => 'Complete',
  12493.             => 'Partial',
  12494.         );
  12495.         $data = [];
  12496.         foreach ($q as $entry) {
  12497.             $data[] = array(
  12498.                 'doc_date' => $entry->getStoreRequisitionDate(),
  12499.                 'id' => $entry->getStoreRequisitionId(),
  12500.                 'doc_hash' => $entry->getDocumentHash(),
  12501.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12502.                 'stage' => $stage_list[$entry->getStage()],
  12503.                 'prTagged' => $entry->getIndentTagged(),
  12504.                 'srIds' => $entry->getSrIds(),
  12505.                 'irIds' => $entry->getIrIds(),
  12506.                 'prIds' => $entry->getPrIds(),
  12507.                 'poIds' => $entry->getPoIds(),
  12508.             );
  12509.         }
  12510.         return $this->render('@Inventory/pages/views/ir_list.html.twig',
  12511.             array(
  12512.                 'page_title' => 'Indent Requisition List',
  12513.                 'data' => $data
  12514.             )
  12515.         );
  12516.     }
  12517.     public
  12518.     function ViewIrAction(Request $request$id)
  12519.     {
  12520.         $em $this->getDoctrine()->getManager();
  12521.         $dt Inventory::GetIrDetails($em$id);
  12522.         return $this->render('@Inventory/pages/views/view_indent_requisition.html.twig',
  12523.             array(
  12524.                 'page_title' => 'Indent',
  12525.                 'data' => $dt,
  12526.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12527.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12528.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12529.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12530.                     $id,
  12531.                     $dt['created_by'],
  12532.                     $dt['edited_by'])
  12533.             )
  12534.         );
  12535.     }
  12536.     public
  12537.     function PrintIrAction(Request $request$id)
  12538.     {
  12539.         $em $this->getDoctrine()->getManager();
  12540.         $dt Inventory::GetIrDetails($em$id);
  12541.         $company_data Company::getCompanyData($em1);
  12542.         $document_mark = array(
  12543.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12544.             'copy' => ''
  12545.         );
  12546.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12547.             $html $this->renderView('@Inventory/pages/print/print_ir.html.twig',
  12548.                 array(
  12549.                     //full array here
  12550.                     'pdf' => true,
  12551.                     'page_title' => 'Indent Requisition',
  12552.                     'export' => 'pdf,print',
  12553.                     'data' => $dt,
  12554.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12555.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12556.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12557.                         array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12558.                         $id,
  12559.                         $dt['created_by'],
  12560.                         $dt['edited_by']),
  12561.                     'document_mark_image' => $document_mark['original'],
  12562.                     'company_name' => $company_data->getName(),
  12563.                     'company_data' => $company_data,
  12564.                     'company_address' => $company_data->getAddress(),
  12565.                     'company_image' => $company_data->getImage(),
  12566.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12567.                     'red' => 0
  12568.                 )
  12569.             );
  12570.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12571. //                'orientation' => 'landscape',
  12572. //                'enable-javascript' => true,
  12573. //                'javascript-delay' => 1000,
  12574.                 'no-stop-slow-scripts' => false,
  12575.                 'no-background' => false,
  12576.                 'lowquality' => false,
  12577.                 'encoding' => 'utf-8',
  12578. //            'images' => true,
  12579. //            'cookie' => array(),
  12580.                 'dpi' => 300,
  12581.                 'image-dpi' => 300,
  12582. //                'enable-external-links' => true,
  12583. //                'enable-internal-links' => true
  12584.             ));
  12585.             return new Response(
  12586.                 $pdf_response,
  12587.                 200,
  12588.                 array(
  12589.                     'Content-Type' => 'application/pdf',
  12590.                     'Content-Disposition' => 'attachment; filename="indent_' $id '.pdf"'
  12591.                 )
  12592.             );
  12593.         }
  12594.         return $this->render('@Inventory/pages/print/print_ir.html.twig',
  12595.             array(
  12596.                 'page_title' => 'Indent Requisition',
  12597.                 'export' => 'pdf,print',
  12598.                 'data' => $dt,
  12599.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12600.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12601.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12602.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12603.                     $id,
  12604.                     $dt['created_by'],
  12605.                     $dt['edited_by']),
  12606.                 'document_mark_image' => $document_mark['original'],
  12607.                 'company_name' => $company_data->getName(),
  12608.                 'company_data' => $company_data,
  12609.                 'company_address' => $company_data->getAddress(),
  12610.                 'company_image' => $company_data->getImage(),
  12611.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12612.                 'red' => 0
  12613.             )
  12614.         );
  12615.     }
  12616. //PR
  12617.     public
  12618.     function PrListAction(Request $request)
  12619.     {
  12620.         $q $this->getDoctrine()
  12621.             ->getRepository('ApplicationBundle:PurchaseRequisition')
  12622.             ->findBy(
  12623.                 array(
  12624.                     'status' => GeneralConstant::ACTIVE,
  12625. //                    'approved' =>  GeneralConstant::APPROVED,
  12626.                 ),
  12627.                 array(
  12628.                     'purchaseRequisitionDate' => 'DESC'
  12629.                 )
  12630.             );
  12631.         $stage_list = array(
  12632.             => 'Pending',
  12633.             => 'Pending',
  12634.             => 'Complete',
  12635.             => 'Partial',
  12636.         );
  12637.         $data = [];
  12638.         foreach ($q as $entry) {
  12639.             $data[] = array(
  12640.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  12641.                 'id' => $entry->getPurchaseRequisitionId(),
  12642.                 'doc_hash' => $entry->getDocumentHash(),
  12643.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12644.                 'acquisition_status' => $entry->getAcquisitionStatus(),
  12645.                 'acquisition_start_date' => $entry->getAcquisitionStartDate(),
  12646.                 'acquisition_end_date' => $entry->getAcquisitionEndDate(),
  12647.                 'acquisition_method' => $entry->getquotationAcquisitionMethod(),
  12648.                 'poTagged' => $entry->getPoTagged(),
  12649.                 'typeHash' => $entry->getTypehash(),
  12650.                 'srIds' => $entry->getSrIds(),
  12651.                 'irIds' => $entry->getIrIds(),
  12652.                 'prIds' => $entry->getPrIds(),
  12653.                 'poIds' => $entry->getPoIds(),
  12654.             );
  12655.         }
  12656.         return $this->render('@Inventory/pages/views/pr_list.html.twig',
  12657.             array(
  12658.                 'page_title' => 'Purchase Requisition List',
  12659.                 'data' => $data
  12660.             )
  12661.         );
  12662.     }
  12663.     public
  12664.     function ServiceRequisitionListAction(Request $request)
  12665.     {
  12666.         $q $this->getDoctrine()
  12667.             ->getRepository('ApplicationBundle:PurchaseRequisition')
  12668.             ->findBy(
  12669.                 array(
  12670.                     'status' => GeneralConstant::ACTIVE,
  12671. //                    'approved' =>  GeneralConstant::APPROVED,
  12672.                 ),
  12673.                 array(
  12674.                     'purchaseRequisitionDate' => 'DESC'
  12675.                 )
  12676.             );
  12677.         $stage_list = array(
  12678.             => 'Pending',
  12679.             => 'Pending',
  12680.             => 'Complete',
  12681.             => 'Partial',
  12682.         );
  12683.         $data = [];
  12684.         foreach ($q as $entry) {
  12685.             $data[] = array(
  12686.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  12687.                 'id' => $entry->getPurchaseRequisitionId(),
  12688.                 'doc_hash' => $entry->getDocumentHash(),
  12689.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12690.                 'poTagged' => $entry->getPoTagged(),
  12691.                 'typeHash' => $entry->getTypehash(),
  12692.                 'srIds' => $entry->getSrIds(),
  12693.                 'irIds' => $entry->getIrIds(),
  12694.                 'prIds' => $entry->getPrIds(),
  12695.                 'poIds' => $entry->getPoIds(),
  12696.             );
  12697.         }
  12698.         return $this->render('@Inventory/pages/views/service_requisition_list.html.twig',
  12699.             array(
  12700.                 'page_title' => 'Service Requisition List',
  12701.                 'data' => $data
  12702.             )
  12703.         );
  12704.     }
  12705.     public
  12706.     function ViewPrAction(Request $request$id)
  12707.     {
  12708.         $em $this->getDoctrine()->getManager();
  12709.         $dt Inventory::GetPrDetails($em$id);
  12710.         $companyId $this->getLoggedUserCompanyId($request);
  12711.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  12712.             array(
  12713.                 'page_title' => 'Purchase Requisition',
  12714.                 'data' => $dt,
  12715.                 'branchList' => Client::BranchList($em$companyId),
  12716.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12717.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12718.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12719.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12720.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12721.                     $id,
  12722.                     $dt['created_by'],
  12723.                     $dt['edited_by'])
  12724.             )
  12725.         );
  12726.     }
  12727.     public
  12728.     function ViewServiceRequisitionAction(Request $request$id)
  12729.     {
  12730.         $em $this->getDoctrine()->getManager();
  12731.         $dt Inventory::GetPrDetails($em$id);
  12732.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  12733.             array(
  12734.                 'page_title' => 'Service Requisition',
  12735.                 'data' => $dt,
  12736.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12737.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12738.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12739.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12740.                     $id,
  12741.                     $dt['created_by'],
  12742.                     $dt['edited_by'])
  12743.             )
  12744.         );
  12745.     }
  12746.     public
  12747.     function PrintPrAction(Request $request$id)
  12748.     {
  12749.         $em $this->getDoctrine()->getManager();
  12750.         $dt Inventory::GetPrDetails($em$id);
  12751.         $companyId $this->getLoggedUserCompanyId($request);
  12752.         $company_data Company::getCompanyData($em$companyId);
  12753.         $document_mark = array(
  12754.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12755.             'copy' => ''
  12756.         );
  12757.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12758.             $html $this->renderView('@Inventory/pages/print/print_pr.html.twig',
  12759.                 array(
  12760.                     //full array here
  12761.                     'pdf' => true,
  12762.                     'page_title' => 'Purchase Requisition',
  12763.                     'export' => 'pdf,print',
  12764.                     'data' => $dt,
  12765.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12766.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12767.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12768.                         array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12769.                         $id,
  12770.                         $dt['created_by'],
  12771.                         $dt['edited_by']),
  12772.                     'document_mark_image' => $document_mark['original'],
  12773.                     'branchList' => Client::BranchList($em$companyId),
  12774.                     'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12775.                     'company_name' => $company_data->getName(),
  12776.                     'company_data' => $company_data,
  12777.                     'company_address' => $company_data->getAddress(),
  12778.                     'company_image' => $company_data->getImage(),
  12779.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12780.                     'red' => 0
  12781.                 )
  12782.             );
  12783.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12784. //                'orientation' => 'landscape',
  12785. //                'enable-javascript' => true,
  12786. //                'javascript-delay' => 1000,
  12787.                 'no-stop-slow-scripts' => false,
  12788.                 'no-background' => false,
  12789.                 'lowquality' => false,
  12790.                 'encoding' => 'utf-8',
  12791. //            'images' => true,
  12792. //            'cookie' => array(),
  12793.                 'dpi' => 300,
  12794.                 'image-dpi' => 300,
  12795. //                'enable-external-links' => true,
  12796. //                'enable-internal-links' => true
  12797.             ));
  12798.             return new Response(
  12799.                 $pdf_response,
  12800.                 200,
  12801.                 array(
  12802.                     'Content-Type' => 'application/pdf',
  12803.                     'Content-Disposition' => 'attachment; filename="purchase_requisition_' $id '.pdf"'
  12804.                 )
  12805.             );
  12806.         }
  12807.         return $this->render('@Inventory/pages/print/print_pr.html.twig',
  12808.             array(
  12809.                 'page_title' => 'Purchase Requisition',
  12810.                 'export' => 'pdf,print',
  12811.                 'data' => $dt,
  12812.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12813.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12814.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12815.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12816.                     $id,
  12817.                     $dt['created_by'],
  12818.                     $dt['edited_by']),
  12819.                 'document_mark_image' => $document_mark['original'],
  12820.                 'company_name' => $company_data->getName(),
  12821.                 'company_data' => $company_data,
  12822.                 'branchList' => Client::BranchList($em$companyId),
  12823.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12824.                 'company_address' => $company_data->getAddress(),
  12825.                 'company_image' => $company_data->getImage(),
  12826.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12827.                 'red' => 0
  12828.             )
  12829.         );
  12830.     }
  12831.     public
  12832.     function CreateSecondaryDeliveryReceiptAction(Request $request)
  12833.     {
  12834.         $em $this->getDoctrine()->getManager();
  12835.         $companyId $this->getLoggedUserCompanyId($request);
  12836.         $userBranchIdList $request->getSession()->get('branchIdList');
  12837.         if ($userBranchIdList == null$userBranchIdList = [];
  12838.         $userBranchId $request->getSession()->get('branchId');
  12839.         if ($request->isMethod('POST')) {
  12840.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  12841.             $dochash $request->request->get('docHash'); //change
  12842.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12843.             $approveRole 1;  //created
  12844.             $approveHash $request->request->get('approvalHash');
  12845.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  12846.                 $loginId$approveRole$approveHash)
  12847.             ) {
  12848.                 $this->addFlash(
  12849.                     'error',
  12850.                     'Sorry Couldnot insert Data.'
  12851.                 );
  12852.             } else {
  12853.                 $receiptId SalesOrderM::CreateNewSecondaryDeliveryReceipt($this->getDoctrine()->getManager(), $request->request,
  12854.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  12855.                     $this->getLoggedUserCompanyId($request));
  12856.                 //now add Approval info
  12857.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12858.                 $approveRole 1;  //created
  12859.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12860.                     $receiptId,
  12861.                     $loginId,
  12862.                     $approveRole,
  12863.                     $request->request->get('approvalHash'));
  12864.                 $options = array(
  12865.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  12866.                     'notification_server' => $this->container->getParameter('notification_server'),
  12867.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  12868.                     'url' => $this->generateUrl(
  12869.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  12870.                         ['entity_view_route_path_name']
  12871.                     )
  12872.                 );
  12873.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  12874.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12875.                     $receiptId,
  12876.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  12877.                 );
  12878.                 $this->addFlash(
  12879.                     'success',
  12880.                     'New Delivery Receipt Created'
  12881.                 );
  12882.                 $url $this->generateUrl(
  12883.                     'view_delivery_receipt'
  12884.                 );
  12885.                 return $this->redirect($url "/" $receiptId);
  12886.             }
  12887.         }
  12888.         $debugData = [];
  12889. //        $dr_data=$em->getRepository('ApplicationBundle:DeliveryReceipt')->findOneBy(
  12890. //            array(
  12891. //                'deliveryReceiptId'=>$dr_id
  12892. //            )
  12893. //        );
  12894.         $new_swld = new \DateTime('2017-07-09');
  12895. //        if ($entry->getWarranty() > 0)
  12896. //            $new_swld->modify('+' . $entry->getWarranty() . ' month');
  12897.         $debugData[] = $new_swld->format('Y-m-d');
  12898.         $debugData[] = $new_swld;
  12899. //        $debugData[]=$dr_data->getDeliveryReceiptDate();
  12900.         $debugData[] = '+' '1' ' month';
  12901.         $branchList Client::BranchList($em$companyId, [], $userBranchIdList);
  12902.         $warehouseIds = [];
  12903.         foreach ($branchList as $br) {
  12904.             $warehouseIds[] = $br['warehouseId'];
  12905.         }
  12906.         return $this->render('@Inventory/pages/input_forms/secondaryDeliveryReceipt.html.twig',
  12907.             array(
  12908.                 'page_title' => 'New Delivery Receipt',
  12909.                 'ExistingClients' => Accounts::getClientLedgerHeads($em),
  12910.                 'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($em),
  12911.                 'ClientList' => SalesOrderM::GetSecondaryClientList($em),
  12912.                 'warehouse' => Inventory::WarehouseList($em$companyId$warehouseIds),
  12913.                 'salesOrders' => SalesOrderM::SecondarySalesOrderListPendingDelivery($em$warehouseIds),
  12914.                 'salesOrdersArray' => SalesOrderM::SecondarySalesOrderListPendingDeliveryArray($em$warehouseIds),
  12915.                 'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
  12916.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
  12917.                 'debugData' => $debugData,
  12918.             )
  12919.         );
  12920.     }
  12921.     public
  12922.     function AddUnitTypeAction(Request $request$id 0)
  12923.     {
  12924.         $em $this->getDoctrine()->getManager();
  12925.         $companyId $this->getLoggedUserCompanyId($request);
  12926.         if ($request->isMethod('POST')) {
  12927.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12928.             $unitType = new UnitType();
  12929.             $unitType->setName($request->request->get('name'));
  12930.             $unitType->setStatus(1);
  12931.             $em->persist($unitType);
  12932.             $em->flush();
  12933.             $this->addFlash(
  12934.                 'success',
  12935.                 'Unit Type Added'
  12936.             );
  12937.         }
  12938.         $unitTypeDeatails $em->getRepository(UnitType::class)->findAll();
  12939.         return $this->render('@Inventory/pages/input_forms/addUnitType.html.twig',
  12940.             array(
  12941.                 'page_title' => 'Add Unit Type',
  12942.                 'unitTypeDeatails' => $unitTypeDeatails
  12943.             )
  12944.         );
  12945.     }
  12946.     public function AddSpecTypeAction(Request $request$id 0)
  12947.     {
  12948.         $em $this->getDoctrine()->getManager();
  12949.         $companyId $this->getLoggedUserCompanyId($request);
  12950.         if ($request->isMethod('POST')) {
  12951.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12952.             $specType = new SpecType();
  12953.             $specType->setName($request->request->get('name'));
  12954.             $specType->setStatus(1);
  12955.             $em->persist($specType);
  12956.             $em->flush();
  12957.             $this->addFlash(
  12958.                 'success',
  12959.                 'Spec Type Added'
  12960.             );
  12961.         }
  12962.         $specTypeDeatails $em->getRepository(SpecType::class)->findAll();
  12963.         return $this->render('@Inventory/pages/input_forms/addSpecType.html.twig',
  12964.             array(
  12965.                 'page_title' => 'Add Spec Type',
  12966.                 'specTypeDeatails' => $specTypeDeatails
  12967.             )
  12968.         );
  12969.     }
  12970.     public
  12971.     function SubcategoryListAction()
  12972.     {
  12973.         return $this->render('@Inventory/pages/input_forms/subCategoryList.html.twig',
  12974.             array(
  12975.                 'page_title' => 'Sub Category List',
  12976.             )
  12977.         );
  12978.     }
  12979.     public function SyncProductAction(Request $request$id)
  12980.     {
  12981.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  12982.         $em_local $this->getDoctrine()->getManager();
  12983.         if ($systemType == '_ERP_') {
  12984.             $product $em_local->getRepository('ApplicationBundle:InvProducts')->find($id);
  12985.             if (!$product) {
  12986.                 return new JsonResponse(['error' => 'Product not found'], 404);
  12987.             }
  12988.             // Get category details
  12989.             $category $em_local->getRepository('ApplicationBundle:InvProductCategories')->find($product->getCategoryId());
  12990.             $brand $em_local -> getRepository('ApplicationBundle:BrandCompany')->find($product->getBrandCompany());
  12991.             $productData = [];
  12992.             $categoryData = [];
  12993.             $brandData = [];
  12994.             // Get product fields
  12995.             $reflectionClass = new \ReflectionClass($product);
  12996.             foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  12997.                 if (strpos($method->getName(), 'get') === 0) {
  12998.                     $property lcfirst(str_replace('get'''$method->getName()));
  12999.                     $productData[$property] = $method->invoke($product);
  13000.                 }
  13001.             }
  13002.             // Get category fields
  13003.             if ($category) {
  13004.                 $categoryReflection = new \ReflectionClass($category);
  13005.                 foreach ($categoryReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  13006.                     if (strpos($method->getName(), 'get') === 0) {
  13007.                         $property lcfirst(str_replace('get'''$method->getName()));
  13008.                         $categoryData[$property] = $method->invoke($category);
  13009.                     }
  13010.                 }
  13011.             }
  13012.             // Brand data
  13013.             if ($brand) {
  13014.                 $brandReflection = new \ReflectionClass($brand);
  13015.                 foreach ($brandReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  13016.                     if (strpos($method->getName(), 'get') === 0) {
  13017.                         $property lcfirst(str_replace('get'''$method->getName()));
  13018.                         $brandData[$property] = $method->invoke($brand);
  13019.                     }
  13020.                 }
  13021.             }
  13022.             // Store product data in pending_data
  13023.             $product->setPendingData(json_encode($productData));
  13024.             $em_local->flush();
  13025.             // Send  product,brand & category to central
  13026.             $syncData = [
  13027.                 'product' => $productData,
  13028.                 'category' => $categoryData,
  13029.                 'brand' => $brandData
  13030.             ];
  13031.             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/product_sync/' $id;
  13032.             $curl curl_init();
  13033.             curl_setopt_array($curl, [
  13034.                 CURLOPT_RETURNTRANSFER => true,
  13035.                 CURLOPT_POST => true,
  13036.                 CURLOPT_URL => $urlToCall,
  13037.                 CURLOPT_CONNECTTIMEOUT => 10,
  13038.                 CURLOPT_SSL_VERIFYPEER => false,
  13039.                 CURLOPT_SSL_VERIFYHOST => false,
  13040.                 CURLOPT_HTTPHEADER => [],
  13041.                 CURLOPT_POSTFIELDS => ['syncData' => json_encode($syncData)]
  13042.             ]);
  13043.             $retData curl_exec($curl);
  13044.             $errData curl_error($curl);
  13045.             curl_close($curl);
  13046.             if ($errData) {
  13047.                 return new JsonResponse(['error' => $errData], 500);
  13048.             }
  13049.             $retDataObj json_decode($retDatatrue);
  13050.             if (isset($retDataObj['globalId'])) {
  13051.                 $product->setGlobalId($retDataObj['globalId']);
  13052.                 $em_local->flush();
  13053.             }
  13054.             return new JsonResponse(['message' => 'Product (pending) and category synced to central server!']);
  13055.         }
  13056.         // CENTRAL SYSTEM PROCESSING
  13057.         else if ($systemType == '_CENTRAL_') {
  13058.             $requestData $request->get('syncData');
  13059.             if (!$requestData) {
  13060.                 return new JsonResponse(['error' => 'Invalid data received'], 400);
  13061.             }
  13062.             $requestData json_decode($requestDatatrue);
  13063.             $productData $requestData['product'] ?? null;
  13064.             $categoryData $requestData['category'] ?? null;
  13065.             $brandData $requestData['brand'] ?? null;
  13066.             if (!$productData) {
  13067.                 return new JsonResponse(['error' => 'Product data missing'], 400);
  13068.             }
  13069.             // Process product (Store in pending_data)
  13070.             $product $em_local->getRepository('ApplicationBundle:InvProducts')->find($productData['id']) ?? new InvProducts();
  13071.             // Store in pending_data until approval
  13072.             $product->setPendingData(json_encode($productData));
  13073.             $this->ApproveProductAction($id);
  13074.             $em_local->persist($product);
  13075.             // Process category (Save directly)
  13076.             if ($categoryData) {
  13077.                 $category $em_local->getRepository('ApplicationBundle:InvProductCategories')->find($categoryData['id']) ?? new InvProductCategories();
  13078.                 foreach ($categoryData as $field => $value) {
  13079.                     if ($field === 'id') continue;
  13080.                     $setterMethod 'set' ucfirst($field);
  13081.                     if (method_exists($category$setterMethod)) {
  13082.                         $category->$setterMethod($value);
  13083.                     }
  13084.                 }
  13085.                 $em_local->persist($category);
  13086.             }
  13087.             // process brand data
  13088.             if($brandData){
  13089.                 $brand $em_local->getRepository('ApplicationBundle:BrandCompany')->find($brandData['id']) ?? new BrandCompany();
  13090.                 foreach ($brandData as $field => $value){
  13091.                     if($field === 'id') continue;
  13092.                     $setterMethod 'set'.ucfirst($field);
  13093.                     if(method_exists($brand,$setterMethod)){
  13094.                         $brand->$setterMethod($value);
  13095.                     }
  13096.                 }
  13097.                 $em_local->persist($brand);
  13098.             }
  13099.             $em_local->flush();
  13100.             return new JsonResponse(['globalId' => $product->getId()]);
  13101.         }
  13102.         return new JsonResponse("Product (pending) and category updated successfully in central!");
  13103.     }
  13104.     public function ApproveProductAction($id)
  13105.     {
  13106.         $em $this->getDoctrine()->getManager();
  13107.         $product $em->getRepository('ApplicationBundle:InvProducts')->find($id);
  13108.         if (!$product) {
  13109.             return new JsonResponse(['error' => 'Product not found'], 404);
  13110.         }
  13111.         $pendingData $product->getPendingData();
  13112.         if (!$pendingData) {
  13113.             return new JsonResponse(['error' => 'No pending data found for this product'], 400);
  13114.         }
  13115.         $data json_decode($pendingDatatrue);
  13116.         if (!$data || !is_array($data)) {
  13117.             return new JsonResponse(['error' => 'Invalid pending data format'], 400);
  13118.         }
  13119.         // Populate actual fields
  13120.         foreach ($data as $field => $value) {
  13121.             if ($field === 'id') continue; // Skip ID
  13122.             $setter 'set' ucfirst($field);
  13123.             if (method_exists($product$setter)) {
  13124.                 $product->$setter($value);
  13125.             }
  13126.         }
  13127.         $product->setPendingData(null); // Clear pending data
  13128.         $em->flush();
  13129.         return new JsonResponse(['message' => 'Product approved and data applied successfully!']);
  13130.     }
  13131. }