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

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Modules\Inventory\Controller;
  3. use ApplicationBundle\Constants\AccountsConstant;
  4. use ApplicationBundle\Constants\GeneralConstant;
  5. use ApplicationBundle\Constants\HumanResourceConstant;
  6. use ApplicationBundle\Constants\InventoryConstant;
  7. use ApplicationBundle\Constants\LabelConstant;
  8. use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
  9. use ApplicationBundle\Modules\Api\Constants\ApiConstants;
  10. use ApplicationBundle\Controller\GenericController;
  11. use ApplicationBundle\Entity\Carton;
  12. use ApplicationBundle\Entity\InvItemInOut;
  13. use ApplicationBundle\Entity\StockReceivedNote;
  14. use ApplicationBundle\Entity\ProductByCode;
  15. use ApplicationBundle\Entity\StockReceivedNoteItem;
  16. use ApplicationBundle\Entity\ConsumptionType;
  17. use ApplicationBundle\Entity\LabelFormat;
  18. use ApplicationBundle\Entity\Currencies;
  19. use ApplicationBundle\Entity\UnitType;
  20. use ApplicationBundle\Entity\SpecType;
  21. use ApplicationBundle\Entity\EmployeeAttendance;
  22. use ApplicationBundle\Entity\EmployeeAttendanceLog;
  23. use ApplicationBundle\Modules\Project\ProjectM;
  24. use ApplicationBundle\Modules\Sales\Client;
  25. use ApplicationBundle\Modules\User\Users;
  26. use ApplicationBundle\Constants\ProjectConstant;
  27. use ApplicationBundle\Interfaces\SessionCheckInterface;
  28. use ApplicationBundle\Entity\InvProductCategories;
  29. use ApplicationBundle\Helper\Generic;
  30. use ApplicationBundle\Modules\Accounts\Accounts;
  31. use ApplicationBundle\Modules\Inventory\Inventory;
  32. use ApplicationBundle\Modules\Purchase\Purchase;
  33. use ApplicationBundle\Modules\Sales\SalesOrderM;
  34. use ApplicationBundle\Modules\Production\ProductionM;
  35. use ApplicationBundle\Modules\System\System;
  36. use ApplicationBundle\Modules\HumanResource\HumanResource;
  37. use ApplicationBundle\Modules\Purchase\Supplier;
  38. use ApplicationBundle\Modules\System\DeleteDocument;
  39. use ApplicationBundle\Modules\System\DocValidation;
  40. use ApplicationBundle\Modules\System\MiscActions;
  41. use ApplicationBundle\Modules\User\Company;
  42. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  43. use Symfony\Component\HttpFoundation\JsonResponse;
  44. use Symfony\Component\HttpFoundation\Request;
  45. use Symfony\Component\HttpFoundation\Response;
  46. use Symfony\Component\Routing\Generator\UrlGenerator;
  47. class InventoryController extends GenericController implements SessionCheckInterface
  48. {
  49.     private function getProductDependencyRows($em$parentProductId)
  50.     {
  51.         $rows = array();
  52.         $dependencies $em->getRepository('ApplicationBundle\\Entity\\InvProductDependencies')->findBy(
  53.             array(
  54.                 'parentProductId' => $parentProductId,
  55.             ),
  56.             array(
  57.                 'id' => 'ASC',
  58.             )
  59.         );
  60.         foreach ($dependencies as $dependency) {
  61.             $childProduct $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($dependency->getChildProductId());
  62.             $rows[] = array(
  63.                 'id' => $dependency->getId(),
  64.                 'parentProductId' => $dependency->getParentProductId(),
  65.                 'childProductId' => $dependency->getChildProductId(),
  66.                 'childProductName' => $childProduct $childProduct->getName() : '',
  67.                 'qty' => $dependency->getQty(),
  68.                 'repeatationThreshold' => $dependency->getRepeatationThreshold(),
  69.                 'repeatQty' => $dependency->getRepeatQty(),
  70.                 'required' => $dependency->getRequired() ? 0,
  71.                 'fdm' => $dependency->getFdm(),
  72.             );
  73.         }
  74.         return $rows;
  75.     }
  76.     private function saveProductDependencies($em$parentProductId$dependencies)
  77.     {
  78.         $parentProductId = (int) $parentProductId;
  79.         if ($parentProductId <= 0) {
  80.             return;
  81.         }
  82.         if (!is_array($dependencies)) {
  83.             $dependencies = array();
  84.         }
  85.         $connection $em->getConnection();
  86.         $connection->beginTransaction();
  87.         try {
  88.             $em->createQuery(
  89.                 'DELETE FROM ApplicationBundle\\Entity\\InvProductDependencies d WHERE d.parentProductId = :parentProductId'
  90.             )->setParameter('parentProductId'$parentProductId)->execute();
  91.             foreach ($dependencies as $dependencyRow) {
  92.                 if (!is_array($dependencyRow)) {
  93.                     continue;
  94.                 }
  95.                 $childProductId = (int) (
  96.                     $dependencyRow['child_product_id']
  97.                     ?? $dependencyRow['childProductId']
  98.                     ?? $dependencyRow['child_product']
  99.                     ?? $dependencyRow['childProduct']
  100.                     ?? 0
  101.                 );
  102.                 if ($childProductId <= || $childProductId === $parentProductId) {
  103.                     continue;
  104.                 }
  105.                 $qty = isset($dependencyRow['qty']) ? (float) $dependencyRow['qty'] : 0;
  106.                 if ($qty <= 0) {
  107.                     continue;
  108.                 }
  109.                 $repeatationThreshold = isset($dependencyRow['repeatation_threshold'])
  110.                     ? (int) $dependencyRow['repeatation_threshold']
  111.                     : (isset($dependencyRow['repeatationThreshold']) ? (int) $dependencyRow['repeatationThreshold'] : 1);
  112.                 if ($repeatationThreshold <= 0) {
  113.                     $repeatationThreshold 1;
  114.                 }
  115.                 $repeatQtyRaw $dependencyRow['repeat_qty'] ?? $dependencyRow['repeatQty'] ?? null;
  116.                 $repeatQty = ($repeatQtyRaw === '' || $repeatQtyRaw === null) ? null : (float) $repeatQtyRaw;
  117.                 $required $dependencyRow['required'] ?? 1;
  118.                 $required = ($required === '0' || $required === || $required === false || $required === 'false') ? 1;
  119.                 $fdm trim((string) ($dependencyRow['fdm'] ?? ''));
  120.                 if ($fdm === '') {
  121.                     $fdm null;
  122.                 }
  123.                 $dependency = new \ApplicationBundle\Entity\InvProductDependencies();
  124.                 $dependency->setParentProductId($parentProductId);
  125.                 $dependency->setChildProductId($childProductId);
  126.                 $dependency->setQty($qty);
  127.                 $dependency->setRepeatationThreshold($repeatationThreshold);
  128.                 $dependency->setRepeatQty($repeatQty);
  129.                 $dependency->setRequired($required);
  130.                 $dependency->setFdm($fdm);
  131.                 $em->persist($dependency);
  132.             }
  133.             $em->flush();
  134.             $connection->commit();
  135.         } catch (\Exception $e) {
  136.             if ($connection->isTransactionActive()) {
  137.                 $connection->rollBack();
  138.             }
  139.             throw $e;
  140.         }
  141.     }
  142.     private function normalizeSqlIntList($values): array
  143.     {
  144.         $normalized = array();
  145.         foreach ((array) $values as $value) {
  146.             if ($value === '' || $value === null) {
  147.                 continue;
  148.             }
  149.             if (is_numeric($value)) {
  150.                 $normalized[] = (int) $value;
  151.             }
  152.         }
  153.         return $normalized;
  154.     }
  155.     private function buildNamedInClause(array $valuesstring $paramPrefix, array &$params): string
  156.     {
  157.         $placeholders = array();
  158.         foreach ($values as $index => $value) {
  159.             $paramName $paramPrefix $index;
  160.             $placeholders[] = ':' $paramName;
  161.             $params[$paramName] = $value;
  162.         }
  163.         return implode(', '$placeholders);
  164.     }
  165.     private function buildTokenizedLikeSearchFragment(array $fields, array $queryGroupsstring $outerOperatorstring $paramPrefix): array
  166.     {
  167.         $fragment ' ';
  168.         $params = array();
  169.         $paramIndex 0;
  170.         foreach ($fields as $field) {
  171.             if (empty($queryGroups)) {
  172.                 continue;
  173.             }
  174.             $fragment .= ' ' $outerOperator ' ( ';
  175.             foreach ($queryGroups as $queryGroup) {
  176.                 $terms preg_split('/\s+/'trim((string) $queryGroup));
  177.                 $terms array_values(array_filter($terms, static function ($term) {
  178.                     return $term !== '';
  179.                 }));
  180.                 if (empty($terms)) {
  181.                     continue;
  182.                 }
  183.                 $fragment .= '( ';
  184.                 $andNeeded 0;
  185.                 foreach ($terms as $term) {
  186.                     if ($andNeeded === 1) {
  187.                         $fragment .= ' and ';
  188.                     }
  189.                     $paramName $paramPrefix $paramIndex++;
  190.                     $fragment .= ' ' $field ' like :' $paramName ' ';
  191.                     $params[$paramName] = '%' $term '%';
  192.                     $andNeeded 1;
  193.                 }
  194.                 $fragment .= ') or ';
  195.             }
  196.             $fragment .= ' 1=0 ) ';
  197.         }
  198.         return array($fragment$params);
  199.     }
  200.     private function buildFlatLikeSearchFragment(array $fields, array $valuesstring $outerOperatorstring $paramPrefix): array
  201.     {
  202.         $fragment ' ';
  203.         $params = array();
  204.         $paramIndex 0;
  205.         foreach ($fields as $field) {
  206.             $sanitizedValues array_values(array_filter(array_map('trim', (array) $values), static function ($value) {
  207.                 return $value !== '';
  208.             }));
  209.             if (empty($sanitizedValues)) {
  210.                 continue;
  211.             }
  212.             $fragment .= ' ' $outerOperator ' ( 1=0 ';
  213.             foreach ($sanitizedValues as $value) {
  214.                 $paramName $paramPrefix $paramIndex++;
  215.                 $fragment .= ' or ' $field ' like :' $paramName ' ';
  216.                 $params[$paramName] = '%' $value '%';
  217.             }
  218.             $fragment .= ' ) ';
  219.         }
  220.         return array($fragment$params);
  221.     }
  222.     private function buildConjunctiveLikeFragment(string $column, array $valuesstring $paramPrefix): array
  223.     {
  224.         $fragment '';
  225.         $params = array();
  226.         if (!empty($values)) {
  227.             $fragment .= ' and ( ';
  228.             foreach (array_values($values) as $index => $value) {
  229.                 $paramName $paramPrefix $index;
  230.                 $fragment .= ' ' $column ' like :' $paramName ' and';
  231.                 $params[$paramName] = '%' $value '%';
  232.             }
  233.             $fragment .= ' 1=1 ) ';
  234.         }
  235.         return array($fragment$params);
  236.     }
  237.     public function GetInitialDataForProductSelectVendorAppAction(Request $request)
  238.     {
  239.         $em $this->getDoctrine()->getManager();
  240.         $em_goc $this->getDoctrine()->getManager('company_group');
  241.         $session $request->getSession();
  242.         $companyId $this->getLoggedUserCompanyId($request);
  243.         $userRestrictions = [];
  244.         $selectiveDocumentsFlag 0;
  245.         $allowedLoginIds = [];
  246. //        $salesPersonList = Client::SalesPersonList($this->getDoctrine()->getManager());
  247. //
  248. //        $clientList = SalesOrderM::GetClientList($em, [], $companyId);
  249.         $userType $session->get(UserConstants::USER_TYPE);
  250.         $userId $session->get(UserConstants::USER_ID);
  251.         $productListArray = [];
  252.         $subCategoryListArray = [];
  253.         $categoryListArray = [];
  254.         $igListArray = [];
  255.         $unitListArray = [];
  256.         $skipProductList $request->request->has('skipProductList') ? $request->request->get('skipProductList') : 0;
  257.         $productList = ($skipProductList == 1) ? [] : Inventory::ProductList($em$companyId);
  258.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  259.         $categoryList Inventory::ProductCategoryList($em$companyId);
  260.         $igList Inventory::ItemGroupList($em$companyId);
  261.         $unitList Inventory::UnitTypeList($em);
  262.         $brandList Inventory::GetBrandList($em$companyId);
  263.         $defaultSuffix 'lemon-o';
  264.         $pidsByCategory = [];
  265.         $pidsBySubCategory = [];
  266.         $pidsByIg = [];
  267.         $pidsByBrand = [];
  268.         foreach ($igList as $key => $product) {
  269.             if ($product['classSuffix'] == '') {
  270.                 $product['classSuffix'] = $defaultSuffix;
  271.                 $igList[$key]['classSuffix'] = $defaultSuffix;
  272.             }
  273.             $igListArray[] = $product;
  274.         }
  275.         foreach ($categoryList as $product) {
  276.             if ($product['classSuffix'] == '' && isset($igList[$product['igId']]))
  277.                 $product['classSuffix'] = $igList[$product['igId']]['classSuffix'];
  278.             $categoryListArray[] = $product;
  279.         }
  280.         foreach ($subCategoryList as $product) {
  281.             if ($product['classSuffix'] == '' && isset($igList[$product['igId']]))
  282.                 $product['classSuffix'] = $igList[$product['igId']]['classSuffix'];
  283.             $subCategoryListArray[] = $product;
  284.         }
  285.         foreach ($unitList as $product) {
  286.             $unitListArray[] = $product;
  287.         }
  288.         $brandListArray = [];
  289.         foreach ($brandList as $product) {
  290.             $brandListArray[] = $product;
  291.         }
  292.         foreach ($productList as $key => $product) {
  293. //            $productListArray[] = $product;
  294.             $product['igName'] = $igList[$product['igId']]['name'];
  295.             $product['categoryName'] = $categoryList[$product['categoryId']]['name'];
  296.             $product['subCategoryName'] = $subCategoryList[$product['subCategoryId']]['name'];
  297.             $product['brandName'] = $brandList[$product['brandCompany']]['name'];
  298.             $pidsByCategory[$product['categoryId']][] = $key;
  299.             $pidsBySubCategory[$product['subCategoryId']][] = $key;
  300.             $pidsIg[$product['igId']][] = $key;
  301.             $pidsByBrand[$product['brandCompany']][] = $key;
  302. //            $pidsBySubCategory=[];
  303. //            $pidsByIg=[];
  304.             $productListArray[] = $product;
  305.             $productList[$key] = $product;
  306.         }
  307.         $data = [
  308.             ''
  309.         ];
  310. //        if ($request->request->has('returnJson') || $request->query->has('returnJson'))
  311.         {
  312.             return new JsonResponse(
  313.                 array(
  314.                     'page_title' => ' ',
  315.                     'data' => $data,
  316.                     'productList' => $productList,
  317.                     'subCategoryList' => $subCategoryList,
  318.                     'categoryList' => $categoryList,
  319.                     'igList' => $igList,
  320.                     'unitList' => $unitList,
  321.                     'brandList' => $brandList,
  322.                     'productListArray' => $productListArray,
  323.                     'subCategoryListArray' => $subCategoryListArray,
  324.                     'categoryListArray' => $categoryListArray,
  325.                     'igListArray' => $igListArray,
  326.                     'unitListArray' => $unitListArray,
  327.                     'brandListArray' => $brandListArray,
  328.                     'pidsByCategory' => $pidsByCategory,
  329.                     'pidsBySubCategory' => $pidsBySubCategory,
  330.                     'pidsByBrand' => $pidsByBrand,
  331.                     'pidsByIg' => $pidsByIg,
  332.                     'success' => true
  333.                 )
  334.             );
  335.         }
  336.     }
  337.     public function GetRefreshedItemAction(Request $request$type 0)
  338.     {
  339.         $em $this->getDoctrine()->getManager();
  340.         $companyId $this->getLoggedUserCompanyId($request);
  341.         $productListArray = [];
  342.         $subCategoryListArray = [];
  343.         $categoryListArray = [];
  344.         $igListArray = [];
  345.         $unitListArray = [];
  346.         $skipProductList $request->request->has('skipProductList') ? $request->request->get('skipProductList') : 0;
  347.         $productList = ($skipProductList == 1) ? [] : Inventory::ProductList($em$companyId$type);
  348.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  349.         $categoryList Inventory::ProductCategoryList($em$companyId);
  350.         $igList Inventory::ItemGroupList($em$companyId);
  351.         $unitList Inventory::UnitTypeList($em);
  352.         $brandList Inventory::GetBrandList($em$companyId);
  353.         foreach ($productList as $product) {
  354.             $productListArray[] = $product;
  355.         }
  356.         foreach ($categoryList as $product) {
  357.             $categoryListArray[] = $product;
  358.         }
  359.         foreach ($subCategoryList as $product) {
  360.             $subCategoryListArray[] = $product;
  361.         }
  362.         foreach ($igList as $product) {
  363.             $igListArray[] = $product;
  364.         }
  365.         foreach ($unitList as $product) {
  366.             $unitListArray[] = $product;
  367.         }
  368.         $brandListArray = [];
  369.         foreach ($brandList as $product) {
  370.             $brandListArray[] = $product;
  371.         }
  372.         $qry $em->getRepository("ApplicationBundle\\Entity\\AccService")->findBy(array(
  373.             "status" => GeneralConstant::ACTIVE,
  374.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  375. //            'type'=>1//trade items
  376.         ));
  377.         $sl = [];
  378.         $sl_array = [];
  379.         foreach ($qry as $product) {
  380.             $sl[$product->getServiceId()] = array(
  381.                 'text' => $product->getServiceName(),
  382.                 'value' => $product->getServiceId(),
  383.                 'name' => $product->getServiceName(),
  384.                 'id' => $product->getServiceId(),
  385.             );
  386.             $sl_array[] = array(
  387.                 'text' => $product->getServiceName(),
  388.                 'value' => $product->getServiceId(),
  389.                 'name' => $product->getServiceName(),
  390.                 'id' => $product->getServiceId(),
  391.             );
  392.         }
  393.         $hl Accounts::HeadList($em);
  394.         $hl_array Accounts::getParentLedgerHeads($em"""", [], 1$this->getLoggedUserCompanyId($request));
  395.         return new JsonResponse(
  396.             array(
  397. //                'page_title'=>'BOM',
  398. //                'clients'=>SalesOrderM::GetClientList($em),
  399. //                'clients_by_ac_head'=>SalesOrderM::GetClientListByAcHead($em),
  400.                 'productList' => $productList,
  401.                 'subCategoryList' => $subCategoryList,
  402.                 'categoryList' => $categoryList,
  403.                 'igList' => $igList,
  404.                 'unitList' => $unitList,
  405.                 'brandList' => $brandList,
  406.                 'productListArray' => $productListArray,
  407.                 'subCategoryListArray' => $subCategoryListArray,
  408.                 'categoryListArray' => $categoryListArray,
  409.                 'igListArray' => $igListArray,
  410.                 'unitListArray' => $unitListArray,
  411.                 'brandListArray' => $brandListArray,
  412.                 "success" => true,
  413.                 'users' => Users::getUserListById($em),
  414.                 'stages' => ProjectConstant::$projectStages,
  415.                 'sl' => $sl,
  416.                 'hl' => $hl,
  417.                 'hl_array' => $hl_array,
  418.                 'sl_array' => $sl_array,
  419. //                'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
  420.             )
  421.         );
  422.     }
  423.     public function GetProductListForMisAction(Request $request)
  424.     {
  425.         $em $this->getDoctrine()->getManager();
  426.         $productIds $request->query->get('productId');
  427.         $fdmList = [];
  428.         $find_array = array('id' => $productIds);
  429.         if ($request->query->get('fdmList')) {
  430.             $find_array = array();
  431.             $fdmList $productIds $request->query->get('fdmList');
  432.         }
  433. //            $find_array=array('id' =>  $productIds);
  434.         $products $this->getDoctrine()
  435.             ->getRepository('ApplicationBundle\\Entity\\InvProducts')
  436.             ->findBy(
  437.                 $find_array
  438.             );
  439.         $productList = [];
  440.         $productListForShow = [];
  441.         foreach ($products as $entry) {
  442.             $productList[$entry->getId()] = array(
  443.                 'id' => $entry->getId(),
  444.                 'name' => $entry->getName(),
  445.                 'fdm' => $entry->getProductFdm(),
  446.             );
  447.         }
  448.         $products_in_stock $this->getDoctrine()
  449.             ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  450.             ->findBy(
  451.                 $find_array
  452.             );
  453.         $warehouseList Inventory::WarehouseList($em);
  454.         if (!empty($fdmList)) {
  455.             foreach ($products_in_stock as $dt) {
  456. //            if()
  457.                 $matched_a_product 0;
  458.                 foreach ($fdmList as $fdm) {
  459.                     $matchFdm Inventory::MatchFdm($fdm$productList[$dt->getProductId()]['fdm']);
  460.                     if ($matchFdm['hasMatched'] == 1) {
  461.                         if ($matchFdm['isIdentical'] == || $matchFdm['FirstBelongsToSecond'] == 1) {
  462.                             $matched_a_product 1;
  463.                             if (isset($productListForShow[$dt->getProductId()])) {
  464.                             } else {
  465.                                 $productListForShow[$dt->getProductId()] = array(
  466.                                     'id' => $productList[$dt->getProductId()]['id'],
  467.                                     'name' => $productList[$dt->getProductId()]['name'],
  468.                                     'fdm' => $productList[$dt->getProductId()]['fdm'],
  469.                                 );
  470.                             }
  471.                             if (isset($productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  472.                                 $productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  473.                             else {
  474.                                 $productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  475.                             }
  476.                             break;
  477.                         }
  478.                     }
  479.                 }
  480.                 if ($matched_a_product == 0) {
  481.                     continue;
  482.                 }
  483.                 if (isset($productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  484.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  485.                 else
  486.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  487.             }
  488.         } else {
  489.             foreach ($products_in_stock as $dt) {
  490. //            if()
  491.                 if (isset($productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  492.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  493.                 else
  494.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  495.             }
  496.             $productListForShow $productList;
  497.         }
  498.         $engine $this->container->get('twig');
  499. //        $SD=Supplier::GetSupplierDetailsForMis($em,$supplier_id);
  500.         if ($productList) {
  501.             $Content $engine->render('@Inventory/pages/report/selected_item_stock.html.twig', array("productList" => $productListForShow'warehouseList' => $warehouseList));
  502.             return new JsonResponse(array("success" => true"content" => $Content'productListForShow' => $productListForShow));
  503.         }
  504.         return new JsonResponse(array("success" => false));
  505.     }
  506.     public function CreateProductAction(Request $request$id 0)
  507.     {
  508.         $ex_id 0;
  509.         $prod_det = [];
  510.         $product_duplicate 0;
  511.         $createdProduct null;
  512.         $createdService null;
  513.         $group_type 1;//item
  514.         $em $this->getDoctrine()->getManager();
  515.         $companyId $this->getLoggedUserCompanyId($request);
  516.         $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  517.         $route $request->get('_route');
  518.         if ($route == 'create_service')
  519.             $group_type 2;//service
  520.         $quickCreateMode = (int)$request->request->get('quick_create_mode'0);
  521.         $productFormDefaults $this->getProductFormDefaults($em$companyId$loginId);
  522.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  523.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  524. //                $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  525. //        file_put_contents($path, json_encode(array(
  526. //            'sessionDataString'=>$request->request->get('sessionDataString'),
  527. //            'sessionData'=>json_decode($request->request->get('sessionDataString')),
  528. ////            'invData'=>$data_searched,
  529. //
  530. //        )));//overwrite
  531.         if ($request->isMethod('POST')) {
  532.             if ($id == 0)
  533.                 $id $request->request->has('ex_id') ? $request->request->get('ex_id') : 0;
  534.             if ($id == 0) {
  535.                 if ($group_type == 2)
  536.                     $ext_pr $this->getDoctrine()
  537.                         ->getRepository('ApplicationBundle\\Entity\\AccService')
  538.                         ->findOneBy(
  539.                             array(
  540.                                 'serviceName' => $request->request->get('name'),
  541.                             )
  542.                         );
  543.                 else
  544.                     $ext_pr $this->getDoctrine()
  545.                         ->getRepository('ApplicationBundle\\Entity\\InvProducts')
  546.                         ->findOneBy(
  547.                             array(
  548.                                 'name' => $request->request->get('name'),
  549.                             )
  550.                         );
  551.                 if ($ext_pr)
  552.                     $product_duplicate 1;
  553.             }
  554.             if ($product_duplicate == 1) {
  555.                 $this->addFlash(
  556.                     'error',
  557.                     'Duplicate Entry Found'
  558.                 );
  559.             } else {
  560.                 $image_list = [];
  561.                 $defaultImage "";
  562.                 $defaultImageUploadedFile null;
  563.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  564. //
  565. //                if ($request->files->has('product_default_image')) {
  566. //
  567. //
  568. ////                    foreach ($request->files->get('product_default_image') as $uploadedFile)
  569. //                    $defaultImageUploadedFile = $request->files->get('product_default_image');
  570. //                    {
  571. //
  572. //                        $path = "";
  573. //
  574. //                        if ($defaultImageUploadedFile != null) {
  575. //
  576. //                            $fileName = 'p' . md5(uniqid()) . '.' . $defaultImageUploadedFile->guessExtension();
  577. //                            $path = $fileName;
  578. //
  579. //                            if (!file_exists($upl_dir)) {
  580. //                                mkdir($upl_dir, 0777, true);
  581. //                            }
  582. ////                            $file = $uploadedFile->move($upl_dir, $path);
  583. //
  584. //                        }
  585. //                        $file_list[] = $path;
  586. //                        $defaultImage = $path;
  587. //                    }
  588. //
  589. //
  590. //                }
  591. //                if ($request->files->has('product_images')) {
  592. //
  593. //
  594. //                    foreach ($request->files->get('product_default_image') as $ind=>$uploadedFile)
  595. //                    {
  596. //
  597. //                        $path = "";
  598. //
  599. //                        if ($uploadedFile != null) {
  600. //
  601. //                            $fileName = 'p_'.$ind . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
  602. //                            $path = $fileName;
  603. //
  604. //                            if (!file_exists($upl_dir)) {
  605. //                                mkdir($upl_dir, 0777, true);
  606. //                            }
  607. ////                            $file = $uploadedFile->move($upl_dir, $path);
  608. //
  609. //                        }
  610. //                        $image_list[] = $path;
  611. //                        if($defaultImage=='' && $ind==0) {
  612. //                            $defaultImage = $path;
  613. //                            $uploadedFile = $path;
  614. //                        }
  615. //
  616. //                    }
  617. //
  618. //
  619. //                }
  620.                 if ($group_type == 2) {
  621.                     $ig $this->getDoctrine()
  622.                         ->getRepository('ApplicationBundle\\Entity\\InvItemGroup')
  623.                         ->findOneBy(
  624.                             array(
  625.                                 'id' => $request->request->get('itemgroupId')
  626.                             )
  627.                         );
  628.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Service/';
  629.                     $defaultPurchaseActionTagId $request->request->get('defaultPurchaseActionTagId''');
  630.                     $ledgerHitAs $request->request->get('ledgerHitAs''');
  631.                     $defaultExpenseId $request->request->get('defaultExpenseId''');
  632.                     $createdService Inventory::CreateNewService(
  633.                         $this->getDoctrine()->getManager(),
  634.                         $request->request->get('ex_id'),
  635.                         $request->request->get('name'),
  636.                         $companyId,
  637.                         $request->request->get('typeId'),
  638.                         $request->request->get('categoryId'),
  639.                         $request->request->get('brandCompany'),
  640.                         $request->request->get('subCategoryId'),
  641.                         $request->request->get('itemgroupId'),
  642.                         $request->request->get('unitTypeId'),
  643.                         $request->request->get('note'),
  644.                         $request->request->get('alias'''),
  645.                         $request->files->get('dataSheets', []),
  646.                         $request->files->get('service_default_image'null),
  647.                         $upl_dir,
  648.                         $request->files->get('service_images', []),
  649.                         [
  650.                             $request->request->get('categorization_1'''),
  651.                             $request->request->get('categorization_2'''),
  652.                             $request->request->get('categorization_3'''),
  653.                             $request->request->get('categorization_4'''),
  654.                             $request->request->get('categorization_5'''),
  655.                             $request->request->get('categorization_6'''),
  656.                             $request->request->get('categorization_7'''),
  657.                             $request->request->get('categorization_8'''),
  658.                             $request->request->get('categorization_9'''),
  659.                             $request->request->get('categorization_10'''),
  660.                         ],
  661.                         $request->request->get('purchasePrice'0),
  662.                         $request->request->get('salesPrice'0),
  663.                         $request->request->get('productFdm'''),
  664.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  665.                         ($ledgerHitAs != '') ? $ledgerHitAs $ig->getLedgerHitAs(),
  666.                         ($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId $ig->getDefaultPurchaseActionTagId(),
  667.                         ($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId $ig->getDefaultExpenseId(),
  668.                         $request->request->get('taxConfigIds', []),
  669.                         $request->request->get('defaultTaxConfigId'0),
  670.                         $request->request->get('purchaseTaxConfigIds', []),
  671.                         $request->request->get('defaultPurchaseTaxConfigId'0),
  672.                         $request->request->get('product_type''simple_product')
  673.                     );
  674.                     $this->saveProductFormDefaults($em$companyId$loginId$createdService$request);
  675.                     $this->addFlash(
  676.                         'success',
  677.                         'Service Have Been Added/Updated'
  678.                     );
  679.                 } else {
  680.                     $ig $this->getDoctrine()
  681.                         ->getRepository('ApplicationBundle\\Entity\\InvItemGroup')
  682.                         ->findOneBy(
  683.                             array(
  684.                                 'id' => $request->request->get('itemgroupId')
  685.                             )
  686.                         );
  687.                     $defaultPurchaseActionTagId $request->request->get('defaultPurchaseActionTagId''');
  688.                     $ledgerHitAs $request->request->get('ledgerHitAs''');
  689.                     $defaultExpenseId $request->request->get('defaultExpenseId''');
  690.                     $specData = [];
  691.                     $specData = [];
  692.                     foreach ($request->request->get('spec', []) as $specIndex => $specId) {
  693.                         $specData[] = array(
  694.                             'id' => $request->request->get('spec', [])[$specIndex],
  695.                             'value' => $request->request->get('spec_value', [])[$specIndex],
  696.                         );
  697.                     }
  698.                     $crateData = [];
  699.                     $crateData = [];
  700.                     foreach ($request->request->get('product_crate', []) as $crateIndex => $crateId) {
  701.                         $crateData[] = array(
  702.                             'id' => $crateId,
  703.                             'qty' => $request->request->get('product_qty', []),
  704.                         );
  705.                     }
  706.                     $sizesData = [];
  707.                     foreach ($request->request->get('product_crate', []) as $crateIndex => $crateId) {
  708.                         $sizesData[] = array(
  709.                             'size' => $request->request->get('product_size', []),
  710.                             'dimension' => $request->request->get('product_dimension', []),
  711.                             'dimensionUnitType' => $request->request->get('product_dimension_unit_type', []),
  712.                             'weight' => $request->request->get('product_weight', []),
  713.                             'weightUnitType' => $request->request->get('product_weight_unit_type', []),
  714.                         );
  715.                     }
  716.                     $createdProduct Inventory::CreateNewProduct(
  717.                         $this->getDoctrine()->getManager(),
  718.                         $request->request->get('ex_id'0),
  719.                         $request->request->get('name'''),
  720.                         $request->request->get('model_no'''),
  721.                         $this->getLoggedUserCompanyId($request),
  722.                         $request->request->get('typeId'1),
  723.                         $request->request->get('categoryId'null),
  724.                         $request->request->get('hasSerial'null),
  725.                         $ig->getDraccountsHeadId(),
  726.                         $ig->getCraccountsHeadId(),
  727.                         ($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId $ig->getDefaultPurchaseActionTagId(),
  728.                         $ig->getVatAsExpenseFlag(),
  729.                         $request->request->get('brandCompany'null),
  730.                         $request->request->get('subCategoryId'null),
  731.                         $request->request->get('yearlyDepreciation'0),
  732.                         $request->request->get('purchaseWarrantyMonths'0),
  733.                         $request->request->get('salesWarrantyMonths'0),
  734.                         $request->request->get('startingBalanceUnit'0),
  735.                         $request->request->get('reorderLevel'0),
  736.                         $request->request->get('note'''),
  737.                         $request->request->get('alias'''),
  738.                         $request->request->get('itemgroupId'null),
  739.                         $request->request->get('unitTypeId'null),
  740.                         $request->request->get('hsCode'''),
  741.                         $request->request->get('skuCode'''),
  742.                         $request->files->get('dataSheets', []),
  743.                         $request->request->get('partId'''),
  744.                         $request->request->get('productCode'''),
  745.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  746.                         $request->request->get('purchasePrice'0),
  747.                         $request->request->get('salesPrice'0),
  748.                         $request->files->get('product_default_image'null),
  749.                         $upl_dir,
  750.                         $request->files->get('product_images', []),
  751.                         $request->request->get('expiryDays'0),
  752.                         $request->request->get('dimension'''),
  753.                         $request->request->get('dimensionUnitTypeId'0),
  754.                         $request->request->get('productFdm'''),
  755.                         $request->request->get('weight'''),
  756.                         $request->request->get('weightUnitTypeId'0),
  757.                         $request->request->get('specification'null),
  758.                         $request->request->get('ingredient'null),
  759.                         $request->request->get('nutrition'null),
  760.                         $request->request->get('segregatePriceByColorsFlag'null),
  761.                         $request->request->get('segregatePriceBySizesFlag'null),
  762.                         [
  763.                             $request->request->get('categorization_1'''),
  764.                             $request->request->get('categorization_2'''),
  765.                             $request->request->get('categorization_3'''),
  766.                             $request->request->get('categorization_4'''),
  767.                             $request->request->get('categorization_5'''),
  768.                             $request->request->get('categorization_6'''),
  769.                             $request->request->get('categorization_7'''),
  770.                             $request->request->get('categorization_8'''),
  771.                             $request->request->get('categorization_9'''),
  772.                             $request->request->get('categorization_10'''),
  773.                         ],
  774.                         $request->request->get('weightVarianceValue'0),
  775.                         $request->request->get('weightVarianceType'0),
  776.                         $request->request->get('singleWeight'''),
  777.                         $request->request->get('singleWeightUnitTypeId'0),
  778.                         $request->request->get('singleWeightVarianceValue'0),
  779.                         $request->request->get('singleWeightVarianceType'0),
  780.                         $request->request->get('cartonWeightVarianceValue'0),
  781.                         $request->request->get('cartonWeightVarianceType'0),
  782.                         $request->request->get('cartonCapacityCount'0),
  783.                         $request->request->get('tac'''),
  784.                         $request->request->get('sellable'0),
  785.                         $request->request->get('abstract'0),
  786.                         $request->request->get('tags'''),
  787.                         $request->request->get('markerFlags'''),
  788.                         $request->request->get('defaultColorId'0),
  789.                         $request->request->get('product_color', []),
  790.                         $request->request->get('product_size', []),
  791.                         ($ledgerHitAs != '') ? $ledgerHitAs $ig->getLedgerHitAs(),
  792.                         ($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId $ig->getDefaultExpenseId(),
  793.                         $crateData,
  794.                         $sizesData,
  795.                         $specData,
  796.                         $request->request->get('taxConfigIds', []),
  797.                         $request->request->get('defaultTaxConfigId'0),
  798.                         $request->request->get('purchaseTaxConfigIds', []),
  799.                         $request->request->get('defaultPurchaseTaxConfigId'0),
  800.                         $request->request->get('product_type''simple_product')
  801.                     );
  802.                     if ($group_type != 2) {
  803.                         $savedProductId $createdProduct $createdProduct->getId() : (int) $request->request->get('ex_id'0);
  804.                         // S2.2 — persist epc_category_code
  805.                         $epcCode trim($request->request->get('epc_category_code'''));
  806.                         if ($savedProductId 0) {
  807.                             $productToTag $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($savedProductId);
  808.                             if ($productToTag) {
  809.                                 $productToTag->setEpcCategoryCode($epcCode !== '' $epcCode null);
  810.                                 // S3.3 — persist dispositionMethod
  811.                                 $dispMethod $request->request->get('dispositionMethod''demand_driven');
  812.                                 $allowedDisp = ['demand_driven''make_to_order''min_max''none'];
  813.                                 $productToTag->setDispositionMethod(in_array($dispMethod$allowedDisp) ? $dispMethod 'demand_driven');
  814.                                 $em->flush();
  815.                             }
  816.                         }
  817.                         $this->saveProductDependencies(
  818.                             $this->getDoctrine()->getManager(),
  819.                             $savedProductId,
  820.                             $request->request->get('dependencies', array())
  821.                         );
  822.                     }
  823.                     $this->saveProductFormDefaults($em$companyId$loginId$group_type == $createdService $createdProduct$request);
  824.                     $this->addFlash(
  825.                         'success',
  826.                         'Product Have Been Added/Updated'
  827.                     );
  828.                     // push new/updated product to central catalog
  829.                     if ($createdProduct) {
  830.                         $syncSystemType $this->container->hasParameter('system_type')
  831.                             ? $this->container->getParameter('system_type')
  832.                             : '_ERP_';
  833.                         Inventory::SyncProductToGlobal($em$createdProduct$ig $ig->getName() : ''$syncSystemType);
  834.                     }
  835.                 }
  836.             }
  837.             if ($request->request->has('returnJson')) {
  838.                 return new JsonResponse(array(
  839.                     'success' => true
  840.                 ));
  841.             }
  842.             if ($quickCreateMode === 1) {
  843.                 if ($group_type == 2) {
  844.                     $savedServiceId $createdService $createdService->getServiceId() : (int)$request->request->get('ex_id'0);
  845.                     return $this->redirectToRoute("create_service", array('id' => $savedServiceId));
  846.                 }
  847.                 $savedProductId $createdProduct $createdProduct->getId() : (int)$request->request->get('ex_id'0);
  848.                 return $this->redirectToRoute("create_product", array('id' => $savedProductId));
  849.             }
  850.             if ($group_type == 2)
  851.                 return $this->redirectToRoute("create_service");
  852.             else
  853.                 return $this->redirectToRoute("create_product");
  854.         }
  855.         if ($id != 0) {
  856.             $ex_id $id;
  857.             if ($group_type == 2)
  858.                 $prod_det $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccService')->findOneBy(array(
  859.                     'serviceId' => $id//for now for stock of goods
  860. //                    'opening_locked'=>0
  861.                 ));
  862.             else
  863.                 $prod_det $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(array(
  864.                     'id' => $id//for now for stock of goods
  865. //                    'opening_locked'=>0
  866.                 ));
  867.         }
  868. //        dump($prod_det);
  869.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  870.             'name' => 'warehouse_action_1'//for now for stock of goods
  871.         ));
  872.         return $this->render('@Inventory/pages/input_forms/create_product.html.twig',
  873.             array(
  874.                 'page_title' => $group_type == 'Service Entry' 'Product Entry',
  875.                 'group_type' => $group_type,
  876.                 'inv_head' => $inv_head $inv_head->getData() : '',
  877. //                'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  878.                 'services' => Inventory::ServiceList($this->getDoctrine()->getManager()),
  879.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  880.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  881.                 'itemgroup' => Inventory::ItemGroupList($em$companyId$group_type),
  882.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  883.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  884.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager(), 1),
  885.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  886.                 'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  887.                 'productDependencies' => $ex_id != $this->getProductDependencyRows($this->getDoctrine()->getManager(), $ex_id) : array(),
  888.                 'ex_id' => $ex_id,
  889.                 'warehouse_action_list' => $warehouse_action_list,
  890.                 'warehouse_action_list_array' => $warehouse_action_list_array,
  891.                 'markerFlags' => InventoryConstant::$SPECIAL_MARKER_ARRAY,
  892.                 'productFormDefaults' => $productFormDefaults,
  893. //                'isUpdate' => true,
  894.                 'ex_prod_det' => $prod_det,
  895.                 'epcCategories' => $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')
  896.                     ->findBy(['active' => 1], ['displayOrder' => 'ASC']),
  897.             )
  898.         );
  899.     }
  900.     public function ProductListAction(Request $request)
  901.     {
  902.         $em $this->getDoctrine()->getManager();
  903.         $companyId $this->getLoggedUserCompanyId($request);
  904.         $listData Inventory::GetProductListForProductListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  905.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  906.             if ($request->query->has('dataTableQry')) {
  907.                 return new JsonResponse(
  908.                     $listData
  909.                 );
  910.             }
  911.         }
  912.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  913.             'name' => 'warehouse_action_1'//for now for stock of goods
  914.         ));
  915.         return $this->render('@Inventory/pages/list/product_list.html.twig',
  916.             array(
  917.                 'page_title' => 'Product List',
  918.                 'inv_head' => $inv_head $inv_head->getData() : '',
  919. //                'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  920.                 'products' => [],
  921.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  922.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  923.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  924.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  925.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  926. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  927.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  928.                 'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  929.             )
  930.         );
  931.     }
  932.     public function SalesVsDeliveryListAction(Request $request)
  933.     {
  934.         $em $this->getDoctrine()->getManager();
  935.         $session $request->getSession();
  936.         $userType $session->get(UserConstants::USER_TYPE);
  937.         $userId $session->get(UserConstants::USER_ID);
  938.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  939.             'approved' => GeneralConstant::APPROVED,
  940. //            'stage' => GeneralConstant::STAGE_PENDING
  941.         );
  942.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  943.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  944.         }
  945. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  946. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  947. //            $selectiveDocumentsFlag=1; //by default will show only selective
  948. //            if(isset($userRestrictions['canSeeAllSo'])) {
  949. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  950. //                    $selectiveDocumentsFlag = 0;
  951. //                }
  952. //            }
  953. //
  954. //            if($selectiveDocumentsFlag==1)
  955. //            {
  956. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  957. //            }
  958. //        }
  959.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  960.             'name' => 'warehouse_action_1'//for now for stock of goods
  961.         ));
  962.         if ($request->query->has('queryDate')) {
  963.             $date = new \DateTime($request->query->get('queryDate'));
  964.         } else {
  965.             $today = new \DateTime();
  966.             $todayStr $today->format('Y-m-d');
  967.             $date = new \DateTime($todayStr);
  968.         }
  969.         $orderQryArray['salesOrderDate'] = $date;
  970.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findBy($orderQryArray);
  971.         $so_ids = [];
  972.         $so_data = [];
  973.         $so_item_ids = [];
  974.         $so_item_data = [];
  975.         foreach ($salesOrders as $salesOrder) {
  976.             if ($salesOrder->getSalesOrderDate() > $date)
  977.                 continue;
  978.             $so_ids[] = $salesOrder->getSalesOrderId();
  979.             $so_data[$salesOrder->getSalesOrderId()] = array(
  980.                 "id" => $salesOrder->getSalesOrderId(),
  981.                 "documentHash" => $salesOrder->getDocumentHash(),
  982.                 "clientId" => $salesOrder->getClientId(),
  983.             );
  984.         }
  985.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findBy(array(
  986.             'salesOrderId' => $so_ids,
  987.         ));
  988.         foreach ($salesOrderItems as $salesOrderItem) {
  989.             $so_item_ids[] = $salesOrderItem->getId();
  990.             $so_item_data[$salesOrderItem->getId()] = array(
  991.                 "id" => $salesOrderItem->getId(),
  992.                 "productId" => $salesOrderItem->getProductId(),
  993.                 "productName" => $salesOrderItem->getProductNameFdm(),
  994.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  995.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  996.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  997. //                "documentHash"=>$salesOrder->getDocumentHash(),
  998.                 "qty" => $salesOrderItem->getQty(),
  999.                 "transitQty" => $salesOrderItem->getTransitQty(),
  1000.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  1001.             );
  1002.         }
  1003.         return $this->render('@Inventory/pages/views/sales_vs_delivery_status.html.twig',
  1004.             array(
  1005.                 'page_title' => 'Order Vs. Disperse',
  1006.                 'inv_head' => $inv_head $inv_head->getData() : '',
  1007.                 'so_data' => $so_data,
  1008.                 'queryDate' => $date,
  1009.                 'so_item_data' => $so_item_data,
  1010.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  1011.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  1012.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  1013.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  1014.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  1015.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  1016.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  1017. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  1018.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  1019.             )
  1020.         );
  1021.     }
  1022.     public function DeliveryPendingOrderListAction(Request $request)
  1023.     {
  1024.         $em $this->getDoctrine()->getManager();
  1025.         $session $request->getSession();
  1026.         $userType $session->get(UserConstants::USER_TYPE);
  1027.         $userId $session->get(UserConstants::USER_ID);
  1028.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  1029.             'approved' => GeneralConstant::APPROVED,
  1030.             'stage' => GeneralConstant::STAGE_PENDING
  1031.         );
  1032.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  1033.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  1034.         }
  1035. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  1036. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  1037. //            $selectiveDocumentsFlag=1; //by default will show only selective
  1038. //            if(isset($userRestrictions['canSeeAllSo'])) {
  1039. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  1040. //                    $selectiveDocumentsFlag = 0;
  1041. //                }
  1042. //            }
  1043. //
  1044. //            if($selectiveDocumentsFlag==1)
  1045. //            {
  1046. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  1047. //            }
  1048. //        }
  1049.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1050.             'name' => 'warehouse_action_1'//for now for stock of goods
  1051.         ));
  1052.         if ($request->query->has('queryDate')) {
  1053.             $date = new \DateTime($request->query->get('queryDate'));
  1054.         } else {
  1055.             $today = new \DateTime();
  1056.             $todayStr $today->format('Y-m-d');
  1057.             $date = new \DateTime($todayStr);
  1058.         }
  1059. //        $orderQryArray['salesOrderDate'] = $date;
  1060.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findBy($orderQryArray);
  1061.         $so_ids = [];
  1062.         $so_data = [];
  1063.         $so_item_ids = [];
  1064.         $so_item_data = [];
  1065.         foreach ($salesOrders as $salesOrder) {
  1066.             if ($salesOrder->getSalesOrderDate() > $date)
  1067.                 continue;
  1068.             $so_ids[] = $salesOrder->getSalesOrderId();
  1069.             $so_data[$salesOrder->getSalesOrderId()] = array(
  1070.                 "id" => $salesOrder->getSalesOrderId(),
  1071.                 "documentHash" => $salesOrder->getDocumentHash(),
  1072.                 "clientId" => $salesOrder->getClientId(),
  1073.             );
  1074.         }
  1075.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findBy(array(
  1076.             'salesOrderId' => $so_ids,
  1077.         ));
  1078.         foreach ($salesOrderItems as $salesOrderItem) {
  1079.             $so_item_ids[] = $salesOrderItem->getId();
  1080.             $so_item_data[$salesOrderItem->getId()] = array(
  1081.                 "id" => $salesOrderItem->getId(),
  1082.                 "productId" => $salesOrderItem->getProductId(),
  1083.                 "productName" => $salesOrderItem->getProductNameFdm(),
  1084.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  1085.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  1086.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  1087. //                "documentHash"=>$salesOrder->getDocumentHash(),
  1088.                 "qty" => $salesOrderItem->getQty(),
  1089.                 "transitQty" => $salesOrderItem->getTransitQty(),
  1090.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  1091.             );
  1092.         }
  1093.         return $this->render('@Inventory/pages/views/delivery_pending_order_list.html.twig',
  1094.             array(
  1095.                 'page_title' => 'Pending Delivery',
  1096.                 'inv_head' => $inv_head $inv_head->getData() : '',
  1097.                 'so_data' => $so_data,
  1098.                 'queryDate' => $date,
  1099.                 'so_item_data' => $so_item_data,
  1100.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  1101.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  1102.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  1103.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  1104.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  1105.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  1106.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  1107. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  1108.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  1109.             )
  1110.         );
  1111.     }
  1112.     public function AddSpecTypeAction(Request $request$id 0)
  1113.     {
  1114.         $ex_id 0;
  1115.         $det = [];
  1116.         $em $this->getDoctrine()->getManager();
  1117.         $companyId $this->getLoggedUserCompanyId($request);
  1118.         if ($request->isMethod('POST')) {
  1119. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  1120. //            $request->request->get('ex_id');
  1121. //
  1122. //
  1123. //            $this->addFlash(
  1124. //                'success',
  1125. //                'Spec Type Added'
  1126. //            );
  1127.             Inventory::CreateSpecType(
  1128.                 $this->getDoctrine()->getManager(),
  1129.                 $request->request->get('ex_id'),
  1130.                 $request->request,
  1131.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  1132.             );
  1133.         }
  1134.         if ($id != 0) {
  1135.             $ex_id $id;
  1136.             $det $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SpecType')->findOneBy(array(
  1137.                 'id' => $id
  1138.             ));
  1139.         }
  1140.         $specTypeDetails $em->getRepository(SpecType::class)->findAll();
  1141.         return $this->render('@Inventory/pages/input_forms/addSpecType.html.twig',
  1142.             array(
  1143.                 'page_title' => 'Add Spec Type',
  1144.                 'ex_id' => $ex_id,
  1145.                 'ex_det' => $det,
  1146.                 'specTypeDetails' => $specTypeDetails,
  1147.             )
  1148.         );
  1149.     }
  1150.     public function ItemGroupAction(Request $request$id 0)
  1151.     {
  1152.         $ex_id 0;
  1153.         $det = [];
  1154.         $em $this->getDoctrine()->getManager();
  1155.         $companyId $this->getLoggedUserCompanyId($request);
  1156.         $group_type 1;//item
  1157.         $route $request->get('_route');
  1158.         if ($route == 'service_group')
  1159.             $group_type 2;//service
  1160.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');
  1161.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');
  1162.         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ItemGroup/';
  1163.         if ($request->isMethod('POST')) {
  1164.             Inventory::CreateItemGroup(
  1165.                 $this->getDoctrine()->getManager(),
  1166.                 $request->request->get('ex_id'),
  1167.                 $this->getLoggedUserCompanyId($request),
  1168.                 $request->request,
  1169.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  1170.                 $request->files->get('dataSheets', []),
  1171.                 $request->files->get('item_group_icon'),
  1172.                 $request->files->get('item_group_banner_image'),
  1173.                 $request->files->get('item_group_default_image'),
  1174.                 $upl_dir,
  1175.                 $request->files->get('item_group_images', []));
  1176.         }
  1177.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1178.             'name' => 'warehouse_action_1',
  1179.         ));
  1180.         if ($group_type == 1) {
  1181.             if ($id != 0) {
  1182.                 $ex_id $id;
  1183.                 $det $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(array(
  1184.                     'id' => $id//for now for stock of goods
  1185. //                    'opening_locked'=>0
  1186.                 ));
  1187.             }
  1188.         } else {
  1189.             if ($id != 0) {
  1190.                 $ex_id $id;
  1191.                 $det $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccService')->findOneBy(array(
  1192.                     'serviceId' => $id
  1193.                 ));
  1194.             }
  1195.         }
  1196. //        dump($det);
  1197.         return $this->render('@Inventory/pages/input_forms/item_group.html.twig',
  1198.             array(
  1199.                 'page_title' => $group_type == "Item Group" "Service Group",
  1200.                 'inv_head' => $inv_head $inv_head->getData() : '',
  1201.                 'group_type' => $group_type,
  1202.                 'igList' => Inventory::ItemGroupList($em$companyId$group_type),
  1203.                 'warehouse_action_list' => $warehouse_action_list,
  1204. //                'data'=>Inventory::ItemGroupFormRelatedData($this->getDoctrine()->getManager()),
  1205.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  1206.                 'spec_type_list' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  1207.                 'ex_id' => $ex_id,
  1208.                 'ex_det' => $det,
  1209.                 'upl_dir' => $upl_dir,
  1210.             )
  1211.         );
  1212.     }
  1213.     public function addStartingOpeningInOutAction(Request $request$refreshed_opening 0)
  1214.     {
  1215.         //be very careful!!
  1216.         $em $this->getDoctrine()->getManager();
  1217. //        $last_refresh_date="";
  1218.         //steps
  1219.         //1. set all inventory to their opening position
  1220.         $assign_list = array();
  1221.         $data = array();
  1222.         if ($refreshed_opening == 0) {
  1223.             $new_cc $em
  1224.                 ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  1225.                 ->findOneBy(
  1226.                     array(
  1227.                         'name' => 'accounting_year_start',
  1228.                     )
  1229.                 );
  1230.             $date_start = new \DateTime($new_cc->getData());
  1231.             $date_start_str $date_start->format('Y-m-d');
  1232.             $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  1233. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  1234.             $stmt $em->getConnection()->fetchAllAssociative($closingQuery);
  1235.             $iniClosing $stmt;
  1236. //                $stmt = $em->getConnection()->fetchAllAssociative($transQuery);
  1237. //                
  1238. //                $iniTrans = $stmt;
  1239.             $singleClosing_byProductId = array();
  1240.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1241.             foreach ($iniClosing as $item) {
  1242.                 if (!isset($singleClosing_byProductId[$item['product_id']])) {
  1243.                     $singleClosing_byProductId[$item['product_id']] = array(
  1244.                         'date' => $item['date'],
  1245.                         'qtyAdd' => $item['qty_addition'],
  1246.                         'qtySub' => '0',
  1247.                         'valueAdd' => $item['addition'],
  1248.                         'valueSub' => '0',
  1249.                         'fromWarehouse' => 0,
  1250.                         'toWarehouse' => $item['warehouse_id'],
  1251.                         'fromWarehouseSub' => 0,
  1252.                         'toWarehouseSub' => $item['action_tag_id'],
  1253.                         'price' => ($item['addition'] / $item['qty_addition'])
  1254.                     );
  1255.                 }
  1256.             }
  1257.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1258. //                foreach ($iniTrans as $item) {
  1259. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  1260. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  1261. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  1262. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  1263. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  1264. //                    }
  1265. //                }
  1266.             foreach ($singleClosing_byProductId as $key => $item) {
  1267.                 if (!isset($data[$key])) {
  1268.                     $data[$key][] = $item;
  1269.                 }
  1270.             }
  1271.             //now that we go the data we can empty the closing table
  1272. //                $get_kids_sql ='UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  1273. //    truncate `inv_closing_balance`;
  1274. //    truncate `inventory_storage`;
  1275. //    truncate `inv_item_transaction`;';
  1276. //                $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1277. //                
  1278. //                
  1279. //                $stmt;
  1280.             $total_inv_value_in 0;
  1281.             foreach ($data as $key => $item) {
  1282.                 if (!empty($item)) {
  1283.                     foreach ($item as $entry) {
  1284.                         $transDate = new \DateTime($entry['date']);
  1285.                         $new = new InvItemInOut();
  1286.                         $new->setProductId($key);
  1287.                         $new->setWarehouseId($entry['toWarehouse']);
  1288.                         $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  1289.                         $new->setActionTagId($entry['toWarehouseSub']);
  1290.                         $new->setTransactionDate($transDate);
  1291.                         $new->setQty($entry['qtyAdd']);
  1292.                         $new->setPrice($entry['price']);
  1293.                         $new->setAmount($entry['qtyAdd'] * $entry['price']);
  1294.                         $new->setEntity(0);// opening =0
  1295.                         $new->setEntityId(0);// opening =0
  1296.                         $new->setDebitCreditHeadId(0);// opening =0
  1297.                         $new->setVoucherIds(null);// opening =0
  1298.                         $em->persist($new);
  1299.                         $em->flush();
  1300.                         $total_inv_value_in += $entry['qtyAdd'] * $entry['price'];
  1301.                     }
  1302.                 }
  1303.             }
  1304.             $refreshed_opening 1;
  1305. //                $terminate=1;
  1306. //                $last_refresh_date=$last_refresh_date_obj->format('Y-m-d');
  1307.             return new JsonResponse(array(
  1308.                 "success" => true,
  1309.             ));
  1310.             //now call the function which will add the 1st ever entry or opening entry
  1311.         }
  1312.         //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  1313.         return new JsonResponse(array(
  1314.             "success" => false,
  1315.         ));
  1316.     }
  1317.     public function RefreshInventoryAction(Request $request$refreshed_opening 0)
  1318.     {
  1319.         //be very careful!!
  1320.         $em $this->getDoctrine()->getManager();
  1321.         $refreshed_opening 0;
  1322.         $last_refresh_date "";
  1323.         $last_refresh_date_obj "";
  1324.         $terminate 0;
  1325.         $companyId $this->getLoggedUserCompanyId($request);
  1326.         $modifyAccTransaction $request->request->has('modify_acc_trans_flag') ? $request->request->get('modify_acc_trans_flag') : 0;
  1327.         $modifyProductionPrice $request->request->has('modify_production_price') ? $request->request->get('modify_production_price') : 0;
  1328. //        $last_refresh_date="";
  1329.         if ($request->isMethod('POST')) {
  1330.             //steps
  1331.             //1. set all inventory to their opening position
  1332.             $assign_list = array();
  1333.             $data = array();
  1334.             if ($request->request->has('inventory_refreshed'))
  1335.                 $refreshed_opening $request->request->get('inventory_refreshed');
  1336.             if ($request->request->has('last_refresh_date'))
  1337.                 $last_refresh_date $request->request->get('last_refresh_date');
  1338.             if ($refreshed_opening == 0) {
  1339. //                System::log_it($this->container->getParameter('kernel.root_dir'), "",
  1340. //                    'inventory_refresh_debug', 0); //last er 1 is append
  1341.                 $new_cc $em
  1342.                     ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  1343.                     ->findOneBy(
  1344.                         array(
  1345.                             'name' => 'accounting_year_start',
  1346.                         )
  1347.                     );
  1348.                 $date_start = new \DateTime($new_cc->getData());
  1349.                 $date_start_str $date_start->format('Y-m-d');
  1350.                 $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  1351. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  1352.                 $stmt $em->getConnection()->fetchAllAssociative($closingQuery);
  1353.                 $iniClosing $stmt;
  1354. //                $stmt = $em->getConnection()->fetchAllAssociative($transQuery);
  1355. //                
  1356. //                $iniTrans = $stmt;
  1357.                 $singleClosing_byProductId = array();
  1358.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1359.                 foreach ($iniClosing as $item) {
  1360.                     if (!isset($singleClosing_byProductId[$item['product_id']])) {
  1361.                         $singleClosing_byProductId[$item['product_id']] = array(
  1362.                             'date' => $item['date'],
  1363.                             'qtyAdd' => $item['qty_addition'],
  1364.                             'qtySub' => '0',
  1365.                             'valueAdd' => $item['addition'],
  1366.                             'valueSub' => '0',
  1367.                             'fromWarehouse' => 0,
  1368.                             'toWarehouse' => $item['warehouse_id'],
  1369.                             'fromWarehouseSub' => 0,
  1370.                             'toWarehouseSub' => $item['action_tag_id'],
  1371.                             'price' => $item['qty_addition'] != ? ($item['addition'] / $item['qty_addition']) : $item['addition']
  1372.                         );
  1373.                     }
  1374.                 }
  1375.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1376. //                foreach ($iniTrans as $item) {
  1377. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  1378. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  1379. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  1380. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  1381. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  1382. //                    }
  1383. //                }
  1384.                 foreach ($singleClosing_byProductId as $key => $item) {
  1385.                     if (!isset($data[$key])) {
  1386.                         $data[$key][] = $item;
  1387.                     }
  1388.                 }
  1389.                 //new one
  1390.                 //chekc if ultra opening stock received note exists if not create it
  1391.                 $mo $em
  1392.                     ->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')
  1393.                     ->findOneBy(
  1394.                         array(
  1395.                             'documentHash' => '_MASTER_OPENING_',
  1396.                             'typeHash' => 'SR',
  1397.                             'prefixHash' => 4,
  1398.                             'assocHash' => '_MASTER_OPENING_',
  1399.                             'numberHash' => 1,
  1400.                         )
  1401.                     );
  1402.                 if (!$mo) {
  1403.                     //doensot exist to add :)
  1404. //                    $products = $post_data->get('products');
  1405. //                    $qty = $post_data->get('qty');
  1406. //                    $note = $post_data->get('note');
  1407.                     $new = new StockReceivedNote();
  1408.                     $new->setStockReceivedNoteDate(new \DateTime($date_start_str));
  1409.                     $new->setCompanyId($companyId);
  1410.                     $new->setDocumentHash('_MASTER_OPENING_');
  1411.                     $new->setTypeHash('SR');
  1412.                     $new->setPrefixHash(4);
  1413.                     $new->setAssocHash('_MASTER_OPENING_');
  1414.                     $new->setNumberHash(1);
  1415.                     $new->setCreditHeadId(0);
  1416.                     $new->setStockTransferId(0);
  1417.                     $new->setSalesOrderId(0);
  1418.                     $new->setType(4);
  1419.                     $new->setStatus(GeneralConstant::ACTIVE);
  1420.                     $new->setWarehouseId(0);
  1421.                     $new->setNote('');
  1422.                     $new->setAutoCreated(1);
  1423.                     $new->setApproved(GeneralConstant::APPROVED);
  1424. //        $new->setIndentTagged(0);
  1425.                     $new->setStage(GeneralConstant::STAGE_COMPLETE);
  1426.                     $new->setCreatedLoginId(0);
  1427.                     $new->setEditedLoginId(0);
  1428.                     $em->persist($new);
  1429.                     $em->flush();
  1430.                     $SRID $new->getStockReceivedNoteId();
  1431.                     $last_refresh_date_obj $new->getStockReceivedNoteDate();
  1432.                     //now add items to details
  1433.                     foreach ($data as $key => $item) {
  1434.                         if (!empty($item)) {
  1435.                             foreach ($item as $entry) {
  1436.                                 $transDate = new \DateTime($entry['date']);
  1437.                                 if ($last_refresh_date_obj == '') {
  1438.                                     $last_refresh_date_obj $transDate;
  1439.                                 } else if ($transDate $last_refresh_date_obj) {
  1440.                                     $last_refresh_date_obj $transDate;
  1441.                                 }
  1442.                                 $new = new StockReceivedNoteItem();
  1443.                                 $new->setStockReceivedNoteId($SRID);
  1444.                                 $new->setStockTransferItemId(0);
  1445.                                 $salesCodeRange = [];
  1446.                                 $salesCodeRangeStr '';
  1447.                                 $new->setSalesCodeRange("[" $salesCodeRangeStr "]");
  1448.                                 $new->setQty($entry['qtyAdd']);
  1449.                                 $new->setPrice($entry['price']);
  1450.                                 $new->setBalance($entry['qtyAdd']);
  1451.                                 $new->setProductId($key);
  1452.                                 $new->setWarrantyMon(0);
  1453.                                 $new->setWarehouseId($entry['toWarehouse']);
  1454.                                 $new->setWarehouseActionId($entry['toWarehouseSub']);
  1455.                                 $em->persist($new);
  1456.                                 $em->flush();
  1457.                             }
  1458.                         }
  1459.                     }
  1460. //                    for ($i = 0; $i < count($products); $i++) {
  1461. //
  1462. //
  1463. //                        $srItem = self::CreateNewStockReceivedNoteItem($em, $post_data, $i, $new->getStockReceivedNoteId(), $LoginID);
  1464. //                    }
  1465.                 }
  1466.                 if ($mo)
  1467.                     $last_refresh_date_obj $mo->getStockReceivedNoteDate();
  1468.                 $last_refresh_date_obj->modify('-1 day');///new so that it willstart form this day on next call
  1469.                 //new ends
  1470.                 //now that we go the data we can empty the closing table
  1471.                 $get_kids_sql "UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  1472. UPDATE `purchase_order` SET expense_amount=0, expense_pending_balance_amount=0, grn_tag_pending_expense_invoice_ids='[]' WHERE 1;
  1473.     truncate `inv_closing_balance`;
  1474.     truncate `inventory_storage`;
  1475.     truncate `inv_item_transaction`;";
  1476. //                $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1477.                 $stmt $em->getConnection()->executeStatement($get_kids_sql);
  1478. //                $stmt;
  1479. //                foreach ($data as $key => $item) {
  1480. //                    if (!empty($item)) {
  1481. //                        foreach ($item as $entry) {
  1482. //                            $transDate = new \DateTime($entry['date']);
  1483. //                            Inventory::addItemToInventoryCompact($em,
  1484. //                                $key,
  1485. //                                $entry['fromWarehouse'],
  1486. //                                $entry['toWarehouse'],
  1487. //                                $entry['fromWarehouseSub'],
  1488. //                                $entry['toWarehouseSub'],
  1489. //                                $transDate,
  1490. //                                $entry['qtyAdd'],
  1491. //                                $entry['qtySub'],
  1492. //                                $entry['valueAdd'],
  1493. //                                $entry['valueSub'],
  1494. //                                $entry['price'],
  1495. //                                $this->getLoggedUserCompanyId($request));
  1496. //                            if ($last_refresh_date_obj == '') {
  1497. //                                $last_refresh_date_obj = $transDate;
  1498. //                            } else if ($transDate < $last_refresh_date_obj) {
  1499. //                                $last_refresh_date_obj = $transDate;
  1500. //                            }
  1501. //                        }
  1502. //                    }
  1503. //                }
  1504.                 $refreshed_opening 1;
  1505. //                $terminate=1;
  1506.                 if ($last_refresh_date_obj == "") {
  1507.                     $last_refresh_date $date_start_str;
  1508.                 } else {
  1509.                     $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1510.                 }
  1511.                 return new JsonResponse(array(
  1512.                     "success" => true,
  1513.                     "last_refresh_date" => $last_refresh_date,
  1514.                     "inventory_refreshed" => $refreshed_opening
  1515.                 ));
  1516.                 //now call the function which will add the 1st ever entry or opening entry
  1517.             }
  1518.             //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  1519.             if ($last_refresh_date != '')
  1520.                 $last_refresh_date_obj = new \DateTime($last_refresh_date);
  1521.             else {
  1522.                 $new_cc $em
  1523.                     ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  1524.                     ->findOneBy(
  1525.                         array(
  1526.                             'name' => 'accounting_year_start',
  1527.                         )
  1528.                     );
  1529.                 $last_refresh_date_obj = new \DateTime($new_cc->getData());
  1530.                 $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1531.             }
  1532.             $last_refresh_date_obj->modify('+1 day');
  1533.             $today = new \DateTime();
  1534.             if ($last_refresh_date_obj $today) {
  1535.                 $terminate 1;
  1536.             }
  1537.             $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1538.             //ok now we got the date so get grn item on this date
  1539.             //GRN
  1540.             $query "SELECT grn_item.*, grn.grn_date, grn.document_hash from  grn_item
  1541.               join grn on grn.grn_id=grn_item.grn_id
  1542.             where grn.grn_date ='" $last_refresh_date " 00:00:00' and grn.approved=1";
  1543.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1544.             $queryData $stmt;
  1545.             $grn_ids = [];
  1546.             foreach ($queryData as $item) {
  1547.                 $data[$item['product_id']][] = array(
  1548.                     'date' => $last_refresh_date,
  1549.                     'entity' => array_flip(GeneralConstant::$Entity_list)['Grn'],
  1550.                     'entityId' => $item['grn_id'],
  1551.                     'colorId' => $item['color_id'],
  1552.                     'sizeId' => $item['size_id'],
  1553.                     'entityDocHash' => $item['document_hash'],
  1554.                     'qtyAdd' => $item['qty'],
  1555.                     'qtySub' => 0,
  1556.                     'valueAdd' => ($item['qty'] * $item['price_with_expense']),
  1557.                     'valueSub' => 0,
  1558.                     'price' => $item['price_with_expense'],
  1559.                     'fromWarehouse' => 0,
  1560.                     'toWarehouse' => $item['warehouse_id'],
  1561.                     'fromWarehouseSub' => 0,
  1562. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1563.                     'toWarehouseSub' => $item['warehouse_action_id']
  1564.                 );
  1565.                 if (!in_array($item['grn_id'], $grn_ids))
  1566.                     $grn_ids[] = $item['grn_id'];
  1567.             }
  1568.             //now add grns
  1569.             foreach ($data as $key => $item) {
  1570.                 if (!empty($item)) {
  1571.                     foreach ($item as $entry) {
  1572.                         $transDate = new \DateTime($entry['date']);
  1573.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1574.                             $key,
  1575.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1576.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1577.                             $entry['fromWarehouse'],
  1578.                             $entry['toWarehouse'],
  1579.                             $entry['fromWarehouseSub'],
  1580.                             $entry['toWarehouseSub'],
  1581.                             $transDate,
  1582.                             $entry['qtyAdd'],
  1583.                             $entry['qtySub'],
  1584.                             $entry['valueAdd'],
  1585.                             $entry['valueSub'],
  1586.                             $entry['price'],
  1587.                             $this->getLoggedUserCompanyId($request),
  1588.                             0,
  1589.                             $entry['entity'],
  1590.                             $entry['entityId'],
  1591.                             $entry['entityDocHash'],
  1592.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_SUPPLER
  1593.                         );
  1594.                         if ($last_refresh_date_obj == '') {
  1595.                             $last_refresh_date_obj $transDate;
  1596.                         } else if ($transDate $last_refresh_date_obj) {
  1597.                             $last_refresh_date_obj $transDate;
  1598.                         }
  1599.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1600.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1601.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1602.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1603.                             "",
  1604.                             'inventory_refresh_debug'1); //last er 1 is append
  1605.                     }
  1606.                 }
  1607.             }
  1608.             ///adding grn vouhcer mod here too incase it wasnot in the distributed IG for heads
  1609. //            $grn=$em->getRepository('ApplicationBundle\\Entity\\Grn')->findBy(array(
  1610. //                'grnId'=>$grn_ids,
  1611. //                'modifyVoucherFlag'=>1 //have to add this flag
  1612. //            ));
  1613.             foreach ($grn_ids as $grn_id) {
  1614.                 if ($modifyAccTransaction == 1)
  1615.                     Inventory::ModifyGrnTransactions($em$grn_id1);
  1616.                 else
  1617.                     Inventory::ModifyGrnTransactions($em$grn_id);
  1618.             }
  1619.             //adding voucher ends
  1620.             $inv_head_list_by_wa = [];
  1621.             $inv_head_list = [];
  1622.             $cogs_head 0;
  1623.             $cogs_head 0;
  1624.             $internal_proj 0;
  1625. //            if ($project) {
  1626. //                if ($project->getProjectType() == 2) {
  1627. //                    $cogs_head = $project->getInternalProjectAssetHeadId();
  1628. //                    $internal_proj = 1;
  1629. //                } else {
  1630. //                    $cogs_head_qry = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1631. //                        'name' => 'cogs'
  1632. //                    ));
  1633. //                    $cogs_head = $cogs_head_qry->getData();
  1634. //                }
  1635. //            } else {
  1636.             $cogs_head_qry $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1637.                 'name' => 'cogs'
  1638.             ));
  1639.             $cogs_head $cogs_head_qry->getData();
  1640. //            }
  1641.             $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');
  1642.             foreach ($warehouse_action_list as $wa) {
  1643.                 $inv_head_data $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1644.                         'name' => 'warehouse_action_' $wa['id'])
  1645.                 );
  1646.                 if ($inv_head_data) {
  1647.                     $inv_head_list_by_wa[$wa['id']] = $inv_head_data->getData();
  1648.                     $inv_head_list[] = $inv_head_data->getData();
  1649.                 }
  1650.             }
  1651.             $data = [];
  1652.             //____________STOCK_RECEIVED___________________
  1653.             $docEntity "StockReceivedNote";
  1654.             $docEntityIdField "stockReceivedNoteId";
  1655.             $accTransactionDataByDocId = [];
  1656.             $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
  1657.               join stock_received_note on stock_received_note.stock_received_note_id=stock_received_note_item.stock_received_note_id
  1658.             where stock_received_note.stock_received_note_date ='" $last_refresh_date " 00:00:00' and stock_received_note.approved=1";
  1659.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1660.             $queryData $stmt;
  1661.             $grn_ids = [];
  1662.             foreach ($queryData as $item) {
  1663.                 $data[$item['product_id']][] = array(
  1664.                     'date' => $last_refresh_date,
  1665.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  1666.                     'entityId' => $item['stock_received_note_id'],
  1667.                     'colorId' => $item['color_id'],
  1668.                     'sizeId' => $item['size_id'],
  1669.                     'type' => $item['type'],
  1670.                     'entityDocHash' => $item['document_hash'],
  1671.                     'qtyAdd' => $item['qty'],
  1672.                     'qtySub' => 0,
  1673.                     'valueAdd' => ($item['qty'] * $item['price']),
  1674.                     'valueSub' => 0,
  1675.                     'price' => $item['price'],
  1676.                     'fromWarehouse' => 0,
  1677.                     'toWarehouse' => $item['warehouse_id'],
  1678.                     'fromWarehouseSub' => 0,
  1679. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1680.                     'toWarehouseSub' => $item['warehouse_action_id']
  1681.                 );
  1682. //                if (!in_array($item['grn_id'], $grn_ids))
  1683. //                    $grn_ids[] = $item['grn_id'];
  1684.             }
  1685.             foreach ($data as $key => $item) {
  1686.                 if (!empty($item)) {
  1687.                     foreach ($item as $entry) {
  1688.                         $transDate = new \DateTime($entry['date']);
  1689.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1690.                             $key,
  1691.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1692.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1693.                             $entry['fromWarehouse'],
  1694.                             $entry['toWarehouse'],
  1695.                             $entry['fromWarehouseSub'],
  1696.                             $entry['toWarehouseSub'],
  1697.                             $transDate,
  1698.                             $entry['qtyAdd'],
  1699.                             $entry['qtySub'],
  1700.                             $entry['valueAdd'],
  1701.                             $entry['valueSub'],
  1702.                             $entry['price'],
  1703.                             $this->getLoggedUserCompanyId($request),
  1704.                             0,
  1705.                             $entry['entity'],
  1706.                             $entry['entityId'],
  1707.                             $entry['entityDocHash'],
  1708.                             $entry['type'] == ?
  1709.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_OPENING :
  1710.                                 ($entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_STOCK_IN :
  1711.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT)
  1712.                         );
  1713.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1714.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1715.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1716.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1717.                             "",
  1718.                             'inventory_refresh_debug'1); //last er 1 is append
  1719.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1720.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1721.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  1722.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  1723.                         else
  1724.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  1725.                         if ($last_refresh_date_obj == '') {
  1726.                             $last_refresh_date_obj $transDate;
  1727.                         } else if ($transDate $last_refresh_date_obj) {
  1728.                             $last_refresh_date_obj $transDate;
  1729.                         }
  1730.                     }
  1731.                 }
  1732.             }
  1733.             if ($modifyAccTransaction == 1) {
  1734.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1735.                     $docHere $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  1736.                         $docEntityIdField => $docId,
  1737.                     ));;
  1738.                     if ($docHere) {
  1739.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1740.                         if ($curr_v_ids == null)
  1741.                             $curr_v_ids = [];
  1742.                         $skipVids = [];
  1743.                         $toChangeVid 0;
  1744.                         $voucher null;
  1745.                         foreach ($curr_v_ids as $vid) {
  1746.                             if (in_array($vid$skipVids))
  1747.                                 continue;
  1748.                             $skipVids[] = $vid//to prevent duplicate query
  1749.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  1750.                                 'transactionId' => $vid,
  1751.                             ));;
  1752.                             if ($voucher) {
  1753.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1754.                                     $toChangeVid $vid;
  1755.                                 } else {
  1756.                                     continue;
  1757.                                 }
  1758.                             }
  1759.                         }
  1760.                         if ($toChangeVid == 0) {
  1761.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1762.                                 $em,
  1763.                                 $docHere->getStockReceivedNoteDate()->format('Y-m-d'),
  1764.                                 0,
  1765.                                 AccountsConstant::VOUCHER_JOURNAL,
  1766.                                 'Journal For Stock Received Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  1767.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1768.                                 'JV',
  1769.                                 'GN',
  1770.                                 0,
  1771.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1772.                                 0,
  1773.                                 $docHere->getCreatedLoginId(),
  1774.                                 $docHere->getCompanyId(),
  1775.                                 '',
  1776.                                 0,
  1777.                                 1
  1778.                             );
  1779.                             $em->flush();
  1780.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  1781.                                 'transactionId' => $toChangeVid,
  1782.                             ));;
  1783.                         }
  1784.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  1785.                         $tot_inv_amount 0;
  1786.                         foreach ($transData as $k => $v) {
  1787.                             $tot_inv_amount += ($v);
  1788.                             Accounts::CreateNewTransactionDetails($em,
  1789.                                 '',
  1790.                                 $toChangeVid,
  1791.                                 Generic::CurrToInt($v),
  1792.                                 $k,
  1793.                                 'Inventory Inward For - ' $docHere->getDocumentHash(),
  1794.                                 AccountsConstant::DEBIT,
  1795.                                 0,
  1796.                                 [],
  1797.                                 [],
  1798.                                 $docHere->getCreatedLoginId()
  1799.                             );
  1800.                         }
  1801.                         $stockReceivedType $docHere->getType();
  1802.                         $to_balance_head 0;
  1803.                         if (in_array($stockReceivedType, [23]))
  1804.                             $to_balance_head $docHere->getCreditHeadId();
  1805.                         else {
  1806.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1807.                                     'name' => 'inv_on_transit_head')
  1808.                             );
  1809.                             if ($inv_transit_head)
  1810.                                 $to_balance_head $inv_transit_head->getData();
  1811.                         }
  1812.                         Accounts::CreateNewTransactionDetails($em,
  1813.                             '',
  1814.                             $toChangeVid,
  1815.                             Generic::CurrToInt($tot_inv_amount),
  1816.                             $to_balance_head,
  1817.                             in_array($stockReceivedType, [23]) ? 'Balancing of Stock in Items for -' $docHere->getDocumentHash() : 'In Transit Items for -' $docHere->getDocumentHash(),
  1818.                             AccountsConstant::CREDIT,
  1819.                             0,
  1820.                             [],
  1821.                             [],
  1822.                             $docHere->getCreatedLoginId()
  1823.                         );
  1824.                         if ($voucher)
  1825.                             $voucher->setTransactionAmount($tot_inv_amount);
  1826.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1827.                         if ($curr_v_ids != null)
  1828.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1829.                         else
  1830.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1831.                         $em->flush();
  1832. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  1833.                     }
  1834.                 }
  1835.             }
  1836.             $data = [];
  1837.             $query "SELECT purchase_invoice.* from  purchase_invoice
  1838. where purchase_invoice.purchase_invoice_date ='" $last_refresh_date " 00:00:00' and purchase_invoice.approved=1
  1839.             ";
  1840.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1841.             $queryData $stmt;
  1842.             foreach ($queryData as $pi) {
  1843.                 $transDate = new \DateTime($pi['purchase_invoice_date']);
  1844.                 if ($last_refresh_date_obj == '') {
  1845.                     $last_refresh_date_obj $transDate;
  1846.                 } else if ($transDate $last_refresh_date_obj) {
  1847.                     $last_refresh_date_obj $transDate;
  1848.                 }
  1849.                 Accounts::CalibrateProductPriceWithPi($em$pi['purchase_invoice_id'], 1);
  1850.             }
  1851.             $data = [];
  1852.             $query "SELECT expense_invoice.* from  expense_invoice
  1853. where expense_invoice.expense_invoice_date ='" $last_refresh_date " 00:00:00' and expense_invoice.approved=1 and
  1854.             expense_invoice_type_id=1";
  1855.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1856.             $queryData $stmt;
  1857.             foreach ($queryData as $ei) {
  1858.                 $transDate = new \DateTime($ei['expense_invoice_date']);
  1859.                 if ($last_refresh_date_obj == '') {
  1860.                     $last_refresh_date_obj $transDate;
  1861.                 } else if ($transDate $last_refresh_date_obj) {
  1862.                     $last_refresh_date_obj $transDate;
  1863.                 }
  1864.                 $grn_ids json_decode($ei['grn_id_list'], true);
  1865.                 if ($grn_ids == null)
  1866.                     $grn_ids = [];
  1867. //                if (!empty($grn_ids)) {
  1868. //
  1869. //
  1870. //                        if ($ei->getExpenseInvocationStrategyOnGrn() != 2) {
  1871. //                            $grn = $em->getRepository('ApplicationBundle\\Entity\\Grn')->findBy(array(
  1872. //                                'purchaseOrderId' => $ei->getPurchaseOrderId()
  1873. //                            ));
  1874. //
  1875. //                        }
  1876. //                        else
  1877. //                        {
  1878. //                            $po = $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(array(
  1879. //                                'purchaseOrderId' => $ei['purchase_order_id']
  1880. //                            ));
  1881. //
  1882. //                            if ($po) {
  1883. //                                $po->setExpenseAmount($po->getExpenseAmount() + $ei['invoice_amount']);
  1884. //                            }
  1885. //                            continue; //grn expense will be there anyway
  1886. //                        }
  1887. //
  1888. //
  1889. //
  1890. //                }
  1891.                 Accounts::CalibrateProductPriceWithExpense($em$ei['expense_invoice_id']);
  1892. //                $po = $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(array(
  1893. //                    'purchaseOrderId' => $ei['purchase_order_id']
  1894. //                ));
  1895. //
  1896. //
  1897. //                //first get the total valuation
  1898. //                if ($po) {
  1899. //                    $total_product_value = 0;
  1900. //                    $total_pending_expense = 0;
  1901. //                    $po_item_data = $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(array(
  1902. ////                'productId' => $item->getProductId(),
  1903. //                        'purchaseOrderId' => $ei['purchase_order_id']
  1904. //                    ));
  1905. //
  1906. //
  1907. //                    foreach ($po_item_data as $it) {
  1908. ////                    $product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(array(
  1909. ////                        'id' => $item->getProductId()
  1910. ////                    ));
  1911. //
  1912. //                        $poqty = $it->getReceived();
  1913. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);
  1914. //                        $total_product_value += (1 * $po_price);
  1915. //
  1916. //
  1917. //                    }
  1918. //
  1919. //
  1920. //                    //now we know the total grn price value. lets get the fraction increase
  1921. //                    $total_pending_expense = $ei['invoice_amount'];
  1922. //                    if ($total_product_value != 0)
  1923. //                        $fraction_increase = ($total_pending_expense) / ($total_product_value);
  1924. //                    else
  1925. //                        $fraction_increase = 0;
  1926. //
  1927. //                    foreach ($po_item_data as $it) {
  1928. //                        $item = $it;
  1929. //                        $product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(array(
  1930. //                            'id' => $it->getProductId()
  1931. //                        ));
  1932. //                        if (!$product)
  1933. //                            continue;
  1934. //
  1935. ////                    $items_in_inventory=$em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(array(
  1936. ////                        'productId'=>$item->getProductId()
  1937. ////                    ));
  1938. //
  1939. //                        $poqty = $it->getReceived();
  1940. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);;
  1941. //
  1942. //                        $existing_qty = $product->getQty();;
  1943. //
  1944. //
  1945. //                        $increased_po_price = ($po_price * $fraction_increase);
  1946. //
  1947. //                        //now lets see homuch is the total price
  1948. //                        $new_purchase_price = $product->getPurchasePrice();
  1949. //
  1950. //                        if ($increased_po_price != 0) {
  1951. //                            $last_grn_item = $em->getRepository('ApplicationBundle\\Entity\\GrnItem')->findOneBy(array(
  1952. //                                'purchaseOrderItemId' => $item->getId()
  1953. //                            ));
  1954. //                            if ($last_grn_item) {
  1955. //
  1956. //                                $data[$last_grn_item->getProductId()][] = array(
  1957. //                                    'date' => $last_refresh_date,
  1958. //
  1959. //                                    'entity' => array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  1960. //                                    'entityId' => $ei['expense_invoice_id'],
  1961. //                                    'colorId' => $last_grn_item->getColorId(),
  1962. //                                    'sizeId' => $last_grn_item->getSizeId(),
  1963. //                                    'entityDocHash' => $ei['document_hash'],
  1964. //                                    'qtyAdd' => 0,
  1965. //                                    'qtySub' => 0,
  1966. //                                    'valueAdd' => $increased_po_price,
  1967. ////                                    'valueAdd' => $increased_po_price>=0?$increased_po_price:0,
  1968. ////                    'valueSub' => ($item['qty'] * $item['price']),
  1969. ////                                    'valueSub' => $increased_po_price<0?((-1)*$increased_po_price):0,
  1970. //                                    'valueSub' => 0,
  1971. //                                    'price' => '_UNSET_',
  1972. //                                    'fromWarehouse' => 0,
  1973. //                                    'toWarehouse' => $last_grn_item->getWarehouseId(),
  1974. //                                    'fromWarehouseSub' => 0,
  1975. ////                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1976. //                                    'toWarehouseSub' => $last_grn_item->getWarehouseActionId()
  1977. //                                );
  1978. //
  1979. ////                                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);
  1980. ////
  1981. ////                                $total_item_price = $increased_po_price + ($product->getPurchasePrice() * ($existing_qty));
  1982. ////                                if ($existing_qty != 0)
  1983. ////                                    $new_purchase_price = $total_item_price / $existing_qty;
  1984. //
  1985. //
  1986. //                                $total_pending_expense -= $increased_po_price;
  1987. //                            }
  1988. //                        }
  1989. //                    }
  1990. //
  1991. //
  1992. //
  1993. //
  1994. //
  1995. //
  1996. //                } else {
  1997. //                    continue;
  1998. //                }
  1999.             }
  2000.             $data = [];
  2001.             //____________STOCK_TRANSFER___________________
  2002.             $docEntity "StockTransfer";
  2003.             $docEntityIdField "stockTransferId";
  2004.             $accTransactionDataByDocId = [];
  2005.             $query "SELECT stock_transfer_item.*,  stock_transfer.stock_transfer_date, stock_transfer.document_hash, stock_transfer.transfer_action_type from  stock_transfer_item
  2006.               join stock_transfer on stock_transfer.stock_transfer_id=stock_transfer_item.stock_transfer_id
  2007.             where stock_transfer.stock_transfer_date ='" $last_refresh_date " 00:00:00' and stock_transfer.approved=1";
  2008.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2009.             $queryData $stmt;
  2010.             $grn_ids = [];
  2011.             foreach ($queryData as $item) {
  2012.                 $data[$item['product_id']][] = array(
  2013.                     'date' => $last_refresh_date,
  2014.                     'transfer_action_type' => $item['transfer_action_type'],
  2015.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  2016.                     'entityId' => $item['stock_transfer_id'],
  2017.                     'colorId' => $item['color_id'],
  2018.                     'sizeId' => $item['size_id'],
  2019.                     'entityDocHash' => $item['document_hash'],
  2020.                     'qtyAdd' => $item['transfer_action_type'] == $item['qty'] : 0,
  2021.                     'qtySub' => $item['qty'],
  2022.                     'valueAdd' => 0,
  2023. //                    'valueSub' => ($item['qty'] * $item['price']),
  2024.                     'valueSub' => '_AUTO_',
  2025.                     'price' => $item['price'],
  2026.                     'fromWarehouse' => $item['warehouse_id'],
  2027.                     'toWarehouse' => $item['transfer_action_type'] == $item['to_warehouse_id'] : 0,
  2028.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  2029. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  2030.                     'toWarehouseSub' => $item['transfer_action_type'] == $item['to_warehouse_action_id'] : 0
  2031.                 );
  2032. //                if (!in_array($item['grn_id'], $grn_ids))
  2033. //                    $grn_ids[] = $item['grn_id'];
  2034.             }
  2035.             //now add grns
  2036.             foreach ($data as $key => $item) {
  2037.                 if (!empty($item)) {
  2038.                     foreach ($item as $entry) {
  2039.                         $transDate = new \DateTime($entry['date']);
  2040.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2041.                             $key,
  2042.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2043.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2044.                             $entry['fromWarehouse'],
  2045.                             $entry['toWarehouse'],
  2046.                             $entry['fromWarehouseSub'],
  2047.                             $entry['toWarehouseSub'],
  2048.                             $transDate,
  2049.                             $entry['qtyAdd'],
  2050.                             $entry['qtySub'],
  2051.                             $entry['valueAdd'],
  2052.                             $entry['valueSub'],
  2053.                             $entry['price'],
  2054.                             $this->getLoggedUserCompanyId($request),
  2055.                             0,
  2056.                             $entry['entity'],
  2057.                             $entry['entityId'],
  2058.                             $entry['entityDocHash'],
  2059.                             $entry['transfer_action_type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_INTER_WAREHOUSE GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT
  2060.                         );
  2061.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2062.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2063.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2064.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2065.                             "",
  2066.                             'inventory_refresh_debug'1); //last er 1 is append
  2067.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2068.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  2069.                         if ($entry['transfer_action_type'] == 4) {
  2070.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2071.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2072.                             else
  2073.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2074.                         }
  2075.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2076.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2077.                         else
  2078.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2079.                         if ($last_refresh_date_obj == '') {
  2080.                             $last_refresh_date_obj $transDate;
  2081.                         } else if ($transDate $last_refresh_date_obj) {
  2082.                             $last_refresh_date_obj $transDate;
  2083.                         }
  2084.                     }
  2085.                 }
  2086.             }
  2087.             if ($modifyAccTransaction == 1) {
  2088.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2089.                     $docHere $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  2090.                         $docEntityIdField => $docId,
  2091.                     ));;
  2092.                     if ($docHere) {
  2093.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2094.                         if ($curr_v_ids == null)
  2095.                             $curr_v_ids = [];
  2096.                         $skipVids = [];
  2097.                         $toChangeVid 0;
  2098.                         $voucher null;
  2099.                         foreach ($curr_v_ids as $vid) {
  2100.                             if (in_array($vid$skipVids))
  2101.                                 continue;
  2102.                             $skipVids[] = $vid//to prevent duplicate query
  2103.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2104.                                 'transactionId' => $vid,
  2105.                             ));;
  2106.                             if ($voucher) {
  2107.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2108.                                     $toChangeVid $vid;
  2109.                                 } else {
  2110.                                     continue;
  2111.                                 }
  2112.                             }
  2113.                         }
  2114.                         if ($toChangeVid == 0) {
  2115.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2116.                                 $em,
  2117.                                 $docHere->getStockTransferDate()->format('Y-m-d'),
  2118.                                 0,
  2119.                                 AccountsConstant::VOUCHER_JOURNAL,
  2120.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  2121.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2122.                                 'JV',
  2123.                                 'GN',
  2124.                                 0,
  2125.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2126.                                 0,
  2127.                                 $docHere->getCreatedLoginId(),
  2128.                                 $docHere->getCompanyId(),
  2129.                                 '',
  2130.                                 0,
  2131.                                 1
  2132.                             );
  2133.                             $em->flush();
  2134.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2135.                                 'transactionId' => $toChangeVid,
  2136.                             ));;
  2137.                         }
  2138.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  2139.                         $tot_inv_amount 0;
  2140.                         foreach ($transData as $k => $v) {
  2141.                             $tot_inv_amount += ($v);
  2142.                             Accounts::CreateNewTransactionDetails($em,
  2143.                                 '',
  2144.                                 $toChangeVid,
  2145.                                 Generic::CurrToInt($v),
  2146.                                 $k,
  2147.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2148.                                 $v >= AccountsConstant::DEBIT AccountsConstant::CREDIT,
  2149.                                 0,
  2150.                                 [],
  2151.                                 [],
  2152.                                 $docHere->getCreatedLoginId()
  2153.                             );
  2154.                         }
  2155. //                        $stockReceivedType = $docHere->getType();
  2156.                         $to_balance_head 0;
  2157.                         if ($docHere->getTransferActionType() == 4) {
  2158.                         } else {
  2159.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  2160.                                     'name' => 'inv_on_transit_head')
  2161.                             );
  2162.                             if ($inv_transit_head)
  2163.                                 $to_balance_head $inv_transit_head->getData();
  2164.                         }
  2165.                         if ($to_balance_head != 0) {
  2166.                             Accounts::CreateNewTransactionDetails($em,
  2167.                                 '',
  2168.                                 $toChangeVid,
  2169.                                 Generic::CurrToInt($tot_inv_amount),
  2170.                                 $to_balance_head,
  2171.                                 'In Transit Items for -' $docHere->getDocumentHash(),
  2172.                                 $tot_inv_amount >= AccountsConstant::CREDIT AccountsConstant::DEBIT,
  2173.                                 0,
  2174.                                 [],
  2175.                                 [],
  2176.                                 $docHere->getCreatedLoginId()
  2177.                             );
  2178.                         }
  2179.                         if ($voucher)
  2180.                             $voucher->setTransactionAmount($tot_inv_amount);
  2181.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2182.                         if ($curr_v_ids != null)
  2183.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2184.                         else
  2185.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2186.                         $em->flush();
  2187. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2188.                     }
  2189.                 }
  2190.             }
  2191.             $data = [];
  2192.             //____________IRR___________________
  2193.             $docEntity "ItemReceivedAndReplacement";
  2194.             $docEntityIdField "itemReceivedAndReplacementId";
  2195.             $accTransactionDataByDocId = [];
  2196.             $query "SELECT irr_item.*,  item_received_replacement.irr_date, item_received_replacement.document_hash from  irr_item
  2197.               join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  2198.             where item_received_replacement.irr_date ='" $last_refresh_date " 00:00:00' and item_received_replacement.approved=1";
  2199.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2200.             $queryData $stmt;
  2201.             $irr_add_data = [];
  2202.             $irr_replace_data = [];
  2203.             $irr_dispose_data = [];
  2204.             foreach ($queryData as $item) {
  2205.                 $irr_add_data[$item['received_product_id']][] = array(
  2206.                     'date' => $last_refresh_date,
  2207.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  2208.                     'entityId' => $item['irr_id'],
  2209.                     'colorId' => $item['received_product_color_id'],
  2210.                     'sizeId' => $item['received_product_color_id'],
  2211.                     'entityDocHash' => $item['document_hash'],
  2212.                     'qtyAdd' => $item['received_qty'],
  2213.                     'qtySub' => 0,
  2214.                     'valueAdd' => ($item['received_qty'] * $item['received_unit_purchase_price']),
  2215.                     'valueSub' => 0,
  2216.                     'price' => $item['received_unit_purchase_price'],
  2217.                     'fromWarehouse' => 0,
  2218.                     'toWarehouse' => $item['received_warehouse_id'],
  2219.                     'fromWarehouseSub' => 0,
  2220.                     'toWarehouseSub' => $item['received_warehouse_action_id']
  2221.                 );
  2222.                 $irr_replace_data[$item['replaced_product_id']][] = array(
  2223.                     'date' => $last_refresh_date,
  2224.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  2225.                     'entityId' => $item['irr_id'],
  2226.                     'colorId' => $item['replaced_product_color_id'],
  2227.                     'sizeId' => $item['replaced_product_color_id'],
  2228.                     'entityDocHash' => $item['document_hash'],
  2229.                     'qtyAdd' => 0,
  2230.                     'qtySub' => $item['replaced_qty'],
  2231.                     'valueAdd' => 0,
  2232.                     'valueSub' => ($item['replaced_qty'] * $item['replaced_unit_purchase_price']),
  2233.                     'price' => $item['replaced_unit_purchase_price'],
  2234.                     'fromWarehouse' => $item['replaced_warehouse_id'],
  2235.                     'toWarehouse' => 0,
  2236.                     'fromWarehouseSub' => $item['replaced_warehouse_action_id'],
  2237.                     'toWarehouseSub' => 0
  2238.                 );
  2239.                 $irr_dispose_data[$item['received_product_id']][] = array(
  2240.                     'date' => $last_refresh_date,
  2241.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  2242.                     'entityId' => $item['irr_id'],
  2243.                     'colorId' => $item['received_product_color_id'],
  2244.                     'sizeId' => $item['received_product_size_id'],
  2245.                     'entityDocHash' => $item['document_hash'],
  2246.                     'qtyAdd' => 0,
  2247.                     'qtySub' => $item['dispose_qty'],
  2248.                     'valueAdd' => 0,
  2249.                     'valueSub' => ($item['dispose_qty'] * $item['received_unit_purchase_price']),
  2250.                     'price' => $item['received_unit_purchase_price'],
  2251.                     'fromWarehouse' => $item['received_warehouse_id'],
  2252.                     'toWarehouse' => 0,
  2253.                     'fromWarehouseSub' => $item['received_warehouse_id'],
  2254.                     'toWarehouseSub' => 0
  2255.                 );
  2256.             }
  2257.             //now add irrs
  2258.             foreach ($irr_add_data as $key => $item) {
  2259.                 if (!empty($item)) {
  2260.                     foreach ($item as $entry) {
  2261.                         $transDate = new \DateTime($entry['date']);
  2262.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2263.                             $key,
  2264.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2265.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2266.                             $entry['fromWarehouse'],
  2267.                             $entry['toWarehouse'],
  2268.                             $entry['fromWarehouseSub'],
  2269.                             $entry['toWarehouseSub'],
  2270.                             $transDate,
  2271.                             $entry['qtyAdd'],
  2272.                             $entry['qtySub'],
  2273.                             $entry['valueAdd'],
  2274.                             $entry['valueSub'],
  2275.                             $entry['price'],
  2276.                             $this->getLoggedUserCompanyId($request),
  2277.                             0,
  2278.                             $entry['entity'],
  2279.                             $entry['entityId'],
  2280.                             $entry['entityDocHash'],
  2281.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2282.                         );
  2283.                         if ($modifiedData)
  2284.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2285.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2286.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2287.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2288.                                 "",
  2289.                                 'inventory_refresh_debug'1); //last er 1 is append
  2290.                         if ($last_refresh_date_obj == '') {
  2291.                             $last_refresh_date_obj $transDate;
  2292.                         } else if ($transDate $last_refresh_date_obj) {
  2293.                             $last_refresh_date_obj $transDate;
  2294.                         }
  2295.                     }
  2296.                 }
  2297.             }
  2298.             foreach ($irr_replace_data as $key => $item) {
  2299.                 if (!empty($item)) {
  2300.                     foreach ($item as $entry) {
  2301.                         $transDate = new \DateTime($entry['date']);
  2302.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2303.                             $key,
  2304.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2305.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2306.                             $entry['fromWarehouse'],
  2307.                             $entry['toWarehouse'],
  2308.                             $entry['fromWarehouseSub'],
  2309.                             $entry['toWarehouseSub'],
  2310.                             $transDate,
  2311.                             $entry['qtyAdd'],
  2312.                             $entry['qtySub'],
  2313.                             $entry['valueAdd'],
  2314.                             $entry['valueSub'],
  2315.                             $entry['price'],
  2316.                             $this->getLoggedUserCompanyId($request),
  2317.                             0,
  2318.                             $entry['entity'],
  2319.                             $entry['entityId'],
  2320.                             $entry['entityDocHash']);
  2321.                         if ($modifiedData)
  2322.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2323.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2324.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2325.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2326.                                 "",
  2327.                                 'inventory_refresh_debug'1); //last er 1 is append
  2328.                         if ($last_refresh_date_obj == '') {
  2329.                             $last_refresh_date_obj $transDate;
  2330.                         } else if ($transDate $last_refresh_date_obj) {
  2331.                             $last_refresh_date_obj $transDate;
  2332.                         }
  2333.                     }
  2334.                 }
  2335.             }
  2336.             foreach ($irr_dispose_data as $key => $item) {
  2337.                 if (!empty($item)) {
  2338.                     foreach ($item as $entry) {
  2339.                         $transDate = new \DateTime($entry['date']);
  2340.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2341.                             $key,
  2342.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2343.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2344.                             $entry['fromWarehouse'],
  2345.                             $entry['toWarehouse'],
  2346.                             $entry['fromWarehouseSub'],
  2347.                             $entry['toWarehouseSub'],
  2348.                             $transDate,
  2349.                             $entry['qtyAdd'],
  2350.                             $entry['qtySub'],
  2351.                             $entry['valueAdd'],
  2352.                             $entry['valueSub'],
  2353.                             $entry['price'],
  2354.                             $this->getLoggedUserCompanyId($request),
  2355.                             0,
  2356.                             $entry['entity'],
  2357.                             $entry['entityId'],
  2358.                             $entry['entityDocHash'],
  2359.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2360.                         );
  2361.                         if ($modifiedData)
  2362.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2363.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2364.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2365.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2366.                                 "",
  2367.                                 'inventory_refresh_debug'1); //last er 1 is append
  2368.                         if ($last_refresh_date_obj == '') {
  2369.                             $last_refresh_date_obj $transDate;
  2370.                         } else if ($transDate $last_refresh_date_obj) {
  2371.                             $last_refresh_date_obj $transDate;
  2372.                         }
  2373.                     }
  2374.                 }
  2375.             }
  2376.             $data = [];
  2377.             //____________DELIVERY_RECEIPT___________________
  2378.             $docEntity "DeliveryReceipt";
  2379.             $docEntityIdField "deliveryReceiptId";
  2380.             $accTransactionDataByDocId = [];
  2381.             $query "SELECT delivery_receipt_item.*, delivery_receipt.delivery_receipt_date, delivery_receipt.document_hash, delivery_receipt.skip_inventory_hit from  delivery_receipt_item
  2382.               join delivery_receipt on delivery_receipt.delivery_receipt_id=delivery_receipt_item.delivery_receipt_id
  2383.             where delivery_receipt.delivery_receipt_date ='" $last_refresh_date " 00:00:00' and delivery_receipt.approved=1";
  2384.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2385.             $queryData $stmt;
  2386.             foreach ($queryData as $item) {
  2387.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  2388.                     ->findOneBy(
  2389.                         array(
  2390.                             'id' => $item['product_id']
  2391.                         )
  2392.                     );
  2393.                 $curr_purchase_price $product->getPurchasePrice();
  2394.                 if ($item['skip_inventory_hit'] != 1) {
  2395.                     $data[$item['product_id']][] = array(
  2396.                         'date' => $last_refresh_date,
  2397.                         'entity' => array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  2398.                         'entityId' => $item['delivery_receipt_id'],
  2399.                         'colorId' => $item['color_id'],
  2400.                         'sizeId' => $item['size_id'],
  2401.                         'entityDocHash' => $item['document_hash'],
  2402.                         'qtyAdd' => 0,
  2403.                         'qtySub' => ($item['qty'] * $item['unit_multiplier']),
  2404.                         'valueAdd' => 0,
  2405.                         'valueSub' => '_AUTO_',
  2406.                         'price' => $curr_purchase_price,
  2407.                         'fromWarehouse' => $item['warehouse_id'],
  2408.                         'toWarehouse' => 0,
  2409.                         'fromWarehouseSub' => $item['warehouse_action_id'] != null $item['warehouse_action_id'] : GeneralConstant::WAREHOUSE_ACTION_GOODS,
  2410.                         'toWarehouseSub' => 0
  2411.                     );
  2412.                 }
  2413.                 $get_kids_sql "UPDATE `delivery_receipt_item` SET current_purchase_price='" $curr_purchase_price "' WHERE id=" $item['id'] . ";";
  2414.                 $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2415.             }
  2416.             foreach ($data as $key => $item) {
  2417.                 if (!empty($item)) {
  2418.                     foreach ($item as $entry) {
  2419.                         $transDate = new \DateTime($entry['date']);
  2420.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2421.                             $key,
  2422.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2423.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2424.                             $entry['fromWarehouse'],
  2425.                             $entry['toWarehouse'],
  2426.                             $entry['fromWarehouseSub'],
  2427.                             $entry['toWarehouseSub'],
  2428.                             $transDate,
  2429.                             $entry['qtyAdd'],
  2430.                             $entry['qtySub'],
  2431.                             $entry['valueAdd'],
  2432.                             $entry['valueSub'],
  2433.                             $entry['price'],
  2434.                             $this->getLoggedUserCompanyId($request),
  2435.                             0,
  2436.                             $entry['entity'],
  2437.                             $entry['entityId'],
  2438.                             $entry['entityDocHash'],
  2439.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2440.                         );
  2441.                         if ($modifiedData)
  2442.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2443.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2444.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2445.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2446.                                 "",
  2447.                                 'inventory_refresh_debug'1); //last er 1 is append
  2448.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2449.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  2450.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2451.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2452.                         else
  2453.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2454.                         if ($last_refresh_date_obj == '') {
  2455.                             $last_refresh_date_obj $transDate;
  2456.                         } else if ($transDate $last_refresh_date_obj) {
  2457.                             $last_refresh_date_obj $transDate;
  2458.                         }
  2459.                     }
  2460.                 }
  2461.             }
  2462.             if ($modifyAccTransaction == 1) {
  2463.                 //for now we are suuming there is only receipt without confirmation needed
  2464.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2465.                     $docHereDr $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  2466.                         $docEntityIdField => $docId,
  2467.                     ));;
  2468.                     $so $em->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findOneBy(
  2469.                         array(
  2470.                             'salesOrderId' => $docHereDr->getSalesOrderId()
  2471.                         )
  2472.                     );
  2473.                     $query $em->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
  2474.                         ->createQueryBuilder('p');
  2475.                     $query->where('p.salesOrderId = :soID')
  2476.                         ->setParameter('soID'$docHereDr->getSalesOrderId());
  2477.                     $query->andWhere("p.deliveryReceiptIds LIKE '%" $docId "%' ");
  2478.                     $query->setMaxResults(1);
  2479.                     $results $query->getQuery()->getResult();
  2480.                     $docHere null;
  2481.                     if (!empty($results))
  2482.                         $docHere $results[0];
  2483.                     if ($docHere) {
  2484.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2485.                         if ($curr_v_ids == null)
  2486.                             $curr_v_ids = [];
  2487.                         $skipVids = [];
  2488.                         $toChangeVid 0;
  2489.                         $voucher null;
  2490.                         foreach ($curr_v_ids as $vid) {
  2491.                             if (in_array($vid$skipVids))
  2492.                                 continue;
  2493.                             $skipVids[] = $vid//to prevent duplicate query
  2494.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2495.                                 'transactionId' => $vid,
  2496.                             ));;
  2497.                             if ($voucher) {
  2498.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2499.                                     $toChangeVid $vid;
  2500.                                 } else {
  2501.                                     continue;
  2502.                                 }
  2503.                                 if (strpos($voucher->getDescription(), 'Inventory') !== false) {
  2504. //                                    echo "Word Found!";
  2505.                                     $toChangeVid $vid;
  2506.                                 } else {
  2507.                                     continue;
  2508.                                 }
  2509.                             }
  2510.                         }
  2511.                         if ($toChangeVid == 0) {
  2512.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2513.                                 $em,
  2514.                                 $docHere->getSalesInvoiceDate()->format('Y-m-d'),
  2515.                                 0,
  2516.                                 AccountsConstant::VOUCHER_JOURNAL,
  2517.                                 'Journal For Inventory balance for Sales Invoice ' $docHere->getDocumentHash(),
  2518.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2519.                                 'JV',
  2520.                                 'GN',
  2521.                                 0,
  2522.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2523.                                 0,
  2524.                                 $docHere->getCreatedLoginId(),
  2525.                                 $docHere->getCompanyId(),
  2526.                                 '',
  2527.                                 0,
  2528.                                 1,
  2529.                                 0''$so->getBranchId(),
  2530.                                 AccountsConstant::INVOICE_REVENUE_JOURNAL,
  2531.                                 array_flip(GeneralConstant::$Entity_list)['SalesInvoice'], $docHere->getSalesInvoiceId(), $docHere->getDocumentHash()
  2532.                             );
  2533.                             $em->flush();
  2534.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2535.                                 'transactionId' => $toChangeVid,
  2536.                             ));;
  2537.                         }
  2538. //                        DeleteDocument::AccTransactions($em, $toChangeVid, 0);
  2539.                         //now remove cogs or inventory related transactions
  2540.                         $voucherDetails $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(array(
  2541.                             'transactionId' => $toChangeVid,
  2542.                         ));;
  2543.                         foreach ($voucherDetails as $vdtls) {
  2544.                             if (in_array($vdtls->getAccountsHeadId(), $inv_head_list)) {
  2545.                                 $em->remove($vdtls);
  2546.                                 $em->flush();
  2547.                             }
  2548.                             if ($cogs_head == $vdtls->getAccountsHeadId()) {
  2549.                                 $em->remove($vdtls);
  2550.                                 $em->flush();
  2551.                             }
  2552.                         }
  2553.                         $tot_inv_amount 0;
  2554.                         foreach ($transData as $k => $v) {
  2555.                             $tot_inv_amount += ($v);
  2556.                             Accounts::CreateNewTransactionDetails($em,
  2557.                                 '',
  2558.                                 $toChangeVid,
  2559.                                 Generic::CurrToInt($v),
  2560.                                 $k,
  2561.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2562.                                 AccountsConstant::DEBIT,
  2563.                                 0,
  2564.                                 [],
  2565.                                 [],
  2566.                                 $docHere->getCreatedLoginId()
  2567.                             );
  2568.                         }
  2569. //                        $stockReceivedType = $docHere->getType();
  2570.                         $to_balance_head 0;
  2571. //                        if ($docHere->getTransferActionType() == 4)
  2572.                         if (1) {
  2573.                         } else {
  2574.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  2575.                                     'name' => 'inv_on_transit_head')
  2576.                             );
  2577.                             if ($inv_transit_head)
  2578.                                 $to_balance_head $inv_transit_head->getData();
  2579.                         }
  2580.                         if ($to_balance_head != 0) {
  2581.                             Accounts::CreateNewTransactionDetails($em,
  2582.                                 '',
  2583.                                 $toChangeVid,
  2584.                                 Generic::CurrToInt($tot_inv_amount),
  2585.                                 $to_balance_head,
  2586.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  2587.                                 AccountsConstant::CREDIT,
  2588.                                 0,
  2589.                                 [],
  2590.                                 [],
  2591.                                 $docHere->getCreatedLoginId()
  2592.                             );
  2593.                         }
  2594.                         if ($voucher)
  2595.                             $voucher->setTransactionAmount($tot_inv_amount);
  2596.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2597.                         if ($curr_v_ids != null)
  2598.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2599.                         else
  2600.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2601.                         $em->flush();
  2602. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2603.                     }
  2604.                 }
  2605.             }
  2606.             $data = [];
  2607.             //____________STOCK_CONSUMPTION___________________
  2608.             $docEntity "StockConsumptionNote";
  2609.             $docEntityIdField "stockConsumptionNoteId";
  2610.             $accTransactionDataByDocId = [];
  2611.             $query "SELECT stock_consumption_note_item.*,  stock_consumption_note.stock_consumption_note_date, stock_consumption_note.document_hash, stock_consumption_note.data
  2612.               from  stock_consumption_note_item
  2613.               join stock_consumption_note on stock_consumption_note.stock_consumption_note_id=stock_consumption_note_item.stock_consumption_note_id
  2614.             where stock_consumption_note.stock_consumption_note_date ='" $last_refresh_date " 00:00:00' and stock_consumption_note.approved=1";
  2615.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2616.             $queryData $stmt;
  2617.             $consumption_data = [];
  2618.             $produced_data = [];
  2619.             $checked_stcm_ids = [];
  2620.             foreach ($queryData as $item) {
  2621. //                $product=$em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  2622. //                    ->findOneBy(
  2623. //                        array(
  2624. //                            'id'=>$item['product_id']
  2625. //                        )
  2626. //                    );
  2627. //
  2628. //                $curr_purchase_price=$product->getPurchasePrice();
  2629.                 if (!in_array($item['stock_consumption_note_id'], $checked_stcm_ids)) {
  2630.                     $conversion_data json_decode($item['data'], true);
  2631.                     if ($conversion_data == null)
  2632.                         $conversion_data = [];
  2633.                     if (isset($conversion_data['conversionData'])) {
  2634.                         if (isset($conversion_data['conversionData']['converted_products'])) {
  2635.                             $curr_spec_data $conversion_data['conversionData'];
  2636.                             foreach ($curr_spec_data['converted_products'] as $pika_key => $val) {
  2637.                                 $consumption_data[$val][] = array(
  2638.                                     'date' => $last_refresh_date,
  2639.                                     'type' => 2,
  2640.                                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2641.                                     'entityId' => $item['stock_consumption_note_id'],
  2642.                                     'colorId' => isset($curr_spec_data['converted_product_colors'][$pika_key]) ? ($curr_spec_data['converted_product_colors'][$pika_key]) : 0,
  2643.                                     'sizeId' => isset($curr_spec_data['converted_product_sizes'][$pika_key]) ? ($curr_spec_data['converted_product_sizes'][$pika_key]) : 0,
  2644.                                     'entityDocHash' => $item['document_hash'],
  2645.                                     'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_units'][$pika_key]) : 0,
  2646.                                     'qtySub' => 0,
  2647.                                     '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,
  2648.                                     'valueSub' => 0,
  2649.                                     'price' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_unit_price'][$pika_key]) : 0,
  2650.                                     'fromWarehouse' => 0,
  2651.                                     'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key]) ? ($curr_spec_data['converted_warehouseId'][$pika_key]) : 0,
  2652.                                     'fromWarehouseSub' => 0,
  2653.                                     'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key]) ? ($curr_spec_data['converted_warehouseActionId'][$pika_key]) : 0
  2654.                                 );
  2655.                             }
  2656.                         }
  2657.                     }
  2658. //                    if(isset($conversion_data['expenseCost'] ))
  2659. //                    if(isset($conversion_data['expenseCost']['expense_heads'] ))
  2660. //                    {
  2661. //                        $curr_spec_data=$conversion_data['expenseCost'];
  2662. //                        foreach($curr_spec_data['expense_heads'] as $pika_key=>$val)
  2663. //                        {
  2664. //
  2665. //                            $consumption_data[$val][] = array(
  2666. //                                'date' => $last_refresh_date,
  2667. //                                'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2668. //                                'entityId' => $item['stock_consumption_note_id'],
  2669. //                                'entityDocHash' => $item['document_hash'],
  2670. //                                'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_units'][$pika_key]):0,
  2671. //                                'qtySub' => 0,
  2672. //                                '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,
  2673. //                                'valueSub' => 0,
  2674. //                                'price' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_unit_price'][$pika_key]):0,
  2675. //                                'fromWarehouse' => 0,
  2676. //                                'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key])?(1*$curr_spec_data['converted_warehouseId'][$pika_key]):0,
  2677. //                                'fromWarehouseSub' => 0,
  2678. //                                'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key])?(1*$curr_spec_data['converted_warehouseActionId'][$pika_key]):0
  2679. //                            );
  2680. //                        }
  2681. //                    }
  2682.                     $checked_stcm_ids[] = $item['stock_consumption_note_id'];
  2683.                 }
  2684.                 $consumption_data[$item['product_id']][] = array(
  2685.                     'date' => $last_refresh_date,
  2686.                     'type' => 1,
  2687.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2688.                     'entityId' => $item['stock_consumption_note_id'],
  2689.                     'colorId' => $item['color_id'],
  2690.                     'sizeId' => $item['size_id'],
  2691.                     'entityDocHash' => $item['document_hash'],
  2692.                     'qtyAdd' => 0,
  2693.                     'qtySub' => ($item['qty'] * 1),
  2694.                     'valueAdd' => 0,
  2695.                     'valueSub' => (($item['qty']) * ($item['price'])),
  2696.                     'price' => $item['price'],
  2697.                     'fromWarehouse' => $item['warehouse_id'],
  2698.                     'toWarehouse' => 0,
  2699.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  2700.                     'toWarehouseSub' => 0
  2701.                 );
  2702. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2703. //                $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  2704. //                
  2705.             }
  2706.             foreach ($consumption_data as $key => $item) {
  2707.                 if (!empty($item)) {
  2708.                     foreach ($item as $entry) {
  2709.                         $transDate = new \DateTime($entry['date']);
  2710.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2711.                             $key,
  2712.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2713.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2714.                             $entry['fromWarehouse'],
  2715.                             $entry['toWarehouse'],
  2716.                             $entry['fromWarehouseSub'],
  2717.                             $entry['toWarehouseSub'],
  2718.                             $transDate,
  2719.                             $entry['qtyAdd'],
  2720.                             $entry['qtySub'],
  2721.                             $entry['valueAdd'],
  2722.                             $entry['valueSub'],
  2723.                             $entry['price'],
  2724.                             $this->getLoggedUserCompanyId($request),
  2725.                             0,
  2726.                             $entry['entity'],
  2727.                             $entry['entityId'],
  2728.                             $entry['entityDocHash'],
  2729.                             $entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION
  2730.                         );
  2731.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2732.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2733.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2734.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2735.                             "",
  2736.                             'inventory_refresh_debug'1); //last er 1 is append
  2737.                         if ($last_refresh_date_obj == '') {
  2738.                             $last_refresh_date_obj $transDate;
  2739.                         } else if ($transDate $last_refresh_date_obj) {
  2740.                             $last_refresh_date_obj $transDate;
  2741.                         }
  2742.                     }
  2743.                 }
  2744.             }
  2745.             $data = [];
  2746.             //____________PRODUCTION___________________
  2747.             $docEntity "Production";
  2748.             $docEntityIdField "productionId";
  2749.             $accTransactionDataByDocId = [];
  2750.             $consumedAmountByProductionId = [];
  2751.             $query "SELECT * from production_process_settings
  2752.             where approved=1 order by production_process_settings_id asc  ";
  2753.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2754.             $processList $stmt;
  2755. //            $processList=[];
  2756.             foreach ($processList as $process) {
  2757.                 $query "SELECT production_entry_item.*,  production.production_date, production.document_hash
  2758.               from  production_entry_item
  2759.               join production on production_entry_item.production_id=production.production_id
  2760.             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  ";
  2761.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  2762.                 $queryData $stmt;
  2763.                 $produced_data = [];
  2764.                 $rejected_data = [];
  2765.                 $consumed_data = [];
  2766.                 foreach ($queryData as $item) {
  2767. //                $product=$em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  2768. //                    ->findOneBy(
  2769. //                        array(
  2770. //                            'id'=>$item['product_id']
  2771. //                        )
  2772. //                    );
  2773. //
  2774. //                $curr_purchase_price=$product->getPurchasePrice();
  2775.                     if ($item['price'] == '')
  2776.                         $item['price'] = 0;
  2777.                     if ($item['price'] < 0)
  2778.                         $item['price'] = 0;
  2779.                     $item['production_nature_id'];
  2780.                     $consumed_data[$item['product_id']][] = array(
  2781.                         'date' => $last_refresh_date,
  2782.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2783.                         'entityId' => $item['production_id'],
  2784.                         'colorId' => $item['color_id'],
  2785.                         'sizeId' => $item['size_id'],
  2786.                         'entityDocHash' => $item['document_hash'],
  2787.                         'qtyAdd' => 0,
  2788.                         'qtySub' => ($item['additional_consumed_qty'] * 1) + ($item['consumed_qty']),
  2789.                         'valueAdd' => 0,
  2790.                         'valueSub' => '_AUTO_',
  2791.                         'price' => $item['price'],
  2792.                         'fromWarehouse' => $item['warehouse_id'],
  2793.                         'toWarehouse' => 0,
  2794.                         'fromWarehouseSub' => $item['consumed_item_action_tag_id'],
  2795.                         'toWarehouseSub' => 0,
  2796.                         'production_nature_id' => $item['production_nature_id'],
  2797.                     );
  2798.                     $produced_data[$item['product_id']][] = array(
  2799.                         'date' => $last_refresh_date,
  2800.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2801.                         'entityId' => $item['production_id'],
  2802.                         'colorId' => $item['color_id'],
  2803.                         'sizeId' => $item['size_id'],
  2804.                         'entityDocHash' => $item['document_hash'],
  2805.                         'qtyAdd' => ($item['accepted_qty'] * 1),
  2806.                         'qtySub' => 0,
  2807.                         'valueAdd' => (($item['accepted_qty'] * 1) * ($item['price'])),
  2808.                         'valueSub' => 0,
  2809.                         'price' => $item['price'],
  2810.                         'fromWarehouse' => 0,
  2811.                         'toWarehouse' => $item['warehouse_id'],
  2812.                         'fromWarehouseSub' => 0,
  2813.                         'toWarehouseSub' => $item['produced_item_action_tag_id'],
  2814.                         'production_nature_id' => $item['production_nature_id'],
  2815.                     );
  2816.                     $rejected_data[$item['product_id']][] = array(
  2817.                         'date' => $last_refresh_date,
  2818.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2819.                         'entityId' => $item['production_id'],
  2820.                         'colorId' => $item['color_id'],
  2821.                         'sizeId' => $item['size_id'],
  2822.                         'entityDocHash' => $item['document_hash'],
  2823.                         'qtyAdd' => ($item['rejected_qty'] * 1),
  2824.                         'qtySub' => 0,
  2825.                         'valueAdd' => (($item['rejected_qty'] * 1) * ($item['price'])),
  2826.                         'valueSub' => 0,
  2827.                         'price' => $item['price'],
  2828.                         'fromWarehouse' => 0,
  2829.                         'toWarehouse' => $item['warehouse_id'],
  2830.                         'fromWarehouseSub' => 0,
  2831.                         'toWarehouseSub' => $item['rejected_item_action_tag_id'],
  2832.                         'production_nature_id' => $item['production_nature_id'],
  2833.                     );
  2834. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2835. //                $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  2836. //                
  2837.                 }
  2838.                 foreach ($consumed_data as $key => $item) {
  2839.                     if (!empty($item)) {
  2840.                         foreach ($item as $entry) {
  2841.                             $transDate = new \DateTime($entry['date']);
  2842.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2843.                                 $key,
  2844.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2845.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2846.                                 $entry['fromWarehouse'],
  2847.                                 $entry['toWarehouse'],
  2848.                                 $entry['fromWarehouseSub'],
  2849.                                 $entry['toWarehouseSub'],
  2850.                                 $transDate,
  2851.                                 $entry['qtyAdd'],
  2852.                                 $entry['qtySub'],
  2853.                                 $entry['valueAdd'],
  2854.                                 $entry['valueSub'],
  2855.                                 $entry['price'],
  2856.                                 $this->getLoggedUserCompanyId($request),
  2857.                                 0,
  2858.                                 $entry['entity'],
  2859.                                 $entry['entityId'],
  2860.                                 $entry['entityDocHash'],
  2861.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION);
  2862.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2863.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2864.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2865.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2866.                                 "",
  2867.                                 'inventory_refresh_debug'1); //last er 1 is append
  2868.                             if (!isset($consumedAmountByProductionId[$entry['entityId']]))
  2869.                                 $consumedAmountByProductionId[$entry['entityId']] = ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2870.                             else
  2871.                                 $consumedAmountByProductionId[$entry['entityId']] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2872.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2873.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  2874.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2875.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2876.                             else
  2877.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2878.                             if ($last_refresh_date_obj == '') {
  2879.                                 $last_refresh_date_obj $transDate;
  2880.                             } else if ($transDate $last_refresh_date_obj) {
  2881.                                 $last_refresh_date_obj $transDate;
  2882.                             }
  2883.                         }
  2884.                     }
  2885.                 }
  2886.                 foreach ($produced_data as $key => $item) {
  2887.                     if (!empty($item)) {
  2888.                         foreach ($item as $entry) {
  2889.                             $transDate = new \DateTime($entry['date']);
  2890.                             $productionNature $entry['production_nature_id'];
  2891.                             if (in_array($productionNature, [12])) {
  2892.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2893.                                     $key,
  2894.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2895.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2896.                                     $entry['fromWarehouse'],
  2897.                                     $entry['toWarehouse'],
  2898.                                     $entry['fromWarehouseSub'],
  2899.                                     $entry['toWarehouseSub'],
  2900.                                     $transDate,
  2901.                                     $entry['qtyAdd'],
  2902.                                     $entry['qtySub'],
  2903. //                                $entry['valueAdd'],
  2904.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2905.                                     $entry['valueSub'],
  2906.                                     $entry['price'],
  2907.                                     $this->getLoggedUserCompanyId($request),
  2908.                                     0,
  2909.                                     $entry['entity'],
  2910.                                     $entry['entityId'],
  2911.                                     $entry['entityDocHash'],
  2912.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2913.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2914.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2915.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2916.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2917.                                     "",
  2918.                                     'inventory_refresh_debug'1); //last er 1 is append
  2919.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2920.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2921.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2922.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2923.                                 else
  2924.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2925. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2926. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2927. //                            else
  2928. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2929.                             } else {
  2930.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2931.                                     $key,
  2932.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2933.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2934.                                     $entry['fromWarehouse'],
  2935.                                     $entry['toWarehouse'],
  2936.                                     $entry['fromWarehouseSub'],
  2937.                                     $entry['toWarehouseSub'],
  2938.                                     $transDate,
  2939.                                     0,
  2940.                                     0,
  2941. //                                $entry['valueAdd'],
  2942.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2943.                                     0,
  2944.                                     $entry['price'],
  2945.                                     $this->getLoggedUserCompanyId($request),
  2946.                                     0,
  2947.                                     $entry['entity'],
  2948.                                     $entry['entityId'],
  2949.                                     $entry['entityDocHash'],
  2950.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2951.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2952.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2953.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2954.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2955.                                     "",
  2956.                                     'inventory_refresh_debug'1); //last er 1 is append
  2957.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2958.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2959.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2960.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2961.                                 else
  2962.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2963. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2964. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2965. //                            else
  2966. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2967.                             }
  2968.                             if ($last_refresh_date_obj == '') {
  2969.                                 $last_refresh_date_obj $transDate;
  2970.                             } else if ($transDate $last_refresh_date_obj) {
  2971.                                 $last_refresh_date_obj $transDate;
  2972.                             }
  2973.                         }
  2974.                     }
  2975.                 }
  2976.                 foreach ($rejected_data as $key => $item) {
  2977.                     if (!empty($item)) {
  2978.                         foreach ($item as $entry) {
  2979.                             $transDate = new \DateTime($entry['date']);
  2980.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2981.                                 $key,
  2982.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2983.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2984.                                 $entry['fromWarehouse'],
  2985.                                 $entry['toWarehouse'],
  2986.                                 $entry['fromWarehouseSub'],
  2987.                                 $entry['toWarehouseSub'],
  2988.                                 $transDate,
  2989.                                 $entry['qtyAdd'],
  2990.                                 $entry['qtySub'],
  2991.                                 $entry['valueAdd'],
  2992.                                 $entry['valueSub'],
  2993.                                 $entry['price'],
  2994.                                 $this->getLoggedUserCompanyId($request),
  2995.                                 0,
  2996.                                 $entry['entity'],
  2997.                                 $entry['entityId'],
  2998.                                 $entry['entityDocHash'],
  2999.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  3000.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  3001.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  3002.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  3003.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  3004.                                 "",
  3005.                                 'inventory_refresh_debug'1); //last er 1 is append
  3006.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  3007.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  3008.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  3009.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = (-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  3010.                             else
  3011.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ((-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  3012.                             if ($last_refresh_date_obj == '') {
  3013.                                 $last_refresh_date_obj $transDate;
  3014.                             } else if ($transDate $last_refresh_date_obj) {
  3015.                                 $last_refresh_date_obj $transDate;
  3016.                             }
  3017.                         }
  3018.                     }
  3019.                 }
  3020.             }
  3021.             if ($modifyAccTransaction == 1) {
  3022.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  3023.                     $docHere $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  3024.                         $docEntityIdField => $docId,
  3025.                     ));;
  3026.                     if ($docHere) {
  3027.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  3028.                         if ($curr_v_ids == null)
  3029.                             $curr_v_ids = [];
  3030.                         $skipVids = [];
  3031.                         $toChangeVid 0;
  3032.                         $voucher null;
  3033.                         foreach ($curr_v_ids as $vid) {
  3034.                             if (in_array($vid$skipVids))
  3035.                                 continue;
  3036.                             $skipVids[] = $vid//to prevent duplicate query
  3037.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  3038.                                 'transactionId' => $vid,
  3039.                             ));;
  3040.                             if ($voucher) {
  3041.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  3042.                                     $toChangeVid $vid;
  3043.                                 } else {
  3044.                                     continue;
  3045.                                 }
  3046.                             }
  3047.                         }
  3048.                         if ($toChangeVid == 0) {
  3049.                             $toChangeVid Accounts::CreateNewTransaction(0,
  3050.                                 $em,
  3051.                                 $docHere->getProductionDate()->format('Y-m-d'),
  3052.                                 0,
  3053.                                 AccountsConstant::VOUCHER_JOURNAL,
  3054.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  3055.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  3056.                                 'JV',
  3057.                                 'GN',
  3058.                                 0,
  3059.                                 Accounts::GetVNoHash($em'jv''gn'0),
  3060.                                 0,
  3061.                                 $docHere->getCreatedLoginId(),
  3062.                                 $docHere->getCompanyId(),
  3063.                                 '',
  3064.                                 0,
  3065.                                 1
  3066.                             );
  3067.                             $em->flush();
  3068.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  3069.                                 'transactionId' => $toChangeVid,
  3070.                             ));;
  3071.                         }
  3072.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  3073.                         $tot_inv_amount 0;
  3074.                         foreach ($transData as $k => $v) {
  3075.                             $tot_inv_amount += ($v);
  3076.                             Accounts::CreateNewTransactionDetails($em,
  3077.                                 '',
  3078.                                 $toChangeVid,
  3079.                                 Generic::CurrToInt($v),
  3080.                                 $k,
  3081.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  3082.                                 AccountsConstant::DEBIT,
  3083.                                 0,
  3084.                                 [],
  3085.                                 [],
  3086.                                 $docHere->getCreatedLoginId()
  3087.                             );
  3088.                         }
  3089. //                        $stockReceivedType = $docHere->getType();
  3090.                         $to_balance_head 0;
  3091. //                        if ($docHere->getTransferActionType() == 4)
  3092.                         if (1) {
  3093.                         } else {
  3094.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  3095.                                     'name' => 'inv_on_transit_head')
  3096.                             );
  3097.                             if ($inv_transit_head)
  3098.                                 $to_balance_head $inv_transit_head->getData();
  3099.                         }
  3100.                         if ($to_balance_head != 0) {
  3101.                             Accounts::CreateNewTransactionDetails($em,
  3102.                                 '',
  3103.                                 $toChangeVid,
  3104.                                 Generic::CurrToInt($tot_inv_amount),
  3105.                                 $to_balance_head,
  3106.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  3107.                                 AccountsConstant::CREDIT,
  3108.                                 0,
  3109.                                 [],
  3110.                                 [],
  3111.                                 $docHere->getCreatedLoginId()
  3112.                             );
  3113.                         }
  3114.                         if ($voucher)
  3115.                             $voucher->setTransactionAmount($tot_inv_amount);
  3116.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  3117.                         if ($curr_v_ids != null)
  3118.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  3119.                         else
  3120.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  3121.                         $em->flush();
  3122. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  3123.                     }
  3124.                 }
  3125.             }
  3126.             if ($terminate == 0) {
  3127.                 return new JsonResponse(array(
  3128.                     "success" => true,
  3129.                     "last_refresh_date" => $last_refresh_date,
  3130.                     "inventory_refreshed" => $refreshed_opening
  3131.                 ));
  3132.             } else {
  3133.                 return new JsonResponse(array(
  3134.                     "success" => false,
  3135.                     "last_refresh_date" => $last_refresh_date,
  3136.                     "inventory_refreshed" => $refreshed_opening
  3137.                 ));
  3138.             }
  3139.         }
  3140.         return new JsonResponse(array(
  3141.             "success" => false,
  3142.             "last_refresh_date" => $last_refresh_date,
  3143.             "inventory_refreshed" => $refreshed_opening
  3144.         ));
  3145.         //2 .now make an array with necessary data based on challan and grn for now willl need consumption later
  3146.         //broken into transactions not closing
  3147.         //structure---> $data['productId']=array(
  3148.         //'date'=>'2017-09-02 00:00:00'
  3149.         //'qtyAdd'=>'2'
  3150.         //'qtySub'=>'0'
  3151.         //'valueAdd'=>'2000'
  3152.         //'valueSub'=>'0'
  3153.         //'fromWarehouse'=>'0'
  3154.         //'toWarehouse'=>'0'
  3155.         //'fromWarehouseSub'=>'0'
  3156.         //'toWarehouseSub'=>'0'
  3157.         //)
  3158.         //
  3159.     }
  3160.     public function OpeningItemAction(Request $request)
  3161.     {
  3162.         $em $this->getDoctrine()->getManager();
  3163.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  3164.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  3165.         if ($request->isMethod('POST')) {
  3166.             $pp trim($request->request->get('purchasePrice'));
  3167. //replace comma with space
  3168.             $pp str_replace(","""$pp);
  3169.             if ($request->request->get('productId') != '') {
  3170.                 foreach ($request->request->get('warehouseId') as $key => $value) {
  3171.                     $data = array(
  3172.                         'productId' => $request->request->get('productId'),
  3173.                         'warehouseId' => $request->request->get('warehouseId')[$key],
  3174.                         'warehouseActionId' => $request->request->get('warehouseActionId')[$key],
  3175.                         'purchasePrice' => $pp,
  3176.                         'date' => new \DateTime($request->request->get('date')),
  3177.                         'qty' => $request->request->get('qty')[$key],
  3178.                     );
  3179.                     $transDate = new \DateTime($request->request->get('date'));
  3180.                     $new = new InvItemInOut();
  3181.                     $new->setProductId($request->request->get('productId'));
  3182.                     $new->setWarehouseId($request->request->get('warehouseId')[$key]);
  3183.                     $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  3184.                     $new->setActionTagId($request->request->get('warehouseActionId')[$key]);
  3185.                     $new->setTransactionDate($transDate);
  3186.                     $new->setQty($request->request->get('qty')[$key]);
  3187.                     $new->setPrice($pp);
  3188.                     $new->setAmount($request->request->get('qty')[$key] * $pp);
  3189.                     $new->setEntity(0);// opening =0
  3190.                     $new->setEntityId(0);// opening =0
  3191.                     $new->setDebitCreditHeadId(0);// opening =0
  3192.                     $new->setVoucherIds(null);// opening =0
  3193.                     $em->persist($new);
  3194.                     $em->flush();
  3195. //                    $total_inv_value_in_by_id += $request->request->get('qty')[$key] * $pp;
  3196.                     Inventory::AddOpeningInventoryStock($em$data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3197.                 }
  3198.             }
  3199.         }
  3200.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  3201.             'name' => 'warehouse_action_1'//for now for stock of goods
  3202.         ));
  3203.         return $this->render('@Inventory/pages/input_forms/opening_item_assign.html.twig',
  3204.             array(
  3205.                 'page_title' => "Opening Items",
  3206.                 'inv_head' => $inv_head $inv_head->getData() : '',
  3207.                 'products' => $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\InvProducts')->findBy(array(
  3208.                     'status' => GeneralConstant::ACTIVE//for now for stock of goods
  3209. //                    'opening_locked'=>0
  3210.                 )),
  3211.                 'warehouseList' => Inventory::WarehouseList($em),
  3212.                 'warehouseActionList' => $warehouse_action_list
  3213.             )
  3214.         );
  3215.     }
  3216.     public function CreateProductCategoryAction(Request $request)
  3217.     {
  3218.         if ($request->isMethod('POST')) {
  3219.             $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));
  3220.             if ($cat_data['id'] != '')
  3221.                 return new JsonResponse(array("success" => true'cat_data' => $cat_data));
  3222.         }
  3223.         return new JsonResponse(array("success" => false,));
  3224. //        return $this->redirectToRoute("create_product");
  3225.     }
  3226.     public function CreateProductSubCategoryAction(Request $request)
  3227.     {
  3228.         if ($request->isMethod('POST')) {
  3229.             $spec_data Inventory::CreateSubCategory($this->getDoctrine()->getManager(),
  3230.                 $this->getLoggedUserCompanyId($request), $request->request->get('spec_name'),
  3231.                 $request->request->get('level'0),
  3232.                 $request->request->get('parentId'0),
  3233.                 $request->request->get('itemgroupId'),
  3234.                 $request->request->get('categoryId'),
  3235.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3236.             if ($spec_data['id'] != '')
  3237.                 return new JsonResponse(array("success" => true'spec_data' => $spec_data'level' => $request->request->get('level'0)));
  3238.         }
  3239.         return new JsonResponse(array("success" => false,));
  3240. //        return $this->redirectToRoute("create_product");
  3241.     }
  3242.     public function CreateProductSpecAction(Request $request)
  3243.     {
  3244.         $em $this->getDoctrine()->getManager();
  3245.         if ($request->isMethod('POST')) {
  3246.             //1st add to cnetral server
  3247.             $spec_data=[
  3248.                 'id' => 0,
  3249.                 'global_id' => 0,
  3250.                 'name' => $request->request->get('name'''),
  3251.                 'unit_text' => $request->request->get('unitText'''),
  3252.                 'unique_hash' => $request->request->get('uniqueHash'''),
  3253.                 'markers' => $request->request->get('markers'''),
  3254.                 'tags' => $request->request->get('tags'''),
  3255.             ];
  3256.             $specType $em->getRepository('ApplicationBundle\\Entity\\SpecType')->findOneBy(array(
  3257.                 'uniqueHash' => $request->request->get('uniqueHash'''),
  3258.             ));
  3259.             if ($specType) {
  3260.                 $spec_data['id'] = $specType->getId();
  3261.                 $spec_data['global_id'] = $specType->getGlobalId();
  3262.             }
  3263.             if(!$spec_data['global_id']) {
  3264.                 $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/api/create_product_spec_public';
  3265.                 $curl curl_init();
  3266.                 curl_setopt_array($curl, [
  3267.                     CURLOPT_RETURNTRANSFER => true,
  3268.                     CURLOPT_POST => true,
  3269.                     CURLOPT_URL => $urlToCall,
  3270.                     CURLOPT_CONNECTTIMEOUT => 10,
  3271.                     CURLOPT_SSL_VERIFYPEER => false,
  3272.                     CURLOPT_SSL_VERIFYHOST => false,
  3273.                     CURLOPT_HTTPHEADER => [],
  3274.                     CURLOPT_POSTFIELDS => http_build_query([
  3275.                         'name' => $request->request->get('name'''),
  3276.                         'unitText' => $request->request->get('unitText'''),
  3277.                         'uniqueHash' => $request->request->get('uniqueHash'''),
  3278.                         'markers' => $request->request->get('markers'''),
  3279.                         'tags' => $request->request->get('tags'''),
  3280.                     ])
  3281.                 ]);
  3282.                 $retData curl_exec($curl);
  3283.                 $errData curl_error($curl);
  3284.                 curl_close($curl);
  3285.                 if ($errData) {
  3286.                     return new JsonResponse(['success' => false]);
  3287.                 }
  3288.                 $retData json_decode($retDatatrue);
  3289.                 $spec_data $retData['spec_data'];
  3290.             }
  3291.             $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  3292.             $spec_data Inventory::CreateProductSpecification($em,
  3293.                 $systemType,
  3294.                 $spec_data['name'],
  3295.                 $spec_data['unit_text'],
  3296.                 $spec_data['unique_hash'],
  3297.                 $spec_data['markers'],
  3298.                 $spec_data['tags'],
  3299.                 $spec_data['global_id'],
  3300.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3301.             );
  3302.             if ($spec_data['id'] != '')
  3303.                 return new JsonResponse(array("success" => true'spec_data' => $spec_data));
  3304.         }
  3305.         return new JsonResponse(array("success" => false,));
  3306. //        return $this->redirectToRoute("create_product");
  3307.     }
  3308.     public function CreateProductBrandAction(Request $request)
  3309.     {
  3310.         if ($request->isMethod('POST')) {
  3311.             $data Inventory::CreateBrand($this->getDoctrine()->getManager(),
  3312.                 $this->getLoggedUserCompanyId($request), $request->request->get('brand_name'),
  3313.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3314.             if ($data['id'] != '')
  3315.                 return new JsonResponse(array("success" => true'data' => $data));
  3316.         }
  3317.         return new JsonResponse(array("success" => false,));
  3318. //        return $this->redirectToRoute("create_product");
  3319.     }
  3320.     public function CreateIssueNoteAction(Request $request)
  3321.     {
  3322.         return $this->render('@Inventory/pages/input_forms/issue_note.html.twig',
  3323.             array(
  3324.                 'page_title' => 'Issue Note'
  3325.             )
  3326.         );
  3327.     }
  3328.     public function ProcessDraftDeliveryReceiptAction(Request $request$id 0)
  3329.     {
  3330.         $em $this->getDoctrine()->getManager();
  3331.         $companyId $this->getLoggedUserCompanyId($request);
  3332.         $extId $id;
  3333.         $receiptId $id;
  3334.         $allowed 0;
  3335.         if ($request->isMethod('POST')) {
  3336.             $receiptId $request->request->get('deliveryReceiptId');
  3337.             $QD $this->getDoctrine()
  3338.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3339.                 ->findOneBy(
  3340.                     array(
  3341.                         'deliveryReceiptId' => $receiptId
  3342.                     ),
  3343.                     array()
  3344.                 );
  3345.             $soId $QD->getSalesOrderId();
  3346.             $drData = [];
  3347.             $dr_item_data $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')->findBy(
  3348.                 array(
  3349.                     'deliveryReceiptId' => $receiptId,
  3350.                 )
  3351.             );
  3352.             foreach ($dr_item_data as $dr_item) {
  3353.                 $drData[] = array(
  3354.                     'soItemId' => $dr_item->getSalesorderItemId(),
  3355.                     'qty' => $dr_item->getQty()
  3356.                 );
  3357.             }
  3358. //            $drData=[
  3359. //                ['soItemId'=>9,'qty'=>9],
  3360. //                ['soItemId'=>9,'qty'=>9],
  3361. //                ['soItemId'=>9,'qty'=>9],
  3362. //            ];
  3363.             $toGetSoItemsId = [];
  3364.             $toGetDoItemsId = [];
  3365.             $drDataBySoItemId = [];
  3366.             $drDataByDoItemId = [];
  3367.             $so $em->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findOneBy(array(
  3368.                 'salesOrderId' => $soId   //$id is soId
  3369.             ));
  3370.             if ($so->getDeliveryOrderSkipFlag() == 1) {
  3371.                 foreach ($drData as $pp) {
  3372.                     $toGetSoItemsId[] = $pp['soItemId'];
  3373.                     $drDataBySoItemId[$pp['soItemId']] = $pp;
  3374.                 }
  3375.             } else {
  3376.                 foreach ($drData as $pp) {
  3377.                     $toGetDoItemsId[] = $pp['soItemId'];
  3378.                     $drDataByDoItemId[$pp['soItemId']] = $pp;
  3379.                 }
  3380.                 $do_item_data $em->getRepository('ApplicationBundle\\Entity\\DeliveryOrderItem')->findBy(
  3381.                     array(
  3382.                         'salesorderId' => $id,
  3383.                         'id' => $toGetDoItemsId
  3384.                     )
  3385.                 );
  3386.                 foreach ($do_item_data as $dd) {
  3387.                     $toGetSoItemsId[] = $dd->getSalesorderItemId();
  3388.                     $drDataBySoItemId[$dd->getSalesorderItemId()] = $drDataByDoItemId[$dd->getId()];
  3389.                 }
  3390. //                $do_item_data = $em->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findOneBy(
  3391. //                    array(
  3392. ////                'salesOrderId'=>$post_data->get('soId', null),
  3393. //                        'id' => $post_data->get('do_details_id')[$key]
  3394. //                    )
  3395. //                );
  3396.             }
  3397.             $so_item_data $em->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findBy(
  3398.                 array(
  3399.                     'salesOrderId' => $soId,
  3400.                     'id' => $toGetSoItemsId
  3401.                 )
  3402.             );
  3403.             $prev_so_amount $so->getSoAmount();
  3404.             $total_discounted_amount 0;
  3405.             $total_product_amount 0;
  3406.             $total_discount 0;
  3407.             $total_special_discount $so->getSpecialDiscountAmount();
  3408.             $total_special_discount_rate $so->getSpecialDiscountRate();
  3409.             foreach ($so_item_data as $item) {
  3410.                 $qty $drDataBySoItemId[$item->getId()]['qty'];
  3411.                 $price $item->getPrice();
  3412.                 $amount $qty $price;
  3413.                 $discountAmount $amount * ($item->getDiscountRate() / 100);
  3414.                 $discountedAmount $amount $discountAmount;
  3415.                 $total_discounted_amount += $discountedAmount;
  3416.                 $total_discount += $discountAmount;
  3417.                 $total_product_amount += $amount;
  3418.             }
  3419.             $aitRate $so->getAitRate();
  3420.             $vatRate $so->getVatRate();
  3421.             if ($aitRate == '' || $aitRate == null$aitRate 0;
  3422.             if ($vatRate == '' || $vatRate == null$vatRate 0;
  3423. //        $so->setVatRate($post->get('vat_rate', null));
  3424.             $vatAmount $total_discounted_amount * ($vatRate 100);
  3425.             $aitAmount $total_discounted_amount * ($aitRate 100);
  3426.             $total_sales_amount $total_discounted_amount $vatAmount $aitAmount $total_special_discount;
  3427.             //now get client
  3428.             $client $em->getRepository('ApplicationBundle\\Entity\\AccClients')->findOneBy(array(
  3429.                 'clientId' => $so->getClientId(),
  3430.             ));
  3431.             if ($client->getCreditLimitEnabled() != 1) {
  3432.                 $allowed 1;
  3433.             } else {
  3434.                 $creditLimit $client->getCreditLimit();
  3435.                 $due $client->getClientDue();
  3436.                 if ($creditLimit >= ($due $total_sales_amount))
  3437.                     $allowed 1;
  3438.             }
  3439.             //now package data
  3440.             if ($allowed == 0) {
  3441.                 return new JsonResponse(array(
  3442.                     'success' => false,
  3443. //                        'documentHash' => $order->getDocumentHash(),
  3444.                     'documentId' => $receiptId,
  3445.                     'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3446.                     'viewUrl' => '',
  3447.                 ));
  3448.             }
  3449.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  3450.             $dochash $request->request->get('docHash'); //change
  3451.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3452.             $approveRole 1;  //created
  3453.             $approveHash $request->request->get('approvalHash');
  3454.             $receiptId $request->request->get('deliveryReceiptId');
  3455.             $sig DocValidation::isSignatureOk($em$loginId$approveHash);
  3456. //            $this->addFlash(
  3457. //                'success',
  3458. //                'New Transaction Added.'
  3459. //            );
  3460.             $success $sig == false true;
  3461.             if ($success == true) {
  3462.                 $QD $this->getDoctrine()
  3463.                     ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3464.                     ->findOneBy(
  3465.                         array(
  3466.                             'deliveryReceiptId' => $receiptId
  3467.                         ),
  3468.                         array()
  3469.                     );
  3470.                 $draftFlag $QD->getDraftFlag();
  3471.                 if ($draftFlag == 1) {
  3472.                     //now add Approval info
  3473.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3474.                     $approveRole 1;  //created
  3475.                     System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3476.                         $receiptId,
  3477.                         $loginId,
  3478.                         $approveRole,
  3479.                         $request->request->get('approvalHash'));
  3480.                     $options = array(
  3481.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3482.                         'notification_server' => $this->container->getParameter('notification_server'),
  3483.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3484.                         'url' => $this->generateUrl(
  3485.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  3486.                             ['entity_view_route_path_name']
  3487.                         )
  3488.                     );
  3489.                     System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3490.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3491.                         $receiptId,
  3492.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3493.                     );
  3494.                     $QD->setDraftFlag(0);
  3495.                     $em->flush();
  3496.                 }
  3497.                 $url $this->generateUrl(
  3498.                     'view_delivery_receipt'
  3499.                 );
  3500.                 if ($request->request->has('returnJson')) {
  3501. //                    $dr = $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findBy(
  3502. //                        array(
  3503. //                            'salesOrderId' => $orderId, ///material
  3504. //
  3505. //                        )
  3506. //                    );
  3507.                     return new JsonResponse(array(
  3508.                         'success' => true,
  3509. //                        'documentHash' => $order->getDocumentHash(),
  3510.                         'documentId' => $receiptId,
  3511.                         'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3512.                         'viewUrl' => $url "/" $receiptId,
  3513.                     ));
  3514.                 } else {
  3515.                     $this->addFlash(
  3516.                         'success',
  3517.                         'Action Successful'
  3518.                     );
  3519.                     return $this->redirect($url "/" $receiptId);
  3520.                 }
  3521.             }
  3522.         }
  3523.         return new JsonResponse(array(
  3524.             'success' => false,
  3525. //                        'documentHash' => $order->getDocumentHash(),
  3526.             'documentId' => $receiptId,
  3527.             'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3528.             'viewUrl' => '',
  3529.         ));
  3530.     }
  3531.     public function CreateServiceChallanAction(Request $request)
  3532.     {
  3533.         $em $this->getDoctrine()->getManager();
  3534.         if ($request->isMethod('POST')) {
  3535.             $entity_id array_flip(GeneralConstant::$Entity_list)['ServiceChallan']; //change
  3536.             $dochash $request->request->get('docHash'); //change
  3537.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3538.             $approveRole $request->request->get('approvalRole');
  3539.             $approveHash $request->request->get('approvalHash');
  3540.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  3541.                 $loginId$approveRole$approveHash)
  3542.             ) {
  3543.                 $this->addFlash(
  3544.                     'error',
  3545.                     'Sorry Could not insert Data.'
  3546.                 );
  3547.             } else {
  3548.                 $receiptId SalesOrderM::CreateNewServiceChallan($this->getDoctrine()->getManager(), $request->request,
  3549.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  3550.                     $this->getLoggedUserCompanyId($request));
  3551.                 //now add Approval info
  3552.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3553. //                $approveRole = 1;  //created
  3554.                 $options = array(
  3555.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3556.                     'notification_server' => $this->container->getParameter('notification_server'),
  3557.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3558.                     'url' => $this->generateUrl(
  3559.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ServiceChallan']]
  3560.                         ['entity_view_route_path_name']
  3561.                     )
  3562.                 );
  3563.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3564.                     array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3565.                     $receiptId,
  3566.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3567.                 );
  3568.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3569.                     $receiptId,
  3570.                     $loginId,
  3571.                     $approveRole,
  3572.                     $request->request->get('approvalHash'));
  3573.                 $this->addFlash(
  3574.                     'success',
  3575.                     'New Service Challan Created'
  3576.                 );
  3577.                 $url $this->generateUrl(
  3578.                     'view_service_challan'
  3579.                 );
  3580.                 return $this->redirect($url "/" $receiptId);
  3581.             }
  3582.         }
  3583.         return $this->render('@Inventory/pages/input_forms/create_service_challan.html.twig',
  3584.             array(
  3585.                 'page_title' => 'New Service Challan',
  3586.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  3587.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  3588.                 'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  3589.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  3590.                 'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
  3591.                 'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
  3592.                 'deliveryOrders' => SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
  3593.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
  3594.                 'serviceList' => Inventory::ServiceList($em$this->getLoggedUserCompanyId($request))
  3595.             )
  3596.         );
  3597.     }
  3598.     public function GetItemListForDrAction(Request $request)
  3599.     {
  3600.         $em $this->getDoctrine()->getManager();
  3601.         $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3602.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3603.         if ($request->isMethod('POST')) {
  3604.             $em $this->getDoctrine();
  3605.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3606.             );
  3607.             $Content = [];
  3608.             $Transport_data = [];
  3609.             $Lul_data = [];
  3610.             if ($request->request->get('doId') != '')
  3611.                 $find_array['deliveryOrderId'] = $request->request->get('doId');
  3612. //            if($request->request->get('warehouseId')!='')
  3613. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3614.             $QD $this->getDoctrine()
  3615.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryOrderItem')
  3616.                 ->findBy(
  3617.                     $find_array,
  3618.                     array()
  3619.                 );
  3620. //            if($request->request->get('wareHouseId')!='')
  3621.             $DO $this->getDoctrine()
  3622.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryOrder')
  3623.                 ->findOneBy(
  3624.                     $find_array,
  3625.                     array()
  3626.                 );
  3627.             $sendData = array(
  3628. //                'salesType'=>$SO->getSalesType(),
  3629. //                'packageData'=>[],
  3630.                 'productList' => [],
  3631. //                'productListByPackage'=>[],
  3632.             );
  3633.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3634.             $pckg_item_cross_match_data = [];
  3635.             $unitList Inventory::UnitTypeList($em);
  3636.             $colorList Inventory::GetColorList($em);
  3637.             foreach ($QD as $product) {
  3638. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  3639.                 if (($product->getBalance()) <= 0)
  3640.                     continue;
  3641.                 $fdm $product->getProductFdm();
  3642.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3643.                 $find_query = array();
  3644.                 $soItem $this->getDoctrine()
  3645.                     ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  3646.                     ->findOneBy(
  3647.                         array(
  3648.                             'id' => $product->getSalesorderItemId()
  3649.                         )
  3650.                     );
  3651.                 if (!$soItem)
  3652.                     continue;
  3653. //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3654. //                $soBalance = $soItem->getBalance();
  3655.                 $soBalance $soItem->getQty();
  3656. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3657. //                $doBalance = $product->getBalance();
  3658.                 $doBalance $product->getQty();
  3659.                 //now check if any so ir do item id there that is at
  3660.                 //least pending
  3661.                 $approvalPendingDrs $this->getDoctrine()
  3662.                     ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3663.                     ->findBy(
  3664.                         array(
  3665.                             'deliveryOrderId' => $DO->getDeliveryOrderId(),
  3666.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3667.                         )
  3668.                     );
  3669.                 foreach ($approvalPendingDrs as $appPendDr) {
  3670.                     $appPendDrItem $this->getDoctrine()
  3671.                         ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3672.                         ->findOneBy(
  3673.                             array(
  3674.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3675.                                 'salesorderItemId' => $product->getSalesorderItemId()
  3676.                             )
  3677.                         );
  3678.                     if ($appPendDrItem) {
  3679.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3680.                             $soBalance $soBalance $appPendDrItem->getQty();
  3681.                             $doBalance $doBalance $appPendDrItem->getQty();
  3682.                         }
  3683.                     }
  3684.                 }
  3685.                 $colorId $product->getColorId();
  3686.                 $size $product->getSizeId();
  3687. //                $find_query['colorId']=
  3688.                 if ($productData['productId'] != 0) {
  3689.                     $find_query['productId'] = $productData['productId'];
  3690.                     if ($colorId == '' || $colorId == || $colorId == null)
  3691.                         $colorId $productData['defaultColorId'] ?? 0;
  3692.                     if ($size == '' || $size == || $size == null)
  3693.                         $size $productData['defaultSize'] ?? 0;
  3694.                     $find_query['productId'] = $productData['productId'];
  3695.                 } else {
  3696.                     if ($productData['igId'] != 0) {
  3697.                         $find_query['igId'] = $productData['igId'];
  3698.                     }
  3699.                     if ($productData['categoryId'] != 0) {
  3700.                         $find_query['categoryId'] = $productData['categoryId'];
  3701.                     }
  3702.                     if ($productData['subCategoryId'] != 0) {
  3703.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3704.                     }
  3705.                     if ($productData['brandId'] != 0) {
  3706.                         $find_query['brandId'] = $productData['brandId'];
  3707.                     }
  3708.                 }
  3709.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3710.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3711.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3712. //                    $find_query['color'] = $colorId;
  3713.                 } else
  3714.                     $find_query['color'] = $colorId;
  3715.                 if ($size == '' || $size == || $size == null) {
  3716. //                    $find_query['size'] = $size;
  3717.                 } else
  3718.                     $find_query['size'] = 0;
  3719.                 $inventory_by_warehouse_list $this->getDoctrine()
  3720.                     ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  3721.                     ->findBy(
  3722.                         $find_query,
  3723.                         array()
  3724.                     );
  3725.                 $new_pid $productData['productId'];
  3726.                 $p_data = array(
  3727.                     'details_id' => $product->getId(),
  3728. //                        'productId'=>$new_pid,
  3729.                     'productIdList' => [],
  3730.                     'multList' => [],
  3731.                     'drItemIds' => [],
  3732.                     'drItemQty' => [],
  3733.                     'drItemCodeIds' => [],
  3734.                     'drItemCartonIds' => [],
  3735.                     'drItemReturnableFlag' => [],
  3736.                     'drItemReturnDueDate' => [],
  3737.                     'drItemReturnNote' => [],
  3738.                     'drItemReturnStatus' => [],
  3739.                     'colorIds' => [],
  3740.                     'colorNames' => [],
  3741.                     'sizeIds' => [],
  3742.                     'productNameList' => [],
  3743.                     'availableInventoryList' => [],
  3744.                     'warehouseActionId' => [],
  3745.                     'warehouseActionName' => [],
  3746.                     'availableBarcodes' => [],
  3747.                     'availableBarcodesStr' => [],
  3748. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3749. //                        'available_inventory'=>0,
  3750. //                        'package_id'=>$product->getPackageId(),
  3751.                     'qty' => $product->getQty(),
  3752.                     'delivered' => $product->getDelivered(),
  3753. //                    'deliverable' => $product->getDeliverable() - $product->getTransitQty(),
  3754.                     'deliverable' => min($soBalance$doBalance),
  3755. //                    'balance' => $product->getBalance(),
  3756.                     'balance' => min($soBalance$doBalance),
  3757.                     'productNameFdm' => $product->getProductNameFdm(),
  3758.                     'productFdm' => $product->getProductFdm(),
  3759. //                        'delivered'=>$product->getDelivered(),
  3760.                 );
  3761.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  3762.                     if ($inventory_by_warehouse->getQty() <= 0)
  3763.                         continue;
  3764.                     $unitType $product->getUnitTypeId();
  3765.                     $mult_unit 1;
  3766.                     if ($drId != 0) {
  3767.                         $drItem $this->getDoctrine()
  3768.                             ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3769.                             ->findOneBy(
  3770.                                 array(
  3771.                                     'deliveryReceiptId' => $drId,
  3772.                                     'productId' => $inventory_by_warehouse->getProductId(),
  3773.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  3774.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  3775.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  3776.                                 )
  3777.                             );
  3778.                         if ($drItem) {
  3779.                             $returnableMeta SalesOrderM::GetDeliveryReceiptItemReturnableMetaFromOtherdata($drItem->getOtherdata());
  3780.                             $p_data['drItemIds'][] = $drItem->getId();
  3781.                             $p_data['drItemQty'][] = $drItem->getQty();
  3782.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  3783.                             if ($codes == null)
  3784.                                 $codes = [];
  3785.                             $p_data['drItemCodeIds'][] = $codes;
  3786.                             $codes json_decode($drItem->getCartonIds(), true);
  3787.                             if ($codes == null)
  3788.                                 $codes = [];
  3789.                             $p_data['drItemCartonIds'][] = $codes;
  3790.                             $p_data['drItemReturnableFlag'][] = $returnableMeta['temporary_returnable_flag'];
  3791.                             $p_data['drItemReturnDueDate'][] = $returnableMeta['temporary_return_due_date'];
  3792.                             $p_data['drItemReturnNote'][] = $returnableMeta['temporary_return_note'];
  3793.                             $p_data['drItemReturnStatus'][] = $returnableMeta['temporary_return_status'];
  3794.                         } else {
  3795.                             $p_data['drItemIds'][] = 0;
  3796.                             $p_data['drItemQty'][] = 0;
  3797.                             $p_data['drItemCodeIds'][] = 0;
  3798.                             $p_data['drItemCartonIds'][] = 0;
  3799.                             $p_data['drItemReturnableFlag'][] = 0;
  3800.                             $p_data['drItemReturnDueDate'][] = '';
  3801.                             $p_data['drItemReturnNote'][] = '';
  3802.                             $p_data['drItemReturnStatus'][] = '';
  3803.                         }
  3804.                     } else {
  3805.                         $p_data['drItemIds'][] = 0;
  3806.                         $p_data['drItemQty'][] = 0;
  3807.                         $p_data['drItemCodeIds'][] = 0;
  3808.                         $p_data['drItemCartonIds'][] = 0;
  3809.                         $p_data['drItemReturnableFlag'][] = 0;
  3810.                         $p_data['drItemReturnDueDate'][] = '';
  3811.                         $p_data['drItemReturnNote'][] = '';
  3812.                         $p_data['drItemReturnStatus'][] = '';
  3813.                     }
  3814.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  3815.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  3816.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  3817.                         }
  3818.                     };
  3819.                     if ($mult_unit == 0)
  3820.                         $mult_unit 1;
  3821.                     $inv_product_id $inventory_by_warehouse->getProductId();
  3822.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  3823.                     $p_data['multList'][] = $mult_unit;
  3824.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  3825.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  3826.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  3827.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  3828.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  3829. //                        $p_data['availableInventoryList'][]=$inventory_by_warehouse?(($inventory_by_warehouse->getQty())*$mult_unit):0;
  3830.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  3831.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  3832.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  3833.                 }
  3834.                 $sendData['productList'][] = $p_data;
  3835.             }
  3836.             //now package data
  3837.             if ($sendData) {
  3838.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3839.             }
  3840.             return new JsonResponse(array("success" => false));
  3841.         }
  3842.         return new JsonResponse(array("success" => false));
  3843.     }
  3844.     public function GetItemListForDrBySoAction(Request $request)
  3845.     {
  3846.         $em $this->getDoctrine()->getManager();
  3847.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3848.         if ($request->isMethod('POST')) {
  3849.             $em $this->getDoctrine();
  3850.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3851. //                'type'=>1//product only
  3852.             );
  3853.             $find_item_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3854.                 'type' => 1//product only
  3855.             );
  3856.             $Content = [];
  3857.             $Transport_data = [];
  3858.             $Lul_data = [];
  3859.             $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3860.             if ($request->request->get('soId') != '') {
  3861.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3862.                 $find_item_array['salesOrderId'] = $request->request->get('soId');
  3863.             }
  3864. //            if($request->request->get('warehouseId')!='')
  3865. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3866.             $QD $this->getDoctrine()
  3867.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  3868.                 ->findBy(
  3869.                     $find_item_array,
  3870.                     array()
  3871.                 );
  3872. //            if($request->request->get('wareHouseId')!='')
  3873.             $DO $this->getDoctrine()
  3874.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  3875.                 ->findOneBy(
  3876.                     $find_array,
  3877.                     array()
  3878.                 );
  3879.             $sendData = array(
  3880. //                'salesType'=>$SO->getSalesType(),
  3881. //                'packageData'=>[],
  3882.                 'productList' => [],
  3883. //                'productListByPackage'=>[],
  3884.             );
  3885.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3886.             $pckg_item_cross_match_data = [];
  3887.             $unitList Inventory::UnitTypeList($em);
  3888.             $colorList Inventory::GetColorList($em);
  3889.             foreach ($QD as $product) {
  3890.                 if (($product->getBalance() - $product->getTransitQty()) <= 0)
  3891.                     continue;
  3892.                 //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3893. //                $soBalance = $soItem->getBalance();
  3894.                 $soBalance $product->getQty();
  3895. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3896. //                $doBalance = $product->getBalance();
  3897. //                $doBalance = 0;
  3898.                 //now check if any so ir do item id there that is at
  3899.                 //least pending
  3900.                 $approvalPendingDrs $this->getDoctrine()
  3901.                     ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3902.                     ->findBy(
  3903.                         array(
  3904.                             'salesOrderId' => $DO->getSalesOrderId(),
  3905.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3906.                         )
  3907.                     );
  3908.                 foreach ($approvalPendingDrs as $appPendDr) {
  3909.                     $appPendDrItem $this->getDoctrine()
  3910.                         ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3911.                         ->findOneBy(
  3912.                             array(
  3913.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3914. //                                'salesorderItemId' => $product->getId(),
  3915.                                 'salesorderItemId' => $product->getId()
  3916.                             )
  3917.                         );
  3918.                     if ($appPendDrItem) {
  3919.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3920.                             $soBalance $soBalance $appPendDrItem->getQty();
  3921.                         }
  3922. //                        $doBalance=$doBalance-$appPendDrItem->getQty();
  3923.                     }
  3924.                 }
  3925.                 $fdm $product->getProductFdm();
  3926.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3927.                 $find_query = array();
  3928.                 $colorId $product->getColorId();
  3929.                 $size $product->getSizeId();
  3930. //                $find_query['colorId']=
  3931.                 if ($productData['productId'] != 0) {
  3932.                     $find_query['productId'] = $productData['productId'];
  3933.                     if ($colorId == '' || $colorId == || $colorId == null)
  3934.                         $colorId $productData['defaultColorId'] ?? 0;
  3935.                     if ($size == '' || $size == || $size == null)
  3936.                         $size $productData['defaultSize'] ?? 0;
  3937.                 } else {
  3938.                     if ($productData['igId'] != 0) {
  3939.                         $find_query['igId'] = $productData['igId'];
  3940.                     }
  3941.                     if ($productData['categoryId'] != 0) {
  3942.                         $find_query['categoryId'] = $productData['categoryId'];
  3943.                     }
  3944.                     if ($productData['subCategoryId'] != 0) {
  3945.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3946.                     }
  3947.                     if ($productData['brandId'] != 0) {
  3948.                         $find_query['brandId'] = $productData['brandId'];
  3949.                     }
  3950.                 }
  3951.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3952.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3953.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3954. //                    $find_query['color'] = $colorId;
  3955.                 } else
  3956.                     $find_query['color'] = $colorId;
  3957.                 if ($size == '' || $size == || $size == null) {
  3958. //                    $find_query['size'] = $size;
  3959.                 } else
  3960.                     $find_query['size'] = 0;
  3961.                 $inventory_by_warehouse_list $this->getDoctrine()
  3962.                     ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  3963.                     ->findBy(
  3964.                         $find_query,
  3965.                         array()
  3966.                     );
  3967.                 $new_pid $productData['productId'];
  3968.                 $unitType $product->getUnitTypeId();
  3969.                 $p_data = array(
  3970.                     'details_id' => $product->getId(),
  3971.                     'unitType' => $unitType,
  3972.                     'productIdList' => [],
  3973.                     'multList' => [],
  3974.                     'drItemIds' => [],
  3975.                     'drItemQty' => [],
  3976.                     'drItemCodeIds' => [],
  3977.                     'drItemCartonIds' => [],
  3978.                     'drItemReturnableFlag' => [],
  3979.                     'drItemReturnDueDate' => [],
  3980.                     'drItemReturnNote' => [],
  3981.                     'drItemReturnStatus' => [],
  3982.                     'colorIds' => [],
  3983.                     'colorNames' => [],
  3984.                     'sizeIds' => [],
  3985.                     'productNameList' => [],
  3986.                     'availableInventoryList' => [],
  3987.                     'warehouseActionId' => [],
  3988.                     'warehouseActionName' => [],
  3989.                     'availableBarcodes' => [],
  3990.                     'availableBarcodesStr' => [],
  3991. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3992. //                        'available_inventory'=>0,
  3993. //                        'package_id'=>$product->getPackageId(),
  3994.                     'qty' => $product->getQty(),
  3995.                     'delivered' => $product->getDelivered(),
  3996. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  3997. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  3998.                     'deliverable' => $soBalance,
  3999. //                    'deliverable' => $product->getBalance(),
  4000.                     'balance' => $soBalance,
  4001. //                    'balance' => $product->getBalance(),
  4002.                     'productNameFdm' => $product->getProductNameFdm(),
  4003.                     'productFdm' => $product->getProductFdm(),
  4004. //                        'delivered'=>$product->getDelivered(),
  4005.                 );
  4006.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  4007.                     if ($inventory_by_warehouse->getQty() <= 0)
  4008.                         continue;
  4009.                     $mult_unit 1;
  4010.                     if ($drId != 0) {
  4011.                         $drItem $this->getDoctrine()
  4012.                             ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  4013.                             ->findOneBy(
  4014.                                 array(
  4015.                                     'deliveryReceiptId' => $drId,
  4016.                                     'productId' => $inventory_by_warehouse->getProductId(),
  4017.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  4018.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  4019.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  4020.                                 )
  4021.                             );
  4022.                         if ($drItem) {
  4023.                             $returnableMeta SalesOrderM::GetDeliveryReceiptItemReturnableMetaFromOtherdata($drItem->getOtherdata());
  4024.                             $p_data['drItemIds'][] = $drItem->getId();
  4025.                             $p_data['drItemQty'][] = $drItem->getQty();
  4026.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  4027.                             if ($codes == null)
  4028.                                 $codes = [];
  4029.                             $p_data['drItemCodeIds'][] = $codes;
  4030.                             $codes json_decode($drItem->getCartonIds(), true);
  4031.                             if ($codes == null)
  4032.                                 $codes = [];
  4033.                             $p_data['drItemCartonIds'][] = $codes;
  4034.                             $p_data['drItemReturnableFlag'][] = $returnableMeta['temporary_returnable_flag'];
  4035.                             $p_data['drItemReturnDueDate'][] = $returnableMeta['temporary_return_due_date'];
  4036.                             $p_data['drItemReturnNote'][] = $returnableMeta['temporary_return_note'];
  4037.                             $p_data['drItemReturnStatus'][] = $returnableMeta['temporary_return_status'];
  4038.                         } else {
  4039.                             $p_data['drItemIds'][] = 0;
  4040.                             $p_data['drItemQty'][] = 0;
  4041.                             $p_data['drItemCodeIds'][] = 0;
  4042.                             $p_data['drItemCartonIds'][] = 0;
  4043.                             $p_data['drItemReturnableFlag'][] = 0;
  4044.                             $p_data['drItemReturnDueDate'][] = '';
  4045.                             $p_data['drItemReturnNote'][] = '';
  4046.                             $p_data['drItemReturnStatus'][] = '';
  4047.                         }
  4048.                     } else {
  4049.                         $p_data['drItemIds'][] = 0;
  4050.                         $p_data['drItemQty'][] = 0;
  4051.                         $p_data['drItemCodeIds'][] = 0;
  4052.                         $p_data['drItemCartonIds'][] = 0;
  4053.                         $p_data['drItemReturnableFlag'][] = 0;
  4054.                         $p_data['drItemReturnDueDate'][] = '';
  4055.                         $p_data['drItemReturnNote'][] = '';
  4056.                         $p_data['drItemReturnStatus'][] = '';
  4057.                     }
  4058.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  4059.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  4060.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  4061.                         }
  4062.                     };
  4063.                     if ($mult_unit == 0)
  4064.                         $mult_unit 1;
  4065.                     $inv_product_id $inventory_by_warehouse->getProductId();
  4066.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  4067.                     $p_data['multList'][] = $mult_unit;
  4068.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  4069.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  4070.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  4071.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  4072.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  4073.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  4074.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  4075.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  4076.                 }
  4077.                 $sendData['productList'][] = $p_data;
  4078.             }
  4079.             //now package data
  4080.             if ($sendData) {
  4081.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4082.             }
  4083.             return new JsonResponse(array("success" => false));
  4084.         }
  4085.         return new JsonResponse(array("success" => false));
  4086.     }
  4087.     public function GetExtraTemporaryReturnableItemsForDrAction(Request $request)
  4088.     {
  4089.         $em $this->getDoctrine()->getManager();
  4090.         $companyId $this->getLoggedUserCompanyId($request);
  4091.         $warehouseActionList Inventory::warehouse_action_list($em$companyId'');
  4092.         $unitList Inventory::UnitTypeList($em);
  4093.         $colorList Inventory::GetColorList($em);
  4094.         if (!$request->isMethod('POST')) {
  4095.             return new JsonResponse(array("success" => false));
  4096.         }
  4097.         $productId $request->request->get('productId'0);
  4098.         $warehouseId $request->request->get('warehouseId'0);
  4099.         $drId $request->request->get('drId'0);
  4100.         if (($productId) == || ($warehouseId) == 0) {
  4101.             return new JsonResponse(array("success" => false));
  4102.         }
  4103.         $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($productId);
  4104.         if (!$product) {
  4105.             return new JsonResponse(array("success" => false));
  4106.         }
  4107.         $productList Inventory::ProductList($em$companyId);
  4108.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(array(
  4109.             'CompanyId' => $companyId,
  4110.             'warehouseId' => $warehouseId,
  4111.             'productId' => $productId,
  4112.         ));
  4113.         $sendData = array(
  4114.             'productList' => [],
  4115.         );
  4116.         foreach ($slotList as $slot) {
  4117.             if ($slot->getQty() <= 0) {
  4118.                 continue;
  4119.             }
  4120.             $multUnit 1;
  4121.             if ($product->getUnitTypeId() != $slot->getUnitTypeId()) {
  4122.                 if (isset($unitList[$slot->getUnitTypeId()]['conversion'][$product->getUnitTypeId()])) {
  4123.                     $multUnit $unitList[$slot->getUnitTypeId()]['conversion'][$product->getUnitTypeId()];
  4124.                 }
  4125.             }
  4126.             if ($multUnit == 0) {
  4127.                 $multUnit 1;
  4128.             }
  4129.             $drItem null;
  4130.             if (($drId) != 0) {
  4131.                 $drItem $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')->findOneBy(array(
  4132.                     'deliveryReceiptId' => $drId,
  4133.                     'salesorderItemId' => [0null''],
  4134.                     'productId' => $slot->getProductId(),
  4135.                     'warehouseActionId' => $slot->getActionTagId(),
  4136.                     'colorId' => $slot->getColor() == ? [0null''] : $slot->getColor(),
  4137.                     'sizeId' => $slot->getSize() == ? [0null''] : $slot->getSize(),
  4138.                 ));
  4139.             }
  4140.             $returnableMeta SalesOrderM::GetDeliveryReceiptItemReturnableMetaFromOtherdata($drItem $drItem->getOtherdata() : []);
  4141.             $availableQty = (($slot->getQty()) / $multUnit);
  4142.             if ($drItem && $availableQty < ($drItem->getQty())) {
  4143.                 $availableQty $drItem->getQty();
  4144.             }
  4145.             $sendData['productList'][] = array(
  4146.                 'details_id' => 0,
  4147.                 'productIdList' => array($slot->getProductId()),
  4148.                 'multList' => array($multUnit),
  4149.                 'drItemIds' => array($drItem $drItem->getId() : 0),
  4150.                 'drItemQty' => array($drItem ? ($drItem->getQty()) : 0),
  4151.                 'drItemCodeIds' => array($drItem ? (json_decode($drItem->getProductByCodeIds(), true) ?: []) : []),
  4152.                 'drItemCartonIds' => array($drItem ? (json_decode($drItem->getCartonIds(), true) ?: []) : []),
  4153.                 'drItemReturnableFlag' => array($drItem $returnableMeta['temporary_returnable_flag'] : 1),
  4154.                 'drItemReturnDueDate' => array($drItem $returnableMeta['temporary_return_due_date'] : ''),
  4155.                 'drItemReturnNote' => array($drItem $returnableMeta['temporary_return_note'] : ''),
  4156.                 'drItemReturnStatus' => array($drItem $returnableMeta['temporary_return_status'] : 'pending'),
  4157.                 'colorIds' => array($slot->getColor() ? $slot->getColor() : 0),
  4158.                 'colorNames' => array($slot->getColor() && isset($colorList[$slot->getColor()]) ? $colorList[$slot->getColor()]['name'] : ''),
  4159.                 'sizeIds' => array($slot->getSize() ? $slot->getSize() : 0),
  4160.                 'productNameList' => array(isset($productList[$slot->getProductId()]) ? $productList[$slot->getProductId()]['name'] : $product->getName()),
  4161.                 'availableInventoryList' => array($availableQty),
  4162.                 'warehouseActionId' => array($slot->getActionTagId()),
  4163.                 'warehouseActionName' => array(isset($warehouseActionList[$slot->getActionTagId()]) ? $warehouseActionList[$slot->getActionTagId()] : ''),
  4164.                 'availableBarcodes' => array([]),
  4165.                 'availableBarcodesStr' => array(''),
  4166.                 'serialEnabled' => array(isset($productList[$slot->getProductId()]) ? $productList[$slot->getProductId()]['has_serial'] : 0),
  4167.                 'qty' => $availableQty,
  4168.                 'delivered' => 0,
  4169.                 'deliverable' => $availableQty,
  4170.                 'balance' => $availableQty,
  4171.                 'productNameFdm' => 'Temporary returnable item',
  4172.                 'productFdm' => $product->getProductFdm(),
  4173.                 'extraTempItemFlag' => 1,
  4174.             );
  4175.         }
  4176.         return new JsonResponse(array("success" => true"content" => $sendData));
  4177.     }
  4178.     public function GetItemListForStockReqBySoAction(Request $request)
  4179.     {
  4180.         $em $this->getDoctrine()->getManager();
  4181.         if ($request->isMethod('POST')) {
  4182.             $em $this->getDoctrine();
  4183.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  4184.             );
  4185.             $Content = [];
  4186.             $Transport_data = [];
  4187.             $Lul_data = [];
  4188.             // NOTE: do NOT pre-filter by serviceId. In the filter-based sales model every sales-order
  4189.             // line carries a serviceId (>0, referencing AccService) with an empty product_fdm, so the
  4190.             // old `serviceId => [0, null]` filter excluded 100% of the items and the Stock Requisition
  4191.             // item list always came back empty. We fetch all lines of the SO and resolve their names below.
  4192.             $sendData = array(
  4193. //                'salesType'=>$SO->getSalesType(),
  4194. //                'packageData'=>[],
  4195.                 'productList' => [],
  4196. //                'productListByPackage'=>[],
  4197.             );
  4198.             if ($request->request->get('soId') != '') {
  4199.                 $find_array['salesOrderId'] = $request->request->get('soId');
  4200. //            if($request->request->get('warehouseId')!='')
  4201. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4202.                 $QD $this->getDoctrine()
  4203.                     ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  4204.                     ->findBy(
  4205.                         $find_array,
  4206.                         array()
  4207.                     );
  4208. //            if($request->request->get('wareHouseId')!='')
  4209. //            $DO = $this->getDoctrine()
  4210. //                ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  4211. //                ->findOneBy(
  4212. //                    $find_array,
  4213. //                    array()
  4214. //                );
  4215.                 $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4216.                 $pckg_item_cross_match_data = [];
  4217.                 $unitList Inventory::UnitTypeList($em);
  4218.                 // Service/filter lines have no productNameFdm yet — resolve their name from AccService.
  4219.                 $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  4220.                 foreach ($QD as $product) {
  4221. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  4222. //                    continue;
  4223.                     $fdm $product->getProductFdm();
  4224.                     $serviceId = (int) $product->getServiceId();
  4225.                     $unitType $product->getUnitTypeId();
  4226.                     // Display name: product lines carry a productNameFdm; filter/service-based lines
  4227.                     // (no FDM finalised yet) are named from the AccService they reference.
  4228.                     $nameFdm $product->getProductNameFdm();
  4229.                     if (($nameFdm === null || $nameFdm === '') && $serviceId && isset($serviceList[$serviceId])) {
  4230.                         $nameFdm $serviceList[$serviceId]['name'];
  4231.                         if (!$unitType && isset($serviceList[$serviceId]['unit_type'])) {
  4232.                             $unitType $serviceList[$serviceId]['unit_type'];
  4233.                         }
  4234.                     }
  4235.                     $p_data = array(
  4236.                         'details_id' => $product->getId(),
  4237.                         'serviceId' => $serviceId,
  4238.                         'unitType' => $unitType,
  4239.                         'productIdList' => [],
  4240.                         'multList' => [],
  4241.                         'productNameList' => [],
  4242.                         'availableInventoryList' => [],
  4243.                         'warehouseActionId' => [],
  4244.                         'warehouseActionName' => [],
  4245.                         'availableBarcodes' => [],
  4246.                         'availableBarcodesStr' => [],
  4247. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  4248. //                        'available_inventory'=>0,
  4249. //                        'package_id'=>$product->getPackageId(),
  4250.                         'qty' => $product->getQty(),
  4251.                         'delivered' => $product->getDelivered(),
  4252. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  4253. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  4254.                         'deliverable' => $product->getBalance(),
  4255.                         'balance' => $product->getBalance(),
  4256.                         'productNameFdm' => $nameFdm,
  4257.                         'productFdm' => $product->getProductFdm(),
  4258. //                        'delivered'=>$product->getDelivered(),
  4259.                     );
  4260.                     $sendData['productList'][] = $p_data;
  4261.                 }
  4262.             }
  4263.             //now package data
  4264.             if ($sendData) {
  4265.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4266.             }
  4267.             return new JsonResponse(array("success" => false));
  4268.         }
  4269.         return new JsonResponse(array("success" => false));
  4270.     }
  4271.     public function GetProductPriceAjaxAction(Request $request)
  4272.     {
  4273.         $em $this->getDoctrine()->getManager();
  4274.         $priceData = [];
  4275.         $defaultData = [
  4276.             => [    //currId
  4277.                 => 0       ///customerID=> value
  4278.             ]
  4279.         ];
  4280.         $priceData = [
  4281.             => $defaultData
  4282.         ];
  4283.         if ($request->isMethod('POST')) {
  4284.             $em $this->getDoctrine();
  4285.             $find_query = array();
  4286.             $pid $request->request->get('productId'0);
  4287.             $find_query['productId'] = $pid;
  4288.             $priceData = [
  4289. //                $pid =>$defaultData
  4290.             ];
  4291.             $priceDataQry $em
  4292.                 ->getRepository('ApplicationBundle\\Entity\\ProductMrp')
  4293.                 ->findBy(
  4294.                     $find_query,
  4295.                     array(
  4296.                         'productMrpId' => 'desc'
  4297.                     )
  4298.                 );
  4299.             if (!empty($priceDataQry)) {
  4300.                 foreach ($priceDataQry as $priceDataQ) {
  4301.                     $currId $priceDataQ->getCurrency();
  4302.                     if ($currId == null$currId 0;
  4303.                     if (!isset($priceData[$pid][$currId]))
  4304.                         $priceData[$pid][$currId] = $defaultData;
  4305.                     $priceByCustomerType json_decode($priceDataQ->getPriceByCustomerTypes(), true);
  4306.                     if ($priceByCustomerType == null$priceByCustomerType = [];
  4307.                     foreach ($priceByCustomerType as $ct => $pbct) {
  4308.                         if (!isset($priceData[$pid][$currId][$ct]))
  4309.                             $priceData[$pid][$currId][$ct] = $pbct;
  4310.                     }
  4311.                 }
  4312.             }
  4313.         }
  4314.         //now package data
  4315.         $retData = array(
  4316.             'success' => true,
  4317.             'data' => $priceData
  4318.         );
  4319.         return new JsonResponse($retData);
  4320.     }
  4321.     public function GetBarcodesListForStAction(Request $request)
  4322.     {
  4323.         $em $this->getDoctrine()->getManager();
  4324.         $sendData = [];
  4325.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  4326.         if ($request->isMethod('POST')) {
  4327.             $em $this->getDoctrine();
  4328.             $find_query = array();
  4329.             $find_query['warehouseId'] = $request->request->get('warehouseId');
  4330.             $find_query['actionTagId'] = $request->request->get('warehouseActionId');
  4331.             $find_query['productId'] = $request->request->get('productId');
  4332.             $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  4333.             $inventory_by_warehouse_list $this->getDoctrine()
  4334.                 ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  4335.                 ->findBy(
  4336.                     $find_query,
  4337.                     array()
  4338.                 );
  4339.             $new_pid $request->request->get('productId');
  4340.             $p_data = array();
  4341.             //now get bacodes if available
  4342. //                    $query = "SELECT product_by_code_id, GROUP_CONCAT(DISTINCT sales_code SEPARATOR ',') sales_code_list_str
  4343. //FROM product_by_code
  4344. //where company_id=" . $this->getLoggedUserCompanyId($request).
  4345. //                        " and product_id=".$inv_product_id.
  4346. //                        " and warehouse_id=".$inventory_by_warehouse->getWarehouseId().
  4347. //                        " and warehouse_action_id=".$inventory_by_warehouse->getActionTagId();
  4348. //                        " GROUP BY product_by_code_id" ;
  4349.             $query "SELECT product_by_code_id, sales_code
  4350. FROM product_by_code
  4351. where company_id = :companyId
  4352.   and product_id = :productId
  4353.   and warehouse_id = :warehouseId
  4354.   and warehouse_action_id = :warehouseActionId";
  4355.             $stmt $em->getConnection()->fetchAllAssociative($query, array(
  4356.                 'companyId' => (int) $this->getLoggedUserCompanyId($request),
  4357.                 'productId' => (int) $request->request->get('productId'),
  4358.                 'warehouseId' => (int) $request->request->get('warehouseId'),
  4359.                 'warehouseActionId' => (int) $request->request->get('warehouseActionId'),
  4360.             ));
  4361.             $results $stmt;
  4362.             $sales_code_list_str '';
  4363.             foreach ($results as $pika => $result) {
  4364.                 if ($pika != 0)
  4365.                     $sales_code_list_str .= ',';
  4366.                 $sales_code_list_str .= str_pad($result['sales_code'], 13'0'STR_PAD_LEFT);
  4367.             }
  4368.             if ($results) {
  4369.                 $p_data['availableBarcodes'] = $sales_code_list_str != '' || $sales_code_list_str != null
  4370.                     explode(','$sales_code_list_str) : [];
  4371.                 $p_data['availableBarcodesStr'] = $sales_code_list_str != '' || $sales_code_list_str != null
  4372.                     $sales_code_list_str "";
  4373. //
  4374.             } else {
  4375.                 $p_data['availableBarcodes'] = [];
  4376.                 $p_data['availableBarcodesStr'] = "";
  4377. //
  4378.             }
  4379.             $sendData $p_data;
  4380.         }
  4381.         //now package data
  4382.         if (!empty($sendData['availableBarcodes'])) {
  4383.             return new JsonResponse(array("success" => true"content" => $sendData));
  4384.         }
  4385.         return new JsonResponse(array("success" => false));
  4386.     }
  4387.     public function GetItemListForSalesReturnAction(Request $request)
  4388.     {
  4389.         if ($request->isMethod('POST')) {
  4390.             $em $this->getDoctrine();
  4391.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  4392.             );
  4393.             $Content = [];
  4394.             $Transport_data = [];
  4395.             $Lul_data = [];
  4396.             if ($request->request->get('drId') != '')
  4397.                 $find_array['deliveryReceiptId'] = $request->request->get('drId');
  4398. //            if($request->request->get('warehouseId')!='')
  4399. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4400.             $QD $this->getDoctrine()
  4401.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  4402.                 ->findBy(
  4403.                     $find_array,
  4404.                     array()
  4405.                 );
  4406. //            if($request->request->get('wareHouseId')!='')
  4407.             $DR $this->getDoctrine()
  4408.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  4409.                 ->findOneBy(
  4410.                     $find_array,
  4411.                     array()
  4412.                 );
  4413.             $sendData = array(
  4414.                 'productList' => [],
  4415.             );
  4416.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4417.             $pckg_item_cross_match_data = [];
  4418.             $unitList Inventory::UnitTypeList($em);
  4419.             foreach ($QD as $product) {
  4420.                 if (($product->getQty()) <= 0)
  4421.                     continue;
  4422.                 $new_pid $product->getProductId();
  4423.                 $sales_code_range = [];
  4424.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  4425.                     $sales_code_range json_decode($product->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  4426.                 } else {
  4427.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  4428.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getSalesCodeRange());
  4429.                     $sales_code_range json_decode($json_without_bigintstrue);
  4430.                 }
  4431.                 $p_data = array(
  4432.                     'details_id' => $product->getId(),
  4433.                     'dr_id' => $product->getDeliveryReceiptId(),
  4434.                     'productId' => $new_pid,
  4435.                     'product_name' => isset($productList[$new_pid]) ? $productList[$new_pid]['name'] : '',
  4436.                     'qty' => $product->getQty(),
  4437.                     'delivered' => $product->getDelivered(),
  4438.                     'unitTypeId' => $product->getUnitTypeId(),
  4439.                     'deliverable' => $product->getDeliverable(),
  4440.                     'balance' => $product->getBalance(),
  4441.                     'salesCodeRangeStr' => $product->getSalesCodeRange(),
  4442.                     'salesCodeRange' => $sales_code_range,
  4443.                     'sales_codes' => $sales_code_range,
  4444.                     'sales_price' => $product->getPrice(),
  4445.                     'purchase_price' => $product->getCurrentPurchasePrice()
  4446. //                        'delivered'=>$product->getDelivered(),
  4447.                 );
  4448.                 $sendData['productList'][] = $p_data;
  4449.             }
  4450.             //now package data
  4451.             if ($sendData) {
  4452.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4453.             }
  4454.             return new JsonResponse(array("success" => false));
  4455.         }
  4456.         return new JsonResponse(array("success" => false));
  4457.     }
  4458.     public function GetItemListForIrrAction(Request $request)
  4459.     {
  4460.         if ($request->isMethod('POST')) {
  4461.             $em $this->getDoctrine();
  4462.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  4463.             );
  4464.             $Content = [];
  4465.             $Transport_data = [];
  4466.             $Lul_data = [];
  4467.             if ($request->request->get('srId') != '')
  4468.                 $find_array['salesReturnId'] = $request->request->get('srId');
  4469. //            if($request->request->get('warehouseId')!='')
  4470. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4471.             $QD $this->getDoctrine()
  4472.                 ->getRepository('ApplicationBundle\\Entity\\SalesReturnItem')
  4473.                 ->findBy(
  4474.                     $find_array,
  4475.                     array()
  4476.                 );
  4477. //            if($request->request->get('wareHouseId')!='')
  4478.             $sendData = array(
  4479.                 'productList' => [],
  4480.             );
  4481.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4482.             $pckg_item_cross_match_data = [];
  4483.             $unitList Inventory::UnitTypeList($em);
  4484.             foreach ($QD as $product) {
  4485.                 if (($product->getReceivedBalance()) <= && ($product->getReplacedBalance()) <= 0)
  4486.                     continue;
  4487.                 $DR_ITEM null;
  4488.                 $DR_TAGGED_CODES = [];
  4489.                 $DR_TAGGED_CODES_FOR_SELECTIZE = [];
  4490.                 $RESTRICT_RECEIVED_CODES_FLAG 0;
  4491.                 $sales_code_range = [];
  4492.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  4493.                     $sales_code_range json_decode($product->getReceivedCodeRange(), true512JSON_BIGINT_AS_STRING);
  4494.                 } else {
  4495.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  4496.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getReceivedCodeRange());
  4497.                     $sales_code_range json_decode($json_without_bigintstrue);
  4498.                 }
  4499.                 $DR_TAGGED_CODES $sales_code_range;
  4500.                 if (!empty($DR_TAGGED_CODES)) {
  4501.                     $RESTRICT_RECEIVED_CODES_FLAG 1;
  4502.                     foreach ($DR_TAGGED_CODES as $DTC) {
  4503.                         $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  4504.                             'value' => $DTC
  4505.                         );
  4506.                     }
  4507.                 }
  4508. //                if ($product->getTaggedDetailsId() != 0 && $product->getTaggedDetailsId() != null) {
  4509. //
  4510. //                    $DR_ITEM = $this->getDoctrine()
  4511. //                        ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  4512. //                        ->findOneBy(
  4513. //                            array(
  4514. //                                'id' => $product->getTaggedDetailsId()
  4515. //                            ),
  4516. //                            array()
  4517. //                        );
  4518. //                    if ($DR_ITEM) {
  4519. //                        if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  4520. //
  4521. //                            $DR_TAGGED_CODES = json_decode($DR_ITEM->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  4522. //                        } else {
  4523. //
  4524. //                            $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  4525. //                            $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $DR_ITEM->getSalesCodeRange());
  4526. //                            $DR_TAGGED_CODES = json_decode($json_without_bigints, true);
  4527. //                        }
  4528. //
  4529. //                        if ($DR_TAGGED_CODES == null)
  4530. //                            $DR_TAGGED_CODES = [];
  4531. //                        if (!empty($DR_TAGGED_CODES)) {
  4532. //                            $RESTRICT_RECEIVED_CODES_FLAG = 1;
  4533. //                            foreach ($DR_TAGGED_CODES as $DTC) {
  4534. //                                $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  4535. //                                    'value' => $DTC
  4536. //                                );
  4537. //                            }
  4538. //                        }
  4539. //                    }
  4540. //                }
  4541.                 $p_data = array(
  4542.                     'details_id' => $product->getId(),
  4543.                     'receivedDrTaggedCodes' => $DR_TAGGED_CODES,
  4544.                     'receivedDrTaggedCodesStr' => implode(','$DR_TAGGED_CODES),
  4545.                     'receivedDrTaggedCodesForSel' => $DR_TAGGED_CODES_FOR_SELECTIZE,
  4546.                     'receivedRestrictCodesFlag' => $RESTRICT_RECEIVED_CODES_FLAG,
  4547.                     'receivedProductId' => $product->getReceivedProductId(),
  4548.                     'receivedBalance' => $product->getReceivedBalance(),
  4549.                     'receivedUnitSalesPrice' => $product->getReceivedUnitSalesPrice(),
  4550.                     'receivedUnitPurchasePrice' => $product->getReceivedUnitPurchasePrice(),
  4551.                     'receivedProductName' => isset($productList[$product->getReceivedProductId()]) ? $productList[$product->getReceivedProductId()]['name'] : '',
  4552.                     'replacedProductId' => $product->getReplacedProductId(),
  4553.                     'replacedBalance' => $product->getReplacedBalance(),
  4554.                     'replacedUnitSalesPrice' => $product->getReplacedUnitSalesPrice(),
  4555.                     'replacedUnitPurchasePrice' => $product->getReplacedUnitPurchasePrice(),
  4556.                     'replacedProductName' => isset($productList[$product->getReplacedProductId()]) ? $productList[$product->getReplacedProductId()]['name'] : '',
  4557.                     'disposeBalance' => $product->getDisposeBalance(),
  4558.                     'unusedBalance' => $product->getUnusedBalance(),
  4559.                     'disposeTag' => $product->getDisposeTag(),
  4560.                     'unitTypeId' => $product->getUnitTypeId(),
  4561. //                        'delivered'=>$product->getDelivered(),
  4562.                 );
  4563.                 $sendData['productList'][] = $p_data;
  4564.             }
  4565.             //now package data
  4566.             if ($sendData) {
  4567.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4568.             }
  4569.             return new JsonResponse(array("success" => false));
  4570.         }
  4571.         return new JsonResponse(array("success" => false));
  4572.     }
  4573.     public function LabelFormatAction(Request $request$id 0)
  4574.     {
  4575.         $data = array(
  4576.             'formatId' => '',
  4577.             'formatCode' => '',
  4578.             'name' => '',
  4579.             'labelType' => 0,
  4580.             'width' => 60,
  4581.             'pageWidth' => 6,
  4582.             'height' => 39,
  4583.             'pageHeight' => 2,
  4584.             'formatData' => '',
  4585.         );
  4586.         if ($request->isMethod('POST')) {
  4587.             $post $request->request;
  4588.             $exists_already 0;
  4589.             if ($request->request->get('formatId') != '') {
  4590.                 $query_here $this->getDoctrine()
  4591.                     ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  4592.                     ->findOneBy(
  4593.                         array(
  4594.                             'formatId' => $request->request->get('formatId')
  4595.                         )
  4596.                     );
  4597.                 if (!empty($query_here)) {
  4598.                     $exists_already 1;
  4599.                     $new $query_here;
  4600.                 } else
  4601.                     $new = new LabelFormat();
  4602.             } else
  4603.                 $new = new LabelFormat();
  4604.             $new->setName($request->request->get('name'));
  4605.             $new->setLabelType($request->request->get('labelType'));
  4606.             $new->setWidth($request->request->get('width'));
  4607.             $new->setHeight($request->request->get('height'));
  4608.             $new->setFormatCode($request->request->get('formatCode'));
  4609.             $new->setActive(GeneralConstant::ACTIVE);
  4610.             $new->setPageHeight($request->request->get('pageHeight'));
  4611.             $new->setPageWidth($request->request->get('pageWidth'));
  4612.             $new->setFormatData($request->request->get('formatData'));
  4613.             if ($exists_already == 0)
  4614.                 $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4615.             $new->setEditLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4616.             $new->setCompanyId($request->getSession()->get(UserConstants::USER_COMPANY_ID));
  4617.             $em $this->getDoctrine()->getManager();
  4618.             $em->persist($new);
  4619.             $em->flush();
  4620.         }
  4621.         if ($id != 0) {
  4622.             $query_here $this->getDoctrine()
  4623.                 ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  4624.                 ->findOneBy(
  4625.                     array(
  4626.                         'formatId' => $id
  4627.                     )
  4628.                 );
  4629.             if ($query_here)
  4630.                 $data $query_here;
  4631.         } else if ($request->query->has('formatId')) {
  4632.             $query_here $this->getDoctrine()
  4633.                 ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  4634.                 ->findOneBy(
  4635.                     array(
  4636.                         'formatId' => $request->query->get('formatId')
  4637.                     )
  4638.                 );
  4639.             if ($query_here)
  4640.                 $data $query_here;
  4641.         }
  4642.         return $this->render(
  4643.             '@Inventory/pages/input_forms/label_format.html.twig',
  4644.             array(
  4645.                 'page_title' => 'Label Format',
  4646.                 'data' => $data,
  4647.                 'labelTypeList' => LabelConstant::$label_type_list,
  4648.                 'labelFieldsList' => LabelConstant::$label_fields_list,
  4649.                 'formatList' => $this->getDoctrine()
  4650.                     ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  4651.                     ->findBy(
  4652.                         array( //                            'formatId' => $request->query->get('formatId')
  4653.                         )
  4654.                     )
  4655.                 //                'incomeLedgerHeads'=>Accounts::getChildLedgerHeads($this->getDoctrine()->getManager(),AccountsConstant::INCOME)
  4656.             )
  4657.         );
  4658.     }
  4659.     public function GetServiceListForScAction(Request $request)
  4660.     {
  4661.         if ($request->isMethod('POST')) {
  4662.             $em $this->getDoctrine();
  4663.             $find_array = array(
  4664.                 'type' => 2//service
  4665.             );
  4666.             $Content = [];
  4667.             $Transport_data = [];
  4668.             $Lul_data = [];
  4669.             if ($request->request->get('soId') != '')
  4670.                 $find_array['salesOrderId'] = $request->request->get('soId');
  4671. //            if($request->request->get('warehouseId')!='')
  4672. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4673.             $QD $this->getDoctrine()
  4674.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  4675.                 ->findBy(
  4676.                     $find_array,
  4677.                     array()
  4678.                 );
  4679. //            if($request->request->get('wareHouseId')!='')
  4680.             $SO $this->getDoctrine()
  4681.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  4682.                 ->findOneBy(
  4683.                     array(
  4684.                         'salesOrderId' => $request->request->get('soId')
  4685.                     ),
  4686.                     array()
  4687.                 );
  4688.             $sendData = array(
  4689. //                'salesType'=>$SO->getSalesType(),
  4690. //                'packageData'=>[],
  4691.                 'productList' => [],
  4692. //                'productListByPackage'=>[],
  4693.             );
  4694.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager(), $SO->getCompanyId());
  4695.             $pckg_item_cross_match_data = [];
  4696.             foreach ($QD as $product) {
  4697.                 $p_data = array(
  4698.                     'details_id' => $product->getId(),
  4699.                     'service_id' => $product->getServiceId(),
  4700.                     'service_name' => $serviceList[$product->getServiceId()]['name'],
  4701.                     'available_inventory' => $product->getBalance(),
  4702. //                        'package_id'=>$product->getPackageId(),
  4703.                     'qty' => $product->getQty(),
  4704.                     'delivered' => $product->getDelivered(),
  4705. //                    'deliverable'=>$product->getDeliverable(),
  4706.                     'balance' => $product->getBalance(),
  4707. //                        'delivered'=>$product->getDelivered(),
  4708.                 );
  4709.                 $sendData['serviceList'][] = $p_data;
  4710.             }
  4711.             //now package data
  4712.             if ($sendData) {
  4713.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4714.             }
  4715.             return new JsonResponse(array("success" => false));
  4716.         }
  4717.         return new JsonResponse(array("success" => false));
  4718.     }
  4719.     public function CreateReceivedNoteAction(Request $request)
  4720.     {
  4721.         if ($request->isMethod('POST')) {
  4722.             $em $this->getDoctrine()->getManager();
  4723.             $entity_id array_flip(GeneralConstant::$Entity_list)['Grn']; //change
  4724.             $dochash $request->request->get('docHash'); //change
  4725.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4726.             $approveRole 1;  //created
  4727.             $approveHash $request->request->get('approvalHash');
  4728.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4729.                 $loginId$approveRole$approveHash)
  4730.             ) {
  4731.                 $this->addFlash(
  4732.                     'error',
  4733.                     'Sorry Couldnot insert Data.'
  4734.                 );
  4735.             } else {
  4736.                 $data $request->request;
  4737.                 $grnId Inventory::CreateGrn($this->getDoctrine()->getManager(), $data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4738.                 //now add Approval info
  4739.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4740.                 $approveRole 1;  //created
  4741.                 $options = array(
  4742.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4743.                     'notification_server' => $this->container->getParameter('notification_server'),
  4744.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4745.                     'url' => $this->generateUrl(
  4746.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['Grn']]
  4747.                         ['entity_view_route_path_name']
  4748.                     )
  4749.                 );
  4750.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4751.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  4752.                     $grnId,
  4753.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4754.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['Grn'], $grnId,
  4755.                     $loginId,
  4756.                     $approveRole,
  4757.                     $request->request->get('approvalHash'));
  4758.                 $this->addFlash(
  4759.                     'success',
  4760.                     'New GRN Added.'
  4761.                 );
  4762.                 $url $this->generateUrl(
  4763.                     'view_grn'
  4764.                 );
  4765.                 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),
  4766.                     "Good Received Note : " $dochash " Has Been Created And is Under Processing",
  4767.                     'pos',
  4768.                     System::getPositionIdsByDepartment($em, [GeneralConstant::SALES_DEPARTMENTGeneralConstant::PURCHASE_DEPARTMENTGeneralConstant::ACCOUNTS_DEPARTMENTGeneralConstant::INVENTORY_DEPARTMENT]),
  4769.                     'success',
  4770.                     $url "/" $grnId,
  4771.                     "GRN"
  4772.                 );
  4773.                 return $this->redirect($url "/" $grnId);
  4774.             }
  4775.         }
  4776.         return $this->render('@Inventory/pages/input_forms/received_note.html.twig',
  4777.             array(
  4778.                 'page_title' => 'GRN',
  4779.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  4780.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  4781.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  4782.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  4783.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  4784.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  4785.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  4786.                 'material_inward' => $this->getDoctrine()
  4787.                     ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  4788.                     ->findBy(
  4789.                         array(
  4790.                             'stage' => GeneralConstant::STAGE_PENDING_TAG
  4791.                         )
  4792.                     )
  4793. //                'po'=>Inventory::getPurchaseOrderList
  4794.             )
  4795.         );
  4796.     }
  4797.     public function GetQcListForGrnAction(Request $request)
  4798.     {
  4799.         if ($request->isMethod('POST')) {
  4800.             $find_array = array(
  4801.                 'stage' => GeneralConstant::STAGE_PENDING_TAG
  4802.             );
  4803.             $Content = [];
  4804.             $ContentByProductId = [];
  4805.             $Transport_data = [];
  4806.             $Lul_data = [];
  4807.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4808.             if ($request->request->get('poId') != '')
  4809.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4810.             if ($request->request->get('warehouseId') != '')
  4811.                 $find_array['warehouseId'] = $request->request->get('warehouseId');
  4812.             $QD $this->getDoctrine()
  4813.                 ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  4814.                 ->findBy(
  4815.                     $find_array,
  4816.                     array(
  4817.                         'inwardDate' => 'ASC',
  4818.                         'qcDate' => 'ASC'
  4819.                     )
  4820.                 );
  4821.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4822.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4823.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4824.             $lotNumArray = [];
  4825.             foreach ($QD as $entry) {
  4826. //                $inwardDate=strtotime($entry->getInwardDate());
  4827. //                $qcDate=strtotime($entry->getQcDate());
  4828.                 $inwardDate = ($entry->getInwardDate() instanceof \DateTime) ? $entry->getInwardDate()->format('m/d/Y') : '';
  4829.                 $qcDate = ($entry->getQcDate() instanceof \DateTime) ? $entry->getQcDate()->format('m/d/Y') : '';
  4830.                 if (!in_array($entry->getLotNumber(), $lotNumArray))
  4831.                     $lotNumArray[] = $entry->getLotNumber();
  4832.                 if (isset($ContentByProductId[$entry->getPurchaseOrderItemId()])) {
  4833.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['inwardDateList'][] = $inwardDate;
  4834.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcDateList'][] = $inwardDate;
  4835.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcIdList'][] = $entry->getQcId();
  4836.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['appQtyList'][] = $entry->getApprovedQty();
  4837.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['totQty'] += ($entry->getApprovedQty());
  4838.                 } else {
  4839.                     $ContentByProductId[$entry->getPurchaseOrderItemId()] = array(
  4840.                         'productName' => $productList[$entry->getProductId()]['name'],
  4841.                         'productUnitName' => $unitList[$productList[$entry->getProductId()]['unit_type']]['name'],
  4842.                         'qcHash' => $entry->getDocumentHash(),
  4843.                         'warehouseName' => $warehouse[$entry->getWarehouseId()]['name'],
  4844.                         'inwardDate' => $inwardDate,
  4845.                         'inwardDateList' => [$inwardDate],
  4846.                         'qcDateList' => [$qcDate],
  4847.                         'qcIdList' => [$entry->getQcId()],
  4848.                         'qcDate' => $qcDate,
  4849.                         'poQty' => $entry->getPoQty(),
  4850.                         'poPrevbalance' => $entry->getPoBalance(),
  4851.                         'appQty' => $entry->getApprovedQty(),
  4852.                         'appQtyList' => [$entry->getApprovedQty()],
  4853.                         'totQty' => $entry->getApprovedQty(),
  4854.                         'poBalance' => $entry->getPoBalance() - $entry->getApprovedQty(),
  4855.                         'qcId' => $entry->getQcId(),
  4856.                         'productId' => $entry->getProductId()
  4857.                     );
  4858.                 }
  4859.                 $Expense_Cost[$entry->getQcId()] = json_decode($entry->getExpenseCost());
  4860.                 $Expense_Id[$entry->getQcId()] = json_decode($entry->getExpenseId());
  4861.             }
  4862.             foreach ($ContentByProductId as $c) {
  4863.                 $Content[] = $c;
  4864.             }
  4865.             if ($QD) {
  4866.                 return new JsonResponse(array("success" => true"content" => $Content"lotNumber" => implode(', '$lotNumArray), 'Expense_Cost' => $Expense_Cost'Expense_Id' => $Expense_Id));
  4867.             }
  4868.             return new JsonResponse(array("success" => false));
  4869.         }
  4870.         return new JsonResponse(array("success" => false));
  4871.     }
  4872.     public function GetSrListForIrAction(Request $request)
  4873.     {
  4874.         if ($request->isMethod('POST')) {
  4875.             $find_array = array();
  4876.             $Content = [];
  4877.             if ($request->request->get('srId') != '')
  4878.                 $find_array['stockRequisitionId'] = $request->request->get('srId');
  4879.             $find_array['forceSkipTag'] = [0null];
  4880.             $QD $this->getDoctrine()
  4881.                 ->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')
  4882.                 ->findBy(
  4883.                     $find_array
  4884.                 );
  4885.             $itemList Inventory::ItemGroupList($this->getDoctrine()->getManager());
  4886.             $catgoryList Inventory::ProductCategoryList($this->getDoctrine()->getManager());
  4887.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4888.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4889.             $fdmData = array();
  4890.             $em $this->getDoctrine()->getManager();
  4891.             $matchType 'MAXIMUM';
  4892.             if ($request->request->has('matchType') != '') {
  4893.                 $matchType $request->request->get('matchType');
  4894.             }
  4895.             if ($matchType == 'MINIMUM') {
  4896.                 foreach ($QD as $entry) {
  4897.                     if ($entry->getTagPendingAmount() <= 0)
  4898.                         continue;
  4899.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4900.                     $combined_id $entry->getProductFdm();
  4901.                     if (isset($fdmData[$combined_id])) {
  4902.                         $fdmData[$combined_id]['unit'] += $entry->getTagPendingAmount();
  4903.                         $fdmData[$combined_id]['specific_unit'][] = $entry->getTagPendingAmount();
  4904.                         $fdmData[$combined_id]['detailsIds'][] = $entry->getId();
  4905.                         $fdmData[$combined_id]['docIds'][] = $entry->getStockRequisitionId();
  4906.                     } else {
  4907.                         $fdmData[$combined_id] = array(
  4908.                             'id' => 0,
  4909.                             'alias' => $entry->getNote(),
  4910.                             'unit' => $entry->getTagPendingAmount(),
  4911.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4912.                             'warranty' => 0,
  4913.                             'unitTypeId' => 0,
  4914.                             'unit_price' => 0,
  4915.                             'fdm' => $combined_id,
  4916.                             'extDetailsId' => 0,
  4917.                             'product_name' => $productData['productName'],
  4918.                             'total_price' => 0,
  4919.                             'detailsIds' => [$entry->getId()],
  4920.                             'docIds' => [$entry->getStockRequisitionId()],
  4921.                         );
  4922.                     }
  4923.                 }
  4924.             }
  4925.             if ($matchType == 'MAXIMUM') {
  4926.                 foreach ($QD as $entry) {
  4927.                     if ($entry->getTagPendingAmount() <= 0)
  4928.                         continue;
  4929.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4930.                     $combined_id $entry->getProductFdm();
  4931.                     $assigned 0;
  4932.                     foreach ($fdmData as $key_ind => $rel_val) {
  4933.                         $matchFdm Inventory::MatchFdm($key_ind$combined_id);
  4934.                         if ($matchFdm['hasMatched'] == 1) {
  4935.                             if ($matchFdm['isIdentical'] == 1) {
  4936.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4937.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4938.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4939.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4940.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4941.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4942.                                 $assigned 1;
  4943.                             } elseif ($matchFdm['SecondBelongsToFirst'] == 1) {
  4944.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4945.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4946.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4947.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4948.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4949.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4950.                                 $assigned 1;
  4951.                             } elseif ($matchFdm['FirstBelongsToSecond'] == 1) {
  4952.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4953.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4954.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4955.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4956.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4957.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4958.                                 $fdmData[$combined_id] = $fdmData[$key_ind];
  4959.                                 unset($fdmData[$key_ind]);
  4960.                                 $assigned 1;
  4961.                             }
  4962.                         } else {
  4963.                         }
  4964.                         if ($assigned == 1)
  4965.                             break;
  4966.                     }
  4967.                     if ($assigned == 0) {
  4968.                         $fdmData[$combined_id] = array(
  4969.                             'id' => 0,
  4970.                             'alias' => $entry->getNote(),
  4971.                             'unit' => $entry->getTagPendingAmount(),
  4972.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4973.                             'specific_unit_type_id' => [$entry->getUnitTypeId()],
  4974.                             'warranty' => 0,
  4975.                             'unitTypeId' => $productData['unitTypeId'],
  4976. //                            'unitTypeId' => $productData['unitTypeId'],
  4977.                             'unit_price' => 0,
  4978.                             'fdm' => $combined_id,
  4979.                             'extDetailsId' => 0,
  4980.                             'product_name' => htmlspecialchars($productData['productName']),
  4981.                             'total_price' => 0,
  4982.                             'detailsIds' => [$entry->getId()],
  4983.                             'docIds' => [$entry->getStockRequisitionId()],
  4984.                         );
  4985.                     }
  4986.                     if (isset($fdmData[$combined_id])) {
  4987.                     } else {
  4988.                     }
  4989.                 }
  4990.             }
  4991.             $QD $this->getDoctrine()
  4992.                 ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  4993.                 ->findBy(
  4994.                     array('stockRequisitionId' => $request->request->get('srId'))
  4995.                 );
  4996.             $contentNote "";
  4997.             foreach ($QD as $r) {
  4998.                 $contentNote .= $r->getNote();
  4999.                 $contentNote .= " , ";
  5000.             }
  5001.             foreach ($fdmData as $dt) {
  5002.                 $Content[] = $dt;
  5003.             }
  5004.             if ($Content) {
  5005.                 return new JsonResponse(array("success" => true"content" => $Content"contentNote" => $contentNote));
  5006.             }
  5007.             return new JsonResponse(array("success" => false));
  5008.         }
  5009.         return new JsonResponse(array("success" => false));
  5010.     }
  5011.     public function GetGrnListForEiAction(Request $request)
  5012.     {
  5013.         if ($request->isMethod('POST')) {
  5014.             $find_array = array(
  5015.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  5016.                 'approved' => GeneralConstant::APPROVED,
  5017.                 'invoiceTagged' => 1
  5018.             );
  5019.             $Content = [];
  5020.             $Content_obj = [];
  5021.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  5022.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  5023.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  5024.             if ($request->request->get('poId') != '')
  5025.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  5026.             if ($request->request->get('grnId') != '')
  5027.                 $find_array['grnId'] = $request->request->get('grnId');
  5028.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5029.             $QD_GRN $this->getDoctrine()
  5030.                 ->getRepository('ApplicationBundle\\Entity\\Grn')
  5031.                 ->findBy(
  5032.                     $find_array,
  5033.                     array(
  5034.                         'grnDate' => 'ASC'
  5035.                     )
  5036.                 );
  5037.             $poId 0;
  5038. //
  5039. //            $expense_id=$QD_GRN->getExpenseId()!=''?json_decode($QD_GRN->getExpenseId()):[];
  5040. //                $expense_list=$QD_GRN->getExpenseCost()!=''?json_decode($QD_GRN->getExpenseCost()):[];
  5041. //                $expense_tagged=$QD_GRN->getExpenseTagged()!=''?json_decode($QD_GRN->getExpenseTagged()):[];
  5042.             $partyId $request->request->get('partyId');
  5043.             $bill_details = [];
  5044.             $bill_details_data = [];
  5045.             $bill_details_for_grn = [];
  5046.             $exp_list InventoryConstant::$Expense_list_details;
  5047.             $supp_list Inventory::ProductSupplierList($this->getDoctrine()->getManager());
  5048.             $head_qry $this->getDoctrine()
  5049.                 ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  5050.                 ->findAll();
  5051.             $head_list = [];
  5052.             $head_list_by_advance = [];
  5053.             foreach ($head_qry as $data) {
  5054.                 $head_list[$data->getAccountsHeadId()] = array(
  5055.                     'id' => $data->getAccountsHeadId(),
  5056.                     'name' => $data->getName(),
  5057.                     'advanceTagged' => $data->getAdvanceTagged(),
  5058.                     'advanceOf' => $data->getAdvanceOf(),
  5059.                     'balance' => $data->getCurrentBalance()
  5060.                 );
  5061.                 if ($data->getAdvanceOf() != null && $data->getAdvanceOf() != && $data->getAdvanceOf() != '')
  5062.                     $head_list_by_advance[$data->getAdvanceOf()] = array(
  5063.                         'id' => $data->getAccountsHeadId(),
  5064.                         'name' => $data->getName(),
  5065.                         'advanceTagged' => $data->getAdvanceTagged(),
  5066.                         'advanceOf' => $data->getAdvanceOf(),
  5067.                         'balance' => $data->getCurrentBalance()
  5068.                     );
  5069.             }
  5070.             $exp_def_head = [];
  5071.             foreach ($exp_list as $key => $item) {
  5072.                 $def_settings $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  5073.                     'name' => $item['name'] . '_onsite_head'
  5074.                 ));
  5075.                 if ($def_settings)
  5076.                     $exp_def_head[$item['id']] = $def_settings->getData();
  5077.                 else
  5078.                     $exp_def_head[$item['id']] = '';
  5079.             }
  5080.             $bill_details_by_party = [];
  5081. //            System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($QD_GRN),'debug_data');
  5082. //            System::log_it($this->container->getParameter('kernel.root_dir'),$partyId,'debug_data');
  5083. //            System::log_it($this->container->getParameter('kernel.root_dir'),"\nexp list here".json_encode($exp_list),'debug_data');
  5084. //
  5085.             foreach ($QD_GRN as $key => $value) {
  5086.                 $expense_id $value->getExpenseId() != '' json_decode($value->getExpenseId(), true) : [];
  5087.                 $expense_list $value->getExpenseCost() != '' json_decode($value->getExpenseCost(), true) : [];
  5088.                 $expense_tagged $value->getExpenseTagged() != '' json_decode($value->getExpenseTagged(), true) : [];
  5089. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_id),'debug_data');
  5090. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_list),'debug_data');
  5091.                 foreach ($exp_list as $chabi => $entry) {
  5092. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nChabi ".$chabi,'debug_data');
  5093. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nkeys are ".array_keys($expense_id),'debug_data');
  5094.                     if (array_key_exists($chabi$expense_id)) {
  5095. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nFOUND KEY!! ",'debug_data');
  5096.                         if ($partyId == ''//all
  5097.                         {
  5098.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  5099.                                 $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  5100.                                 $advance_balance 0;
  5101.                                 if ($partyHeadId != 0) {
  5102.                                     $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  5103.                                     $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  5104.                                     $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  5105.                                 }
  5106.                                 $bill_details_by_party[$my_val][] = array(
  5107.                                     'partyId' => $my_val,
  5108.                                     'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  5109.                                     'partyHeadId' => $partyHeadId,
  5110.                                     'expTypeId' => $chabi,
  5111.                                     'expTypeName' => $exp_list[$chabi]['name'],
  5112.                                     'expTypeAlias' => $exp_list[$chabi]['alias'],
  5113.                                     'expAmount' => $expense_list[$chabi][$index],
  5114.                                     'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  5115.                                     'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  5116.                                     'AdvanceBalance' => $advance_balance,
  5117.                                     'grnId' => $value->getGrnId(),
  5118.                                     'grnName' => $value->getDocumentHash(),
  5119.                                 );
  5120.                             }
  5121.                         } else {
  5122.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  5123.                                 if (in_array($my_val$partyId)) {
  5124.                                     $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  5125.                                     $advance_balance 0;
  5126.                                     if ($partyHeadId != 0) {
  5127.                                         $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  5128.                                         $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  5129.                                         $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  5130.                                     }
  5131.                                     $bill_details_by_party[$my_val][] = array(
  5132.                                         'partyId' => $my_val,
  5133.                                         'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  5134.                                         'partyHeadId' => $partyHeadId,
  5135.                                         'expTypeId' => $chabi,
  5136.                                         'expTypeName' => $exp_list[$chabi]['name'],
  5137.                                         'expTypeAlias' => $exp_list[$chabi]['alias'],
  5138.                                         'expAmount' => $expense_list[$chabi][$index],
  5139.                                         'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  5140.                                         'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  5141.                                         'AdvanceBalance' => $advance_balance,
  5142.                                         'grnId' => $value->getGrnId(),
  5143.                                         'grnName' => $value->getDocumentHash(),
  5144.                                     );
  5145.                                 }
  5146.                             }
  5147.                         }
  5148.                     }
  5149.                 }
  5150.             }
  5151. //            $Content_obj=
  5152. //
  5153. //            foreach($Content_obj as $item)
  5154. //            {
  5155. //                $Content[]=$item;
  5156. //
  5157. //            }
  5158.             $list_of_keys array_keys($bill_details_by_party);
  5159.             if ($bill_details_by_party) {
  5160.                 return new JsonResponse(array("success" => true"content" => $bill_details_by_party'index' => $list_of_keys'h_l_b_a' => $head_list_by_advance));
  5161.             }
  5162.             return new JsonResponse(array("success" => false));
  5163.         }
  5164.         return new JsonResponse(array("success" => false));
  5165.     }
  5166.     public function GetServiceListForPiAction(Request $request)
  5167.     {
  5168.         if ($request->isMethod('POST')) {
  5169. //            $find_array=array(
  5170. //                'stage' =>  GeneralConstant::STAGE_PENDING_TAG,
  5171. //                'approved'=>GeneralConstant::APPROVED
  5172. //            );
  5173.             $Content = [];
  5174.             $Content_obj = [];
  5175.             $ContentService = [];
  5176.             $Content_service_obj = [];
  5177. //            $warehouse=Inventory::WarehouseList($this->getDoctrine()->getManager());
  5178. //            $poList=Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  5179. //            $productList=Inventory::ProductList($this->getDoctrine()->getManager());
  5180.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  5181.             if ($request->request->get('poId') != '')
  5182.                 $poId $request->request->get('poId');
  5183.             if ($request->request->get('grnId') != '')
  5184.                 $find_array['grnId'] = $request->request->get('grnId');
  5185.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5186.             //adding service data temporarily
  5187.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(
  5188.                 array('purchaseOrderId' => $poId));
  5189.             $multiply_type $po->getCurrencyMultiply();
  5190.             $multiply_rate $po->getCurrencyMultiplyRate();
  5191.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  5192.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  5193.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5194.                 array('purchaseOrderId' => $poId));
  5195.             foreach ($po_items as $item) {
  5196. //                $po_item_list[$item->getProductId()]=$item;
  5197.                 //temporary service add
  5198.                 if ($item->getType() == 2)
  5199.                     $Content_service_obj[$item->getId()] = array(
  5200.                         'serviceId' => $item->getServiceId(),
  5201.                         'poItemId' => $item->getId(),
  5202.                         'colorId' => 0,
  5203.                         'sizeId' => 0,
  5204.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  5205.                         'qty' => $item->getQty(),
  5206.                         'balance' => $item->getBalance(),
  5207.                         'unit_name' => '',
  5208.                         'unit_price' => $item->getPrice() * $multiplier,
  5209.                         'grn_id' => 0,
  5210.                     );
  5211.                 //temprary service add end
  5212.             }
  5213.             //temporary service data adding done
  5214.             $po_data = [];
  5215.             $po_data = array(
  5216.                 'docHash' => $po->getDocumentHash(),
  5217.                 'docDate' => $po->getPurchaseOrderDate(),
  5218.                 'supplierId' => $po->getSupplierId(),
  5219.                 'supplierName' => $po->getSupplierId(),
  5220.                 'vatRate' => $po->getVatRate(),
  5221.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  5222.                 'aitRate' => $po->getAitRate(),
  5223.                 'aitAmount' => $po->getAitAmount(),
  5224.                 'tdsRate' => $po->getTdsRate(),
  5225.                 'tdsAmount' => $po->getTdsAmount(),
  5226.                 'vdsRate' => $po->getVdsRate(),
  5227.                 'vdsAmount' => $po->getVdsAmount(),
  5228.                 'discountRate' => $po->getDiscountRate(),
  5229.                 'discountAmount' => $po->getVatAmount(),
  5230.             );
  5231.             foreach ($Content_obj as $item) {
  5232.                 $Content[] = $item;
  5233.             }
  5234.             foreach ($Content_service_obj as $item) {
  5235.                 $ContentService[] = $item;
  5236.             }
  5237.             if ($Content || $ContentService) {
  5238.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  5239.             }
  5240.             return new JsonResponse(array("success" => false));
  5241.         }
  5242.         return new JsonResponse(array("success" => false));
  5243.     }
  5244.     public function GetGrnListForPiAction(Request $request)
  5245.     {
  5246.         if ($request->isMethod('POST')) {
  5247.             $find_array = array(
  5248.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  5249.                 'approved' => GeneralConstant::APPROVED
  5250.             );
  5251.             $Content = [];
  5252.             $Content_obj = [];
  5253.             $ContentService = [];
  5254.             $Content_service_obj = [];
  5255.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  5256.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  5257.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  5258.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  5259.             if ($request->request->get('poId') != '')
  5260.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  5261.             if ($request->request->get('grnId') != '')
  5262.                 $find_array['grnId'] = $request->request->get('grnId');
  5263.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5264.             $QD_GRN $this->getDoctrine()
  5265.                 ->getRepository('ApplicationBundle\\Entity\\Grn')
  5266.                 ->findBy(
  5267.                     $find_array,
  5268.                     array(
  5269.                         'grnDate' => 'ASC'
  5270.                     )
  5271.                 );
  5272.             $poId 0;
  5273.             foreach ($QD_GRN as $value) {
  5274.                 $grn_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\GrnItem')->findBy(
  5275.                     array('grnId' => $value->getGrnId()));
  5276.                 $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5277.                     array('purchaseOrderId' => $value->getPurchaseOrderId()));
  5278.                 $poId $value->getPurchaseOrderId();
  5279.                 $po_item_list = [];
  5280.                 foreach ($po_items as $item) {
  5281.                     $po_item_list[$item->getProductId()] = $item;
  5282.                 }
  5283.                 foreach ($grn_items as $entry) {
  5284.                     //adding transaction
  5285. //                    System::log_it($this->container->getParameter('kernel.root_dir'),$entry->getProductId(),'debug_data');
  5286.                     $Content_obj[$entry->getId()] = array(
  5287.                         'productId' => $entry->getProductId(),
  5288.                         'poItemId' => $entry->getPurchaseOrderItemId(),
  5289.                         'productName' => $productList[$entry->getProductId()]['name'],
  5290.                         'colorId' => $entry->getColorId(),
  5291.                         'sizeId' => $entry->getSizeId(),
  5292.                         'qty' => isset($Content_obj[$entry->getId()]) ? $Content_obj[$entry->getId()]['qty'] + $entry->getQty() : $entry->getQty(),
  5293.                         'unit_name' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  5294. //                            'unit_price'=>$po_item_list[$entry->getProductId()]->getPrice(),
  5295.                         'unit_price' => $entry->getPrice(),
  5296.                         'grn_id' => $entry->getId(),
  5297.                     );
  5298.                 }
  5299. //            for
  5300.             }
  5301.             //adding service data temporarily
  5302.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(
  5303.                 array('purchaseOrderId' => $poId));
  5304.             $multiply_type $po->getCurrencyMultiply();
  5305.             $multiply_rate $po->getCurrencyMultiplyRate();
  5306.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  5307.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  5308.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5309.                 array('purchaseOrderId' => $poId));
  5310.             foreach ($po_items as $item) {
  5311. //                $po_item_list[$item->getProductId()]=$item;
  5312.                 //temporary service add
  5313.                 if ($item->getType() == 2)
  5314.                     $Content_service_obj[$item->getId()] = array(
  5315.                         'serviceId' => $item->getServiceId(),
  5316.                         'poItemId' => $item->getId(),
  5317.                         'colorId' => 0,
  5318.                         'sizeId' => 0,
  5319.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  5320.                         'qty' => $item->getQty(),
  5321.                         'balance' => $item->getBalance(),
  5322.                         'unit_name' => '',
  5323.                         'unit_price' => $item->getPrice() * $multiplier,
  5324.                         'grn_id' => 0,
  5325.                     );
  5326.                 //temprary service add end
  5327.             }
  5328.             //temporary service data adding done
  5329.             $po_data = [];
  5330.             $vatAmount $po->getVatAmount();
  5331.             $priceAfterDiscount $po->getSupplierPayableAmount() - $po->getVatAmount();
  5332.             $vatRate = ($vatAmount $priceAfterDiscount) * 100;
  5333.             $po_data = array(
  5334.                 'docHash' => $po->getDocumentHash(),
  5335.                 'docDate' => $po->getPurchaseOrderDate(),
  5336.                 'supplierId' => $po->getSupplierId(),
  5337.                 'supplierName' => $po->getSupplierId(),
  5338.                 'vatRate' => $vatRate,
  5339.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  5340.                 'aitRate' => $po->getAitRate(),
  5341.                 'aitAmount' => $po->getAitAmount(),
  5342.                 'tdsRate' => $po->getTdsRate(),
  5343.                 'tdsAmount' => $po->getTdsAmount(),
  5344.                 'vdsRate' => $po->getVdsRate(),
  5345.                 'vdsAmount' => $po->getVdsAmount(),
  5346.                 'discountRate' => $po->getDiscountRate(),
  5347. //                'discountAmount' => $po->getVatAmount(),
  5348.                 'vatAmount' => $vatAmount,
  5349.                 'discountAmount' => $po->getDiscountAmount(),
  5350.                 'supplierPayableAmount' => $po->getSupplierPayableAmount(),
  5351.                 'priceAfterDiscount' => $priceAfterDiscount
  5352.             );
  5353.             foreach ($Content_obj as $item) {
  5354.                 $Content[] = $item;
  5355.             }
  5356.             foreach ($Content_service_obj as $item) {
  5357.                 $ContentService[] = $item;
  5358.             }
  5359.             if ($Content) {
  5360.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  5361.             }
  5362.             return new JsonResponse(array("success" => false));
  5363.         }
  5364.         return new JsonResponse(array("success" => false));
  5365.     }
  5366.     public function GetPoDetailsForPiAction(Request $request$poId)
  5367.     {
  5368.     }
  5369.     public function GetPoDetailsAction(Request $request$poId)
  5370.     {
  5371.         if ($request->isMethod('POST')) {
  5372.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findBy(
  5373.                 array('purchaseOrderId' => $poId));
  5374.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5375.                 array('purchaseOrderId' => $poId));
  5376.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  5377.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5378.             $spec_type Inventory::SpecTypeList($this->getDoctrine()->getManager());
  5379.             $Content = [];
  5380.             $po_items_list = [];
  5381.             foreach ($po_items as $entry) {
  5382.                 $po_items_list[] = array(
  5383.                     'productId' => $entry->getProductId(),
  5384.                     'productName' => $productList[$entry->getProductId()]['name'],
  5385.                     'price' => $entry->getPrice(),
  5386.                     'unit' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  5387.                     'spec' => $spec_type[$productList[$entry->getProductId()]['spec_type']]['name'],
  5388.                     'received' => $entry->getReceived(),
  5389.                     'qty' => $entry->getQty(),
  5390.                     'balance' => $entry->getBalance()
  5391.                 );
  5392.             }
  5393.             $po_data = [];
  5394.             $po_data = array(
  5395.                 'docHash' => $po->getDocumentHash(),
  5396.                 'docDate' => $po->getPurchaseOrderDate(),
  5397.                 'supplierId' => $po->getSupplierId(),
  5398.                 'supplierName' => $po->getSupplierId(),
  5399.             );
  5400.             if ($po_data) {
  5401.                 return new JsonResponse(array("success" => true"content" => $po_data));
  5402.             }
  5403.             return new JsonResponse(array("success" => false));
  5404.         }
  5405.         return new JsonResponse(array("success" => false));
  5406.     }
  5407.     public function CreateSalesReplacementAction(Request $request)
  5408.     {
  5409.         $em $this->getDoctrine()->getManager();
  5410.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5411.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5412.         if ($request->isMethod('POST')) {
  5413.             $em $this->getDoctrine()->getManager();
  5414.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesReplacement']; //change
  5415.             $dochash $request->request->get('voucherNumber'); //change
  5416.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5417.             $approveRole $request->request->get('approvalRole');
  5418.             $approveHash $request->request->get('approvalHash');
  5419.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5420.                 $loginId$approveRole$approveHash)
  5421.             ) {
  5422.                 $this->addFlash(
  5423.                     'error',
  5424.                     'Sorry Couldnot insert Data.'
  5425.                 );
  5426.             } else {
  5427.                 if ($request->request->has('check_allowed'))
  5428.                     $check_allowed 1;
  5429.                 $StID Inventory::CreateNewSalesReplacement(
  5430.                     $this->getDoctrine()->getManager(),
  5431.                     $request->request,
  5432.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5433.                     $this->getLoggedUserCompanyId($request)
  5434.                 );
  5435.                 //now add Approval info
  5436.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5437.                 $approveRole 1;  //created
  5438.                 $options = array(
  5439.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5440.                     'notification_server' => $this->container->getParameter('notification_server'),
  5441.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5442.                     'url' => $this->generateUrl(
  5443.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesReplacement']]
  5444.                         ['entity_view_route_path_name']
  5445.                     )
  5446.                 );
  5447.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5448.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5449.                     $StID,
  5450.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5451.                 );
  5452.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesReplacement'], $StID,
  5453.                     $loginId,
  5454.                     $approveRole,
  5455.                     $request->request->get('approvalHash'));
  5456.                 $this->addFlash(
  5457.                     'success',
  5458.                     'Stock Transfer Added.'
  5459.                 );
  5460.                 $url $this->generateUrl(
  5461.                     'view_st'
  5462.                 );
  5463.                 return $this->redirect($url "/" $StID);
  5464.             }
  5465.         }
  5466.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  5467.             array(
  5468.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5469.             )
  5470.         );
  5471.         $INVLIST = [];
  5472.         foreach ($slotList as $slot) {
  5473.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5474.         }
  5475.         return $this->render('@Inventory/pages/input_forms/sales_replacement.html.twig',
  5476.             array(
  5477.                 'page_title' => 'Sales Replacement Note',
  5478.                 'warehouseList' => Inventory::WarehouseList($em),
  5479.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5480.                 'warehouseActionList' => $warehouse_action_list,
  5481.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5482.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5483.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5484.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5485.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5486.                 'prefix_list' => array(
  5487.                     [
  5488.                         'id' => 1,
  5489.                         'value' => 'GN',
  5490.                         'text' => 'GN'
  5491.                     ]
  5492.                 ),
  5493.                 'assoc_list' => array(
  5494.                     [
  5495.                         'id' => 1,
  5496.                         'value' => 1,
  5497.                         'text' => 'GN'
  5498.                     ]
  5499.                 ),
  5500.                 'INVLIST' => $INVLIST
  5501.             )
  5502.         );
  5503.     }
  5504.     public function SalesReplacementListAction(Request $request)
  5505.     {
  5506.         $q $this->getDoctrine()
  5507.             ->getRepository('ApplicationBundle\\Entity\\SalesReplacement')
  5508.             ->findBy(
  5509.                 array(
  5510.                     'status' => GeneralConstant::ACTIVE,
  5511.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5512. //                    'approved' =>  GeneralConstant::APPROVED,
  5513.                 )
  5514.             );
  5515.         $stage_list = array(
  5516.             => 'Pending',
  5517.             => 'Pending',
  5518.             => 'Complete',
  5519.             => 'Partial',
  5520.         );
  5521.         $data = [];
  5522.         foreach ($q as $entry) {
  5523.             $data[] = array(
  5524.                 'doc_date' => $entry->getSalesReplacementDate(),
  5525.                 'id' => $entry->getSalesReplacementId(),
  5526.                 'doc_hash' => $entry->getDocumentHash(),
  5527.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5528.                 'stage' => $stage_list[$entry->getStage()]
  5529.             );
  5530.         }
  5531.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5532.             array(
  5533.                 'page_title' => 'Stock Transfer List',
  5534.                 'data' => $data
  5535.             )
  5536.         );
  5537.     }
  5538.     public function ViewSalesReplacementAction(Request $request$id)
  5539.     {
  5540.         $em $this->getDoctrine()->getManager();
  5541.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5542.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  5543.             array(
  5544.                 'page_title' => 'Stock Transfer',
  5545.                 'data' => $dt,
  5546.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5547.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5548.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5549.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5550.                     $id,
  5551.                     $dt['created_by'],
  5552.                     $dt['edited_by'])
  5553.             )
  5554.         );
  5555.     }
  5556.     public function PrintSalesReplacementAction(Request $request$id)
  5557.     {
  5558.         $em $this->getDoctrine()->getManager();
  5559.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5560.         $company_data Company::getCompanyData($em1);
  5561.         $document_mark = array(
  5562.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5563.             'copy' => ''
  5564.         );
  5565.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5566.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5567.                 array(
  5568.                     //full array here
  5569.                     'pdf' => true,
  5570.                     'page_title' => 'Stock Transfer',
  5571.                     'export' => 'pdf,print',
  5572.                     'data' => $dt,
  5573.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5574.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5575.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5576.                         array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5577.                         $id,
  5578.                         $dt['created_by'],
  5579.                         $dt['edited_by']),
  5580.                     'document_mark_image' => $document_mark['original'],
  5581.                     'company_name' => $company_data->getName(),
  5582.                     'company_data' => $company_data,
  5583.                     'company_address' => $company_data->getAddress(),
  5584.                     'company_image' => $company_data->getImage(),
  5585.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5586.                     'red' => 0
  5587.                 )
  5588.             );
  5589.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5590. //                'orientation' => 'landscape',
  5591. //                'enable-javascript' => true,
  5592. //                'javascript-delay' => 1000,
  5593.                 'no-stop-slow-scripts' => false,
  5594.                 'no-background' => false,
  5595.                 'lowquality' => false,
  5596.                 'encoding' => 'utf-8',
  5597. //            'images' => true,
  5598. //            'cookie' => array(),
  5599.                 'dpi' => 300,
  5600.                 'image-dpi' => 300,
  5601. //                'enable-external-links' => true,
  5602. //                'enable-internal-links' => true
  5603.             ));
  5604.             return new Response(
  5605.                 $pdf_response,
  5606.                 200,
  5607.                 array(
  5608.                     'Content-Type' => 'application/pdf',
  5609.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5610.                 )
  5611.             );
  5612.         }
  5613.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5614.             array(
  5615.                 'page_title' => 'Stock Transfer',
  5616.                 'export' => 'pdf,print',
  5617.                 'data' => $dt,
  5618.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5619.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5620.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5621.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5622.                     $id,
  5623.                     $dt['created_by'],
  5624.                     $dt['edited_by']),
  5625.                 'document_mark_image' => $document_mark['original'],
  5626.                 'company_name' => $company_data->getName(),
  5627.                 'company_data' => $company_data,
  5628.                 'company_address' => $company_data->getAddress(),
  5629.                 'company_image' => $company_data->getImage(),
  5630.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5631.                 'red' => 0
  5632.             )
  5633.         );
  5634.     }
  5635.     public function CreateStockTransferAction(Request $request)
  5636.     {
  5637.         $em $this->getDoctrine()->getManager();
  5638.         $companyId $this->getLoggedUserCompanyId($request);
  5639.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5640.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5641.         if ($request->isMethod('POST')) {
  5642.             $em $this->getDoctrine()->getManager();
  5643.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  5644.             $dochash $request->request->get('docHash'); //change
  5645.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5646.             $approveRole $request->request->get('approvalRole');
  5647.             $approveHash $request->request->get('approvalHash');
  5648.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5649.                 $loginId$approveRole$approveHash)
  5650.             ) {
  5651.                 $this->addFlash(
  5652.                     'error',
  5653.                     'Sorry Couldnot insert Data.'
  5654.                 );
  5655.             } else {
  5656.                 if ($request->request->has('check_allowed'))
  5657.                     $check_allowed 1;
  5658.                 $StID Inventory::CreateNewStockTransfer(
  5659.                     $this->getDoctrine()->getManager(),
  5660.                     $request->request,
  5661.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5662.                     $this->getLoggedUserCompanyId($request)
  5663.                 );
  5664.                 //now add Approval info
  5665.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5666.                 $approveRole 1;  //created
  5667.                 $options = array(
  5668.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5669.                     'notification_server' => $this->container->getParameter('notification_server'),
  5670.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5671.                     'url' => $this->generateUrl(
  5672.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  5673.                         ['entity_view_route_path_name']
  5674.                     )
  5675.                 );
  5676.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5677.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5678.                     $StID,
  5679.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  5680.                 );
  5681.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  5682.                     $loginId,
  5683.                     $approveRole,
  5684.                     $request->request->get('approvalHash'));
  5685.                 $this->addFlash(
  5686.                     'success',
  5687.                     'Stock Transfer Added.'
  5688.                 );
  5689.                 $url $this->generateUrl(
  5690.                     'view_st'
  5691.                 );
  5692.                 return $this->redirect($url "/" $StID);
  5693.             }
  5694.         }
  5695. //        $slotList = $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  5696. //            array(
  5697. //                'CompanyId' => $this->getLoggedUserCompanyId($request),
  5698. //
  5699. //            )
  5700. //        );
  5701.         $INVLIST = [];
  5702. //        foreach ($slotList as $slot) {
  5703. //            $INVLIST[$slot->getWarehouseId() . '_' . $slot->getActionTagId() . '_' . $slot->getproductId()] = $slot->getQty();
  5704. //        }
  5705.         return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  5706.             array(
  5707.                 'page_title' => 'Stock Transfer Note',
  5708.                 'warehouseList' => Inventory::WarehouseList($em),
  5709.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5710.                 'colorList' => Inventory::GetColorList($em),
  5711.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  5712.                 'srList' => [],
  5713.                 'warehouseActionList' => $warehouse_action_list,
  5714.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5715.                 'item_list' => Inventory::ItemGroupList($em),
  5716.                 'item_list_array' => Inventory::ItemGroupListArray($em),
  5717.                 'category_list_array' => Inventory::ProductCategoryListArray($em),
  5718.                 'product_list_array' => Inventory::ProductListDetailedArray($em),
  5719. //                'product_list_array' => [],
  5720.                 'product_list' => Inventory::ProductList($em$companyId),
  5721. //                'product_list' => [],
  5722.                 'prefix_list' => array(
  5723.                     [
  5724.                         'id' => 1,
  5725.                         'value' => 'GN',
  5726.                         'text' => 'GN'
  5727.                     ]
  5728.                 ),
  5729.                 'assoc_list' => array(
  5730.                     [
  5731.                         'id' => 1,
  5732.                         'value' => 1,
  5733.                         'text' => 'GN'
  5734.                     ]
  5735.                 ),
  5736.                 'INVLIST' => $INVLIST
  5737.             )
  5738.         );
  5739.     }
  5740.     public function GetSrItemForTransferAction(Request $request)
  5741.     {
  5742.         $em $this->getDoctrine()->getManager();
  5743.         $search_query = [];
  5744.         $res_data_by_so_item_id = [];
  5745.         $Content = [];
  5746.         $productionProcessSettings = array(
  5747.             'id' => 0
  5748.         );
  5749.         if ($request->query->has('srId'))
  5750.             $search_query['stockRequisitionId'] = $request->query->get('srId');
  5751.         $DT $this->getDoctrine()
  5752.             ->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')
  5753.             ->findBy(
  5754.                 $search_query
  5755.             );
  5756.         $Content = array(
  5757.             'requisitioned_product_item_id' => [],
  5758.             'requisitioned_products' => [],
  5759.             'requisitioned_product_fdm' => [],
  5760.             'requisitioned_product_name' => [],
  5761.             'requisitioned_product_units' => [],
  5762.             'requisitioned_product_unit_type' => [],
  5763.             'requisitioned_product_balance' => [],
  5764.         );
  5765.         foreach ($DT as $dt) {
  5766. //            $data=json_decode($DT->getData(),true);
  5767.             $Content['requisitioned_products'][] = $dt->getProductId();
  5768.             $Content['requisitioned_product_item_id'][] = $dt->getId();
  5769.             $Content['requisitioned_product_fdm'][] = $dt->getProductFdm();
  5770.             $Content['requisitioned_product_name'][] = $dt->getProductNameFdm();
  5771.             $Content['requisitioned_product_units'][] = $dt->getQty();
  5772.             $Content['requisitioned_product_balance'][] = $dt->getAlottmentPendingAmount();
  5773.         }
  5774.         $INVLIST = [];
  5775.         if (!empty($Content)) {
  5776.             return new JsonResponse(array("success" => true"content" => $Content"INVLIST" => $INVLIST));
  5777.         } else {
  5778.             return new JsonResponse(array("success" => false"content" => $Content"INVLIST" => $INVLIST));
  5779.         }
  5780.     }
  5781.     public function StockTransferListAction(Request $request)
  5782.     {
  5783.         $q $this->getDoctrine()
  5784.             ->getRepository('ApplicationBundle\\Entity\\StockTransfer')
  5785.             ->findBy(
  5786.                 array(
  5787.                     'status' => GeneralConstant::ACTIVE,
  5788.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5789. //                    'approved' =>  GeneralConstant::APPROVED,
  5790.                 )
  5791.             );
  5792.         $stage_list = array(
  5793.             => 'Pending',
  5794.             => 'Pending',
  5795.             => 'Complete',
  5796.             => 'Partial',
  5797.         );
  5798.         $data = [];
  5799.         foreach ($q as $entry) {
  5800.             $data[] = array(
  5801.                 'doc_date' => $entry->getStockTransferDate(),
  5802.                 'id' => $entry->getStockTransferId(),
  5803.                 'doc_hash' => $entry->getDocumentHash(),
  5804.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5805.                 'stage' => $stage_list[$entry->getStage()]
  5806.             );
  5807.         }
  5808.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5809.             array(
  5810.                 'page_title' => 'Stock Transfer List',
  5811.                 'data' => $data
  5812.             )
  5813.         );
  5814.     }
  5815.     public function ViewStockTransferAction(Request $request$id)
  5816.     {
  5817.         $em $this->getDoctrine()->getManager();
  5818.         $dt Inventory::GetStockTransferDetails($em$id);
  5819.         return $this->render(
  5820.             '@Inventory/pages/views/view_stock_transfer.html.twig',
  5821.             array(
  5822.                 'page_title' => 'Stock Transfer',
  5823.                 'data' => $dt,
  5824.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5825.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5826.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5827.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5828.                     $id,
  5829.                     $dt['created_by'],
  5830.                     $dt['edited_by'])
  5831.             )
  5832.         );
  5833.     }
  5834.     public function PrintStockTransferAction(Request $request$id)
  5835.     {
  5836.         $em $this->getDoctrine()->getManager();
  5837.         $dt Inventory::GetStockTransferDetails($em$id);
  5838.         $company_data Company::getCompanyData($em1);
  5839.         $document_mark = array(
  5840.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5841.             'copy' => ''
  5842.         );
  5843.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5844.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5845.                 array(
  5846.                     //full array here
  5847.                     'pdf' => true,
  5848.                     'page_title' => 'Stock Transfer',
  5849.                     'export' => 'pdf,print',
  5850.                     'data' => $dt,
  5851.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5852.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5853.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5854.                         array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5855.                         $id,
  5856.                         $dt['created_by'],
  5857.                         $dt['edited_by']),
  5858.                     'document_mark_image' => $document_mark['original'],
  5859.                     'company_name' => $company_data->getName(),
  5860.                     'company_data' => $company_data,
  5861.                     'company_address' => $company_data->getAddress(),
  5862.                     'company_image' => $company_data->getImage(),
  5863.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5864.                     'red' => 0
  5865.                 )
  5866.             );
  5867.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5868. //                'orientation' => 'landscape',
  5869. //                'enable-javascript' => true,
  5870. //                'javascript-delay' => 1000,
  5871.                 'no-stop-slow-scripts' => false,
  5872.                 'no-background' => false,
  5873.                 'lowquality' => false,
  5874.                 'encoding' => 'utf-8',
  5875. //            'images' => true,
  5876. //            'cookie' => array(),
  5877.                 'dpi' => 300,
  5878.                 'image-dpi' => 300,
  5879. //                'enable-external-links' => true,
  5880. //                'enable-internal-links' => true
  5881.             ));
  5882.             return new Response(
  5883.                 $pdf_response,
  5884.                 200,
  5885.                 array(
  5886.                     'Content-Type' => 'application/pdf',
  5887.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5888.                 )
  5889.             );
  5890.         }
  5891.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5892.             array(
  5893.                 'page_title' => 'Stock Transfer',
  5894.                 'export' => 'pdf,print',
  5895.                 'data' => $dt,
  5896.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5897.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5898.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5899.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5900.                     $id,
  5901.                     $dt['created_by'],
  5902.                     $dt['edited_by']),
  5903.                 'document_mark_image' => $document_mark['original'],
  5904.                 'company_name' => $company_data->getName(),
  5905.                 'company_data' => $company_data,
  5906.                 'company_address' => $company_data->getAddress(),
  5907.                 'company_image' => $company_data->getImage(),
  5908.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5909.                 'red' => 0
  5910.             )
  5911.         );
  5912.     }
  5913.     public function CreateStockConsumptionNoteAction(Request $request)
  5914.     {
  5915.         $em $this->getDoctrine()->getManager();
  5916.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5917.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5918.         if ($request->isMethod('POST')) {
  5919.             $em $this->getDoctrine()->getManager();
  5920.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']; //change
  5921.             $dochash $request->request->get('voucherNumber'); //change
  5922.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5923.             $approveRole $request->request->get('approvalRole');
  5924.             $approveHash $request->request->get('approvalHash');
  5925.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5926.                 $loginId$approveRole$approveHash)
  5927.             ) {
  5928.                 $this->addFlash(
  5929.                     'error',
  5930.                     'Sorry Could not insert Data.'
  5931.                 );
  5932.             } else {
  5933.                 if ($request->request->has('check_allowed'))
  5934.                     $check_allowed 1;
  5935.                 $StID Inventory::CreateNewStockConsumptionNote(
  5936.                     $this->getDoctrine()->getManager(),
  5937.                     $request->request,
  5938.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5939.                     $this->getLoggedUserCompanyId($request)
  5940.                 );
  5941.                 //now add Approval info
  5942.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5943.                 $approveRole 1;  //created
  5944.                 $options = array(
  5945.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5946.                     'notification_server' => $this->container->getParameter('notification_server'),
  5947.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5948.                     'url' => $this->generateUrl(
  5949.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']]
  5950.                         ['entity_view_route_path_name']
  5951.                     )
  5952.                 );
  5953.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5954.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5955.                     $StID,
  5956.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5957.                 );
  5958.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'], $StID,
  5959.                     $loginId,
  5960.                     $approveRole,
  5961.                     $request->request->get('approvalHash'));
  5962.                 $this->addFlash(
  5963.                     'success',
  5964.                     'Stock Consumption Added.'
  5965.                 );
  5966.                 $url $this->generateUrl(
  5967.                     'view_stock_consumption_note'
  5968.                 );
  5969.                 return $this->redirect($url "/" $StID);
  5970.             }
  5971.         }
  5972.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  5973.             array(
  5974.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5975.             )
  5976.         );
  5977.         $INVLIST = [];
  5978.         foreach ($slotList as $slot) {
  5979.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5980.         }
  5981.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  5982.             array(
  5983.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5984.             )
  5985.         );
  5986.         $consumptionTypeList = [];
  5987.         $consumptionTypeListArray = [];
  5988.         foreach ($consumptionTypeQry as $entry) {
  5989.             $p = array(
  5990.                 'name' => $entry->getName(),
  5991.                 'id' => $entry->getConsumptionTypeId(),
  5992.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5993.                 'cost_center_id' => $entry->getCostCenterId(),
  5994.             );
  5995.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5996.             $consumptionTypeListArray[] = $p;
  5997.         }
  5998.         //add bill list
  5999.         $service_purchase_bill_query $this->getDoctrine()
  6000.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  6001.             ->findBy(
  6002.                 array(
  6003.                     'typeHash' => 'SPB',
  6004.                     'approved' => GeneralConstant::APPROVED
  6005.                 )
  6006.             );
  6007.         $service_purchase_bill_list = [];
  6008.         $service_purchase_bill_list_array = [];
  6009.         $bill = array(
  6010.             'id' => 0,
  6011.             'type' => 'SPB',
  6012.             'name' => 'New Expense',
  6013.             'text' => 'New Expense',
  6014.             'amount' => 0,
  6015.         );
  6016.         $service_purchase_bill_list[0] = $bill;
  6017.         $service_purchase_bill_list_array[] = $bill;
  6018.         foreach ($service_purchase_bill_query as $d) {
  6019.             $bill = array(
  6020.                 'id' => $d->getPurchaseInvoiceId(),
  6021.                 'type' => 'SPB',
  6022.                 'name' => $d->getDocumentHash(),
  6023.                 'text' => $d->getDocumentHash(),
  6024.                 'amount' => $d->getInvoiceAmount(),
  6025.             );
  6026.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  6027.             $service_purchase_bill_list_array[] = $bill;
  6028.         }
  6029.         return $this->render('@Inventory/pages/input_forms/stock_consumption_note.html.twig',
  6030.             array(
  6031.                 'page_title' => 'Stock Consumption Note',
  6032.                 'warehouseList' => Inventory::WarehouseList($em),
  6033.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  6034.                 'consumptionTypeList' => $consumptionTypeList,
  6035.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  6036.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  6037.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6038.                 'warehouseActionList' => $warehouse_action_list,
  6039.                 'warehouseActionListArray' => $warehouse_action_list_array,
  6040.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6041.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6042.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6043.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6044.                 'product_list' => Inventory::ProductListDetailed($this->getDoctrine()->getManager()),
  6045.                 'prefix_list' => array(
  6046.                     [
  6047.                         'id' => 1,
  6048.                         'value' => 'GN',
  6049.                         'text' => 'GN'
  6050.                     ]
  6051.                 ),
  6052.                 'assoc_list' => array(
  6053.                     [
  6054.                         'id' => 1,
  6055.                         'value' => 1,
  6056.                         'text' => 'GN'
  6057.                     ]
  6058.                 ),
  6059.                 'INVLIST' => $INVLIST
  6060.             )
  6061.         );
  6062.     }
  6063.     public function StockConsumptionNoteListAction(Request $request)
  6064.     {
  6065.         $q $this->getDoctrine()
  6066.             ->getRepository('ApplicationBundle\\Entity\\StockConsumptionNote')
  6067.             ->findBy(
  6068.                 array(
  6069.                     'status' => GeneralConstant::ACTIVE,
  6070.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  6071. //                    'approved' =>  GeneralConstant::APPROVED,
  6072.                 )
  6073.             );
  6074.         $stage_list = array(
  6075.             => 'Pending',
  6076.             => 'Pending',
  6077.             => 'Complete',
  6078.             => 'Partial',
  6079.         );
  6080.         $data = [];
  6081.         foreach ($q as $entry) {
  6082.             $data[] = array(
  6083.                 'doc_date' => $entry->getStockConsumptionNoteDate(),
  6084.                 'id' => $entry->getStockConsumptionNoteId(),
  6085.                 'doc_hash' => $entry->getDocumentHash(),
  6086.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  6087.                 'stage' => $stage_list[$entry->getStage()]
  6088.             );
  6089.         }
  6090.         return $this->render('@Inventory/pages/views/stock_consumption_note_list.html.twig',
  6091.             array(
  6092.                 'page_title' => 'Stock Consumption Note List',
  6093.                 'data' => $data
  6094.             )
  6095.         );
  6096.     }
  6097.     public function ViewStockConsumptionNoteAction(Request $request$id)
  6098.     {
  6099.         $em $this->getDoctrine()->getManager();
  6100.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  6101.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  6102.             array(
  6103.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6104.             )
  6105.         );
  6106.         $consumptionTypeList = [];
  6107.         $consumptionTypeListArray = [];
  6108.         foreach ($consumptionTypeQry as $entry) {
  6109.             $p = array(
  6110.                 'name' => $entry->getName(),
  6111.                 'id' => $entry->getConsumptionTypeId(),
  6112.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  6113.                 'cost_center_id' => $entry->getCostCenterId(),
  6114.             );
  6115.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  6116.             $consumptionTypeListArray[] = $p;
  6117.         }
  6118.         //add bill list
  6119.         $service_purchase_bill_query $this->getDoctrine()
  6120.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  6121.             ->findBy(
  6122.                 array(
  6123.                     'typeHash' => 'SPB',
  6124.                     'approved' => GeneralConstant::APPROVED
  6125.                 )
  6126.             );
  6127.         $service_purchase_bill_list = [];
  6128.         $service_purchase_bill_list_array = [];
  6129.         $bill = array(
  6130.             'id' => 0,
  6131.             'type' => 'SPB',
  6132.             'name' => 'New Expense',
  6133.             'text' => 'New Expense',
  6134.             'amount' => 0,
  6135.         );
  6136.         $service_purchase_bill_list[0] = $bill;
  6137.         $service_purchase_bill_list_array[] = $bill;
  6138.         foreach ($service_purchase_bill_query as $d) {
  6139.             $bill = array(
  6140.                 'id' => $d->getPurchaseInvoiceId(),
  6141.                 'type' => 'SPB',
  6142.                 'name' => $d->getDocumentHash(),
  6143.                 'text' => $d->getDocumentHash(),
  6144.                 'amount' => $d->getInvoiceAmount(),
  6145.             );
  6146.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  6147.             $service_purchase_bill_list_array[] = $bill;
  6148.         }
  6149.         return $this->render(
  6150.             '@Inventory/pages/views/view_stock_consumption_note.html.twig',
  6151.             array(
  6152.                 'page_title' => 'Stock Transfer',
  6153.                 'data' => $dt,
  6154.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  6155.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6156.                 'consumptionTypeList' => $consumptionTypeList,
  6157.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  6158.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6159.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6160.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6161.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6162.                     $id,
  6163.                     $dt['created_by'],
  6164.                     $dt['edited_by'])
  6165.             )
  6166.         );
  6167.     }
  6168.     public function PrintStockConsumptionNoteAction(Request $request$id)
  6169.     {
  6170.         $em $this->getDoctrine()->getManager();
  6171.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  6172.         $company_data Company::getCompanyData($em1);
  6173.         $document_mark = array(
  6174.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6175.             'copy' => ''
  6176.         );
  6177.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  6178.             array(
  6179.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6180.             )
  6181.         );
  6182.         $consumptionTypeList = [];
  6183.         $consumptionTypeListArray = [];
  6184.         foreach ($consumptionTypeQry as $entry) {
  6185.             $p = array(
  6186.                 'name' => $entry->getName(),
  6187.                 'id' => $entry->getConsumptionTypeId(),
  6188.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  6189.                 'cost_center_id' => $entry->getCostCenterId(),
  6190.             );
  6191.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  6192.             $consumptionTypeListArray[] = $p;
  6193.         }
  6194.         //add bill list
  6195.         $service_purchase_bill_query $this->getDoctrine()
  6196.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  6197.             ->findBy(
  6198.                 array(
  6199.                     'typeHash' => 'SPB',
  6200.                     'approved' => GeneralConstant::APPROVED
  6201.                 )
  6202.             );
  6203.         $service_purchase_bill_list = [];
  6204.         $service_purchase_bill_list_array = [];
  6205.         $bill = array(
  6206.             'id' => 0,
  6207.             'type' => 'SPB',
  6208.             'name' => 'New Expense',
  6209.             'text' => 'New Expense',
  6210.             'amount' => 0,
  6211.         );
  6212.         $service_purchase_bill_list[0] = $bill;
  6213.         $service_purchase_bill_list_array[] = $bill;
  6214.         foreach ($service_purchase_bill_query as $d) {
  6215.             $bill = array(
  6216.                 'id' => $d->getPurchaseInvoiceId(),
  6217.                 'type' => 'SPB',
  6218.                 'name' => $d->getDocumentHash(),
  6219.                 'text' => $d->getDocumentHash(),
  6220.                 'amount' => $d->getInvoiceAmount(),
  6221.             );
  6222.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  6223.             $service_purchase_bill_list_array[] = $bill;
  6224.         }
  6225.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6226.             $html $this->renderView('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  6227.                 array(
  6228.                     //full array here
  6229.                     'pdf' => true,
  6230.                     'page_title' => 'Stock Consumption',
  6231.                     'export' => 'pdf,print',
  6232.                     'data' => $dt,
  6233.                     'service_purchase_bill_list' => $service_purchase_bill_list,
  6234.                     'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6235.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6236.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6237.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6238.                         array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6239.                         $id,
  6240.                         $dt['created_by'],
  6241.                         $dt['edited_by']),
  6242.                     'document_mark_image' => $document_mark['original'],
  6243.                     'consumptionTypeList' => $consumptionTypeList,
  6244.                     'consumptionTypeListArray' => $consumptionTypeListArray,
  6245.                     'company_name' => $company_data->getName(),
  6246.                     'company_data' => $company_data,
  6247.                     'company_address' => $company_data->getAddress(),
  6248.                     'company_image' => $company_data->getImage(),
  6249.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6250.                     'red' => 0
  6251.                 )
  6252.             );
  6253.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6254. //                'orientation' => 'landscape',
  6255. //                'enable-javascript' => true,
  6256. //                'javascript-delay' => 1000,
  6257.                 'no-stop-slow-scripts' => false,
  6258.                 'no-background' => false,
  6259.                 'lowquality' => false,
  6260.                 'encoding' => 'utf-8',
  6261. //            'images' => true,
  6262. //            'cookie' => array(),
  6263.                 'dpi' => 300,
  6264.                 'image-dpi' => 300,
  6265. //                'enable-external-links' => true,
  6266. //                'enable-internal-links' => true
  6267.             ));
  6268.             return new Response(
  6269.                 $pdf_response,
  6270.                 200,
  6271.                 array(
  6272.                     'Content-Type' => 'application/pdf',
  6273.                     'Content-Disposition' => 'attachment; filename="stock_consumption_note_' $id '.pdf"'
  6274.                 )
  6275.             );
  6276.         }
  6277.         return $this->render('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  6278.             array(
  6279.                 'page_title' => 'Stock Consumption',
  6280.                 'export' => 'pdf,print',
  6281.                 'data' => $dt,
  6282.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  6283.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6284.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6285.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6286.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6287.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6288.                     $id,
  6289.                     $dt['created_by'],
  6290.                     $dt['edited_by']),
  6291.                 'document_mark_image' => $document_mark['original'],
  6292.                 'consumptionTypeList' => $consumptionTypeList,
  6293.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  6294.                 'company_name' => $company_data->getName(),
  6295.                 'company_data' => $company_data,
  6296.                 'company_address' => $company_data->getAddress(),
  6297.                 'company_image' => $company_data->getImage(),
  6298.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6299.                 'red' => 0
  6300.             )
  6301.         );
  6302.     }
  6303.     public function CreateStockReceivedNoteAction(Request $request$id 0)
  6304.     {
  6305.         $em $this->getDoctrine()->getManager();
  6306.         $companyId $this->getLoggedUserCompanyId($request);
  6307.         $extDocData = [];
  6308.         $userId $request->getSession()->get(UserConstants::USER_ID);
  6309.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  6310.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  6311. //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  6312.         $userBranchIdList $request->getSession()->get('branchIdList');
  6313.         if ($userBranchIdList == null$userBranchIdList = [];
  6314.         $userBranchId $request->getSession()->get('branchId');
  6315.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  6316.             $em $this->getDoctrine()->getManager();
  6317.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //change
  6318.             $dochash $request->request->get('docHash'); //change
  6319.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6320.             $approveRole $request->request->get('approvalRole');
  6321.             $approveHash $request->request->get('approvalHash');
  6322.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6323.                 $loginId$approveRole$approveHash$id)
  6324.             ) {
  6325.                 if ($request->request->has('returnJson')) {
  6326.                     return new JsonResponse(array(
  6327.                         'success' => false,
  6328.                         'documentHash' => 0,
  6329.                         'documentId' => 0,
  6330.                         'billIds' => [],
  6331.                         'drIds' => [],
  6332.                         'pmntTransIds' => [],
  6333.                         'viewUrl' => '',
  6334.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  6335.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  6336.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  6337.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  6338.                     ));
  6339.                 } else
  6340.                     $this->addFlash(
  6341.                         'error',
  6342.                         'Sorry Could not insert Data.'
  6343.                     );
  6344.             } else {
  6345.                 if ($request->request->has('check_allowed'))
  6346.                     $check_allowed 1;
  6347.                 try {
  6348.                     $StID Inventory::CreateNewStockReceivedNote(
  6349.                         $this->getDoctrine()->getManager(),
  6350.                         $request->request,
  6351.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6352.                         $this->getLoggedUserCompanyId($request)
  6353.                     );
  6354.                 } catch (\InvalidArgumentException $e) {
  6355.                     if ($request->request->has('returnJson')) {
  6356.                         return new JsonResponse(array(
  6357.                             'success' => false,
  6358.                             'message' => $e->getMessage(),
  6359.                         ));
  6360.                     }
  6361.                     $this->addFlash('error'$e->getMessage());
  6362.                     return $this->redirect($request->getUri());
  6363.                 } catch (\Exception $e) {
  6364.                     if ($request->request->has('returnJson')) {
  6365.                         return new JsonResponse(array(
  6366.                             'success' => false,
  6367.                             'message' => 'Sorry Could not insert Data.',
  6368.                         ));
  6369.                     }
  6370.                     $this->addFlash('error''Sorry Could not insert Data.');
  6371.                     return $this->redirect($request->getUri());
  6372.                 }
  6373.                 //now add Approval info
  6374.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6375.                 $approveRole 1;  //created
  6376.                 $options = array(
  6377.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6378.                     'notification_server' => $this->container->getParameter('notification_server'),
  6379.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6380.                     'url' => $this->generateUrl(
  6381.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  6382.                         ['entity_view_route_path_name']
  6383.                     )
  6384.                 );
  6385.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6386.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6387.                     $StID,
  6388.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6389.                 );
  6390.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  6391.                     $loginId,
  6392.                     $approveRole,
  6393.                     $request->request->get('approvalHash'));
  6394.                 $url $this->generateUrl(
  6395.                     'view_srcv'
  6396.                 );
  6397.                 if ($request->request->has('returnJson')) {
  6398.                     return new JsonResponse(array(
  6399.                         'success' => true,
  6400.                         'documentHash' => $dochash,
  6401.                         'documentId' => $StID,
  6402.                         'viewUrl' => $url "/" $StID,
  6403.                     ));
  6404.                 } else {
  6405.                     $this->addFlash(
  6406.                         'success',
  6407.                         'Stock Received Note Added.'
  6408.                     );
  6409.                     return $this->redirect($url "/" $StID);
  6410.                 }
  6411.             }
  6412.         }
  6413.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  6414.             array(
  6415.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6416.             )
  6417.         );
  6418.         if ($id == 0) {
  6419.         } else {
  6420.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')->findOneBy(
  6421.                 array(
  6422.                     'salesOrderId' => $id///material
  6423.                 )
  6424.             );
  6425.             //now if its not editable, redirect to view
  6426.             if ($extDoc) {
  6427.                 if ($extDoc->getEditFlag() != 1) {
  6428.                     $url $this->generateUrl(
  6429.                         'view_srcv'
  6430.                     );
  6431.                     return $this->redirect($url "/" $id);
  6432.                 } else {
  6433.                     $extDocData $extDoc;
  6434.                     $extDocDataDetails $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findOneBy(
  6435.                         array(
  6436.                             'stockReceivedNoteId' => $id///material
  6437.                         )
  6438.                     );
  6439.                 }
  6440.             } else {
  6441.             }
  6442.         }
  6443.         $INVLIST = [];
  6444.         foreach ($slotList as $slot) {
  6445.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  6446.         }
  6447.         $dataArray = array(
  6448.             'page_title' => 'Stock Received Note',
  6449. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  6450.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  6451.             'users' => Users::getUserListById($em),
  6452.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  6453.             'warehouseList' => Inventory::WarehouseList($em),
  6454.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  6455.             'warehouseActionList' => $warehouse_action_list,
  6456.             'warehouseActionListArray' => $warehouse_action_list_array,
  6457.             'extDocData' => $extDocData,
  6458.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  6459.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6460.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6461.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6462. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6463. //            'product_list' => Inventory::ProductList($em, $companyId),
  6464.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  6465.             'prefix_list' => array(
  6466.                 [
  6467.                     'id' => 1,
  6468.                     'value' => 'GN',
  6469.                     'text' => 'GN'
  6470.                 ]
  6471.             ),
  6472.             'assoc_list' => array(
  6473.                 [
  6474.                     'id' => 1,
  6475.                     'value' => 1,
  6476.                     'text' => 'GN'
  6477.                 ]
  6478.             ),
  6479.             'INVLIST' => $INVLIST,
  6480.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  6481.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  6482.             'userBranchIdList' => $userBranchIdList,
  6483.             'userBranchId' => $userBranchId,
  6484. //            'headList' => Accounts::HeadList($em),
  6485.         );
  6486.         //json
  6487.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  6488.         {
  6489.             $dataArray['success'] = true;
  6490.             return new JsonResponse(
  6491.                 $dataArray
  6492.             );
  6493.         }
  6494.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  6495.             $dataArray
  6496.         );
  6497.     }
  6498.     public function GetItemListForStockReceivedAction(Request $request)
  6499.     {
  6500.         if ($request->isMethod('POST')) {
  6501.             $em $this->getDoctrine();
  6502.             $receiveType 1;//transfer
  6503.             if ($request->request->has('receiveType'))
  6504.                 $receiveType $request->request->get('receiveType');
  6505.             $QD = [];
  6506.             if ($receiveType == 1)
  6507.                 $QD $this->getDoctrine()
  6508.                     ->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  6509.                     ->findBy(
  6510.                         array(
  6511. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  6512.                             'stockTransferId' => $request->request->get('stId')
  6513.                         ),
  6514.                         array()
  6515.                     );
  6516.             if ($receiveType == 2)
  6517.                 $QD $this->getDoctrine()
  6518.                     ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  6519.                     ->findBy(
  6520.                         array(
  6521. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  6522.                             'salesOrderId' => $request->request->get('soId')
  6523.                         ),
  6524.                         array()
  6525.                     );
  6526. //            if($request->request->get('wareHouseId')!='')
  6527. //
  6528. //            $DO=$this->getDoctrine()
  6529. //                ->getRepository('ApplicationBundle\\Entity\\DeliveryOrder')
  6530. //                ->findOneBy(
  6531. //                    $find_array,
  6532. //                    array(
  6533. //
  6534. //                    )
  6535. //                );
  6536.             $sendData = array(
  6537. //                'salesType'=>$SO->getSalesType(),
  6538. //                'packageData'=>[],
  6539.                 'productList' => [],
  6540. //                'productListByPackage'=>[],
  6541.             );
  6542.             $productList Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request));
  6543.             $pckg_item_cross_match_data = [];
  6544.             foreach ($QD as $product) {
  6545. //                $b_code=json_decode($product->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  6546.                 $b_code = [];
  6547.                 $newProductId $product->getProductId();
  6548.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  6549.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6550.                     if ($to_analyze_codes_str != null)
  6551.                         $b_code json_decode($to_analyze_codes_strtrue512JSON_BIGINT_AS_STRING);
  6552.                     else
  6553.                         $b_code = [];
  6554.                 } else {
  6555.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6556.                     if ($to_analyze_codes_str != null) {
  6557.                         $max_int_length strlen((string)PHP_INT_MAX) - 1;
  6558.                         $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$to_analyze_codes_str);
  6559.                         $b_code json_decode($json_without_bigintstrue);
  6560.                     } else {
  6561.                         $b_code = [];
  6562.                     }
  6563.                 }
  6564.                 $b_code_data = [];
  6565.                 foreach ($b_code as $d) {
  6566.                     $b_code_data[] = array(
  6567.                         'id' => $d,
  6568.                         'name' => str_pad($d13'0'STR_PAD_LEFT),
  6569.                     );
  6570.                 }
  6571.                 $p_data = array(
  6572.                     'details_id' => $product->getId(),
  6573.                     'productId' => $product->getProductId(),
  6574.                     'product_name' => isset($productList[$product->getProductId()]) ? $productList[$product->getProductId()]['name'] : 'Unknown Product',
  6575.                     'product_barcodes' => $b_code_data,
  6576. //                    'available_inventory'=>$inventory_by_warehouse?$inventory_by_warehouse->getQty():0,
  6577. //                        'package_id'=>$product->getPackageId(),
  6578.                     'qty' => $receiveType == $product->getQty() : $product->getToBeReceived(),
  6579.                     'unit_price' => $receiveType == $product->getPrice() : $productList[$product->getProductId()]['purchase_price'],
  6580.                     'balance' => $receiveType == $product->getBalance() : ($product->getToBeReceived() - $product->getReceived()),
  6581. //                        'delivered'=>$product->getDelivered(),
  6582.                 );
  6583.                 $sendData['productList'][] = $p_data;
  6584.             }
  6585.             //now package data
  6586.             if ($sendData) {
  6587.                 return new JsonResponse(array("success" => true"content" => $sendData));
  6588.             }
  6589.             return new JsonResponse(array("success" => false));
  6590.         }
  6591.         return new JsonResponse(array("success" => false));
  6592.     }
  6593.     public function StockReceivedNoteListAction(Request $request)
  6594.     {
  6595.         $q $this->getDoctrine()
  6596.             ->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')
  6597.             ->findBy(
  6598.                 array(
  6599.                     'status' => GeneralConstant::ACTIVE,
  6600.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  6601. //                    'approved' =>  GeneralConstant::APPROVED,
  6602.                 )
  6603.             );
  6604.         $stage_list = array(
  6605.             => 'Pending',
  6606.             => 'Pending',
  6607.             => 'Complete',
  6608.             => 'Partial',
  6609.         );
  6610.         $data = [];
  6611.         foreach ($q as $entry) {
  6612.             $data[] = array(
  6613.                 'doc_date' => $entry->getStockReceivedNoteDate(),
  6614.                 'id' => $entry->getStockReceivedNoteId(),
  6615.                 'doc_hash' => $entry->getDocumentHash(),
  6616.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  6617.                 'stage' => $stage_list[$entry->getStage()]
  6618.             );
  6619.         }
  6620.         return $this->render('@Inventory/pages/views/stock_received_note_list.html.twig',
  6621.             array(
  6622.                 'page_title' => 'Stock Received List',
  6623.                 'data' => $data
  6624.             )
  6625.         );
  6626.     }
  6627.     public function ViewStockReceivedNoteAction(Request $request$id)
  6628.     {
  6629.         $em $this->getDoctrine()->getManager();
  6630.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6631.         return $this->render(
  6632.             '@Inventory/pages/views/view_stock_received_note.html.twig',
  6633.             array(
  6634.                 'page_title' => 'Stock Received Note',
  6635.                 'data' => $dt,
  6636.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  6637.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6638.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6639.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6640.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6641.                     $id,
  6642.                     $dt['created_by'],
  6643.                     $dt['edited_by'])
  6644.             )
  6645.         );
  6646.     }
  6647.     public function PrintStockReceivedNoteAction(Request $request$id)
  6648.     {
  6649.         $em $this->getDoctrine()->getManager();
  6650.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6651.         $company_data Company::getCompanyData($em1);
  6652.         $document_mark = array(
  6653.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6654.             'copy' => ''
  6655.         );
  6656.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6657.             $html $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
  6658.                 array(
  6659.                     //full array here
  6660.                     'pdf' => true,
  6661.                     'page_title' => 'Stock Received Note',
  6662.                     'export' => 'pdf,print',
  6663.                     'data' => $dt,
  6664.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6665.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6666.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6667.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6668.                         $id,
  6669.                         $dt['created_by'],
  6670.                         $dt['edited_by']),
  6671.                     'document_mark_image' => $document_mark['original'],
  6672.                     'company_name' => $company_data->getName(),
  6673.                     'company_data' => $company_data,
  6674.                     'company_address' => $company_data->getAddress(),
  6675.                     'company_image' => $company_data->getImage(),
  6676.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6677.                     'red' => 0
  6678.                 )
  6679.             );
  6680.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6681. //                'orientation' => 'landscape',
  6682. //                'enable-javascript' => true,
  6683. //                'javascript-delay' => 1000,
  6684.                 'no-stop-slow-scripts' => false,
  6685.                 'no-background' => false,
  6686.                 'lowquality' => false,
  6687.                 'encoding' => 'utf-8',
  6688. //            'images' => true,
  6689. //            'cookie' => array(),
  6690.                 'dpi' => 300,
  6691.                 'image-dpi' => 300,
  6692. //                'enable-external-links' => true,
  6693. //                'enable-internal-links' => true
  6694.             ));
  6695.             return new Response(
  6696.                 $pdf_response,
  6697.                 200,
  6698.                 array(
  6699.                     'Content-Type' => 'application/pdf',
  6700.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  6701.                 )
  6702.             );
  6703.         }
  6704.         return $this->render('@Inventory/pages/print/print_stock_received_note.html.twig',
  6705.             array(
  6706.                 'page_title' => 'Stock Received Note',
  6707.                 'export' => 'pdf,print',
  6708.                 'data' => $dt,
  6709.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6710.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6711.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6712.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6713.                     $id,
  6714.                     $dt['created_by'],
  6715.                     $dt['edited_by']),
  6716.                 'document_mark_image' => $document_mark['original'],
  6717.                 'company_name' => $company_data->getName(),
  6718.                 'company_data' => $company_data,
  6719.                 'company_address' => $company_data->getAddress(),
  6720.                 'company_image' => $company_data->getImage(),
  6721.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6722.                 'red' => 0
  6723.             )
  6724.         );
  6725.     }
  6726.     public function CreateStoreRequisitionSlipAction(Request $request$id 0)
  6727.     {
  6728.         $em $this->getDoctrine()->getManager();
  6729. //        $id;
  6730.         if ($request->isMethod('POST')) {
  6731.             $em $this->getDoctrine()->getManager();
  6732.             $entity_id array_flip(GeneralConstant::$Entity_list)['StoreRequisition']; //change
  6733.             $dochash $request->request->get('voucherNumber'); //change
  6734.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6735.             $approveRole $request->request->get('approvalRole');
  6736.             $approveHash $request->request->get('approvalHash');
  6737.             $validation Inventory::ValidateStoreRequisitionSlip($request->request);
  6738.             if (!$validation['success']) {
  6739.                 $this->addFlash(
  6740.                     'error',
  6741.                     $validation['error']
  6742.                 );
  6743.             } else if (!DocValidation::isInsertable($em$entity_id$dochash,
  6744.                 $loginId$approveRole$approveHash$id)
  6745.             ) {
  6746.                 $this->addFlash(
  6747.                     'error',
  6748.                     'Sorry, could not insert Data.'
  6749.                 );
  6750.             } else {
  6751.                 if ($request->request->has('check_allowed'))
  6752.                     $check_allowed 1;
  6753.                 $IrID Inventory::CreateNewStoreRequisition($id,
  6754.                     $this->getDoctrine()->getManager(),
  6755.                     $request->request,
  6756.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6757.                     $this->getLoggedUserCompanyId($request)
  6758.                 );
  6759.                 //now add Approval info
  6760.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6761.                 $approveRole $request->request->get('approvalRole');
  6762.                 $options = array(
  6763.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6764.                     'notification_server' => $this->container->getParameter('notification_server'),
  6765.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6766.                     'url' => $this->generateUrl(
  6767.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StoreRequisition']]
  6768.                         ['entity_view_route_path_name']
  6769.                     )
  6770.                 );
  6771.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6772.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  6773.                     $IrID,
  6774.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6775.                 );
  6776.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StoreRequisition'], $IrID,
  6777.                     $loginId,
  6778.                     $approveRole,
  6779.                     $request->request->get('approvalHash'));
  6780.                 $this->addFlash(
  6781.                     'success',
  6782.                     'New Indent Added.'
  6783.                 );
  6784.                 $url $this->generateUrl(
  6785.                     'view_ir'
  6786.                 );
  6787.                 return $this->redirect($url "/" $IrID);
  6788.             }
  6789.         }
  6790.         $extDocData = [];
  6791.         $extDocDetailsData = [];
  6792.         if ($id == 0) {
  6793.         } else {
  6794.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StoreRequisition')->findOneBy(
  6795.                 array(
  6796.                     'storeRequisitionId' => $id///material
  6797.                 )
  6798.             );
  6799.             //now if its not editable, redirect to view
  6800.             if ($extDoc) {
  6801.                 if ($extDoc->getEditFlag() != 1) {
  6802.                     $url $this->generateUrl(
  6803.                         'view_ir'
  6804.                     );
  6805.                     return $this->redirect($url "/" $id);
  6806.                 } else {
  6807.                     $extDocData $extDoc;
  6808.                     $extDocDetailsData $em->getRepository('ApplicationBundle\\Entity\\StoreRequisitionItem')->findBy(
  6809.                         array(
  6810.                             'storeRequisitionId' => $id///material
  6811.                         )
  6812.                     );;
  6813.                 }
  6814.             } else {
  6815.             }
  6816.         }
  6817.         $companyId $this->getLoggedUserCompanyId($request);
  6818.         $productListArray = [];
  6819.         $subCategoryListArray = [];
  6820.         $categoryListArray = [];
  6821.         $igListArray = [];
  6822.         $unitListArray = [];
  6823.         $brandListArray = [];
  6824.         $productList Inventory::ProductList($em$companyId);
  6825.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6826.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6827.         $igList Inventory::ItemGroupList($em$companyId);
  6828.         $unitList Inventory::UnitTypeList($em);
  6829.         $brandList Inventory::GetBrandList($em$companyId);
  6830.         foreach ($productList as $product$productListArray[] = $product;
  6831.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6832.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6833.         foreach ($igList as $product$igListArray[] = $product;
  6834.         foreach ($unitList as $product$unitListArray[] = $product;
  6835.         foreach ($brandList as $product$brandListArray[] = $product;
  6836.         $sr_list = [];
  6837.         $QD $this->getDoctrine()
  6838.             ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  6839.             ->findBy(
  6840.                 array(
  6841.                     'indentTagged' => 0,
  6842.                     'approved' => 1
  6843.                 )
  6844.             );
  6845.         foreach ($QD as $dt) {
  6846.             $sr_list[$dt->getStockRequisitionId()] = array(
  6847.                 'id' => $dt->getStockRequisitionId(),
  6848.                 'name' => $dt->getDocumentHash(),
  6849.                 'text' => $dt->getDocumentHash(),
  6850.             );
  6851.         }
  6852.         return $this->render('@Inventory/pages/input_forms/store_requisition.html.twig',
  6853.             array(
  6854.                 'page_title' => 'Indent Requisition Slip',
  6855.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6856.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6857.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6858.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6859.                 'sr_list' => $sr_list,
  6860.                 'productList' => $productList,
  6861.                 'subCategoryList' => $subCategoryList,
  6862.                 'categoryList' => $categoryList,
  6863.                 'igList' => $igList,
  6864.                 'extId' => $id,
  6865.                 'extDocDetailsData' => $extDocDetailsData,
  6866.                 'extDocData' => $extDocData,
  6867.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6868.                 'unitList' => $unitList,
  6869.                 'brandList' => $brandList,
  6870.                 'brandListArray' => $brandListArray,
  6871.                 'productListArray' => $productListArray,
  6872.                 'subCategoryListArray' => $subCategoryListArray,
  6873.                 'categoryListArray' => $categoryListArray,
  6874.                 'igListArray' => $igListArray,
  6875.                 'unitListArray' => $unitListArray,
  6876.                 'prefix_list' => array(
  6877.                     [
  6878.                         'id' => 1,
  6879.                         'value' => 'GN',
  6880.                         'text' => 'General'
  6881.                     ],
  6882.                     [
  6883.                         'id' => 1,
  6884.                         'value' => 'SD',
  6885.                         'text' => 'For Sales Demand'
  6886.                     ]
  6887.                 ),
  6888.                 'assoc_list' => array(
  6889.                     [
  6890.                         'id' => 1,
  6891.                         'value' => 1,
  6892.                         'text' => 'GN'
  6893.                     ]
  6894.                 )
  6895.             )
  6896.         );
  6897.     }
  6898.     public function CreateStockRequisitionSlipAction(Request $request$id 0)
  6899.     {
  6900.         $em $this->getDoctrine()->getManager();
  6901.         if ($request->isMethod('POST')) {
  6902.             $em $this->getDoctrine()->getManager();
  6903.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockRequisition']; //change
  6904.             $dochash $request->request->get('voucherNumber'); //change
  6905.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6906.             $approveRole $request->request->get('approvalRole');
  6907.             $approveHash $request->request->get('approvalHash');
  6908.             $validation Inventory::ValidateStockRequisitionSlip($request->request);
  6909.             if (!$validation['success']) {
  6910.                 $this->addFlash(
  6911.                     'error',
  6912.                     $validation['error']
  6913.                 );
  6914.             } else if (!DocValidation::isInsertable($em$entity_id$dochash,
  6915.                 $loginId$approveRole$approveHash$id)
  6916.             ) {
  6917.                 $this->addFlash(
  6918.                     'error',
  6919.                     'Sorry, could not insert Data.'
  6920.                 );
  6921.             } else {
  6922.                 if ($request->request->has('check_allowed'))
  6923.                     $check_allowed 1;
  6924.                 $SrID Inventory::CreateNewStockRequisition($id,
  6925.                     $this->getDoctrine()->getManager(),
  6926.                     $request->request,
  6927.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6928.                     $this->getLoggedUserCompanyId($request)
  6929.                 );
  6930.                 //now add Approval info
  6931.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6932.                 $approveRole $request->request->get('approvalRole');
  6933.                 $options = array(
  6934.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6935.                     'notification_server' => $this->container->getParameter('notification_server'),
  6936.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6937.                     'url' => $this->generateUrl(
  6938.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockRequisition']]
  6939.                         ['entity_view_route_path_name']
  6940.                     )
  6941.                 );
  6942.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6943.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  6944.                     $SrID,
  6945.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6946.                 );
  6947.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockRequisition'], $SrID,
  6948.                     $loginId,
  6949.                     $approveRole,
  6950.                     $request->request->get('approvalHash'));
  6951.                 $this->addFlash(
  6952.                     'success',
  6953.                     'New Requisition Added.'
  6954.                 );
  6955.                 $url $this->generateUrl(
  6956.                     'view_sr'
  6957.                 );
  6958. //                return $this->redirect($url . "/" . $SrID);
  6959.             }
  6960.         }
  6961.         $extDocData = [];
  6962.         $extDocDetailsData = [];
  6963.         if ($id == 0) {
  6964.         } else {
  6965.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StockRequisition')->findOneBy(
  6966.                 array(
  6967.                     'stockRequisitionId' => $id///material
  6968.                 )
  6969.             );
  6970.             //now if its not editable, redirect to view
  6971.             if ($extDoc) {
  6972.                 if ($extDoc->getEditFlag() != 1) {
  6973.                     $url $this->generateUrl(
  6974.                         'view_sr'
  6975.                     );
  6976.                     return $this->redirect($url "/" $id);
  6977.                 } else {
  6978.                     $extDocData $extDoc;
  6979.                     $extDocDetailsData $em->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')->findBy(
  6980.                         array(
  6981.                             'stockRequisitionId' => $id///material
  6982.                         )
  6983.                     );;
  6984.                 }
  6985.             } else {
  6986.             }
  6987.         }
  6988.         $companyId $this->getLoggedUserCompanyId($request);
  6989.         $productListArray = [];
  6990.         $subCategoryListArray = [];
  6991.         $categoryListArray = [];
  6992.         $igListArray = [];
  6993.         $unitListArray = [];
  6994.         $brandListArray = [];
  6995.         $productList Inventory::ProductList($em$companyId);
  6996.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6997.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6998.         $igList Inventory::ItemGroupList($em$companyId);
  6999.         $unitList Inventory::UnitTypeList($em);
  7000.         $brandList Inventory::GetBrandList($em$companyId);
  7001.         foreach ($productList as $product$productListArray[] = $product;
  7002.         foreach ($categoryList as $product$categoryListArray[] = $product;
  7003.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  7004.         foreach ($igList as $product$igListArray[] = $product;
  7005.         foreach ($unitList as $product$unitListArray[] = $product;
  7006.         foreach ($brandList as $product$brandListArray[] = $product;
  7007.         return $this->render('@Inventory/pages/input_forms/stock_requisition_slip.html.twig',
  7008.             array(
  7009.                 'page_title' => 'Stock Requisition Slip',
  7010.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7011.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  7012.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  7013.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  7014.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  7015.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  7016.                 'productList' => $productList,
  7017.                 'extId' => $id,
  7018.                 'extDocDetailsData' => $extDocDetailsData,
  7019.                 'extDocData' => $extDocData,
  7020.                 'subCategoryList' => $subCategoryList,
  7021.                 'categoryList' => $categoryList,
  7022.                 'igList' => $igList,
  7023.                 'unitList' => $unitList,
  7024.                 'brandList' => $brandList,
  7025.                 'brandListArray' => $brandListArray,
  7026.                 'productListArray' => $productListArray,
  7027.                 'subCategoryListArray' => $subCategoryListArray,
  7028.                 'categoryListArray' => $categoryListArray,
  7029.                 'igListArray' => $igListArray,
  7030.                 'unitListArray' => $unitListArray,
  7031.                 'productionBomList' => ProductionM::ProductionBomList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  7032.                 'productionScheduleList' => ProductionM::ProductionScheduleList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  7033.                 'prefix_list' => array(
  7034.                     [
  7035.                         'id' => 1,
  7036.                         'value' => 'GN',
  7037.                         'text' => 'General'
  7038.                     ],
  7039.                     [
  7040.                         'id' => 1,
  7041.                         'value' => 'SD',
  7042.                         'text' => 'For Sales Demand'
  7043.                     ]
  7044.                 ),
  7045.                 'projectList' => $em->getRepository('ApplicationBundle\\Entity\\Project')->findBy(
  7046.                     array(
  7047.                         'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  7048.                     ), array('projectDate' => 'desc')
  7049.                 ),
  7050.                 'salesOrderList' => SalesOrderM::SalesOrderListPendingDelivery($em),
  7051.                 'assoc_list' => array(
  7052.                     [
  7053.                         'id' => 1,
  7054.                         'value' => 'GN',
  7055.                         'text' => 'General'
  7056.                     ]
  7057.                 )
  7058.             )
  7059.         );
  7060.     }
  7061.     public function CreateStockReturnAction(Request $request)
  7062.     {
  7063.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  7064.             array(
  7065.                 'page_title' => 'Stock Return',
  7066. //                'dataList'=>$dta_list
  7067.             )
  7068.         );
  7069.     }
  7070.     public function MaterialInwardAction(Request $request)
  7071.     {
  7072.         $data = [];
  7073.         if ($request->isMethod('POST')) {
  7074.             $errors = [];
  7075.             $poId = (int)$request->request->get('poId');
  7076.             $warehouseId = (int)$request->request->get('warehouseId');
  7077.             $docHash trim((string)$request->request->get('docHash'));
  7078.             $products $request->request->get('products', []);
  7079.             $receivedQty $request->request->get('receivedQty', []);
  7080.             $purchaseOrderItemId $request->request->get('purchaseOrderItemId', []);
  7081.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  7082.             if ($poId <= 0) {
  7083.                 $errors[] = 'Please select a purchase order.';
  7084.             } elseif (!isset($poList[$poId])) {
  7085.                 $errors[] = 'Please select a valid purchase order.';
  7086.             }
  7087.             if ($warehouseId <= 0) {
  7088.                 $errors[] = 'Please select a warehouse.';
  7089.             }
  7090.             if (empty($products) || !is_array($products)) {
  7091.                 $errors[] = 'Please add at least one item.';
  7092.             }
  7093.             $hasPositiveQty false;
  7094.             foreach ((array)$receivedQty as $qty) {
  7095.                 if ($qty === '' || !is_numeric($qty)) {
  7096.                     $errors[] = 'Please enter a valid received quantity.';
  7097.                     break;
  7098.                 }
  7099.                 if ((float)$qty 0) {
  7100.                     $errors[] = 'Received quantity cannot be negative.';
  7101.                     break;
  7102.                 }
  7103.                 if ((float)$qty 0) {
  7104.                     $hasPositiveQty true;
  7105.                 }
  7106.             }
  7107.             if (!$hasPositiveQty) {
  7108.                 $errors[] = 'Please enter received quantity greater than zero for at least one item.';
  7109.             }
  7110.             if ($docHash === '' || stripos($docHash'undefined') !== false || stripos($docHash'document') !== false) {
  7111.                 $errors[] = 'Please generate a valid document number.';
  7112.             }
  7113.             if (empty($errors)) {
  7114.                 //first of all resolve the transport costs
  7115.                 $total_price_value 0;
  7116.                 $data_list $this->getDoctrine()
  7117.                     ->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')
  7118.                     ->findBy(
  7119.                         array(
  7120.                             'purchaseOrderId' => $poId,
  7121.                             'productId' => $products
  7122.                         )
  7123.                     );
  7124.                 $purchase_items = [];
  7125.                 foreach ($data_list as $key => $value) {
  7126.                     $purchase_items[$value->getProductId()] = $value;
  7127.                 }
  7128.                 foreach ($products as $key => $entry) {
  7129.                     if (!isset($purchase_items[$entry])) {
  7130.                         $errors[] = 'Selected product list does not match the chosen purchase order.';
  7131.                         break;
  7132.                     }
  7133.                     $total_price_value $total_price_value + ($receivedQty[$key]) * ($purchase_items[$entry]->getPrice());
  7134.                 }
  7135.                 if (empty($errors)) {
  7136.                     $po_data $poList[$poId];
  7137.                     $supplier_id $po_data['supplier_id'];
  7138.                     $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  7139.                     foreach ($products as $key => $entry) {
  7140.                         if ((float)$receivedQty[$key] > 0) {
  7141.                             Inventory::NewMaterialInward($this->getDoctrine()->getManager(),
  7142.                                 $request->request,
  7143.                                 $key,
  7144.                                 $poId,
  7145.                                 $purchaseOrderItemId,
  7146.                                 $supplier_id,
  7147.                                 $warehouseId,
  7148.                                 $request->request->get('lotNumber'),
  7149.                                 $request->request->get('type_hash'),
  7150.                                 $request->request->get('prefix_hash'),
  7151.                                 $request->request->get('assoc_hash'),
  7152.                                 $request->request->get('number_hash'),
  7153.                                 $docHash,
  7154.                                 $request->request->get('docDate'),
  7155.                                 $purchase_items[$entry],
  7156.                                 $total_price_value,
  7157.                                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7158.                         }
  7159.                     }
  7160.                     $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$warehouseId]['name'];
  7161. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  7162.                     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),
  7163.                         "A stack of material Has Arrived at The " $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  7164.                         'all',
  7165.                         "",
  7166.                         'information',
  7167.                         "",
  7168.                         "Inbound Material"
  7169.                     );
  7170.                 }
  7171.             }
  7172.             foreach ($errors as $error) {
  7173.                 $this->addFlash('error'$error);
  7174.             }
  7175. //                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);
  7176.         }
  7177.         return $this->render('@Inventory/pages/input_forms/material_inward.html.twig',
  7178.             array(
  7179.                 'page_title' => 'Material Inward',
  7180.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  7181.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  7182.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  7183.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  7184.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  7185.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  7186.                 "unitList" => Inventory::UnitTypeList($this->getDoctrine()->getManager())
  7187. //                'po'=>Inventory::getPurchaseOrderList
  7188.             )
  7189.         );
  7190.     }
  7191.     public function QualityControlAction(Request $request)
  7192.     {
  7193.         $checked_qc_list_flag 0;
  7194.         if ($request->query->has('checked_qc_list_flag'))
  7195.             $checked_qc_list_flag $request->query->has('checked_qc_list_flag');
  7196.         if ($request->isMethod('POST')) {
  7197.             $errors = [];
  7198.             $checkedRows $request->request->get('qc_checked', []);
  7199.             $approvedQty $request->request->get('approvedQty', []);
  7200.             if (empty($checkedRows)) {
  7201.                 $errors[] = 'Please select at least one QC item.';
  7202.             }
  7203.             $positiveQtyFound false;
  7204.             foreach ($approvedQty as $qcId => $qty) {
  7205.                 $qtyValue trim((string)$qty);
  7206.                 if ($qtyValue === '' || !is_numeric($qtyValue)) {
  7207.                     $errors[] = 'Approved quantity must be numeric.';
  7208.                     break;
  7209.                 }
  7210.                 if ((float)$qtyValue 0) {
  7211.                     $errors[] = 'Approved quantity cannot be negative.';
  7212.                     break;
  7213.                 }
  7214.                 if ((float)$qtyValue 0) {
  7215.                     $positiveQtyFound true;
  7216.                     if (!in_array($qcId$checkedRows)) {
  7217.                         $errors[] = 'Please check QC before submitting approved rows.';
  7218.                         break;
  7219.                     }
  7220.                 }
  7221.             }
  7222.             if (empty($errors) && !$positiveQtyFound) {
  7223.                 $errors[] = 'Please enter approved quantity greater than zero for at least one QC item.';
  7224.             }
  7225.             if (empty($errors)) {
  7226.                 foreach ($checkedRows as $key => $entry) {
  7227.                     $em $this->getDoctrine()->getManager();
  7228.                     $data $this->getDoctrine()
  7229.                         ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  7230.                         ->findOneBy(
  7231.                             array(
  7232.                                 'qcId' => $entry
  7233.                             )
  7234.                         );
  7235.                     if (!$data) {
  7236.                         $errors[] = 'Invalid QC row selected.';
  7237.                         break;
  7238.                     }
  7239.                     $data->setApprovedQty($approvedQty[$entry]);
  7240.                     $data->setRejectedQty($data->getInwardQty() - $approvedQty[$entry]);
  7241.                     $data->setQcDate(new \DateTime($request->request->get('qcDate')));
  7242.                     $data->setStage(GeneralConstant::STAGE_PENDING_TAG);
  7243.                     $em->flush();
  7244.                     //notification
  7245.                     $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$data->getPurchaseOrderId()];
  7246.                     $supplier_id $po_data['supplier_id'];
  7247.                     $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  7248.                     $product_name Inventory::ProductList($this->getDoctrine()->getManager())[$data->getProductId()]['name'];
  7249.                     $qty $approvedQty[$entry];
  7250.                     $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$data->getWarehouseId()]['name'];
  7251. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  7252.                     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),
  7253.                         $qty " among " $data->getInwardQty() . " units of " $product_name " has passed the Quality Control in " .
  7254.                         $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  7255.                         'all',
  7256.                         "",
  7257.                         'success',
  7258.                         "",
  7259.                         "Quality Control"
  7260.                     );
  7261.                 }
  7262.             }
  7263.             foreach ($errors as $error) {
  7264.                 $this->addFlash('error'$error);
  7265.             }
  7266.         }
  7267.         return $this->render('@Inventory/pages/input_forms/qc.html.twig',
  7268.             array(
  7269.                 'page_title' => 'Quality Control',
  7270.                 'checked_qc_list_flag' => $checked_qc_list_flag,
  7271.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  7272.                 'warehouse_indexed' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7273.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  7274.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  7275.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  7276.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  7277.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7278.                 'material_inward' => $this->getDoctrine()
  7279.                     ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  7280.                     ->findBy(
  7281.                         array(
  7282.                             'stage' => $checked_qc_list_flag == GeneralConstant::STAGE_PENDING GeneralConstant::STAGE_PENDING_TAG
  7283.                         )
  7284.                     )
  7285. //                'po'=>Inventory::getPurchaseOrderList
  7286.             )
  7287.         );
  7288.     }
  7289.     public function InventoryTransactionViewAction(Request $request)
  7290.     {
  7291.         $em $this->getDoctrine()->getManager();
  7292.         $qry_data = array(
  7293.             'warehouseId' => [0],
  7294.             'igId' => [0],
  7295.             'brandId' => [0],
  7296.             'categoryId' => [0],
  7297.             'actionTagId' => [0],
  7298.         );
  7299.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  7300.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  7301.         $data_searched = [];
  7302.         $em $this->getDoctrine()->getManager();
  7303.         $companyId $this->getLoggedUserCompanyId($request);
  7304.         $company_data Company::getCompanyData($em$companyId);
  7305.         $data = [];
  7306.         $print_title "Inventory Report";
  7307.         $document_mark = array(
  7308.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  7309.             'copy' => ''
  7310.         );
  7311.         if ($request->isMethod('POST'))
  7312.             $method 'POST';
  7313.         else
  7314.             $method 'GET';
  7315.         {
  7316.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  7317.                 $request->request$method,
  7318.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7319.                 $companyId);
  7320.             if ($request->query->has('returnJson') || $request->request->has('returnJson')) {
  7321.                 return new JsonResponse(
  7322.                     array(
  7323.                         'success' => true,
  7324. //                    'page_title' => 'Product Details',
  7325. //                    'company_data' => $company_data,
  7326.                         'page_title' => 'Inventory Transactions',
  7327.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7328.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7329.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7330.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7331.                         'data_products' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7332.                         'action_tag' => $warehouse_action_list,
  7333.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7334.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7335.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7336.                         'data_searched' => $data_searched
  7337.                     )
  7338.                 );
  7339.             } else if ($request->request->get('print_data_enabled') == 1) {
  7340.                 $print_sub_title "";
  7341.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  7342.                     array(
  7343.                         'page_title' => 'Inventory Report',
  7344.                         'page_header' => 'Report',
  7345.                         'print_title' => $print_title,
  7346.                         'document_type' => 'Journal voucher',
  7347.                         'document_mark_image' => $document_mark['original'],
  7348.                         'page_header_sub' => 'Add',
  7349.                         'item_data' => [],
  7350.                         'received' => 2,
  7351.                         'return' => 1,
  7352.                         'total_w_vat' => 1,
  7353.                         'total_vat' => 1,
  7354.                         'total_wo_vat' => 1,
  7355.                         'invoice_id' => 'abcd1234',
  7356.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  7357.                         'created_by' => 'created by',
  7358.                         'created_at' => '',
  7359.                         'red' => 0,
  7360.                         'company_name' => $company_data->getName(),
  7361.                         'company_data' => $company_data,
  7362.                         'company_address' => $company_data->getAddress(),
  7363.                         'company_image' => $company_data->getImage(),
  7364.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7365.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7366.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7367.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7368.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7369.                         'action_tag' => $warehouse_action_list,
  7370.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7371.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7372.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7373.                         'data_searched' => $data_searched
  7374.                     )
  7375.                 );
  7376.             }
  7377.         }
  7378.         return $this->render('@Inventory/pages/report/inventory_transaction_view.html.twig',
  7379.             array(
  7380.                 'page_title' => 'Inventory Transactions',
  7381.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7382.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7383.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7384.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7385.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7386.                 'action_tag' => $warehouse_action_list,
  7387.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7388.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7389.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7390.                 'data_searched' => $data_searched
  7391.             )
  7392.         );
  7393.     }
  7394.     public function StockConsumptionViewAction(Request $request)
  7395.     {
  7396.         $em $this->getDoctrine()->getManager();
  7397.         $start_date $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
  7398.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : new \DateTime();
  7399.         $qry_data = array(
  7400.             'warehouseId' => [0],
  7401.             'igId' => [0],
  7402.             'brandId' => [0],
  7403.             'categoryId' => [0],
  7404.             'actionTagId' => [0],
  7405.         );
  7406.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  7407.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  7408.         $data_searched = [];
  7409.         $em $this->getDoctrine()->getManager();
  7410.         $company_data Company::getCompanyData($em1);
  7411.         $data = [];
  7412.         $print_title "Inventory Report";
  7413.         $document_mark = array(
  7414.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  7415.             'copy' => ''
  7416.         );
  7417.         if ($request->isMethod('POST'))
  7418.             $method 'POST';
  7419.         else
  7420.             $method 'GET';
  7421.         $post_data $method == 'POST' $request->request $request->query;
  7422.         $data_searched Inventory::GetStockConsumptionData($this->getDoctrine()->getManager(),
  7423.             $post_data,
  7424.             $method,
  7425.             $start_date,
  7426.             $end_date,
  7427.             $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7428.         if ($post_data->get('print_data_enabled') == 1) {
  7429.             $print_sub_title "";
  7430.             if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  7431.                 $html $this->renderView('@Inventory/pages/print/print_stock_consumption.html.twig',
  7432.                     array(
  7433.                         'pdf' => 'true',
  7434.                         'page_title' => 'Inventory Report',
  7435.                         'page_header' => 'Report',
  7436.                         'print_title' => $print_title,
  7437.                         'document_type' => 'Journal voucher',
  7438.                         'document_mark_image' => $document_mark['original'],
  7439.                         'page_header_sub' => 'Add',
  7440.                         'item_data' => [],
  7441.                         'received' => 2,
  7442.                         'return' => 1,
  7443.                         'total_w_vat' => 1,
  7444.                         'total_vat' => 1,
  7445.                         'total_wo_vat' => 1,
  7446.                         'invoice_id' => 'abcd1234',
  7447.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  7448.                         'created_by' => 'created by',
  7449.                         'created_at' => '',
  7450.                         'red' => 0,
  7451.                         'start_date' => $start_date,
  7452.                         'end_date' => $end_date,
  7453.                         'openFilter' => empty($post_data->keys()) ? 0,
  7454.                         'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  7455.                         'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  7456.                         'company_name' => $company_data->getName(),
  7457.                         'company_data' => $company_data,
  7458.                         'company_address' => $company_data->getAddress(),
  7459.                         'company_image' => $company_data->getImage(),
  7460.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7461.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7462.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7463.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7464.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7465.                         'action_tag' => $warehouse_action_list,
  7466.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7467.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7468.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7469.                         'data_searched' => $data_searched,
  7470.                         'export' => 'all'
  7471.                     )
  7472.                 );
  7473.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  7474.                     'orientation' => count($data_searched['query_columns_filter']) > 'landscape' 'portrait',
  7475.                     'no-stop-slow-scripts' => true,
  7476.                     'no-background' => false,
  7477.                     'lowquality' => false,
  7478.                     'encoding' => 'utf-8',
  7479.                     'dpi' => 300,
  7480.                     'image-dpi' => 300,
  7481.                 ));
  7482.                 return new Response(
  7483.                     $pdf_response,
  7484.                     200,
  7485.                     array(
  7486.                         'Content-Type' => 'application/pdf',
  7487.                         'Content-Disposition' => 'attachment; filename="Stock_Consumption.pdf"'
  7488.                     )
  7489.                 );
  7490.             }
  7491.             return $this->render('@Inventory/pages/print/print_stock_consumption.html.twig',
  7492.                 array(
  7493.                     'page_title' => 'Inventory Report',
  7494.                     'page_header' => 'Report',
  7495.                     'print_title' => $print_title,
  7496.                     'document_type' => 'Journal voucher',
  7497.                     'document_mark_image' => $document_mark['original'],
  7498.                     'page_header_sub' => 'Add',
  7499.                     'item_data' => [],
  7500.                     'received' => 2,
  7501.                     'return' => 1,
  7502.                     'total_w_vat' => 1,
  7503.                     'total_vat' => 1,
  7504.                     'total_wo_vat' => 1,
  7505.                     'invoice_id' => 'abcd1234',
  7506.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  7507.                     'created_by' => 'created by',
  7508.                     'created_at' => '',
  7509.                     'red' => 0,
  7510.                     'start_date' => $start_date,
  7511.                     'end_date' => $end_date,
  7512.                     'openFilter' => empty($post_data->keys()) ? 0,
  7513.                     'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  7514.                     'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  7515.                     'company_name' => $company_data->getName(),
  7516.                     'company_data' => $company_data,
  7517.                     'company_address' => $company_data->getAddress(),
  7518.                     'company_image' => $company_data->getImage(),
  7519.                     'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7520.                     'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7521.                     'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7522.                     'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7523.                     'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7524.                     'action_tag' => $warehouse_action_list,
  7525.                     'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7526.                     'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7527.                     'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7528.                     'data_searched' => $data_searched,
  7529.                     'export' => 'all'
  7530.                 )
  7531.             );
  7532.         }
  7533. //        return new JsonResponse(Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()));
  7534.         return $this->render('@Inventory/pages/report/stock_consumption.html.twig',
  7535.             array(
  7536.                 'page_title' => 'Stock Consumption',
  7537.                 'start_date' => $start_date,
  7538.                 'end_date' => $end_date,
  7539.                 'openFilter' => empty($post_data->keys()) ? 0,
  7540.                 'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  7541.                 'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  7542.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7543.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7544.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7545.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7546.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7547.                 'action_tag' => $warehouse_action_list,
  7548.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7549.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7550.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7551.                 'data_searched' => $data_searched
  7552.             )
  7553.         );
  7554.     }
  7555.     public function ItemViewAction(Request $request)
  7556.     {
  7557.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  7558.             array(
  7559.                 'page_title' => 'Stock Return'
  7560.             )
  7561.         );
  7562.     }
  7563.     public function ProductViewAction(Request $request$id 0)
  7564.     {
  7565.         $em $this->getDoctrine()->getManager();
  7566.         $companyId $this->getLoggedUserCompanyId($request);
  7567.         $company_data Company::getCompanyData($em$companyId);
  7568.         $data = [];
  7569.         $specData = [];
  7570.         $specIds = [];
  7571.         $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  7572.             ->findOneBy(
  7573.                 array(
  7574.                     'id' => $id
  7575.                 )
  7576.             );
  7577.         if ($productData) {
  7578.             $tempSpecData json_decode($productData->getSpecData(), true);
  7579.             if ($tempSpecData == null) {
  7580.                 $tempSpecData = [];
  7581.             }
  7582.             foreach ($tempSpecData as $indSpecData) {
  7583. //                $specId = $indSpecData['id'];
  7584.                 $specData[] = [
  7585.                     'id' => $indSpecData['id'],
  7586.                     'value' => $indSpecData['value']
  7587.                 ];
  7588.                 $specIds[] = $indSpecData['id'];
  7589.             }
  7590.         }
  7591.         $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  7592.             ->findBy(
  7593.                 array(
  7594.                     'productId' => $id
  7595.                 )
  7596.             );
  7597.         $trans_history $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')
  7598.             ->findBy(
  7599.                 array(
  7600.                     'productId' => $id
  7601.                 ), array(
  7602.                     'transactionDate' => 'ASC',
  7603.                     'id' => 'ASC'
  7604.                 )
  7605.             );
  7606. //        $specId = array_keys($specData);
  7607.         $finSpecData = [];
  7608. //        if($productData){
  7609. //            $tempSpec = json_decode($productData->getSpecData(),true);
  7610. //
  7611. //            if($tempSpec == null){
  7612. //                $tempSpecName=[];
  7613. //            }
  7614. //            foreach ($tempSpec as $indSpec)
  7615. //            {
  7616. //                $specIds[]=$indSpec['id'];
  7617. //
  7618. //                $spec = $em->getRepository('ApplicationBundle\\Entity\\SpecType')
  7619. //                    ->findOneBy(
  7620. //                        array(
  7621. //                            'id' => $indSpec['id']
  7622. //                        )
  7623. //                    );
  7624. //
  7625. //                if($spec)
  7626. //                    $indSpec['name']=$spec->getName();
  7627. //                else
  7628. //                    $indSpec['name']='';
  7629. ////                $specId = $indSpecData['id'];
  7630. //
  7631. //                $finSpecData[]=$indSpec;
  7632. //
  7633. //            }
  7634. //        }
  7635.         $specList $em->getRepository('ApplicationBundle\\Entity\\SpecType')
  7636.             ->findBy(
  7637.                 array(
  7638.                     'id' => $specIds
  7639.                 )
  7640.             );
  7641.         $specListById = [];
  7642.         foreach ($specList as $specHere) {
  7643.             $specListById[$specHere->getId()] = $specHere->getName();
  7644.         }
  7645.         foreach ($specData as $specDatum) {
  7646.             $finSpecData[] = [
  7647.                 'id' => $specDatum['id'],
  7648.                 'name' => isset($specListById[$specDatum['id']]) ? $specListById[$specDatum['id']] : '',
  7649.                 'value' => $specDatum['value']
  7650.             ];
  7651.         }
  7652.         $productDataObj = array();
  7653.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  7654.             $getters array_filter(get_class_methods($productData), function ($method) {
  7655.                 return 'get' === substr($method03);
  7656.             });
  7657.             foreach ($getters as $getter) {
  7658.                 if ($getter == 'getGlobalId')
  7659.                     continue;
  7660. //                    if ($getter == 'getId')
  7661. //                        continue;
  7662.                 $Fieldname str_replace('get'''$getter);
  7663.                 $productDataObj[$Fieldname] = $productData->{$getter}(); // `foo!`
  7664.             }
  7665.             if ($request->request->has('genInfoOnly') && $request->request->get('genInfoOnly') == 1) {
  7666.                 $dataArray = array(
  7667.                     'success' => true,
  7668.                     'page_title' => 'Product Details',
  7669.                     'company_data' => $company_data,
  7670.                     'productData' => $productData,
  7671.                     'productDataObj' => $productDataObj,
  7672.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7673.                 );
  7674.             } else {
  7675.                 $dataArray = array(
  7676.                     'success' => true,
  7677.                     'page_title' => 'Product Details',
  7678.                     'company_data' => $company_data,
  7679.                     'productData' => $productData,
  7680.                     'productDataObj' => $productDataObj,
  7681.                     'currInvList' => $currInvList,
  7682.                     'finSpecData' => $finSpecData,
  7683.                     'specList' => $specList,
  7684.                     'trans_history' => $trans_history,
  7685.                     'entityList' => GeneralConstant::$Entity_list_details,
  7686. //                    'productList' => Inventory::ProductList($em, $companyId),
  7687.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7688.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7689.                     'igList' => Inventory::ItemGroupList($em$companyId),
  7690.                     'unitList' => Inventory::UnitTypeList($em),
  7691.                     'brandList' => Inventory::GetBrandList($em$companyId),
  7692.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7693.                     'warehouseList' => Inventory::WarehouseList($em),
  7694.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7695.                 );
  7696.             }
  7697.             return new JsonResponse(
  7698.                 $dataArray
  7699.             );
  7700.         }
  7701.         $dataArray = array(
  7702.             'page_title' => 'Product Details',
  7703.             'company_data' => $company_data,
  7704.             'productData' => $productData,
  7705.             'currInvList' => $currInvList,
  7706.             'specData' => $specData,
  7707. //            'specListById' => $specListById,
  7708.             'finSpecData' => $finSpecData,
  7709.             'trans_history' => $trans_history,
  7710.             'entityList' => GeneralConstant::$Entity_list_details,
  7711. //            'productList' => Inventory::ProductList($em, $companyId),
  7712.             'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7713.             'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7714.             'igList' => Inventory::ItemGroupList($em$companyId),
  7715.             'unitList' => Inventory::UnitTypeList($em),
  7716.             'brandList' => Inventory::GetBrandList($em$companyId),
  7717.             'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7718.             'warehouseList' => Inventory::WarehouseList($em),
  7719.         );
  7720.         return $this->render('@Inventory/pages/views/product_view.html.twig'$dataArray
  7721.         );
  7722.     }
  7723.     public function CheckForProductInWarehouseAction(Request $request$queryStr '')
  7724.     {
  7725.         $em $this->getDoctrine()->getManager();
  7726.         $companyId $this->getLoggedUserCompanyId($request);
  7727.         $data = [
  7728.             'availableQty' => 0,
  7729.             'productByCodesArray' => [],
  7730.             'indRowId' => 0
  7731.         ];
  7732.         $html '';
  7733.         $productByCodeData = [];
  7734.         if ($request->isMethod('POST')) {
  7735.             $warehouseId $request->request->get('warehouseId'0);
  7736.             $warehouseActionId $request->request->get('warehouseActionId'0);
  7737.             $productId $request->request->get('productId'0);
  7738.             $indRowId $request->request->get('indRowId'0);
  7739.             $data['indRowId'] = $indRowId;
  7740.             $inStorage $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  7741.                 ->findBy(
  7742.                     array(
  7743.                         'productId' => $productId,
  7744.                         'warehouseId' => $warehouseId,
  7745.                         'actionTagId' => $warehouseActionId,
  7746.                         'CompanyId' => $companyId,
  7747.                     )
  7748.                 );
  7749.             foreach ($inStorage as $strg) {
  7750.                 $data['availableQty'] += $strg->getQty();
  7751.             }
  7752.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  7753.                 ->findBy(
  7754.                     array(
  7755.                         'productId' => $productId,
  7756.                         'warehouseId' => $warehouseId,
  7757.                         'warehouseActionId' => $warehouseActionId,
  7758.                         'CompanyId' => $companyId,
  7759.                     )
  7760.                 );
  7761.             foreach ($productByCodeData as $pbc) {
  7762.                 $data['productByCodesArray'][] = array(
  7763.                     'id' => $pbc->getProductByCodeId(),
  7764.                     'productId' => $pbc->getProductId(),
  7765.                     'warehouseId' => $pbc->getWarehouseId(),
  7766.                     'warehouseActionId' => $pbc->getWarehouseActionId(),
  7767. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7768.                     'sales_code' => str_pad($pbc->getSalesCode(), 13'0'STR_PAD_LEFT),
  7769. //                'sales_code'=>$d['sales_code'],
  7770.                 );
  7771.             }
  7772.             return new JsonResponse(array(
  7773.                     'success' => true,
  7774.                     'data' => $data,
  7775.                 )
  7776.             );
  7777.         }
  7778.         return new JsonResponse(
  7779.             array(
  7780.                 'success' => false,
  7781.                 'data' => $data,
  7782.             )
  7783.         );
  7784.     }
  7785.     public function ProductByCodeListAjaxAction(Request $request$queryStr '')
  7786.     {
  7787.         $em $this->getDoctrine()->getManager();
  7788.         $companyId $this->getLoggedUserCompanyId($request);
  7789.         $company_data Company::getCompanyData($em$companyId);
  7790.         $data = [];
  7791.         $html '';
  7792.         $productByCodeData = [];
  7793.         if ($request->request->has('query') && $queryStr == '')
  7794.             $queryStr $request->request->get('queryStr');
  7795.         $likeQueryStr '%' $queryStr '%';
  7796.         $get_kids_sql "select product_by_code_id id, product_id, warehouse_id, warehouse_action_id,
  7797.                             sales_code ,
  7798.                             serial_no,
  7799.                             imei1,
  7800.                             imei2,
  7801.                             imei3,
  7802.                             imei4
  7803.                             from product_by_code
  7804.                             where ( CONVERT(sales_code,char)  like :queryStr
  7805.                                     or  CONVERT(serial_no,char)  like :queryStr
  7806.                                     or  CONVERT(imei1,char)  like :queryStr
  7807.                                     or  CONVERT(imei2,char)  like :queryStr
  7808.                                     or  CONVERT(imei3,char)  like :queryStr
  7809.                                     or  CONVERT(imei4,char)  like :queryStr
  7810.                                     ) ";
  7811.         $queryParams = array(
  7812.             'queryStr' => $likeQueryStr,
  7813.             'companyId' => (int) $companyId,
  7814.         );
  7815.         if ($request->query->has('warehouseId')) {
  7816.             $get_kids_sql .= " and warehouse_id = :warehouseId ";
  7817.             $queryParams['warehouseId'] = (int) $request->query->get('warehouseId');
  7818.         }
  7819.         if ($request->query->has('position')) {
  7820.             $get_kids_sql .= " and position = :position ";
  7821.             $queryParams['position'] = (int) $request->query->get('position');
  7822.         }
  7823.         if ($request->query->has('deliveryReceiptId')) {
  7824.             $get_kids_sql .= " and deliveryReceiptId = :deliveryReceiptId ";
  7825.             $queryParams['deliveryReceiptId'] = (int) $request->query->get('deliveryReceiptId');
  7826.         }
  7827.         if ($request->query->has('warehouseActionId')) {
  7828.             $get_kids_sql .= " and warehouse_action_id = :warehouseActionId ";
  7829.             $queryParams['warehouseActionId'] = (int) $request->query->get('warehouseActionId');
  7830.         }
  7831.         if ($request->query->has('productId')) {
  7832.             $get_kids_sql .= " and product_id = :productId ";
  7833.             $queryParams['productId'] = (int) $request->query->get('productId');
  7834.         }
  7835.         $get_kids_sql .= " and company_id = :companyId limit 25";
  7836.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$queryParams);
  7837.         $get_kids $stmt;
  7838.         if (!empty($get_kids)) {
  7839.             foreach ($get_kids as $d) {
  7840.                 $dt = array(
  7841.                     'id' => $d['id'],
  7842.                     'productId' => $d['product_id'],
  7843.                     'warehouseId' => $d['warehouse_id'],
  7844.                     'warehouseActionId' => $d['warehouse_action_id'],
  7845. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7846.                     'sales_code' => str_pad($d['sales_code'], 13'0'STR_PAD_LEFT),
  7847.                     'serial_no' => str_pad($d['serial_no'], 13'0'STR_PAD_LEFT),
  7848.                     'imei1' => str_pad($d['imei1'], 13'0'STR_PAD_LEFT),
  7849.                     'imei2' => str_pad($d['imei2'], 13'0'STR_PAD_LEFT),
  7850.                     'imei3' => str_pad($d['imei3'], 13'0'STR_PAD_LEFT),
  7851.                     'imei4' => str_pad($d['imei4'], 13'0'STR_PAD_LEFT),
  7852. //                'sales_code'=>$d['sales_code'],
  7853.                 );
  7854.                 $data[] = $dt;
  7855.             }
  7856.         }
  7857. //        if($request->query->has('returnJson'))
  7858.         {
  7859.             return new JsonResponse(
  7860.                 array(
  7861.                     'success' => true,
  7862. //                    'page_title' => 'Product Details',
  7863. //                    'company_data' => $company_data,
  7864.                     'data' => $data,
  7865. //                    'exId'=>$id,
  7866. //                'productByCodeData' => $productByCodeData,
  7867. //                'productData' => $productData,
  7868. //                'currInvList' => $currInvList,
  7869. //                'productList' => Inventory::ProductList($em, $companyId),
  7870. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  7871. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  7872. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  7873. //                'unitList' => Inventory::UnitTypeList($em),
  7874. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  7875. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  7876. //                'warehouseList' => Inventory::WarehouseList($em),
  7877.                 )
  7878.             );
  7879.         }
  7880.     }
  7881.     public function selectDataAjaxAction(Request $request$queryStr '',
  7882.                                                  $version 'latest',
  7883.                                                  $identifier '_default_',
  7884.                                                  $apiKey '_ignore_'
  7885.     )
  7886.     {
  7887.         $em $this->getDoctrine()->getManager();
  7888.         $em_goc $this->getDoctrine()->getManager('company_group');
  7889.         $companyId 0;
  7890.         $skipCurrentUserIdRestriction $request->get('skipCurrentUserIdRestriction'0);
  7891.         $dataOnly $request->get('dataOnly'0);
  7892.         $skipCurrentEmployeeIdRestriction $request->get('skipCurrentEmployeeIdRestriction'0);
  7893.         $skipCurrentUserLoginIdRestriction $request->get('skipCurrentUserLoginIdRestriction'0);
  7894.         $currentUserId $request->getSession()->get(UserConstants::USER_ID0);
  7895.         $currentEmployeeId $request->getSession()->get(UserConstants::USER_EMPLOYEE_ID0);
  7896.         $currentUserLoginIds = [];
  7897.         if ($request->request->get('entity_group'0)) {
  7898.             $companyId 0;
  7899.             $em $this->getDoctrine()->getManager('company_group');
  7900.         } else {
  7901.             if ($request->request->get('appId'0) != 0) {
  7902.                 $gocEnabled 0;
  7903.                 if ($this->container->hasParameter('entity_group_enabled'))
  7904.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7905.                 else
  7906.                     $gocEnabled 1;
  7907.                 if ($gocEnabled == 1) {
  7908.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7909.                         $this->getDoctrine()->getManager('company_group'),
  7910.                         $gocEnabled,
  7911.                         $request->request->get('appId'0)
  7912.                     );
  7913.                     if (!empty($dataToConnect)) {
  7914.                         $connector $this->container->get('application_connector');
  7915.                         $connector->resetConnection(
  7916.                             'default',
  7917.                             $dataToConnect['dbName'],
  7918.                             $dataToConnect['dbUser'],
  7919.                             $dataToConnect['dbPass'],
  7920.                             $dataToConnect['dbHost'],
  7921.                             $reset true
  7922.                         );
  7923.                         $em $this->getDoctrine()->getManager();
  7924.                     }
  7925.                 }
  7926.             } else if ($request->getSession()->get(UserConstants::USER_APP_ID) != && $request->getSession()->get(UserConstants::USER_APP_ID) != null) {
  7927.                 $gocEnabled 0;
  7928.                 if ($this->container->hasParameter('entity_group_enabled'))
  7929.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7930.                 else
  7931.                     $gocEnabled 1;
  7932.                 if ($gocEnabled == 1) {
  7933.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7934.                         $this->getDoctrine()->getManager('company_group'),
  7935.                         $gocEnabled,
  7936.                         $request->getSession()->get(UserConstants::USER_APP_ID)
  7937.                     );
  7938.                     if (!empty($dataToConnect)) {
  7939.                         $connector $this->container->get('application_connector');
  7940.                         $connector->resetConnection(
  7941.                             'default',
  7942.                             $dataToConnect['dbName'],
  7943.                             $dataToConnect['dbUser'],
  7944.                             $dataToConnect['dbPass'],
  7945.                             $dataToConnect['dbHost'],
  7946.                             $reset true
  7947.                         );
  7948.                         $em $this->getDoctrine()->getManager();
  7949.                     }
  7950.                 }
  7951.             }
  7952.             $companyId $this->getLoggedUserCompanyId($request);
  7953.         }
  7954.         $configData = [];
  7955.         $isSingleDataset 1;
  7956.         $dataSet $request->request->has('dataset') ? $request->request->get('dataset') : [];
  7957.         if (is_string($dataSet)) $dataSet json_decode($dataSettrue);
  7958.         $valuePairs $request->get('valuePairs', []);
  7959.         if (is_string($valuePairs)) $valuePairs json_decode($valuePairstrue);
  7960.         $allResult = [];
  7961.         $datasetFromConfig = [];
  7962.         if ($identifier != '_default_') {
  7963.             $config_file $this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' $identifier 'Config.json';
  7964.             if (!file_exists($config_file)) {
  7965.             } else {
  7966.                 $fileText file_get_contents($config_file);
  7967.                 //now replace any value pairs
  7968.                 foreach ($valuePairs as $kkeeyy => $vvaalluuee) {
  7969.                     if (is_array($vvaalluuee)) {
  7970.                         if (isset($vvaalluuee['value']) && isset($vvaalluuee['type'])) {
  7971.                             if ($vvaalluuee['type'] == 'array'$fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee['value']), $fileText);
  7972.                             if ($vvaalluuee['type'] == 'value'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7973.                             if ($vvaalluuee['type'] == 'text'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7974.                         } else {
  7975.                             $fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee), $fileText);
  7976.                         }
  7977.                     } else
  7978.                         $fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee$fileText);
  7979.                 }
  7980.                 $fileText str_ireplace('_query_'$request->get('query'$queryStr), $fileText);
  7981.                 $fileText str_ireplace('_itemLimit_'$request->get('itemLimit''_all_'), $fileText);
  7982.                 $fileText str_ireplace('_offset_'$request->get('offset', ($request->get('itemLimit'10)) * ($request->get('page'1) - 1)), $fileText);
  7983.                 if (!(strpos($fileText'_CURRENT_USER_LOGIN_IDS_') === false) && $skipCurrentUserLoginIdRestriction == 0) {
  7984.                     $userInfo = [];
  7985.                     if ($request->getSession()->get(UserConstants::USER_TYPE0) == UserConstants::USER_TYPE_APPLICANT) {
  7986.                         $userInfo $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityLoginLog')->findBy(
  7987.                             array('userId' => $currentUserId)
  7988.                         );
  7989.                     } else {
  7990.                         $userInfo $em->getRepository('ApplicationBundle\\Entity\\SysLoginLog')->findBy(
  7991.                             array('userId' => $currentUserId)
  7992.                         );
  7993.                     }
  7994.                     foreach ($userInfo as $uLogininfo) {
  7995.                         $currentUserLoginIds[] = $uLogininfo->getLoginId();
  7996.                     }
  7997.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_'json_encode($currentUserLoginIds), $fileText);
  7998.                 } else {
  7999.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_''_EMPTY_'$fileText);
  8000.                 }
  8001.                 if (!(strpos($fileText'_CURRENT_USER_ID_') === false) && $skipCurrentUserIdRestriction == 0) {
  8002.                     $fileText str_ireplace('_CURRENT_USER_ID_'$currentUserId$fileText);
  8003.                 } else {
  8004.                     $fileText str_ireplace('_CURRENT_USER_ID_''_EMPTY_'$fileText);
  8005.                 }
  8006.                 if (!(strpos($fileText'_CURRENT_USER_EMPLOYEE_ID_') === false) && $skipCurrentEmployeeIdRestriction == 0) {
  8007.                     if ((strpos($fileText'skipCurrentEmployeeIdRestriction') === false)) {
  8008.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_'$currentEmployeeId$fileText);
  8009.                     } else {
  8010.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  8011.                     }
  8012.                 } else {
  8013.                     $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  8014.                 }
  8015.                 if ($fileText)
  8016.                     $datasetFromConfig json_decode($fileTexttrue);
  8017.                 $skipCurrentUserIdRestriction = isset($datasetFromConfig['skipCurrentUserIdRestriction']) ? $datasetFromConfig['skipCurrentUserIdRestriction'] : $skipCurrentUserIdRestriction;
  8018.                 $skipCurrentEmployeeIdRestriction = isset($datasetFromConfig['skipCurrentEmployeeIdRestriction']) ? $datasetFromConfig['skipCurrentEmployeeIdRestriction'] : $skipCurrentEmployeeIdRestriction;
  8019.                 $skipCurrentUserLoginIdRestriction = isset($datasetFromConfig['skipCurrentUserLoginIdRestriction']) ? $datasetFromConfig['skipCurrentUserLoginIdRestriction'] : $skipCurrentUserLoginIdRestriction;
  8020.             }
  8021.         }
  8022.         if ($dataSet == null$dataSet = [];
  8023. //        return new JsonResponse(array(
  8024. //            'queryStr'=>$queryStr
  8025. //        ));
  8026.         if (!empty($datasetFromConfig)) {
  8027.             if (isset($datasetFromConfig['tableName'])) {
  8028.                 $isSingleDataset 1;
  8029.                 $dataSet[] = $datasetFromConfig;
  8030.             } else {
  8031.                 if (count($datasetFromConfig) == 1)
  8032.                     $isSingleDataset 1;
  8033.                 $dataSet $datasetFromConfig;
  8034.             }
  8035.         }
  8036.         if (empty($dataSet)) {
  8037.             $isSingleDataset 1;
  8038.             $singleDataSet = array(
  8039.                 "valueField" => $request->request->has('valueField') ? $request->request->get('valueField') : 'id',
  8040.                 "query" => $request->get('query'$queryStr),
  8041.                 "headMarkers" => $request->get('headMarkers'''),
  8042.                 "headMarkersStrictMatch" => $request->get('headMarkersStrictMatch'0),
  8043.                 "itemLimit" => $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25,
  8044.                 "selectorId" => $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_',
  8045.                 "textField" => $request->request->has('textField') ? $request->request->get('textField') : 'name',
  8046.                 "tableName" => $request->request->has('tableName') ? $request->request->get('tableName') : '',
  8047.                 "isMultiple" => $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0,
  8048.                 "orConditions" => $request->request->has('orConditions') ? $request->request->get('orConditions') : [],
  8049.                 "andConditions" => $request->request->has('andConditions') ? $request->request->get('andConditions') : [],
  8050.                 "andOrConditions" => $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [],
  8051.                 "mustConditions" => $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [],
  8052.                 "joinTableData" => $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [],
  8053.                 "selectFieldList" => $request->request->has('selectFieldList') ? $request->request->get('selectFieldList') : ['*'],
  8054.                 "renderTextFormat" => $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '',
  8055.                 "setDataForSingle" => $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0,
  8056.                 "dataId" => $request->request->has('dataId') ? $request->request->get('dataId') : 0,
  8057.                 "lastChildrenOnly" => $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0,
  8058.                 "parentOnly" => $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0,
  8059.                 "parentIdField" => $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id',
  8060.                 "skipDefaultCompanyId" => $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1,
  8061.                 "offset" => $request->request->has('offset') ? $request->request->get('offset') : 0,
  8062.                 "returnTotalMatchedEntriesFlag" => $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0,
  8063.                 "nextOffset" => 0,
  8064.                 "totalMatchedEntries" => 0,
  8065.                 "convertToObject" => $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [],
  8066.                 "convertDateToStringFieldList" => $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [],
  8067.                 "orderByConditions" => $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [],
  8068.                 "convertToUrl" => $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [],
  8069.                 "fullPathList" => $request->request->has('fullPathList') ? $request->request->get('fullPathList') : [],
  8070.                 "ret_data" => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8071.             );
  8072.             $dataSet[] = $singleDataSet;
  8073.         }
  8074. //        $lastResult = [
  8075. //            'identifier' => $identifier,
  8076. //            'dataSet' => $dataSet,
  8077. //        ];
  8078. //        return new JsonResponse($lastResult);
  8079.         $userId $request->getSession()->get(UserConstants::USER_ID);
  8080. //        public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [],$userId=0)
  8081.         foreach ($dataSet as $dsIndex => $dataConfig) {
  8082.             $companyId 0;
  8083.             $queryStringIndividual $queryStr;
  8084.             $data = [];
  8085.             $data_by_id = [];
  8086.             $setValueArray = [];
  8087.             $silentChangeSelectize 0;
  8088.             $setValue 0;
  8089.             $setValueType 0;// 0 for id , 1 for query
  8090.             $selectAll 0;
  8091.             $selectAllFound 0;
  8092.             if (isset($dataConfig['query']))
  8093.                 $queryStringIndividual $dataConfig['query'];
  8094.             if ((strpos($queryStringIndividual'_set_matching_value_') !== false)) {
  8095.                 $selectAllFound 1;
  8096.                 $queryStringIndividual str_ireplace('_set_matching_value_'''$queryStringIndividual);
  8097.             }
  8098.             if ($queryStringIndividual == '_EMPTY_')
  8099.                 $queryStringIndividual '';
  8100.             if ($queryStringIndividual == '_EMPTY_')
  8101.                 $queryStringIndividual '';
  8102.             $queryStringIndividual str_replace('_FSLASH_''/'$queryStringIndividual);
  8103.             if ($queryStringIndividual === '#setValue:') {
  8104.                 $queryStringIndividual '';
  8105.             }
  8106.             if (!(strpos($queryStringIndividual'_silent_change_') === false)) {
  8107.                 $silentChangeSelectize 1;
  8108.                 $queryStringIndividual str_ireplace('_silent_change_'''$queryStringIndividual);
  8109.             }
  8110.             if (!(strpos($queryStringIndividual'#setValue:') === false)) {
  8111.                 $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStringIndividual));
  8112.                 foreach ($setValueArrayBeforeFilter as $svf) {
  8113.                     if ($svf == '_ALL_') {
  8114.                         $selectAll 1;
  8115.                         $setValueArray = [];
  8116.                         continue;
  8117.                     }
  8118.                     if (is_numeric($svf)) {
  8119.                         $setValueArray[] = ($svf 1);
  8120.                         $setValue $svf 1;
  8121.                     }
  8122.                 }
  8123.                 $queryStringIndividual '';
  8124.             }
  8125.             $valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
  8126.             $headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''//Special Field
  8127.             $headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0//Special Field
  8128.             $itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
  8129.             $selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
  8130.             $textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
  8131.             $table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
  8132.             $isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
  8133.             $orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
  8134.             $andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
  8135.             $andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
  8136.             $mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
  8137.             $joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
  8138.             $renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
  8139.             $setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
  8140.             $dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
  8141.             $lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
  8142.             $parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
  8143.             $parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
  8144.             $skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
  8145.             $offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
  8146.             $returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
  8147.             $nextOffset 0;
  8148.             $totalMatchedEntries 0;
  8149.             $convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
  8150.             $convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
  8151.             $orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
  8152.             $convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
  8153.             $fullPathList = isset($dataConfig['fullPathList']) ? $dataConfig['fullPathList'] : [];
  8154.             if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  8155.             if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  8156.             if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  8157.             if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  8158.             if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  8159.             if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  8160.             if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  8161.             if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  8162.             if (is_string($fullPathList)) $fullPathList json_decode($fullPathListtrue);
  8163. //            return new JsonResponse(array(
  8164. //                'dataSet'=>$dataSet,
  8165. //                'dataConfig'=>$dataConfig,
  8166. //                'hi'=>$this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json',
  8167. //                'hiD'=>file_get_contents($this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json')
  8168. //            ));
  8169.             if ($table == '') {
  8170.                 $lastResult = array(
  8171.                     'success' => false,
  8172.                     'currentTs' => (new \Datetime())->format('U'),
  8173.                     'isMultiple' => $isMultiple,
  8174.                     'setValueArray' => $setValueArray,
  8175.                     'setValue' => $setValue,
  8176.                     'data' => $data,
  8177.                     'dataId' => $dataId,
  8178.                     'selectorId' => $selectorId,
  8179.                     'dataById' => $data_by_id,
  8180.                     'selectedId' => 0,
  8181.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8182.                 );
  8183.             } else {
  8184.                 $restrictionData = array(
  8185. //            'table'=>'relevantField in restriction'
  8186.                     'warehouse_action' => 'warehouseActionIds',
  8187.                     'branch' => 'branchIds',
  8188.                     'warehouse' => 'warehouseIds',
  8189.                     'production_process_settings' => 'productionProcessIds',
  8190.                 );
  8191.                 $restrictionIdList = [];
  8192.                 $filterQryForCriteria "select ";
  8193.                 $selectQry "";
  8194. //        $selectQry=" `$table`.* ";
  8195.                 $selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
  8196.                 $selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
  8197.                 if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  8198.                 foreach ($selectFieldList as $selFieldFull) {
  8199.                     if ($selectQry != '')
  8200.                         $selectQry .= ", ";
  8201.                     $selFieldArray explode(' '$selFieldFull);
  8202.                     $selField $selFieldArray[0];
  8203.                     $selFieldAlias $selFieldArray[1] ?? '';
  8204.                     if ($selField == '*')
  8205.                         $selectQry .= " `$table`.$selField ";
  8206.                     else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  8207.                         if ($selectPrefix == '')
  8208.                             $selectQry .= " count(*)  ";
  8209.                         else
  8210.                             $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  8211.                     } else {
  8212.                         if ($selectPrefix == '')
  8213.                             $selectQry .= " `$table`.`$selField`  $selFieldAlias";
  8214.                         else
  8215.                             $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  8216.                     }
  8217.                 }
  8218.                 $joinQry " from $table ";
  8219. //        $filterQryForCriteria = "select * from $table ";
  8220.                 foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  8221. //            $conditionStr.=' 1=1 ';
  8222.                     $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  8223.                     $joinTableAlias $joinTableName '_' $joinIndex;
  8224.                     $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  8225.                     $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  8226.                     $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  8227.                     $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  8228.                     $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  8229.                     $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  8230.                     $joinMustConditions = isset($joinTableDatum['joinMustConditions']) ? $joinTableDatum['joinMustConditions'] : [];
  8231.                     $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  8232.                     $joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
  8233.                     $joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
  8234.                     if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  8235.                     if (is_string($joinMustConditions)) $joinMustConditions json_decode($joinMustConditionstrue);
  8236.                     if (is_string($joinAndOrConditions)) $joinAndOrConditions json_decode($joinAndOrConditionstrue);
  8237.                     if (is_string($joinOrConditions)) $joinOrConditions json_decode($joinOrConditionstrue);
  8238.                     foreach ($selectFieldList as $selFieldFull) {
  8239.                         $selFieldArray explode(' '$selFieldFull);
  8240.                         $selField $selFieldArray[0];
  8241.                         $selFieldAlias $selFieldArray[1] ?? '';
  8242.                         if ($selField == '*')
  8243.                             $selectQry .= ", `$joinTableAlias`.$selField ";
  8244.                         else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  8245.                             if ($selectPrefix == '')
  8246.                                 $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  8247.                             else
  8248.                                 $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  8249.                         } else {
  8250.                             if ($selectPrefix == '')
  8251.                                 $selectQry .= ", `$joinTableAlias`.`$selField`  $selFieldAlias";
  8252.                             else
  8253.                                 $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  8254.                         }
  8255.                     }
  8256.                     $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  8257. //            if($joinTablePrimaryField!='')
  8258. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8259. //            $joinAndString = '';
  8260.                     $joinMustString '';
  8261.                     if ($joinTablePrimaryField != '') {
  8262.                         if (!(strpos($joinTablePrimaryField'.') === false)) {
  8263.                             $joinQry .= "  `$joinTableAlias`.`$joinTableOnField`  $fieldJoinType $joinTablePrimaryField ";
  8264.                         } else
  8265.                             $joinQry .= "  `$joinTableAlias`.`$joinTableOnField`  $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8266.                     }
  8267.                     foreach ($joinMustConditions as $mustCondition) {
  8268. //            $conditionStr.=' 1=1 ';
  8269.                         $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  8270.                         $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  8271.                         $aliasInCondition $table;
  8272.                         if (!(strpos($cfield'.') === false)) {
  8273.                             $fullCfieldArray explode('.'$cfield);
  8274.                             $aliasInCondition $fullCfieldArray[0];
  8275.                             $cfield $fullCfieldArray[1];
  8276.                         }
  8277.                         $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  8278.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8279.                             if ($joinMustString != '')
  8280.                                 $joinMustString .= " and ";
  8281.                             if ($ctype == 'like') {
  8282.                                 $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8283.                                 $wordsBySpaces explode(' '$cvalue);
  8284.                                 foreach ($wordsBySpaces as $word) {
  8285.                                     if ($joinMustString != '')
  8286.                                         $joinMustString .= " and ";
  8287.                                     $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8288.                                 }
  8289.                             } else if ($ctype == 'not like') {
  8290.                                 $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8291.                                 $wordsBySpaces explode(' '$cvalue);
  8292.                                 foreach ($wordsBySpaces as $word) {
  8293.                                     if ($joinMustString != '')
  8294.                                         $joinMustString .= " and ";
  8295.                                     $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8296.                                 }
  8297.                             } else if ($ctype == 'not_in') {
  8298.                                 $joinMustString .= " ( ";
  8299.                                 if (in_array('null'$cvalue)) {
  8300.                                     $joinMustString .= " `$joinTableAlias`.$cfield is not null";
  8301.                                     $cvalue array_diff($cvalue, ['null']);
  8302.                                     if (!empty($cvalue))
  8303.                                         $joinMustString .= " and ";
  8304.                                 }
  8305.                                 if (in_array(''$cvalue)) {
  8306.                                     $joinMustString .= "`$joinTableAlias`.$cfield != '' ";
  8307.                                     $cvalue array_diff($cvalue, ['']);
  8308.                                     if (!empty($cvalue))
  8309.                                         $joinMustString .= " and ";
  8310.                                 }
  8311.                                 $joinMustString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8312.                             } else if ($ctype == 'in') {
  8313.                                 if (in_array('null'$cvalue)) {
  8314.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null";
  8315.                                     $cvalue array_diff($cvalue, ['null']);
  8316.                                     if (!empty($cvalue))
  8317.                                         $joinMustString .= " and ";
  8318.                                 }
  8319.                                 if (in_array(''$cvalue)) {
  8320.                                     $joinMustString .= "`$joinTableAlias`.$cfield = '' ";
  8321.                                     $cvalue array_diff($cvalue, ['']);
  8322.                                     if (!empty($cvalue))
  8323.                                         $joinMustString .= " and ";
  8324.                                 }
  8325.                                 $joinMustString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8326.                             } else if ($ctype == '=') {
  8327. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8328. //                            $fullCfieldArray = explode('.', $cfield);
  8329. //                            $aliasInCondition = $fullCfieldArray[0];
  8330. //                            $cfield = $fullCfieldArray[1];
  8331. //                        }
  8332.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8333.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null ";
  8334.                                 else
  8335.                                     $joinMustString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8336.                             } else if ($ctype == '!=') {
  8337.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8338.                                     $joinMustString .= "`$joinTableAlias`.$cfield is not null ";
  8339.                                 else
  8340.                                     $joinMustString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8341.                             } else {
  8342.                                 if (is_string($cvalue))
  8343.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8344.                                 else
  8345.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8346.                             }
  8347.                         }
  8348.                     }
  8349. //            if ($joinMustString != '') {
  8350. //                if ($conditionStr != '')
  8351. //                    $conditionStr .= (" and (" . $joinMustString . ") ");
  8352. //                else
  8353. //                    $conditionStr .= ("  (" . $joinMustString . ") ");
  8354. //            }
  8355.                     if ($joinMustString != '') {
  8356.                         $joinQry .= (' and ' $joinMustString);
  8357. //                        $joinQry.=' and (';
  8358.                     }
  8359.                     $mustBracketDone 0;
  8360.                     $joinAndString '';
  8361. //                    if ($joinTablePrimaryField != '')
  8362. //                        $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8363.                     foreach ($joinAndConditions as $andCondition) {
  8364. //            $conditionStr.=' 1=1 ';
  8365.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  8366.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  8367.                         $aliasInCondition $table;
  8368.                         if (!(strpos($cfield'.') === false)) {
  8369.                             $fullCfieldArray explode('.'$cfield);
  8370.                             $aliasInCondition $fullCfieldArray[0];
  8371.                             $cfield $fullCfieldArray[1];
  8372.                         }
  8373.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  8374.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8375.                             if ($joinAndString != '')
  8376.                                 $joinAndString .= " and ";
  8377.                             if ($ctype == 'like') {
  8378.                                 $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8379.                                 $wordsBySpaces explode(' '$cvalue);
  8380.                                 foreach ($wordsBySpaces as $word) {
  8381.                                     if ($joinAndString != '')
  8382.                                         $joinAndString .= " and ";
  8383.                                     $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8384.                                 }
  8385.                             } else if ($ctype == 'not like') {
  8386.                                 $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8387.                                 $wordsBySpaces explode(' '$cvalue);
  8388.                                 foreach ($wordsBySpaces as $word) {
  8389.                                     if ($joinAndString != '')
  8390.                                         $joinAndString .= " and ";
  8391.                                     $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8392.                                 }
  8393.                             } else if ($ctype == 'not_in') {
  8394.                                 $joinAndString .= " ( ";
  8395.                                 if (in_array('null'$cvalue)) {
  8396.                                     $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  8397.                                     $cvalue array_diff($cvalue, ['null']);
  8398.                                     if (!empty($cvalue))
  8399.                                         $joinAndString .= " and ";
  8400.                                 }
  8401.                                 if (in_array(''$cvalue)) {
  8402.                                     $joinAndString .= "`$joinTableAlias`.$cfield != '' ";
  8403.                                     $cvalue array_diff($cvalue, ['']);
  8404.                                     if (!empty($cvalue))
  8405.                                         $joinAndString .= " and ";
  8406.                                 }
  8407.                                 $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8408.                             } else if ($ctype == 'in') {
  8409.                                 if (in_array('null'$cvalue)) {
  8410.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null";
  8411.                                     $cvalue array_diff($cvalue, ['null']);
  8412.                                     if (!empty($cvalue))
  8413.                                         $joinAndString .= " and ";
  8414.                                 }
  8415.                                 if (in_array(''$cvalue)) {
  8416.                                     $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  8417.                                     $cvalue array_diff($cvalue, ['']);
  8418.                                     if (!empty($cvalue))
  8419.                                         $joinAndString .= " and ";
  8420.                                 }
  8421.                                 $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8422.                             } else if ($ctype == '=') {
  8423. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8424. //                            $fullCfieldArray = explode('.', $cfield);
  8425. //                            $aliasInCondition = $fullCfieldArray[0];
  8426. //                            $cfield = $fullCfieldArray[1];
  8427. //                        }
  8428.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8429.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  8430.                                 else
  8431.                                     $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8432.                             } else if ($ctype == '!=') {
  8433.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8434.                                     $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  8435.                                 else
  8436.                                     $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8437.                             } else {
  8438.                                 if (is_string($cvalue))
  8439.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8440.                                 else
  8441.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8442.                             }
  8443.                         }
  8444.                     }
  8445. //            if ($joinAndString != '') {
  8446. //                if ($conditionStr != '')
  8447. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  8448. //                else
  8449. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  8450. //            }
  8451.                     if ($joinAndString != '') {
  8452.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  8453.                             $joinQry .= ' and (';
  8454.                             $mustBracketDone 1;
  8455.                         }
  8456.                         if ($joinQry != '')
  8457.                             $joinQry .= (" and (" $joinAndString ") ");
  8458.                         else
  8459.                             $joinQry .= ("  (" $joinAndString ") ");
  8460.                     }
  8461.                     $joinAndOrString "";
  8462.                     foreach ($joinAndOrConditions as $andOrCondition) {
  8463. //            $conditionStr.=' 1=1 ';
  8464.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  8465.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  8466.                         $aliasInCondition $table;
  8467.                         if (!(strpos($cfield'.') === false)) {
  8468.                             $fullCfieldArray explode('.'$cfield);
  8469.                             $aliasInCondition $fullCfieldArray[0];
  8470.                             $cfield $fullCfieldArray[1];
  8471.                         }
  8472.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  8473.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8474.                             if ($joinAndOrString != '')
  8475.                                 $joinAndOrString .= " or ";
  8476.                             if ($ctype == 'like') {
  8477.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8478.                                 $wordsBySpaces explode(' '$cvalue);
  8479.                                 foreach ($wordsBySpaces as $word) {
  8480.                                     if ($joinAndOrString != '')
  8481.                                         $joinAndOrString .= " or ";
  8482.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8483.                                 }
  8484.                             } else if ($ctype == 'not like') {
  8485.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8486.                                 $wordsBySpaces explode(' '$cvalue);
  8487.                                 foreach ($wordsBySpaces as $word) {
  8488.                                     if ($joinAndOrString != '')
  8489.                                         $joinAndOrString .= " or ";
  8490.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8491.                                 }
  8492.                             } else if ($ctype == 'not_in') {
  8493.                                 $joinAndOrString .= " ( ";
  8494.                                 if (in_array('null'$cvalue)) {
  8495.                                     $joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
  8496.                                     $cvalue array_diff($cvalue, ['null']);
  8497.                                     if (!empty($cvalue))
  8498.                                         $joinAndOrString .= " or ";
  8499.                                 }
  8500.                                 if (in_array(''$cvalue)) {
  8501.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != '' ";
  8502.                                     $cvalue array_diff($cvalue, ['']);
  8503.                                     if (!empty($cvalue))
  8504.                                         $joinAndOrString .= " or ";
  8505.                                 }
  8506.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8507.                             } else if ($ctype == 'in') {
  8508.                                 if (in_array('null'$cvalue)) {
  8509.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null";
  8510.                                     $cvalue array_diff($cvalue, ['null']);
  8511.                                     if (!empty($cvalue))
  8512.                                         $joinAndOrString .= " or ";
  8513.                                 }
  8514.                                 if (in_array(''$cvalue)) {
  8515.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  8516.                                     $cvalue array_diff($cvalue, ['']);
  8517.                                     if (!empty($cvalue))
  8518.                                         $joinAndOrString .= " or ";
  8519.                                 }
  8520.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8521.                             } else if ($ctype == '=') {
  8522. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8523. //                            $fullCfieldArray = explode('.', $cfield);
  8524. //                            $aliasInCondition = $fullCfieldArray[0];
  8525. //                            $cfield = $fullCfieldArray[1];
  8526. //                        }
  8527.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8528.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
  8529.                                 else
  8530.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8531.                             } else if ($ctype == '!=') {
  8532.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8533.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
  8534.                                 else
  8535.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8536.                             } else {
  8537.                                 if (is_string($cvalue))
  8538.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8539.                                 else
  8540.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8541.                             }
  8542.                         }
  8543.                     }
  8544. //            if ($joinAndOrString != '')
  8545. //                $joinQry .= $joinAndOrString;
  8546.                     if ($joinAndOrString != '') {
  8547.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  8548.                             $joinQry .= ' and (';
  8549.                             $mustBracketDone 1;
  8550.                         }
  8551.                         if ($joinQry != '')
  8552.                             $joinQry .= (" and (" $joinAndOrString ") ");
  8553.                         else
  8554.                             $joinQry .= ("  (" $joinAndOrString ") ");
  8555.                     }
  8556.                     //pika
  8557.                     $joinOrString "";
  8558.                     foreach ($joinOrConditions as $orCondition) {
  8559. //            $conditionStr.=' 1=1 ';
  8560.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  8561.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  8562.                         $aliasInCondition $table;
  8563.                         if (!(strpos($cfield'.') === false)) {
  8564.                             $fullCfieldArray explode('.'$cfield);
  8565.                             $aliasInCondition $fullCfieldArray[0];
  8566.                             $cfield $fullCfieldArray[1];
  8567.                         }
  8568.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  8569.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8570.                             if ($joinOrString != '' || $joinAndString != '' || $joinMustString != '')
  8571.                                 $joinOrString .= " or ";
  8572.                             if ($ctype == 'like') {
  8573.                                 $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8574.                                 $wordsBySpaces explode(' '$cvalue);
  8575.                                 foreach ($wordsBySpaces as $word) {
  8576.                                     if ($joinOrString != '')
  8577.                                         $joinOrString .= " or ";
  8578.                                     $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8579.                                 }
  8580.                             } else if ($ctype == 'not like') {
  8581.                                 $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8582.                                 $wordsBySpaces explode(' '$cvalue);
  8583.                                 foreach ($wordsBySpaces as $word) {
  8584.                                     if ($joinOrString != '')
  8585.                                         $joinOrString .= " or ";
  8586.                                     $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8587.                                 }
  8588.                             } else if ($ctype == 'not_in') {
  8589.                                 $joinOrString .= " ( ";
  8590.                                 if (in_array('null'$cvalue)) {
  8591.                                     $joinOrString .= " `$joinTableAlias`.$cfield is not null";
  8592.                                     $cvalue array_diff($cvalue, ['null']);
  8593.                                     if (!empty($cvalue))
  8594.                                         $joinOrString .= " or ";
  8595.                                 }
  8596.                                 if (in_array(''$cvalue)) {
  8597.                                     $joinOrString .= "`$joinTableAlias`.$cfield != '' ";
  8598.                                     $cvalue array_diff($cvalue, ['']);
  8599.                                     if (!empty($cvalue))
  8600.                                         $joinOrString .= " or ";
  8601.                                 }
  8602.                                 $joinOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8603.                             } else if ($ctype == 'in') {
  8604.                                 if (in_array('null'$cvalue)) {
  8605.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null";
  8606.                                     $cvalue array_diff($cvalue, ['null']);
  8607.                                     if (!empty($cvalue))
  8608.                                         $joinOrString .= " or ";
  8609.                                 }
  8610.                                 if (in_array(''$cvalue)) {
  8611.                                     $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  8612.                                     $cvalue array_diff($cvalue, ['']);
  8613.                                     if (!empty($cvalue))
  8614.                                         $joinOrString .= " or ";
  8615.                                 }
  8616.                                 $joinOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8617.                             } else if ($ctype == '=') {
  8618. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8619. //                            $fullCfieldArray = explode('.', $cfield);
  8620. //                            $aliasInCondition = $fullCfieldArray[0];
  8621. //                            $cfield = $fullCfieldArray[1];
  8622. //                        }
  8623.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8624.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null ";
  8625.                                 else
  8626.                                     $joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8627.                             } else if ($ctype == '!=') {
  8628.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8629.                                     $joinOrString .= "`$joinTableAlias`.$cfield is not null ";
  8630.                                 else
  8631.                                     $joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8632.                             } else {
  8633.                                 if (is_string($cvalue))
  8634.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8635.                                 else
  8636.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8637.                             }
  8638.                         }
  8639.                     }
  8640. //            if ($joinOrString != '')
  8641. //                $joinQry .= $joinOrString;
  8642.                     if ($joinOrString != '') {
  8643.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  8644.                             $joinQry .= ' and (';
  8645.                             $mustBracketDone 1;
  8646.                         }
  8647.                         if ($joinQry != '')
  8648.                             $joinQry .= (" or (" $joinOrString ") ");
  8649.                         else
  8650.                             $joinQry .= ("  (" $joinOrString ") ");
  8651.                     }
  8652.                     if ($joinMustString != '' && $mustBracketDone == 1) {
  8653.                         $joinQry .= ' ) ';
  8654.                     }
  8655. //
  8656. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8657.                 }
  8658.                 $filterQryForCriteria .= $selectQry;
  8659.                 $filterQryForCriteria .= $joinQry;
  8660.                 if ($skipDefaultCompanyId == && $companyId != && !isset($dataConfig['entity_group']))
  8661.                     $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  8662.                 else
  8663.                     $filterQryForCriteria .= " where 1=1 ";
  8664.                 $conditionStr "";
  8665.                 $aliasInCondition $table;
  8666.                 if ($headMarkers != '' && $table == 'acc_accounts_head') {
  8667.                     $markerList explode(','$headMarkers);
  8668.                     $spMarkerQry "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
  8669.                     $markerPassedHeads = [];
  8670.                     foreach ($markerList as $mrkr) {
  8671.                         $spMarkerQry .= " and marker_hash like '%" $mrkr "%'";
  8672.                     }
  8673.                     $spStmt $em->getConnection()->fetchAllAssociative($spMarkerQry);
  8674.                     $spStmtResults $spStmt;
  8675.                     foreach ($spStmtResults as $ggres) {
  8676.                         $markerPassedHeads[] = $ggres['accounts_head_id'];
  8677.                     }
  8678.                     if (!empty($markerPassedHeads)) {
  8679.                         if ($conditionStr != '')
  8680.                             $conditionStr .= " and (";
  8681.                         else
  8682.                             $conditionStr .= " (";
  8683.                         if ($headMarkersStrictMatch != 1) {
  8684.                             foreach ($markerPassedHeads as $mh) {
  8685.                                 $conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" $mh "/%' or ";
  8686.                             }
  8687.                         }
  8688.                         $conditionStr .= "  `$aliasInCondition`.`accounts_head_id` in (" implode(','$markerPassedHeads) . ") ";
  8689.                         $conditionStr .= " )";
  8690.                     }
  8691.                 }
  8692.                 if (isset($restrictionData[$table])) {
  8693.                     $userRestrictionData Users::getUserApplicationAccessSettings($em$userId)['options'];
  8694.                     if (isset($userRestrictionData[$restrictionData[$table]])) {
  8695.                         $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  8696.                         if ($restrictionIdList == null)
  8697.                             $restrictionIdList = [];
  8698.                     }
  8699.                     if (!empty($restrictionIdList)) {
  8700.                         if ($conditionStr != '')
  8701.                             $conditionStr .= " and ";
  8702.                         $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  8703.                     }
  8704.                 }
  8705. //        $aliasInCondition = $table;
  8706.                 if (!empty($setValueArray) || $selectAll == 1) {
  8707.                     if (!empty($setValueArray)) {
  8708.                         if ($conditionStr != '')
  8709.                             $conditionStr .= " and ";
  8710.                         $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  8711.                     }
  8712.                 } else {
  8713.                     $andString '';
  8714.                     foreach ($andConditions as $andCondition) {
  8715. //            $conditionStr.=' 1=1 ';
  8716.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  8717.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  8718.                         $aliasInCondition $table;
  8719.                         if (!(strpos($cfield'.') === false)) {
  8720.                             $fullCfieldArray explode('.'$cfield);
  8721.                             $aliasInCondition $fullCfieldArray[0];
  8722.                             $cfield $fullCfieldArray[1];
  8723.                         }
  8724.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  8725.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8726.                             if ($andString != '')
  8727.                                 $andString .= " and ";
  8728.                             if ($ctype == 'like') {
  8729.                                 $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8730.                                 $wordsBySpaces explode(' '$cvalue);
  8731.                                 foreach ($wordsBySpaces as $word) {
  8732.                                     if ($andString != '')
  8733.                                         $andString .= " and ";
  8734.                                     $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8735.                                 }
  8736.                             } else if ($ctype == 'not like') {
  8737.                                 $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8738.                                 $wordsBySpaces explode(' '$cvalue);
  8739.                                 foreach ($wordsBySpaces as $word) {
  8740.                                     if ($andString != '')
  8741.                                         $andString .= " and ";
  8742.                                     $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8743.                                 }
  8744.                             } else if ($ctype == 'not_in') {
  8745.                                 $andString .= " ( ";
  8746.                                 if (in_array('null'$cvalue)) {
  8747.                                     $andString .= " `$aliasInCondition`.$cfield is not null";
  8748.                                     $cvalue array_diff($cvalue, ['null']);
  8749.                                     if (!empty($cvalue))
  8750.                                         $andString .= " and ";
  8751.                                 }
  8752.                                 if (in_array(''$cvalue)) {
  8753.                                     $andString .= "`$aliasInCondition`.$cfield != '' ";
  8754.                                     $cvalue array_diff($cvalue, ['']);
  8755.                                     if (!empty($cvalue))
  8756.                                         $andString .= " and ";
  8757.                                 }
  8758.                                 $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8759.                             } else if ($ctype == 'in') {
  8760.                                 if (in_array('null'$cvalue)) {
  8761.                                     $andString .= "`$aliasInCondition`.$cfield is null";
  8762.                                     $cvalue array_diff($cvalue, ['null']);
  8763.                                     if (!empty($cvalue))
  8764.                                         $andString .= " and ";
  8765.                                 }
  8766.                                 if (in_array(''$cvalue)) {
  8767.                                     $andString .= "`$aliasInCondition`.$cfield = '' ";
  8768.                                     $cvalue array_diff($cvalue, ['']);
  8769.                                     if (!empty($cvalue))
  8770.                                         $andString .= " and ";
  8771.                                 }
  8772.                                 $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  8773.                             } else if ($ctype == '=') {
  8774.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8775.                                     $andString .= "`$aliasInCondition`.$cfield is null ";
  8776.                                 else
  8777.                                     if (is_string($cvalue))
  8778.                                         $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8779.                                     else
  8780.                                         $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8781.                             } else if ($ctype == '!=') {
  8782.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8783.                                     $andString .= "`$aliasInCondition`.$cfield is not null ";
  8784.                                 else
  8785.                                     $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8786.                             } else {
  8787.                                 if (is_string($cvalue))
  8788.                                     $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8789.                                 else
  8790.                                     $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8791.                             }
  8792.                         }
  8793.                     }
  8794.                     if ($andString != '') {
  8795.                         if ($conditionStr != '')
  8796.                             $conditionStr .= (" and (" $andString ") ");
  8797.                         else
  8798.                             $conditionStr .= ("  (" $andString ") ");
  8799.                     }
  8800.                     $orString '';
  8801.                     foreach ($orConditions as $orCondition) {
  8802.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  8803.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  8804.                         $aliasInCondition $table;
  8805.                         if (!(strpos($cfield'.') === false)) {
  8806.                             $fullCfieldArray explode('.'$cfield);
  8807.                             $aliasInCondition $fullCfieldArray[0];
  8808.                             $cfield $fullCfieldArray[1];
  8809.                         }
  8810.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  8811.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8812.                             if ($orString != '')
  8813.                                 $orString .= " or ";
  8814.                             if ($ctype == 'like') {
  8815.                                 $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8816.                                 $wordsBySpaces explode(' '$cvalue);
  8817.                                 foreach ($wordsBySpaces as $word) {
  8818.                                     if ($orString != '')
  8819.                                         $orString .= " or ";
  8820.                                     $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8821.                                 }
  8822.                             } else if ($ctype == 'not like') {
  8823.                                 $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8824.                                 $wordsBySpaces explode(' '$cvalue);
  8825.                                 foreach ($wordsBySpaces as $word) {
  8826.                                     if ($orString != '')
  8827.                                         $orString .= " or ";
  8828.                                     $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8829.                                 }
  8830.                             } else if ($ctype == 'not_in') {
  8831.                                 $orString .= " ( ";
  8832.                                 if (in_array('null'$cvalue)) {
  8833.                                     $orString .= " `$aliasInCondition`.$cfield is not null";
  8834.                                     $cvalue array_diff($cvalue, ['null']);
  8835.                                     if (!empty($cvalue))
  8836.                                         $orString .= " or ";
  8837.                                 }
  8838.                                 if (in_array(''$cvalue)) {
  8839.                                     $orString .= "`$aliasInCondition`.$cfield != '' ";
  8840.                                     $cvalue array_diff($cvalue, ['']);
  8841.                                     if (!empty($cvalue))
  8842.                                         $orString .= " or ";
  8843.                                 }
  8844.                                 $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8845.                             } else if ($ctype == 'in') {
  8846.                                 $orString .= " ( ";
  8847.                                 if (in_array('null'$cvalue)) {
  8848.                                     $orString .= " `$aliasInCondition`.$cfield is null";
  8849.                                     $cvalue array_diff($cvalue, ['null']);
  8850.                                     if (!empty($cvalue))
  8851.                                         $orString .= " or ";
  8852.                                 }
  8853.                                 if (in_array(''$cvalue)) {
  8854.                                     $orString .= "`$aliasInCondition`.$cfield = '' ";
  8855.                                     $cvalue array_diff($cvalue, ['']);
  8856.                                     if (!empty($cvalue))
  8857.                                         $orString .= " or ";
  8858.                                 }
  8859.                                 $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8860.                             } else if ($ctype == '=') {
  8861.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8862.                                     $orString .= "`$aliasInCondition`.$cfield is null ";
  8863.                                 else
  8864.                                     if (is_string($cvalue))
  8865.                                         $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8866.                                     else
  8867.                                         $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8868.                             } else if ($ctype == '!=') {
  8869.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8870.                                     $orString .= "`$aliasInCondition`.$cfield is not null ";
  8871.                                 else
  8872.                                     $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8873.                             } else {
  8874.                                 if (is_string($cvalue))
  8875.                                     $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8876.                                 else
  8877.                                     $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8878.                             }
  8879.                         }
  8880.                     }
  8881.                     if ($orString != '') {
  8882.                         if ($conditionStr != '')
  8883.                             $conditionStr .= (" or (" $orString ") ");
  8884.                         else
  8885.                             $conditionStr .= ("  (" $orString ") ");
  8886.                     }
  8887.                     $andOrString '';
  8888.                     foreach ($andOrConditions as $andOrCondition) {
  8889.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  8890.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  8891.                         $aliasInCondition $table;
  8892.                         if (!(strpos($cfield'.') === false)) {
  8893.                             $fullCfieldArray explode('.'$cfield);
  8894.                             $aliasInCondition $fullCfieldArray[0];
  8895.                             $cfield $fullCfieldArray[1];
  8896.                         }
  8897.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  8898.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8899.                             if ($andOrString != '')
  8900.                                 $andOrString .= " or ";
  8901.                             if ($ctype == 'like') {
  8902.                                 $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8903.                                 $wordsBySpaces explode(' '$cvalue);
  8904.                                 foreach ($wordsBySpaces as $word) {
  8905.                                     if ($andOrString != '')
  8906.                                         $andOrString .= " or ";
  8907.                                     $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8908.                                 }
  8909.                             } else if ($ctype == 'not like') {
  8910.                                 $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8911.                                 $wordsBySpaces explode(' '$cvalue);
  8912.                                 foreach ($wordsBySpaces as $word) {
  8913.                                     if ($andOrString != '')
  8914.                                         $andOrString .= " or ";
  8915.                                     $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8916.                                 }
  8917.                             } else if ($ctype == 'in') {
  8918.                                 $andOrString .= " ( ";
  8919.                                 if (in_array('null'$cvalue)) {
  8920.                                     $andOrString .= " `$aliasInCondition`.$cfield is null";
  8921.                                     $cvalue array_diff($cvalue, ['null']);
  8922.                                     if (!empty($cvalue))
  8923.                                         $andOrString .= " or ";
  8924.                                 }
  8925.                                 if (in_array(''$cvalue)) {
  8926.                                     $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  8927.                                     $cvalue array_diff($cvalue, ['']);
  8928.                                     if (!empty($cvalue))
  8929.                                         $andOrString .= " or ";
  8930.                                 }
  8931.                                 if (!empty($cvalue))
  8932.                                     $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8933.                                 else
  8934.                                     $andOrString .= "  ) ";
  8935.                             } else if ($ctype == 'not_in') {
  8936.                                 $andOrString .= " ( ";
  8937.                                 if (in_array('null'$cvalue)) {
  8938.                                     $andOrString .= " `$aliasInCondition`.$cfield is not null";
  8939.                                     $cvalue array_diff($cvalue, ['null']);
  8940.                                     if (!empty($cvalue))
  8941.                                         $andOrString .= " or ";
  8942.                                 }
  8943.                                 if (in_array(''$cvalue)) {
  8944.                                     $andOrString .= "`$aliasInCondition`.$cfield != '' ";
  8945.                                     $cvalue array_diff($cvalue, ['']);
  8946.                                     if (!empty($cvalue))
  8947.                                         $andOrString .= " or ";
  8948.                                 }
  8949.                                 if (!empty($cvalue))
  8950.                                     $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8951.                                 else
  8952.                                     $andOrString .= "  ) ";
  8953.                             } else if ($ctype == '=') {
  8954.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8955.                                     $andOrString .= "`$aliasInCondition`.$cfield is null ";
  8956.                                 else
  8957.                                     if (is_string($cvalue))
  8958.                                         $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8959.                                     else
  8960.                                         $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8961.                             } else if ($ctype == '!=') {
  8962.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8963.                                     $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  8964.                                 else
  8965.                                     $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8966.                             } else {
  8967.                                 if (is_string($cvalue))
  8968.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8969.                                 else
  8970.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8971.                             }
  8972.                         }
  8973.                     }
  8974.                     if ($andOrString != '') {
  8975.                         if ($conditionStr != '')
  8976.                             $conditionStr .= (" and (" $andOrString ") ");
  8977.                         else
  8978.                             $conditionStr .= ("  (" $andOrString ") ");
  8979.                     }
  8980.                 }
  8981.                 $mustStr '';
  8982. ///now must conditions
  8983.                 foreach ($mustConditions as $mustCondition) {
  8984. //            $conditionStr.=' 1=1 ';
  8985.                     $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  8986.                     $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  8987.                     $aliasInCondition $table;
  8988.                     if (!(strpos($cfield'.') === false)) {
  8989.                         $fullCfieldArray explode('.'$cfield);
  8990.                         $aliasInCondition $fullCfieldArray[0];
  8991.                         $cfield $fullCfieldArray[1];
  8992.                     }
  8993.                     $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  8994.                     if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8995.                         if ($mustStr != '')
  8996.                             $mustStr .= " and ";
  8997.                         if ($ctype == 'like') {
  8998.                             $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8999.                             $wordsBySpaces explode(' '$cvalue);
  9000.                             foreach ($wordsBySpaces as $word) {
  9001.                                 if ($mustStr != '')
  9002.                                     $mustStr .= " or ";
  9003.                                 $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  9004.                             }
  9005.                             $mustStr .= " )";
  9006.                         } else if ($ctype == 'not like') {
  9007.                             $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  9008.                             $wordsBySpaces explode(' '$cvalue);
  9009.                             foreach ($wordsBySpaces as $word) {
  9010.                                 if ($mustStr != '')
  9011.                                     $mustStr .= " and ";
  9012.                                 $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  9013.                             }
  9014.                         } else if ($ctype == 'in') {
  9015.                             $mustStr .= " ( ";
  9016.                             if (in_array('null'$cvalue)) {
  9017.                                 $mustStr .= " `$aliasInCondition`.$cfield is null";
  9018.                                 $cvalue array_diff($cvalue, ['null']);
  9019.                                 if (!empty($cvalue))
  9020.                                     $mustStr .= " or ";
  9021.                             }
  9022.                             if (in_array(''$cvalue)) {
  9023.                                 $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  9024.                                 $cvalue array_diff($cvalue, ['']);
  9025.                                 if (!empty($cvalue))
  9026.                                     $mustStr .= " or ";
  9027.                             }
  9028.                             $formattedValues array_map(function ($val) {
  9029.                                 $val trim($val);
  9030.                                 if (is_numeric($val)) {
  9031.                                     return $val;
  9032.                                 }
  9033.                                 return "'" addslashes($val) . "'";
  9034.                             }, $cvalue);
  9035.                             $mustStr .= "`$aliasInCondition`.$cfield IN (" implode(','$formattedValues) . ") ) ";
  9036. //                            $mustStr .= "`$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ) ";
  9037.                         } else if ($ctype == 'not_in') {
  9038.                             $mustStr .= " ( ";
  9039.                             if (in_array('null'$cvalue)) {
  9040.                                 $mustStr .= " `$aliasInCondition`.$cfield is not null";
  9041.                                 $cvalue array_diff($cvalue, ['null']);
  9042.                                 if (!empty($cvalue))
  9043.                                     $mustStr .= " and ";
  9044.                             }
  9045.                             if (in_array(''$cvalue)) {
  9046.                                 $mustStr .= "`$aliasInCondition`.$cfield != '' ";
  9047.                                 $cvalue array_diff($cvalue, ['']);
  9048.                                 if (!empty($cvalue))
  9049.                                     $mustStr .= " and ";
  9050.                             }
  9051.                             $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  9052.                         } else if ($ctype == '=') {
  9053.                             if ($cvalue == 'null' || $cvalue == 'Null')
  9054.                                 $mustStr .= "`$aliasInCondition`.$cfield is null ";
  9055.                             else
  9056.                                 if (is_string($cvalue))
  9057.                                     $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  9058.                                 else
  9059.                                     $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  9060.                         } else if ($ctype == '!=') {
  9061.                             if ($cvalue == 'null' || $cvalue == 'Null')
  9062.                                 $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  9063.                             else
  9064.                                 $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  9065.                         } else {
  9066.                             if (is_string($cvalue))
  9067.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  9068.                             else
  9069.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  9070.                         }
  9071.                     }
  9072.                 }
  9073.                 if ($mustStr != '') {
  9074.                     if ($conditionStr != '')
  9075.                         $conditionStr .= (" and (" $mustStr ") ");
  9076.                     else
  9077.                         $conditionStr .= ("  (" $mustStr ") ");
  9078.                 }
  9079.                 if ($conditionStr != '')
  9080.                     $filterQryForCriteria .= (" and (" $conditionStr ") ");
  9081.                 if ($lastChildrenOnly == 1) {
  9082.                     if ($filterQryForCriteria != '')
  9083.                         $filterQryForCriteria .= ' and ';
  9084.                     $filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  9085.                 } else if ($parentOnly == 1) {
  9086.                     if ($filterQryForCriteria != '')
  9087.                         $filterQryForCriteria .= ' and ';
  9088.                     $filterQryForCriteria .= "`$table`.`$valueField`  in ( select distinct $parentIdField from  $table)";
  9089.                 }
  9090.                 if (!empty($orderByConditions)) {
  9091.                     $filterQryForCriteria .= "  order by ";
  9092.                     $fone 1;
  9093.                     foreach ($orderByConditions as $orderByCondition) {
  9094.                         if ($fone != 1) {
  9095.                             $filterQryForCriteria .= " , ";
  9096.                         }
  9097.                         if (isset($orderByCondition['valueList'])) {
  9098.                             if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  9099.                             if ($orderByCondition['valueList'] == null)
  9100.                                 $orderByCondition['valueList'] = [];
  9101.                             $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  9102.                         } else
  9103.                             $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  9104.                         $fone 0;
  9105.                     }
  9106.                 }
  9107.                 if ($returnTotalMatchedEntriesFlag == 1) {
  9108. //            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9109. //            
  9110. //            $get_kids = $stmt;
  9111.                 }
  9112.                 if ($filterQryForCriteria != '')
  9113.                     if (!empty($setValueArray) || $selectAll == 1) {
  9114.                     } else {
  9115.                         if ($itemLimit != '_ALL_')
  9116.                             $filterQryForCriteria .= "  limit $offset$itemLimit ";
  9117.                         else
  9118.                             $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  9119.                     }
  9120.                 $get_kids_sql $filterQryForCriteria;
  9121.                 $get_kids_sql str_ireplace('_set_matching_value_'''$get_kids_sql);
  9122.                 // TODO: This generic selector assembles SQL across many request-driven table branches.
  9123.                 // Converting it safely requires untangling the shared builder so each branch can bind
  9124.                 // its own parameters without changing selector behavior in unrelated endpoints.
  9125.                 $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9126.                 $get_kids $stmt;
  9127.                 $selectedId 0;
  9128.                 if ($table == 'warehouse_action') {
  9129.                     if (empty($get_kids)) {
  9130.                         $get_kids_sql_2 "select * from warehouse_action";
  9131.                         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql_2);
  9132.                         $get_kids2 $stmt;
  9133.                         if (empty($get_kids2))
  9134.                             $get_kids GeneralConstant::$warehouse_action_list;
  9135.                     }
  9136.                 }
  9137.                 if (!empty($get_kids)) {
  9138.                     $nextOffset $offset count($get_kids);
  9139.                     $nextOffset++;
  9140.                     foreach ($get_kids as $pa) {
  9141.                         if (!empty($setValueArray) && $selectAll == 0) {
  9142.                             if (!in_array($pa[$valueField], $setValueArray))
  9143.                                 continue;
  9144.                         }
  9145.                         if (!empty($restrictionIdList)) {
  9146.                             if (!in_array($pa[$valueField], $restrictionIdList))
  9147.                                 continue;
  9148.                         }
  9149.                         if ($selectAll == || $selectAllFound==1) {
  9150.                             $setValueArray[] = $pa[$valueField];
  9151.                             $setValue $pa[$valueField];
  9152.                         } else if (count($get_kids) == && $setDataForSingle == 1) {
  9153.                             $setValueArray[] = $pa[$valueField];
  9154.                             $setValue $pa[$valueField];
  9155.                         }
  9156.                         if ($valueField != '')
  9157.                             $pa['value'] = $pa[$valueField];
  9158.                         $renderedText $renderTextFormat;
  9159.                         $compare_array = [];
  9160.                         if ($renderTextFormat != '') {
  9161.                             $renderedText $renderTextFormat;
  9162.                             $compare_arrayFull = [];
  9163.                             $compare_array = [];
  9164.                             $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  9165.                             );
  9166.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  9167.                             if (isset($compare_arrayFull[0]))
  9168.                                 $compare_array $compare_arrayFull[0];
  9169. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  9170.                             foreach ($compare_array as $cmpdt) {
  9171.                                 $tbr str_replace("__"""$cmpdt);
  9172.                                 if ($tbr != '') {
  9173.                                     if (isset($pa[$tbr])) {
  9174.                                         if ($pa[$tbr] == null)
  9175.                                             $renderedText str_replace($cmpdt''$renderedText);
  9176.                                         else
  9177.                                             $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  9178.                                     } else {
  9179.                                         $renderedText str_replace($cmpdt''$renderedText);
  9180.                                     }
  9181.                                 }
  9182.                             }
  9183.                         }
  9184.                         $pa['rendered_text'] = $renderedText;
  9185.                         $pa['text'] = ($textField != '' $pa[$textField] : '');
  9186. //                $pa['compare_array'] = $compare_array;
  9187.                         foreach ($convertToObjectFieldList as $convField) {
  9188.                             if (isset($pa[$convField])) {
  9189.                                 $taA json_decode($pa[$convField], true);
  9190.                                 if ($taA == null$taA = [];
  9191.                                 $pa[$convField] = $taA;
  9192.                             } else {
  9193.                                 $pa[$convField] = [];
  9194.                             }
  9195.                         }
  9196.                         foreach ($convertDateToStringFieldList as $convField) {
  9197.                             if (is_array($convField)) {
  9198.                                 $fld $convField['field'];
  9199.                                 $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  9200.                             } else {
  9201.                                 $fld $convField;
  9202.                                 $frmt 'Y-m-d H:i:s';
  9203.                             }
  9204.                             if (isset($pa[$fld])) {
  9205.                                 $taA = new \DateTime($pa[$fld]);
  9206.                                 $pa[$fld] = $taA->format($frmt);
  9207.                             }
  9208.                         }
  9209.                         foreach ($convertToUrl as $convField) {
  9210. //
  9211. //                            $fld = $convField;
  9212. //
  9213. //
  9214. //                            if (isset($pa[$fld])) {
  9215. //
  9216. //
  9217. //                                $pa[$fld] =
  9218. //                                    $this->generateUrl(
  9219. //                                        'dashboard', [
  9220. //
  9221. //                                    ], UrlGenerator::ABSOLUTE_URL
  9222. //                                    ).'/'.$pa[$fld];
  9223. //
  9224. //                            }
  9225.                         }
  9226.                         foreach ($fullPathList as $pathField) {
  9227.                             $fld $pathField;
  9228.                             if (isset($pa[$fld])) {
  9229.                                 if ($pa[$fld] != '' && $pa[$fld] != null) {
  9230.                                     $pa[$fld] = ($this->generateUrl(
  9231.                                             'dashboard', [
  9232.                                         ], UrlGenerator::ABSOLUTE_URL
  9233.                                         ) . $pa[$fld]);
  9234.                                 }
  9235.                             }
  9236.                         }
  9237.                         $pa['currentTs'] = (new \Datetime())->format('U');
  9238.                         $data[] = $pa;
  9239.                         if ($valueField != '') {
  9240.                             $data_by_id[$pa[$valueField]] = $pa;
  9241.                             $selectedId $pa[$valueField];
  9242.                         }
  9243.                     }
  9244.                 }
  9245.                 if ($dataOnly == 1)
  9246.                     $lastResult = array(
  9247.                         'success' => true,
  9248.                         'data' => $data,
  9249.                         'currentTs' => (new \Datetime())->format('U'),
  9250.                         'restrictionIdList' => $restrictionIdList,
  9251.                         'nextOffset' => $nextOffset,
  9252.                         'totalMatchedEntries' => $totalMatchedEntries,
  9253.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  9254.                     );
  9255.                 else
  9256.                     $lastResult = array(
  9257.                         'success' => true,
  9258.                         'data' => $data,
  9259.                         'tableName' => $table,
  9260.                         'setValue' => $setValue,
  9261.                         'currentTs' => (new \Datetime())->format('U'),
  9262.                         'restrictionIdList' => $restrictionIdList,
  9263.                         'andConditions' => $andConditions,
  9264.                         'selectFieldList' => $selectFieldList,
  9265.                         'queryStr' => $queryStringIndividual,
  9266.                         'isMultiple' => $isMultiple,
  9267.                         'nextOffset' => $nextOffset,
  9268.                         'totalMatchedEntries' => $totalMatchedEntries,
  9269.                         'selectorId' => $selectorId,
  9270.                         'setValueArray' => $setValueArray,
  9271.                         'silentChangeSelectize' => $silentChangeSelectize,
  9272.                         'convertToObjectFieldList' => $convertToObjectFieldList,
  9273.                         'conditionStr' => $conditionStr,
  9274.                         'selectAll' => $selectAll,
  9275. //                    'andStr' => $andString,
  9276. //                    'andOrStr' => $andOrString,
  9277.                         'dataById' => $data_by_id,
  9278.                         'selectedId' => $selectedId,
  9279.                         'dataId' => $dataId,
  9280.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  9281.                     );
  9282.             }
  9283.             $allResult[] = $lastResult;
  9284.         }
  9285.         if ($isSingleDataset == 1)
  9286.             return new JsonResponse($lastResult);
  9287.         else
  9288.             return new JsonResponse($allResult);
  9289.     }
  9290.     public function updatePlanningItemSequenceAction(Request $request$queryStr '')
  9291.     {
  9292.         $em $this->getDoctrine()->getManager();
  9293.         $stmt $em->getConnection()->fetchAllAssociative("select  `id` , parent_id, sequence from planning_item where sequence is null 
  9294.             ORDER BY parent_id ASC, id ASC
  9295.                         ");
  9296.         $query_output $stmt;
  9297.         foreach ($query_output as $dupe) {
  9298.             System::updatePlanningItemSequence($em$dupe["id"]);
  9299.         }
  9300.         System::updatePlanningItemSequence(
  9301.             $em,
  9302.             $request->request->get('planningItemId'0),
  9303.             $request->request->get('assignType''_ASSIGN_')   ///can be _MOVE_UP_ or _MOVE_DOWN_
  9304.         );
  9305. //        if($request->query->has('returnJson'))
  9306.         return new JsonResponse(
  9307.             array(
  9308.                 'success' => true,
  9309.                 'data' => [],
  9310.             )
  9311.         );
  9312.     }
  9313.     public function insertDataAjaxAction(Request $request$queryStr '')
  9314.     {
  9315.         $em $this->getDoctrine()->getManager();
  9316. //        if($request->query->has('big_data_test'))
  9317. //        {
  9318. //            for($t=0;$t<$request->request->get('big_data_test',10000);$t++) {
  9319. //                $em = $this->getDoctrine()->getManager('company_group');
  9320. //                $NOTIFICATION = new EntityNotification();
  9321. //                $NOTIFICATION->setAppId(1);
  9322. //                $NOTIFICATION->setCompanyId(0);
  9323. //                $NOTIFICATION->setCompanyId(0);
  9324. //                $NOTIFICATION->setBody('Test Description'.$t);
  9325. //                $NOTIFICATION->setTitle('Test Title'.$t);
  9326. //                $NOTIFICATION->setExpireTs(0);
  9327. //                $NOTIFICATION->setIsBuddybee(0);
  9328. //                $NOTIFICATION->setType(0);
  9329. //                $em->persist($NOTIFICATION);
  9330. //                $em->flush();
  9331. //            }
  9332. //
  9333. //            return new JsonResponse(
  9334. //                array(
  9335. //                    'success' => true,
  9336. //                    'data' => [],
  9337. //
  9338. //
  9339. //                )
  9340. //            );
  9341. //
  9342. //
  9343. //        }
  9344.         if ($request->request->get('entity_group'0)) {
  9345.             $companyId 0;
  9346.             $em $this->getDoctrine()->getManager('company_group');
  9347.         } else
  9348.             $companyId $this->getLoggedUserCompanyId($request);
  9349.         if ($companyId) {
  9350.             $company_data = [];
  9351. //            $company_data = Company::getCompanyData($em, $companyId);
  9352.         } else {
  9353.             $companyId 0;
  9354.             $company_data = [];
  9355.         }
  9356. //        $theEntity= new EntityNotification();
  9357. //        $entityName = 'EntityNotification';
  9358. //
  9359. //        $className='\\CompanyGroupBundle\\Entity\\'.$entityName;
  9360. //
  9361. //
  9362. //            $theEntity= new $className();
  9363.         $dataToAdd $request->request->has('dataToAdd') ? $request->request->get('dataToAdd') : [];
  9364.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  9365.         if ($dataToAdd == null$dataToAdd = [];
  9366.         $dataToRemove $request->request->has('dataToRemove') ? $request->request->get('dataToRemove') : [];
  9367.         if (is_string($dataToRemove)) $dataToAdd json_decode($dataToRemovetrue);
  9368.         if ($dataToRemove == null$dataToRemove = [];
  9369.         $relData = [];
  9370.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  9371.         $updatedDataList = [];
  9372.         foreach ($dataToAdd as $dataInd => $dat) {
  9373.             $entityName $dat['entityName'];
  9374.             $idField $dat['idField'];
  9375.             $findByField = isset($dat['findByField']) ? $dat['findByField'] : '';
  9376.             $findByValue = isset($dat['findByValue']) ? $dat['findByValue'] : '';
  9377.             $returnRefIndex $dat['returnRefIndex'];
  9378.             $findById $dat['findId'];
  9379.             $dataFields = isset($dat['dataFields']) ? $dat['dataFields'] : [];
  9380.             $noCreation = isset($dat['noCreation']) ? $dat['noCreation'] : 0;
  9381.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  9382.             $preAdditionalSql = isset($dat['preAdditionalSql']) ? $dat['preAdditionalSql'] : '';
  9383.             if ($preAdditionalSql != '') {
  9384. //            if ($entityName == 'PlanningItem') {
  9385. //
  9386. //                $stmt='select disctinct parent_id from planning_item;';
  9387. //                
  9388. //                $get_kids = $stmt;
  9389. //                $p_ids=[];
  9390. //                foreach($get_kids as $g)
  9391. //                {
  9392. //                    $p_ids[]=$g['parent_id'];
  9393. //                }
  9394. //
  9395. //
  9396. //
  9397.                 $stmt $em->getConnection()->executeStatement($preAdditionalSql);
  9398. //
  9399. //
  9400.             }
  9401.             if ($entityName == 'PlanningItem') {
  9402.                 $stmt $em->getConnection()->fetchAllAssociative("select  `id` , parent_id, sequence from planning_item where sequence is null
  9403.             ORDER BY parent_id ASC, id ASC
  9404.                         ");
  9405.                 $query_output $stmt;
  9406.                 foreach ($query_output as $dupe) {
  9407.                     System::updatePlanningItemSequence($em$dupe["id"]);
  9408.                 }
  9409.             }
  9410.             $className = ($request->request->get('entity_group'0) ? '\\CompanyGroupBundle\\Entity\\' '\\ApplicationBundle\\Entity\\') . $entityName;
  9411.             if (
  9412.                 ($findById == || $findById == '_NA_') && $findByField == '' && $noCreation == 0
  9413.             ) {
  9414.                 $theEntity = new $className();
  9415. //                $theEntity= new EntityNotification();
  9416.             } else {
  9417.                 if ($findByField != '') {
  9418.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle\\Entity\\' 'ApplicationBundle\\Entity\\') . $entityName)->findOneBy(
  9419.                         array
  9420.                         (
  9421.                             $findByField => $findByValue,
  9422.                         )
  9423.                     );
  9424.                 } else {
  9425.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle\\Entity\\' 'ApplicationBundle\\Entity\\') . $entityName)->findOneBy(
  9426.                         array
  9427.                         (
  9428.                             $idField => $findById,
  9429.                         )
  9430.                     );
  9431.                 }
  9432.             }
  9433.             if (!$theEntity && $noCreation == 0)
  9434.                 $theEntity = new $className();
  9435.             foreach ($dataFields as $dt) {
  9436.                 $setMethod 'set' ucfirst($dt['field']);
  9437.                 $getMethod 'get' ucfirst($dt['field']);
  9438.                 $type = isset($dt['type']) ? $dt['type'] : '_VALUE_';
  9439.                 $action = isset($dt['action']) ? $dt['action'] : '_REPLACE_';
  9440.                 if (method_exists($theEntity$setMethod)) {
  9441.                     $oldValue $theEntity->{$getMethod}();
  9442.                     $newValue $oldValue;
  9443.                     if ($type == '_VALUE_') {
  9444.                         $newValue $dt['value'];
  9445.                     }
  9446.                     if ($type == '_DECIMAL_') {
  9447.                         $newValue $dt['value'];
  9448.                     }
  9449.                     if ($type == '_DATE_') {
  9450.                         $newValue = new \DateTime($dt['value']);
  9451.                     }
  9452.                     if ($type == '_ARRAY_') {
  9453.                         $oldValue json_decode($oldValue);
  9454.                         if ($oldValue == null$oldValue = [];
  9455.                         if ($action == '_REPLACE_') {
  9456.                             $newValue json_encode($dt['value']);
  9457.                         }
  9458.                         if ($action == '_APPEND_') {
  9459.                             $newValue array_merge($oldValuearray_values(array_diff([$dt['value']], $oldValue)));
  9460.                         }
  9461.                         if ($action == '_MERGE_') {
  9462.                             $newValue array_merge($oldValuearray_values(array_diff($dt['value'], $oldValue)));
  9463.                         }
  9464.                         if ($action == '_EXCLUDE_') {
  9465.                             $newValue array_values(array_diff($oldValue, [$dt['value']]));
  9466.                         }
  9467.                         if ($action == '_EXCLUDE_ARRAY_') {
  9468.                             $newValue array_values(array_diff($oldValue$dt['value']));
  9469.                         }
  9470.                         $newValue json_encode($newValue);
  9471.                     }
  9472.                     $theEntity->{$setMethod}($newValue); // `foo!`
  9473. //                    $theEntity->setCompletionPercentage(78); // `foo!`
  9474.                 }
  9475.             }
  9476.             if ($additionalSql != '') {
  9477. //            if ($entityName == 'PlanningItem') {
  9478. //
  9479. //                $stmt='select disctinct parent_id from planning_item;';
  9480. //                
  9481. //                $get_kids = $stmt;
  9482. //                $p_ids=[];
  9483. //                foreach($get_kids as $g)
  9484. //                {
  9485. //                    $p_ids[]=$g['parent_id'];
  9486. //                }
  9487. //
  9488. //
  9489. //
  9490.                 $stmt $em->getConnection()->fetchAllAssociative($additionalSql);
  9491. //
  9492. //
  9493.             }
  9494.             if (($findById == || $findById == '_NA_') && $noCreation == 0) {
  9495.                 $em->persist($theEntity);
  9496.                 $em->flush();
  9497.                 $getMethod 'get' ucfirst($idField);
  9498.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  9499.             } else if ($theEntity) {
  9500.                 $em->flush();
  9501.                 $getMethod 'get' ucfirst($idField);
  9502.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  9503.             }
  9504.             if ($entityName == 'PlanningItem') {
  9505.                 $stmt $em->getConnection()->fetchAllAssociative('select distinct parent_id from planning_item;');
  9506.                 $get_kids $stmt;
  9507.                 $p_ids = [];
  9508.                 foreach ($get_kids as $g) {
  9509.                     $p_ids[] = $g['parent_id'];
  9510.                 }
  9511.                 // Only real parent ids: strip NULL / 0 (top-level marker) so the IN list never has a
  9512.                 // stray/leading comma. Run as TWO separate statements — executeStatement is single-statement.
  9513.                 $p_ids array_values(array_unique(array_filter(array_map('intval'$p_ids))));
  9514.                 if (!empty($p_ids)) {
  9515.                     $idList implode(','$p_ids);
  9516.                     $em->getConnection()->executeStatement('UPDATE planning_item d SET d.`has_child` = 0 WHERE d.id NOT IN (' $idList ')');
  9517.                     $em->getConnection()->executeStatement('UPDATE planning_item d SET d.`has_child` = 1 WHERE d.id IN (' $idList ')');
  9518.                 } else {
  9519.                     // no parents recorded → nothing has children
  9520.                     $em->getConnection()->executeStatement('UPDATE planning_item d SET d.`has_child` = 0');
  9521.                 }
  9522.                 $updatedData System::updatePlanningItemSequence($em$theEntity->getId());
  9523.                 $theEntity $updatedData['primaryOne'];
  9524.                 $theEntityUpdated $theEntity;
  9525.                 if ($theEntityUpdated->getEntryType() == 4)///cashflow
  9526.                 {
  9527.                     MiscActions::AddCashFlowProjection($em0, [
  9528.                         'planningItemId' => $theEntityUpdated->getId(),
  9529.                         'fundRequisitionId' => 0,
  9530.                         'concernedPersonId' => 0,
  9531.                         'type' => 1//exp
  9532.                         'subType' => 1//1== khoroch hobe 2: ashbe
  9533.                         'cashFlowType' => 1//2== RCV /in  1: Payment/out
  9534.                         'creationType' => 1//auto
  9535.                         'amountType' => 1//fund
  9536.                         'cashFlowAmount' => 0,
  9537.                         'expAstAmount' => 0,
  9538.                         'accumulatedCashFlowAmount' => 0,
  9539.                         'accumulatedCashFlowBalance' => 0,
  9540.                         'accumulatedExpAstAmount' => 0,
  9541.                         'relevantExpAstHeadId' => 0,
  9542.                         'balancingHeadId' => 0,
  9543.                         'cashFlowHeadId' => 0,
  9544.                         'cashFlowHeadType' => 1,
  9545.                         'relevantProductIds' => [],
  9546.                         'reminderDateTs' => 0,
  9547.                         'cashFlowDateTs' => 0,
  9548.                         'expAstRealizationDateTs' => 0,
  9549.                     ]);
  9550.                 }
  9551.             } else if ($entityName == 'TaskLog') {
  9552.                 $session $request->getSession();
  9553.                 if ($theEntity) {
  9554.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  9555.                     $currTime = new \DateTime();
  9556.                     $options = array(
  9557.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  9558.                         'notification_server' => $this->container->getParameter('notification_server'),
  9559.                     );
  9560.                     $positionsArray = [
  9561.                         array(
  9562.                             'employeeId' => $empId,
  9563.                             'userId' => $session->get(UserConstants::USER_ID0),
  9564.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  9565.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  9566.                             'lat' => 23.8623834,
  9567.                             'lng' => 90.3979294,
  9568.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING,
  9569. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  9570.                         )
  9571.                     ];
  9572.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  9573.                     if ($positionsArray == null$positionsArray = [];
  9574.                     $dataByAttId = [];
  9575.                     $workPlaceType '_UNSET_';
  9576.                     foreach ($positionsArray as $findex => $d) {
  9577.                         $sysUserId 0;
  9578.                         $userId 0;
  9579.                         $empId 0;
  9580.                         $dtTs 0;
  9581.                         $timeZoneStr '+0000';
  9582.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  9583.                         if (isset($d['userId'])) $userId $d['userId'];
  9584.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  9585.                         if (isset($d['tsMilSec'])) {
  9586.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  9587.                         }
  9588.                         if ($dtTs == 0) {
  9589.                             $currTsTime = new \DateTime();
  9590.                             $dtTs $currTsTime->format('U');
  9591.                         } else {
  9592.                             $currTsTime = new \DateTime('@' $dtTs);
  9593.                         }
  9594.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  9595.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  9596.                         $EmployeeAttendance $this->getDoctrine()
  9597.                             ->getRepository(EmployeeAttendance::class)
  9598.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  9599.                         if (!$EmployeeAttendance) {
  9600.                             $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9601.                             $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9602.                             $EmployeeAttendance = new EmployeeAttendance;
  9603.                         } else {
  9604.                             if ($EmployeeAttendance->getCurrentLocation() == 'out') {
  9605.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9606.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9607.                             } else {
  9608.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  9609.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  9610.                             }
  9611.                         }
  9612.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  9613.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  9614.                             $workPlaceType '_STATIC_';
  9615.                         }
  9616.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  9617.                             $dataByAttId[$attendanceInfo->getId()] = array(
  9618.                                 'attendanceInfo' => $attendanceInfo,
  9619.                                 'empId' => $empId,
  9620.                                 'lat' => 0,
  9621.                                 'lng' => 0,
  9622.                                 'address' => 0,
  9623.                                 'sysUserId' => $sysUserId,
  9624.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  9625.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  9626.                                 'positionArray' => []
  9627.                             );
  9628.                         $posData = array(
  9629.                             'ts' => $dtTs,
  9630.                             'lat' => $d['lat'],
  9631.                             'lng' => $d['lng'],
  9632.                             'marker' => $d['markerId'],
  9633.                             'src' => 2,
  9634.                         );
  9635.                         $posDataArray = array(
  9636.                             $dtTs,
  9637.                             $d['lat'],
  9638.                             $d['lng'],
  9639.                             $d['markerId'],
  9640.                             2
  9641.                         );
  9642.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  9643.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  9644.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  9645.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  9646.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  9647.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  9648.                         if (isset($d['address']))
  9649.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  9650. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  9651.                     }
  9652.                     $response = array(
  9653.                         'success' => true,
  9654.                     );
  9655.                     foreach ($dataByAttId as $attInfoId => $d) {
  9656.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  9657.                             $d['empId'],
  9658.                             $d['sysUserId'],
  9659.                             $d['companyId'],
  9660.                             $d['appId'],
  9661.                             $request,
  9662.                             $d['attendanceInfo'],
  9663.                             $options,
  9664.                             $d['positionArray'],
  9665.                             $d['lat'],
  9666.                             $d['lng'],
  9667.                             $d['address'],
  9668.                             $d['markerId']
  9669.                         );
  9670.                     }
  9671.                     $session->set(UserConstants::USER_CURRENT_TASK_ID$theEntity->getId());
  9672.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$theEntity->getPlanningItemId());
  9673.                 } else {
  9674.                     $session->set(UserConstants::USER_CURRENT_TASK_ID0);
  9675.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID0);
  9676.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  9677.                     $currTime = new \DateTime();
  9678.                     $options = array(
  9679.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  9680.                         'notification_server' => $this->container->getParameter('notification_server'),
  9681.                     );
  9682.                     $positionsArray = [
  9683.                         array(
  9684.                             'employeeId' => $empId,
  9685.                             'userId' => $session->get(UserConstants::USER_ID0),
  9686.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  9687.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  9688.                             'lat' => 23.8623834,
  9689.                             'lng' => 90.3979294,
  9690.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT,
  9691. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  9692.                         )
  9693.                     ];
  9694.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  9695.                     if ($positionsArray == null$positionsArray = [];
  9696.                     $dataByAttId = [];
  9697.                     $workPlaceType '_UNSET_';
  9698.                     foreach ($positionsArray as $findex => $d) {
  9699.                         $sysUserId 0;
  9700.                         $userId 0;
  9701.                         $empId 0;
  9702.                         $dtTs 0;
  9703.                         $timeZoneStr '+0000';
  9704.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  9705.                         if (isset($d['userId'])) $userId $d['userId'];
  9706.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  9707.                         if (isset($d['tsMilSec'])) {
  9708.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  9709.                         }
  9710.                         if ($dtTs == 0) {
  9711.                             $currTsTime = new \DateTime();
  9712.                             $dtTs $currTsTime->format('U');
  9713.                         } else {
  9714.                             $currTsTime = new \DateTime('@' $dtTs);
  9715.                         }
  9716.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  9717.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  9718.                         $EmployeeAttendance $this->getDoctrine()
  9719.                             ->getRepository(EmployeeAttendance::class)
  9720.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  9721.                         if (!$EmployeeAttendance) {
  9722.                             continue;
  9723.                         } else {
  9724.                         }
  9725.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  9726.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT) {
  9727.                             $workPlaceType '_STATIC_';
  9728.                         }
  9729.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  9730.                             $dataByAttId[$attendanceInfo->getId()] = array(
  9731.                                 'attendanceInfo' => $attendanceInfo,
  9732.                                 'empId' => $empId,
  9733.                                 'lat' => 0,
  9734.                                 'lng' => 0,
  9735.                                 'address' => 0,
  9736.                                 'sysUserId' => $sysUserId,
  9737.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  9738.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  9739.                                 'positionArray' => []
  9740.                             );
  9741.                         $posData = array(
  9742.                             'ts' => $dtTs,
  9743.                             'lat' => $d['lat'],
  9744.                             'lng' => $d['lng'],
  9745.                             'marker' => $d['markerId'],
  9746.                             'src' => 2,
  9747.                         );
  9748.                         $posDataArray = array(
  9749.                             $dtTs,
  9750.                             $d['lat'],
  9751.                             $d['lng'],
  9752.                             $d['markerId'],
  9753.                             2
  9754.                         );
  9755.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  9756.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  9757.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  9758.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  9759.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  9760.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  9761.                         if (isset($d['address']))
  9762.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  9763. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  9764.                     }
  9765.                     $response = array(
  9766.                         'success' => true,
  9767.                     );
  9768.                     foreach ($dataByAttId as $attInfoId => $d) {
  9769.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  9770.                             $d['empId'],
  9771.                             $d['sysUserId'],
  9772.                             $d['companyId'],
  9773.                             $d['appId'],
  9774.                             $request,
  9775.                             $d['attendanceInfo'],
  9776.                             $options,
  9777.                             $d['positionArray'],
  9778.                             $d['lat'],
  9779.                             $d['lng'],
  9780.                             $d['address'],
  9781.                             $d['markerId']
  9782.                         );
  9783.                     }
  9784.                 }
  9785.                 $theEntityUpdated $theEntity;
  9786.             } else
  9787.                 $theEntityUpdated $theEntity;
  9788. //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  9789.             $getters = [];
  9790.             if ($theEntityUpdated)
  9791.                 $getters array_filter(get_class_methods($theEntityUpdated), function ($method) {
  9792.                     return 'get' === substr($method03);
  9793.                 });
  9794.             $updatedData = [];
  9795.             foreach ($getters as $getter) {
  9796.                 $indForThis str_replace('get'''$getter);
  9797.                 $indForThis lcfirst($indForThis);
  9798.                 $updatedData[$indForThis] = $theEntityUpdated->{$getter}();
  9799.             }
  9800.             $updatedDataList[$dataInd] = $updatedData;
  9801.         }
  9802.         foreach ($dataToRemove as $dataInd => $dat) {
  9803.             $entityName $dat['entityName'];
  9804.             $idField $dat['idField'];
  9805.             $findById $dat['findId'];
  9806.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  9807.             $theEntityList $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle\\Entity\\' 'ApplicationBundle\\Entity\\') . $entityName)->findBy(
  9808.                 array
  9809.                 (
  9810.                     $idField => $findById,
  9811.                 )
  9812.             );
  9813.             foreach ($theEntityList as $dt) {
  9814.                 $em->remove($dt);
  9815.                 $em->flush();
  9816.             }
  9817.             if ($additionalSql != '') {
  9818. //            if ($entityName == 'PlanningItem') {
  9819. //
  9820. //                $stmt='select disctinct parent_id from planning_item;';
  9821. //                
  9822. //                $get_kids = $stmt;
  9823. //                $p_ids=[];
  9824. //                foreach($get_kids as $g)
  9825. //                {
  9826. //                    $p_ids[]=$g['parent_id'];
  9827. //                }
  9828. //
  9829. //
  9830. //
  9831.                 $stmt $em->getConnection()->fetchAllAssociative($additionalSql);
  9832. //
  9833. //
  9834.             }
  9835.             $updatedDataList[$dataInd] = [];
  9836.         }
  9837. //        if ($table == '') {
  9838. //            return new JsonResponse(
  9839. //                array(
  9840. //                    'success' => false,
  9841. ////                    'page_title' => 'Product Details',
  9842. ////                    'company_data' => $company_data,
  9843. //                    'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9844. //
  9845. //                )
  9846. //            );
  9847. //        }
  9848. //        if($request->query->has('returnJson'))
  9849.         return new JsonResponse(
  9850.             array(
  9851.                 'success' => true,
  9852.                 'data' => $relData,
  9853.                 'updatedDataList' => $updatedDataList,
  9854.             )
  9855.         );
  9856.     }
  9857.     public function GetAvailableQtyAction(Request $request$id 0)
  9858.     {
  9859.         $em $this->getDoctrine()->getManager();
  9860.         $productId $request->request->has('productId') ? $request->request->get('productId') : 0;
  9861.         $colorId $request->request->has('colorId') ? $request->request->get('colorId') : 0;
  9862.         $dataId $request->request->has('dataId') ? $request->request->get('dataId') : 0;
  9863.         $allowedWarehouseIds $request->request->has('warehouseId') ? [$request->request->get('warehouseId')] : [];
  9864.         $allowedWarehouseActionIds $request->request->has('warehouseActionId') ? [$request->request->get('warehouseActionId')] : [];
  9865.         $qty Inventory::getSellableProductQty($em$productId$allowedWarehouseIds$allowedWarehouseActionIds$colorId);
  9866.         return new JsonResponse(array("success" => true,
  9867.             "qty" => $qty,
  9868.             "dataId" => $dataId,
  9869.         ));
  9870.     }
  9871.     public
  9872.     function ProductListSelectAjaxAction(Request $request$queryStr '')
  9873.     {
  9874.         $em $this->getDoctrine()->getManager();
  9875.         $companyId $this->getLoggedUserCompanyId($request);
  9876.         $company_data Company::getCompanyData($em$companyId);
  9877.         $data = [];
  9878.         $data_by_id = [];
  9879.         $html '';
  9880.         $productByCodeData = [];
  9881.         if ($queryStr == '_EMPTY_')
  9882.             $queryStr '';
  9883.         if ($request->request->has('query') && $queryStr == '')
  9884.             $queryStr $request->request->get('queryStr');
  9885.         if ($queryStr == '_EMPTY_')
  9886.             $queryStr '';
  9887. //        $queryStr=urldecode($queryStr);
  9888.         $queryStr str_replace('_FSLASH_''/'$queryStr);
  9889.         $filterQryForCriteria "select * from inv_products where 1=1 ";
  9890.         $filterParams = array();
  9891.         if ($request->request->has('sellableOnly') && $request->request->get('sellableOnly') != 0)
  9892.             $filterQryForCriteria .= " and sellable=1";
  9893.         if ($request->request->has('categorizationValues') && $request->request->get('categorizationValues') != '') {
  9894.             foreach ($request->request->get('categorizationValues') as $level => $value) {
  9895.                 if ($value != '' && $value != 0) {
  9896.                     $searchParam GeneralConstant::$fdmSubCatMarkers[$level] . $value '_';
  9897.                     $paramName 'categorizationValue' $level;
  9898.                     $filterQryForCriteria .= " and product_fdm like :" $paramName " ";
  9899.                     $filterParams[$paramName] = '%' $searchParam '%';
  9900.                 }
  9901.             }
  9902.         }
  9903.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9904.             $filterQryForCriteria .= " and sub_category_id = :subCategoryId";
  9905.         else if ($request->request->has('categoryId') && $request->request->get('categoryId') != '')
  9906.             $filterQryForCriteria .= " and category_id = :categoryId";
  9907.         else if ($request->request->has('igId') && $request->request->get('igId') != '')
  9908.             $filterQryForCriteria .= " and ig_id = :igId";
  9909.         if ($request->request->has('brandId') && $request->request->get('brandId') != '')
  9910.             $filterQryForCriteria .= " and brand_company = :brandId";
  9911.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9912.             $filterParams['subCategoryId'] = (int) $request->request->get('subCategoryId');
  9913.         else if ($request->request->has('categoryId') && $request->request->get('categoryId') != '')
  9914.             $filterParams['categoryId'] = (int) $request->request->get('categoryId');
  9915.         else if ($request->request->has('igId') && $request->request->get('igId') != '')
  9916.             $filterParams['igId'] = (int) $request->request->get('igId');
  9917.         if ($request->request->has('brandId') && $request->request->get('brandId') != '')
  9918.             $filterParams['brandId'] = (int) $request->request->get('brandId');
  9919.         if ($request->request->has('restrictedBrandIds') && $request->request->get('restrictedBrandIds') != []) {
  9920.             $restrictedBrandIds $this->normalizeSqlIntList($request->request->get('restrictedBrandIds'));
  9921.             if (!empty($restrictedBrandIds)) {
  9922.                 $filterQryForCriteria .= " and brand_company in (" $this->buildNamedInClause($restrictedBrandIds'restrictedBrandId'$filterParams) . ")";
  9923.             }
  9924.         }
  9925.         if ($request->request->has('productIds')) {
  9926.             $productIds $this->normalizeSqlIntList($request->request->get('productIds'));
  9927.             if (!empty($productIds)) {
  9928.                 $filterQryForCriteria .= " and id in (" $this->buildNamedInClause($productIds'productId'$filterParams) . ") ";
  9929.             }
  9930.         } else if ($request->request->has('productCode')) {
  9931.             $filterQryForCriteria .= " and product_code like :productCode ";
  9932.             $filterParams['productCode'] = '%' $request->request->get('productCode') . '%';
  9933.         } else if ($queryStr != '') {
  9934.             $filterQryForCriteria .= " and  (product_code like :queryProductCode or `name` like :queryName or model_no like :queryModelNo) ";
  9935.             $filterParams['queryProductCode'] = '%' $queryStr '%';
  9936.             $filterParams['queryName'] = '%' $queryStr '%';
  9937.             $filterParams['queryModelNo'] = '%' $queryStr '%';
  9938.         }
  9939.         if ($filterQryForCriteria != '')
  9940.             $filterQryForCriteria .= "  limit 25";
  9941.         $get_kids_sql $filterQryForCriteria;
  9942. //        if ($request->request->has('productIds'))
  9943. //
  9944. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9945. //        else if ($request->request->has('productCode'))
  9946. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9947. //        else if ($filterQryForCriteria!='')
  9948. //            $get_kids_sql = $filterQryForCriteria;
  9949. //
  9950. //        else
  9951. //               $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";
  9952.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  9953.         $get_kids $stmt;
  9954.         $productId 0;
  9955.         if (!empty($get_kids)) {
  9956.             foreach ($get_kids as $product) {
  9957.                 $pa = array();
  9958.                 $pa['id'] = $product['id'];
  9959.                 $pa['name'] = $product['name'];
  9960.                 $pa['id_name'] = $product['id'] . '. ' $product['name'];
  9961.                 $pa['id_mn'] = $product['id'] . '. ' $product['model_no'];;
  9962.                 $pa['id_name_mn'] = $product['id'] . '. ' $product['name'] . ' ( ' $product['model_no'] . ' )';
  9963.                 $pa['globalId'] = $product['global_id'];
  9964.                 $pa['classSuffix'] = $product['class_suffix'];
  9965.                 $pa['productFdm'] = $product['product_fdm'];
  9966.                 $pa['modelNo'] = $product['model_no'];
  9967.                 $pa['partId'] = $product['part_id'];
  9968.                 $pa['hsCode'] = $product['hs_code'];
  9969.                 $pa['productCode'] = $product['product_code'];
  9970.                 $pa['text'] = $product['name'];
  9971.                 $pa['value'] = $product['id'];
  9972.                 $pa['tac'] = $product['tac'];
  9973.                 $pa['igId'] = $product['ig_id'];
  9974.                 $pa['categoryId'] = $product['category_id'];
  9975.                 $pa['subCategoryId'] = $product['sub_category_id'];
  9976.                 $pa['brandCompany'] = $product['brand_company'];
  9977.                 $pa['sales_price'] = $product['curr_sales_price'];
  9978.                 $pa['purchase_price'] = $product['curr_purchase_price'];
  9979.                 $pa['unit_type'] = $product['unit_type_id'];
  9980.                 $pa['single_weight'] = $product['single_weight'];
  9981.                 $pa['single_weight_variance_type'] = $product['single_weight_variance_type'];
  9982.                 $pa['single_weight_variance_value'] = $product['single_weight_variance_value'];
  9983.                 $pa['weight'] = $product['weight'];
  9984.                 $pa['weight_variance_type'] = $product['weight_variance_type'];
  9985.                 $pa['weight_variance_value'] = $product['weight_variance_value'];
  9986.                 $pa['carton_capacity_count'] = $product['carton_capacity_count'];
  9987.                 $pa['type'] = $product['type'];
  9988.                 $pa['qty'] = $product['qty'];
  9989. //                $pa['alias'] = '';
  9990.                 $pa['alias'] = $product['alias'];
  9991.                 $pa['note'] = $product['note'];
  9992.                 $pa['defaultTaxConfigId'] = $product['default_tax_config_id'] == null $product['default_tax_config_id'];
  9993.                 $pa['defaultPurchaseTaxConfigId'] = $product['default_purchase_tax_config_id'] == null $product['default_purchase_tax_config_id'];
  9994.                 $tax_config_ids json_decode($product['tax_config_ids'], true);
  9995.                 if ($tax_config_ids == null)
  9996.                     $tax_config_ids = [];
  9997.                 $pa['taxConfigIds'] = $tax_config_ids;
  9998.                 $purchase_tax_config_ids json_decode($product['purchase_tax_config_ids'], true);
  9999.                 if ($purchase_tax_config_ids == null)
  10000.                     $purchase_tax_config_ids = [];
  10001.                 $pa['purchaseTaxConfigIds'] = $tax_config_ids;
  10002.                 $inco_terms json_decode($product['inco_terms'], true);
  10003.                 if ($inco_terms == null)
  10004.                     $inco_terms = [];
  10005.                 $pa['incoTerms'] = $inco_terms;
  10006.                 $pa['defaultIncoTerm'] = $product['default_inco_term'] == null $product['default_inco_term'];
  10007.                 $pa['has_serial'] = $product['has_serial'];
  10008.                 $pa['expiry_days'] = $product['expiry_days'];
  10009.                 $pa['image'] = $product['default_image'];
  10010.                 $pa['sales_warranty'] = $product['sales_warranty_months'];;
  10011.                 $pa['defaultColorId'] = $product['default_color_id'];;
  10012.                 $allowedColorIds json_decode($product['colors'], true);
  10013.                 if ($allowedColorIds == null$allowedColorIds = [];
  10014.                 if (!in_array($product['default_color_id'], $allowedColorIds))
  10015.                     $allowedColorIds[] = $product['default_color_id'];
  10016.                 $pa['allowedColorIds'] = $allowedColorIds;;
  10017.                 $data[] = $pa;
  10018.                 $data_by_id[$product['id']] = $pa;
  10019.                 $productId $product['id'];
  10020.             }
  10021.         }
  10022. //        if($request->query->has('returnJson'))
  10023.         {
  10024.             return new JsonResponse(
  10025.                 array(
  10026.                     'success' => true,
  10027. //                    'page_title' => 'Product Details',
  10028. //                    'company_data' => $company_data,
  10029.                     'data' => $data,
  10030.                     'dataById' => $data_by_id,
  10031.                     'productId' => $productId,
  10032.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10033. //                    'exId'=>$id,
  10034. //                'productByCodeData' => $productByCodeData,
  10035. //                'productData' => $productData,
  10036. //                'currInvList' => $currInvList,
  10037. //                'productList' => Inventory::ProductList($em, $companyId),
  10038. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10039. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10040. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10041. //                'unitList' => Inventory::UnitTypeList($em),
  10042. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10043. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10044. //                'warehouseList' => Inventory::WarehouseList($em),
  10045.                 )
  10046.             );
  10047.         }
  10048.     }
  10049.     public function SearchByPopulateQueryAction(Request $request$queryStr '')
  10050.     {
  10051.         $em $this->getDoctrine()->getManager();
  10052.         $companyId $this->getLoggedUserCompanyId($request);
  10053.         $company_data Company::getCompanyData($em$companyId);
  10054.         $data = [];
  10055.         //1st search in products
  10056.         foreach ($request->request->get('queryData', []) as $item) {
  10057.             $dt = array(
  10058.                 'dataId' => $item['dataId'] ?? 0,
  10059.                 'id' => 0,
  10060.                 'fdm' => '',
  10061.             );
  10062.             $qryStrForSearch $item['value'] ?? '';
  10063.             $qryArray explode(','$qryStrForSearch);
  10064.             $checkFields = ['name'];
  10065.             list($qryForSearch$queryParams) = $this->buildTokenizedLikeSearchFragment($checkFields$qryArray'or''populateQueryGroup');
  10066.             //selct item group
  10067.             $igId 0;
  10068.             $catId 0;
  10069.             $parId 0;
  10070.             $brandId 0;
  10071.             $fdmSearchQry = [];
  10072.             $result $em->getConnection()->fetchAllAssociative("select * from inv_item_group where 1=0   " $qryForSearch " limit 1"$queryParams);
  10073.             if (!empty($result)) {
  10074.                 $dt['fdm'] .= ('I' $result[0]['id'] . '_');
  10075.                 $fdmSearchQry[] = ('I' $result[0]['id'] . '_');
  10076.                 $igId $result[0]['id'];
  10077.             }
  10078.             list($qryForSearch$queryParams) = $this->buildTokenizedLikeSearchFragment($checkFields$qryArray'and''populateScopedQueryGroup');
  10079.             //then category
  10080.             $result $em->getConnection()->fetchAllAssociative(
  10081.                 "select * from inv_product_categories where ig_id = :igId " $qryForSearch " limit 1",
  10082.                 array_merge(array('igId' => (int) $igId), $queryParams)
  10083.             );
  10084.             if (!empty($result)) {
  10085.                 $dt['fdm'] .= ('C' $result[0]['id'] . '_');
  10086.                 $fdmSearchQry[] = ('C' $result[0]['id'] . '_');
  10087.                 $catId $result[0]['id'];
  10088.             }
  10089.             //then sub category
  10090.             foreach (GeneralConstant::$fdmSubCatMarkers as $ind => $marker) {
  10091.                 $result $em->getConnection()->fetchAllAssociative(
  10092.                     "select * from inv_product_sub_categories where ig_id = :igId and category_id = :catId and parent_id = :parId " $qryForSearch " limit 1",
  10093.                     array_merge(array(
  10094.                         'igId' => (int) $igId,
  10095.                         'catId' => (int) $catId,
  10096.                         'parId' => (int) $parId,
  10097.                     ), $queryParams)
  10098.                 );
  10099.                 if (!empty($result)) {
  10100.                     $dt['fdm'] .= ($marker $result[0]['id'] . '_');
  10101.                     $fdmSearchQry[] = ($marker $result[0]['id'] . '_');
  10102.                     $parId $result[0]['id'];
  10103.                 }
  10104.             }
  10105.             $result $em->getConnection()->fetchAllAssociative("select * from brand_company where 1=1   " $qryForSearch " limit 1"$queryParams);
  10106.             if (!empty($result)) {
  10107.                 $dt['fdm'] .= ('B' $result[0]['id'] . '_');
  10108.                 $fdmSearchQry[] = ('B' $result[0]['id'] . '_');
  10109.                 $brandId $result[0]['id'];
  10110.             }
  10111.             list($qryForSearch$fdmSearchParams) = $this->buildConjunctiveLikeFragment('product_fdm'$fdmSearchQry'populateFdm');
  10112.             $result $em->getConnection()->fetchAllAssociative("select * from inv_products where 1=1   " $qryForSearch " limit 1"$fdmSearchParams);
  10113.             if (!empty($result)) {
  10114.                 $dt['id'] .= $result[0]['id'];
  10115.             }
  10116.             $data[] = $dt;
  10117.         }
  10118.         return new JsonResponse(
  10119.             array(
  10120.                 'success' => !empty($data) ? true false,
  10121.                 'data' => $data
  10122.             )
  10123.         );
  10124.     }
  10125.     public function addProductByGeneralDataAction(Request $request$queryStr '')
  10126.     {
  10127.         $em $this->getDoctrine()->getManager();
  10128.         $companyId $this->getLoggedUserCompanyId($request);
  10129.         $company_data Company::getCompanyData($em$companyId);
  10130.         $data = [];
  10131.         //1st search in products
  10132.         foreach ($request->request->get('dataList', []) as $item) {
  10133. //            $item=Inventory::GetImmutableKeysForProductSyncFromCentralToLocal();
  10134.             //add each part and if not exists, add it
  10135.             $currProductInfo = array(
  10136.                 'dataId' => $item['dataId'] ?? 0,
  10137.                 'id' => 0,
  10138.                 'igId' => 0,
  10139.                 'categoryId' => 0,
  10140.                 'subCategoryIds' => [
  10141.                     => 0,
  10142.                 ],
  10143.                 'fdm' => '',
  10144.             );
  10145.             //iten group
  10146.             if (isset($item['ItemGroup'])) {
  10147.                 $result $em->getConnection()->fetchAllAssociative(
  10148.                     "select * from inv_item_group where id = :itemGroupId or name like :itemGroupName limit 1",
  10149.                     array(
  10150.                         'itemGroupId' => (int) ($item['ItemGroup']['Id'] ?? 0),
  10151.                         'itemGroupName' => (string) ($item['ItemGroup']['Name'] ?? 0),
  10152.                     )
  10153.                 );
  10154.                 if (!empty($result)) {
  10155.                     $currProductInfo['igId'] = $result[0]['id'];
  10156.                 } else {
  10157.                     Inventory::CreateItemGroup($em1);
  10158.                 }
  10159.             }
  10160.             $dt = array(
  10161.                 'dataId' => $item['dataId'] ?? 0,
  10162.                 'id' => 0,
  10163.                 'fdm' => '',
  10164.             );
  10165.             $qryStrForSearch $item['value'] ?? '';
  10166.             $qryArray explode(','$qryStrForSearch);
  10167.             $checkFields = ['name'];
  10168.             list($qryForSearch$queryParams) = $this->buildFlatLikeSearchFragment($checkFields$qryArray'and''generalDataQuery');
  10169.             //selct item group
  10170.             $igId 0;
  10171.             $catId 0;
  10172.             $parId 0;
  10173.             $brandId 0;
  10174.             $fdmSearchQry = [];
  10175.             $result $em->getConnection()->fetchAllAssociative("select * from inv_item_group where 1=1 " $qryForSearch " limit 1"$queryParams);
  10176.             if (!empty($result)) {
  10177.                 $dt['fdm'] .= ('I' $result[0]['id'] . '_');
  10178.                 $fdmSearchQry[] = ('I' $result[0]['id'] . '_');
  10179.                 $igId $result[0]['id'];
  10180.             }
  10181.             //then category
  10182.             $result $em->getConnection()->fetchAllAssociative(
  10183.                 "select * from inv_product_categories where ig_id = :igId " $qryForSearch " limit 1",
  10184.                 array_merge(array('igId' => (int) $igId), $queryParams)
  10185.             );
  10186.             if (!empty($result)) {
  10187.                 $dt['fdm'] .= ('C' $result[0]['id'] . '_');
  10188.                 $fdmSearchQry[] = ('C' $result[0]['id'] . '_');
  10189.                 $catId $result[0]['id'];
  10190.             }
  10191.             //then sub category
  10192.             foreach (GeneralConstant::$fdmSubCatMarkers as $ind => $marker) {
  10193.                 $result $em->getConnection()->fetchAllAssociative(
  10194.                     "select * from inv_product_sub_categories where ig_id = :igId and category_id = :catId and parent_id = :parId " $qryForSearch " limit 1",
  10195.                     array_merge(array(
  10196.                         'igId' => (int) $igId,
  10197.                         'catId' => (int) $catId,
  10198.                         'parId' => (int) $parId,
  10199.                     ), $queryParams)
  10200.                 );
  10201.                 if (!empty($result)) {
  10202.                     $dt['fdm'] .= ($marker $result[0]['id'] . '_');
  10203.                     $fdmSearchQry[] = ($marker $result[0]['id'] . '_');
  10204.                     $parId $result[0]['id'];
  10205.                 }
  10206.             }
  10207.             $result $em->getConnection()->fetchAllAssociative("select * from brand_company where 1=1 " $qryForSearch " limit 1"$queryParams);
  10208.             if (!empty($result)) {
  10209.                 $dt['fdm'] .= ('B' $result[0]['id'] . '_');
  10210.                 $fdmSearchQry[] = ('B' $result[0]['id'] . '_');
  10211.                 $brandId $result[0]['id'];
  10212.             }
  10213.             list($qryForSearch$fdmSearchParams) = $this->buildConjunctiveLikeFragment('product_fdm'$fdmSearchQry'generalDataFdm');
  10214.             $result $em->getConnection()->fetchAllAssociative("select * from inv_products where 1=1 " $qryForSearch " limit 1"$fdmSearchParams);
  10215.             if (!empty($result)) {
  10216.                 $dt['id'] .= $result[0]['id'];
  10217.             }
  10218.             $data[] = $dt;
  10219.         }
  10220.         return new JsonResponse(
  10221.             array(
  10222.                 'success' => empty($data) ? true false,
  10223.                 'data' => $data
  10224.             )
  10225.         );
  10226.     }
  10227.     public function labelFormatSelectAjaxAction(Request $request$queryStr '')
  10228.     {
  10229.         $em $this->getDoctrine()->getManager();
  10230.         $companyId $this->getLoggedUserCompanyId($request);
  10231.         $company_data Company::getCompanyData($em$companyId);
  10232.         $data = [];
  10233.         $data_by_id = [];
  10234.         $html '';
  10235.         $productByCodeData = [];
  10236.         if ($queryStr == '_EMPTY_')
  10237.             $queryStr '';
  10238.         if ($request->request->has('query') && $queryStr == '')
  10239.             $queryStr $request->request->get('queryStr');
  10240.         if ($queryStr == '_EMPTY_')
  10241.             $queryStr '';
  10242.         $filterQryForCriteria "select * from label_format where company_id = :companyId ";
  10243.         $filterParams = array(
  10244.             'companyId' => (int) $companyId,
  10245.         );
  10246.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  10247.             $filterQryForCriteria .= " and label_type = :dataType";
  10248.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  10249.             $filterQryForCriteria .= " and format_id = :formatId";
  10250.         else if ($queryStr != '') {
  10251.             $filterQryForCriteria .= " and (`name` like :labelNameQuery or `format_code` like :labelCodeQuery) ";
  10252.             $filterParams['labelNameQuery'] = '%' $queryStr '%';
  10253.             $filterParams['labelCodeQuery'] = '%' $queryStr '%';
  10254.         }
  10255.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  10256.             $filterParams['dataType'] = (int) $request->request->get('dataType');
  10257.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  10258.             $filterParams['formatId'] = (int) $request->request->get('formatId');
  10259.         if ($filterQryForCriteria != '')
  10260.             $filterQryForCriteria .= "  limit 25";
  10261.         $get_kids_sql $filterQryForCriteria;
  10262. //        if ($request->request->has('productIds'))
  10263. //
  10264. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  10265. //        else if ($request->request->has('productCode'))
  10266. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  10267. //        else if ($filterQryForCriteria!='')
  10268. //            $get_kids_sql = $filterQryForCriteria;
  10269. //
  10270. //        else
  10271. //               $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";
  10272.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  10273.         $get_kids $stmt;
  10274.         $productId 0;
  10275.         if (!empty($get_kids)) {
  10276.             foreach ($get_kids as $product) {
  10277.                 $pa = array();
  10278.                 $pa['id'] = $product['format_id'];
  10279.                 $pa['name'] = $product['name'];
  10280.                 $pa['format_code'] = $product['format_code'] . '. ' $product['name'];
  10281.                 $pa['id_code_name'] = $product['format_id'] . '. ' $product['format_code'] . ' - ' $product['name'] . ' ';
  10282.                 $pa['text'] = $product['name'];
  10283.                 $pa['value'] = $product['format_id'];
  10284.                 $data[] = $pa;
  10285.                 $data_by_id[$product['format_id']] = $pa;
  10286.                 $productId $product['format_id'];
  10287.             }
  10288.         }
  10289. //        if($request->query->has('returnJson'))
  10290.         {
  10291.             return new JsonResponse(
  10292.                 array(
  10293.                     'success' => true,
  10294. //                    'page_title' => 'Product Details',
  10295. //                    'company_data' => $company_data,
  10296.                     'data' => $data,
  10297.                     'dataById' => $data_by_id,
  10298.                     'productId' => $productId,
  10299.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10300. //                    'exId'=>$id,
  10301. //                'productByCodeData' => $productByCodeData,
  10302. //                'productData' => $productData,
  10303. //                'currInvList' => $currInvList,
  10304. //                'productList' => Inventory::ProductList($em, $companyId),
  10305. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10306. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10307. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10308. //                'unitList' => Inventory::UnitTypeList($em),
  10309. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10310. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10311. //                'warehouseList' => Inventory::WarehouseList($em),
  10312.                 )
  10313.             );
  10314.         }
  10315.     }
  10316.     public function CategoryListSelectAjaxAction(Request $request$queryStr '')
  10317.     {
  10318.         $em $this->getDoctrine()->getManager();
  10319.         $companyId $this->getLoggedUserCompanyId($request);
  10320.         $company_data Company::getCompanyData($em$companyId);
  10321.         $data = [];
  10322.         $data_by_id = [];
  10323.         $html '';
  10324.         $productByCodeData = [];
  10325.         if ($queryStr == '_EMPTY_')
  10326.             $queryStr '';
  10327.         if ($request->request->has('query') && $queryStr == '')
  10328.             $queryStr $request->request->get('queryStr');
  10329.         if ($queryStr == '_EMPTY_')
  10330.             $queryStr '';
  10331.         $filterQryForCriteria "select * from inv_product_categories where company_id = :companyId ";
  10332.         $filterParams = array(
  10333.             'companyId' => (int) $companyId,
  10334.             'categoryNameQuery' => '%' $queryStr '%',
  10335.         );
  10336.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10337.             $filterQryForCriteria .= " and ig_id = :igId";
  10338.         $filterQryForCriteria .= " and (`name` like :categoryNameQuery) ";
  10339.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10340.             $filterParams['igId'] = (int) $request->request->get('igId');
  10341.         if ($filterQryForCriteria != '')
  10342.             $filterQryForCriteria .= "  limit 25";
  10343.         $get_kids_sql $filterQryForCriteria;
  10344. //        if ($request->request->has('productIds'))
  10345. //
  10346. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  10347. //        else if ($request->request->has('productCode'))
  10348. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  10349. //        else if ($filterQryForCriteria!='')
  10350. //            $get_kids_sql = $filterQryForCriteria;
  10351. //
  10352. //        else
  10353. //               $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";
  10354.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  10355.         $get_kids $stmt;
  10356.         $productId 0;
  10357.         if (!empty($get_kids)) {
  10358.             foreach ($get_kids as $product) {
  10359.                 $pa = array();
  10360.                 $pa['id'] = $product['id'];
  10361.                 $pa['name'] = $product['name'];
  10362.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  10363.                 $pa['globalId'] = $product['global_id'];
  10364.                 $pa['text'] = $product['name'];
  10365.                 $pa['value'] = $product['id'];
  10366.                 $pa['igId'] = $product['ig_id'];
  10367. //                $pa['categoryId'] = $product['category_id'];
  10368. //                $pa['subCategoryId'] = $product['sub_category_id'];
  10369.                 $data[] = $pa;
  10370.                 $data_by_id[$product['id']] = $pa;
  10371.                 $productId $product['id'];
  10372.             }
  10373.         }
  10374. //        if($request->query->has('returnJson'))
  10375.         {
  10376.             return new JsonResponse(
  10377.                 array(
  10378.                     'success' => true,
  10379. //                    'page_title' => 'Product Details',
  10380. //                    'company_data' => $company_data,
  10381.                     'data' => $data,
  10382.                     'dataById' => $data_by_id,
  10383.                     'productId' => $productId,
  10384.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10385. //                    'exId'=>$id,
  10386. //                'productByCodeData' => $productByCodeData,
  10387. //                'productData' => $productData,
  10388. //                'currInvList' => $currInvList,
  10389. //                'productList' => Inventory::ProductList($em, $companyId),
  10390. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10391. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10392. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10393. //                'unitList' => Inventory::UnitTypeList($em),
  10394. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10395. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10396. //                'warehouseList' => Inventory::WarehouseList($em),
  10397.                 )
  10398.             );
  10399.         }
  10400.     }
  10401.     public function SubCategoryListSelectAjaxAction(Request $request$queryStr '')
  10402.     {
  10403.         $em $this->getDoctrine()->getManager();
  10404.         $companyId $this->getLoggedUserCompanyId($request);
  10405.         $company_data Company::getCompanyData($em$companyId);
  10406.         $data = [];
  10407.         $data_by_id = [];
  10408.         $html '';
  10409.         $productByCodeData = [];
  10410.         if ($queryStr == '_EMPTY_')
  10411.             $queryStr '';
  10412.         if ($request->request->has('query') && $queryStr == '')
  10413.             $queryStr $request->request->get('queryStr');
  10414.         if ($queryStr == '_EMPTY_')
  10415.             $queryStr '';
  10416.         $filterQryForCriteria "select * from inv_product_sub_categories where company_id = :companyId ";
  10417.         $filterParams = array(
  10418.             'companyId' => (int) $companyId,
  10419.             'subCategoryNameQuery' => '%' $queryStr '%',
  10420.         );
  10421.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  10422.             $filterQryForCriteria .= " and sub_category_id = :subCategoryId";
  10423.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  10424.             $filterQryForCriteria .= " and category_id = :categoryId";
  10425.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10426.             $filterQryForCriteria .= " and ig_id = :igId";
  10427.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  10428.             if ($request->request->get('parentId') != 0)
  10429.                 $filterQryForCriteria .= " and parent_id = :parentId";
  10430.             else
  10431.                 $filterQryForCriteria .= " and ( parent_id =0 or parent_id is null ) ";
  10432.         if ($request->request->has('level') && $request->request->get('level') != '')
  10433.             if ($request->request->get('level') != 0)
  10434.                 $filterQryForCriteria .= " and level = :level";
  10435.             else
  10436.                 $filterQryForCriteria .= " and ( level =0 or level is null) ";
  10437.         $filterQryForCriteria .= " and (`name` like :subCategoryNameQuery) ";
  10438.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  10439.             $filterParams['subCategoryId'] = (int) $request->request->get('subCategoryId');
  10440.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  10441.             $filterParams['categoryId'] = (int) $request->request->get('categoryId');
  10442.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10443.             $filterParams['igId'] = (int) $request->request->get('igId');
  10444.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  10445.             if ($request->request->get('parentId') != 0)
  10446.                 $filterParams['parentId'] = (int) $request->request->get('parentId');
  10447.         if ($request->request->has('level') && $request->request->get('level') != '')
  10448.             if ($request->request->get('level') != 0)
  10449.                 $filterParams['level'] = (int) $request->request->get('level');
  10450.         if ($filterQryForCriteria != '')
  10451.             $filterQryForCriteria .= "  limit 25";
  10452.         $get_kids_sql $filterQryForCriteria;
  10453. //        if ($request->request->has('productIds'))
  10454. //
  10455. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  10456. //        else if ($request->request->has('productCode'))
  10457. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  10458. //        else if ($filterQryForCriteria!='')
  10459. //            $get_kids_sql = $filterQryForCriteria;
  10460. //
  10461. //        else
  10462. //               $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";
  10463.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  10464.         $get_kids $stmt;
  10465.         $productId 0;
  10466.         if (!empty($get_kids)) {
  10467.             foreach ($get_kids as $product) {
  10468.                 $pa = array();
  10469.                 $pa['id'] = $product['id'];
  10470.                 $pa['name'] = $product['name'];
  10471.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  10472.                 $pa['globalId'] = $product['global_id'];
  10473.                 $pa['parentId'] = $product['parent_id'];
  10474.                 $pa['text'] = $product['name'];
  10475.                 $pa['value'] = $product['id'];
  10476.                 $pa['igId'] = $product['ig_id'];
  10477.                 $pa['categoryId'] = $product['category_id'];
  10478. //                $pa['subCategoryId'] = $product['sub_category_id'];
  10479.                 $data[] = $pa;
  10480.                 $data_by_id[$product['id']] = $pa;
  10481.                 $productId $product['id'];
  10482.             }
  10483.         }
  10484. //        if($request->query->has('returnJson'))
  10485.         {
  10486.             return new JsonResponse(
  10487.                 array(
  10488.                     'success' => true,
  10489. //                    'page_title' => 'Product Details',
  10490. //                    'company_data' => $company_data,
  10491.                     'data' => $data,
  10492.                     'dataById' => $data_by_id,
  10493.                     'productId' => $productId,
  10494.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10495. //                    'exId'=>$id,
  10496. //                'productByCodeData' => $productByCodeData,
  10497. //                'productData' => $productData,
  10498. //                'currInvList' => $currInvList,
  10499. //                'productList' => Inventory::ProductList($em, $companyId),
  10500. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10501. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10502. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10503. //                'unitList' => Inventory::UnitTypeList($em),
  10504. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10505. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10506. //                'warehouseList' => Inventory::WarehouseList($em),
  10507.                 )
  10508.             );
  10509.         }
  10510.     }
  10511.     public
  10512.     function ProductByCodeViewAction(Request $request$id 0)
  10513.     {
  10514.         $em $this->getDoctrine()->getManager();
  10515.         $companyId $this->getLoggedUserCompanyId($request);
  10516.         $company_data Company::getCompanyData($em$companyId);
  10517.         $data = [];
  10518.         $html '';
  10519.         $productByCodeData = [];
  10520.         if ($id != 0) {
  10521.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10522.                 ->findOneBy(
  10523.                     array(
  10524.                         'productByCodeId' => $id
  10525.                     )
  10526.                 );
  10527.         } else {
  10528.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10529.                 ->findOneBy(
  10530.                     array(
  10531. //                        'productByCodeId' => $id,
  10532.                         'CompanyId' => $companyId
  10533.                     ), array(
  10534.                         'productByCodeId' => 'DESC'
  10535.                     )
  10536.                 );
  10537.             if ($productByCodeData)
  10538.                 $id $productByCodeData->getProductByCodeId();
  10539.         }
  10540.         if ($id != 0) {
  10541.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  10542.                 ->findOneBy(
  10543.                     array(
  10544.                         'id' => $productByCodeData->getProductId()
  10545.                     )
  10546.                 );
  10547.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  10548.                 ->findBy(
  10549.                     array(
  10550.                         'productId' => $id
  10551.                     )
  10552.                 );
  10553.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  10554.                 array(
  10555.                     'page_title' => 'Product Details',
  10556.                     'company_data' => $company_data,
  10557.                     'productByCodeData' => $productByCodeData,
  10558.                     'productData' => $productData,
  10559.                     'currInvList' => $currInvList,
  10560.                     'exId' => $id,
  10561.                     'clientList' => Client::GetExistingClientList($em$companyId),
  10562.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  10563.                     'productList' => Inventory::ProductList($em$companyId),
  10564.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10565.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10566.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10567.                     'unitList' => Inventory::UnitTypeList($em),
  10568.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10569.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10570.                     'warehouseList' => Inventory::WarehouseList($em),
  10571.                 )
  10572.             );
  10573.         } else {
  10574.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  10575.                 array(
  10576.                     'exId' => $id,
  10577.                 )
  10578.             );
  10579.         }
  10580.         if ($request->query->has('returnJson')) {
  10581.             return new JsonResponse(
  10582.                 array(
  10583.                     'success' => true,
  10584.                     'page_title' => 'Product Details',
  10585.                     'company_data' => $company_data,
  10586.                     'renderedHtml' => $html,
  10587.                     'exId' => $id,
  10588. //                'productByCodeData' => $productByCodeData,
  10589. //                'productData' => $productData,
  10590. //                'currInvList' => $currInvList,
  10591. //                'productList' => Inventory::ProductList($em, $companyId),
  10592. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10593. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10594. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10595. //                'unitList' => Inventory::UnitTypeList($em),
  10596. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10597. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10598. //                'warehouseList' => Inventory::WarehouseList($em),
  10599.                 )
  10600.             );
  10601.         } else {
  10602. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10603. //                ->findBy(
  10604. //                    array(
  10605. ////                        'productByCodeId' => $id,
  10606. //                    'CompanyId'=>$companyId
  10607. //                    )
  10608. //                );
  10609.             $productByCodeList = []; //called by ajax
  10610.             return $this->render('@Inventory/pages/views/product_by_code_view.html.twig',
  10611.                 array(
  10612.                     'page_title' => 'Product Details',
  10613.                     'company_data' => $company_data,
  10614.                     'renderedHtml' => $html,
  10615.                     'exId' => $id,
  10616.                     'productByCodeList' => $productByCodeList,
  10617. //                'productByCodeData' => $productByCodeData,
  10618. //                'productData' => $productData,
  10619. //                'currInvList' => $currInvList,
  10620. //                'productList' => Inventory::ProductList($em, $companyId),
  10621. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10622. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10623. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10624. //                'unitList' => Inventory::UnitTypeList($em),
  10625. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10626. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10627. //                'warehouseList' => Inventory::WarehouseList($em),
  10628.                 )
  10629.             );
  10630.         }
  10631.     }
  10632.     public
  10633.     function ConsumptionSettingsAction(Request $request$id)
  10634.     {
  10635.         $cc_id '';
  10636.         $cc_name '';
  10637.         $em $this->getDoctrine()->getManager();
  10638.         $companyId $this->getLoggedUserCompanyId($request);
  10639.         $consumptionTypeId 0;
  10640.         if ($request->isMethod('POST')) {
  10641.             $new_cc = [];
  10642.             if ($request->request->get('consumptionTypeId') != '' && $request->request->get('consumptionTypeId') != 0) {
  10643.                 $em $this->getDoctrine()->getManager();
  10644.                 $new_cc $this->getDoctrine()
  10645.                     ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  10646.                     ->findOneBy(
  10647.                         array(
  10648.                             'consumptionTypeId' => $request->request->get('consumptionTypeId'),
  10649.                         )
  10650.                     );
  10651.                 $new_cc->setName($request->request->get('name'));
  10652.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  10653.                 $new_cc->setCompanyId($companyId);
  10654.                 $em->flush();
  10655.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  10656.                 $this->addFlash(
  10657.                     'success',
  10658.                     'Consumption Information Updated'
  10659.                 );
  10660.             } else {
  10661.                 $new_cc = new ConsumptionType();
  10662.                 $new_cc->setName($request->request->get('name'));
  10663.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  10664.                 $new_cc->setCompanyId($companyId);
  10665.                 $em->persist($new_cc);
  10666.                 $em->flush();
  10667.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  10668.                 $em->flush();
  10669.                 $this->addFlash(
  10670.                     'success',
  10671.                     'New Consumption Type Added'
  10672.                 );
  10673.             }
  10674.         }
  10675.         $extData = [];
  10676.         if ($id != 0) {
  10677.             $extData $this->getDoctrine()
  10678.                 ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  10679.                 ->findOneBy(
  10680.                     array(
  10681.                         'consumptionTypeId' => $id
  10682.                     )
  10683.                 );
  10684. //            $cc_data_list = [];
  10685. //            foreach ($cc_data as $value) {
  10686. //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  10687. //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  10688. //
  10689. //                if ($value->getSupplierCategoryId() == $id) {
  10690. //                    $cc_id = $value->getSupplierCategoryId();
  10691. //                    $cc_name = $value->getName();
  10692. //                }
  10693. //            }
  10694.         }
  10695.         return $this->render('@Inventory/pages/input_forms/consumption_settings.html.twig',
  10696.             array(
  10697.                 'page_title' => 'Consumption Settings',
  10698.                 'consumptionTypeList' => $this->getDoctrine()
  10699.                     ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  10700.                     ->findBy(
  10701.                         array(
  10702.                             'CompanyId' => $companyId
  10703.                         )
  10704.                     ),
  10705.                 'extData' => $extData,
  10706.                 'headList' => Accounts::getParentLedgerHeads($em),
  10707. //                'countryList'=>SalesOrderM::Co
  10708.             )
  10709.         );
  10710.     }
  10711.     public
  10712.     function ProductByCodeCheckAssignPrintAction(Request $request$id 0)
  10713.     {
  10714.         $em $this->getDoctrine()->getManager();
  10715.         $companyId $this->getLoggedUserCompanyId($request);
  10716.         $company_data Company::getCompanyData($em$companyId);
  10717.         $data = [];
  10718.         $html '';
  10719.         $productByCodeData = [];
  10720.         $productDataWeightPackageGm '';
  10721.         $productDataWeightVarianceValue 0;
  10722.         $productDataWeightVarianceType 0;
  10723.         $productByCodeDataObj = [];
  10724.         $dr_id 0;//for dr_id
  10725.         $skipRenderData 0;
  10726.         if ($request->query->has('skipRenderData'))
  10727.             $skipRenderData $request->query->get('skipRenderData');
  10728.         if ($id != 0) {
  10729.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10730.                 ->findOneBy(
  10731.                     array(
  10732.                         'productByCodeId' => $id
  10733.                     )
  10734.                 );
  10735.         } else {
  10736.             if ($request->query->has('scanCode')) {
  10737.                 $query $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10738.                     ->createQueryBuilder('p');
  10739.                 if ($request->query->has('assigned')) {
  10740.                     $query->where('p.assigned > :av')
  10741.                         ->setParameter('av'$request->query->get('assigned'));
  10742.                 } else
  10743.                     $query->where("1=0");
  10744.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  10745.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  10746.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  10747.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  10748.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  10749.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  10750.                 $query->setMaxResults(1);
  10751.                 $results $query->getQuery()->getResult();
  10752.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  10753.             } else
  10754.                 $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10755.                     ->findOneBy(
  10756.                         array(
  10757. //                        'productByCodeId' => $id,
  10758.                             'CompanyId' => $companyId
  10759.                         ), array(
  10760.                             'productByCodeId' => 'DESC'
  10761.                         )
  10762.                     );
  10763.             if ($productByCodeData)
  10764.                 $id $productByCodeData->getProductByCodeId();
  10765.         }
  10766.         if ($id != 0) {
  10767.             $productByCodeDataObj = array(
  10768.                 'salesCode' => $productByCodeData->getSalesCode(),
  10769.                 'sales_code' => $productByCodeData->getSalesCode(),
  10770.                 'sn' => $productByCodeData->getSerialNo(),
  10771.                 'serialNo' => $productByCodeData->getSerialNo(),
  10772.                 'imei1' => $productByCodeData->getImei1(),
  10773.                 'imei2' => $productByCodeData->getImei2(),
  10774.                 'soId' => $productByCodeData->getSalesOrderId(),
  10775.                 'poId' => $productByCodeData->getPurchaseOrderId(),
  10776.                 'irrId' => $productByCodeData->getIrrId(),
  10777.                 'productId' => $productByCodeData->getProductId(),
  10778.                 'productByCodeId' => $productByCodeData->getProductByCodeId(),
  10779.                 'warehouseId' => $productByCodeData->getWarehouseId(),
  10780.                 'warehouseActionId' => $productByCodeData->getWarehouseActionId(),
  10781.                 'stId' => $productByCodeData->getStockTransferId(),
  10782.                 'srId' => $productByCodeData->getStockReceivedNoteId(),
  10783.                 'scmpId' => $productByCodeData->getStockConsumptionNoteId(),
  10784.                 'clientId' => $productByCodeData->getClientId(),
  10785.                 'supplierId' => $productByCodeData->getSupplierId(),
  10786.                 'drId' => $productByCodeData->getDeliveryReceiptId(),
  10787.                 'consumerName' => $productByCodeData->getConsumerName(),
  10788.                 'drItemData' => [],
  10789. //                'salesCodes' => $productByCodeData->getDeliveryReceiptId(),
  10790.             );
  10791.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  10792.                 ->findOneBy(
  10793.                     array(
  10794.                         'id' => $productByCodeData->getProductId()
  10795.                     )
  10796.                 );
  10797.             if ($productByCodeData->getProductionId() != null) {
  10798.                 $productionDataHere $em->getRepository('ApplicationBundle\\Entity\\Production')
  10799.                     ->findOneBy(
  10800.                         array(
  10801.                             'productionId' => $productByCodeData->getProductionId()
  10802.                         )
  10803.                     );
  10804.                 if ($productionDataHere) {
  10805.                     $productDataWeightPackageGm $productionDataHere->getPackageWeight();
  10806.                     $productDataWeightVarianceValue $productionDataHere->getPackageWeightVarianceValue();
  10807.                     $productDataWeightVarianceType $productionDataHere->getPackageWeightVarianceType();
  10808.                 }
  10809.             } else {
  10810.                 if ($productData) {
  10811.                     $productDataWeightPackageGm $productData->getWeight();
  10812.                     $productDataWeightVarianceValue $productData->getWeightVarianceValue();
  10813.                     $productDataWeightVarianceType $productData->getWeightVarianceType();
  10814.                 }
  10815.             }
  10816.             if ($productData) {
  10817.                 $productByCodeDataObj['unitTypeId'] = $productData->getUnitTypeId();
  10818.                 $productByCodeDataObj['purchasePrice'] = $productData->getPurchasePrice();
  10819.                 $productByCodeDataObj['productFdm'] = $productData->getProductFdm();
  10820.                 $productByCodeDataObj['productName'] = $productData->getName();
  10821.                 if ($request->request->has('forSalesReturn') || $request->query->has('forSalesReturn')) {
  10822.                     $QD $this->getDoctrine()
  10823.                         ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  10824.                         ->findOneBy(
  10825.                             array(
  10826.                                 'deliveryReceiptId' => $productByCodeData->getDeliveryReceiptId(),
  10827.                                 'productId' => $productByCodeData->getProductId(),
  10828.                             )
  10829.                         );
  10830. //            if($request->request->get('wareHouseId')!='')
  10831.                     if ($QD) {
  10832.                         $new_pid $QD->getProductId();
  10833.                         $sales_code_range = [];
  10834.                         if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  10835.                             $sales_code_range json_decode($QD->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  10836.                         } else {
  10837.                             $max_int_length strlen((string)PHP_INT_MAX) - 1;
  10838.                             $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$QD->getSalesCodeRange());
  10839.                             $sales_code_range json_decode($json_without_bigintstrue);
  10840.                         }
  10841.                         $p_data = array(
  10842.                             'details_id' => $QD->getId(),
  10843.                             'productId' => $new_pid,
  10844.                             'dr_id' => $productByCodeData->getDeliveryReceiptId(),
  10845.                             'product_name' => $productData->getName(),
  10846.                             'qty' => $QD->getQty(),
  10847.                             'delivered' => $QD->getDelivered(),
  10848.                             'unitTypeId' => $QD->getUnitTypeId(),
  10849.                             'deliverable' => $QD->getDeliverable(),
  10850.                             'balance' => $QD->getBalance(),
  10851.                             'salesCodeRangeStr' => $QD->getSalesCodeRange(),
  10852.                             'salesCodeRange' => $sales_code_range,
  10853.                             'sales_codes' => $sales_code_range,
  10854.                             'sales_price' => $QD->getPrice(),
  10855.                             'purchase_price' => $QD->getCurrentPurchasePrice()
  10856. //                        'delivered'=>$product->getDelivered(),
  10857.                         );
  10858.                         $productByCodeDataObj['drItemData'][] = $p_data;
  10859.                     }
  10860.                 }
  10861.             }
  10862.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  10863.                 ->findBy(
  10864.                     array(
  10865.                         'productId' => $id
  10866.                     )
  10867.                 );
  10868.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  10869.                 array(
  10870.                     'page_title' => 'Details',
  10871.                     'company_data' => $company_data,
  10872.                     'productByCodeData' => $productByCodeData,
  10873.                     'productByCodeDataObj' => $productByCodeDataObj,
  10874.                     'productData' => $productData,
  10875.                     'currInvList' => $currInvList,
  10876.                     'productDataWeightPackageGm' => $productDataWeightPackageGm,
  10877.                     'productDataWeightVarianceValue' => $productDataWeightVarianceValue,
  10878.                     'productDataWeightVarianceType' => $productDataWeightVarianceType,
  10879.                     'exId' => $id,
  10880.                     'clientList' => Client::GetExistingClientList($em$companyId),
  10881.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  10882.                     'productList' => Inventory::ProductList($em$companyId),
  10883.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10884.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10885.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10886.                     'unitList' => Inventory::UnitTypeList($em),
  10887.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10888.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10889.                     'warehouseList' => Inventory::WarehouseList($em),
  10890.                 )
  10891.             ));
  10892.         } else {
  10893.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  10894.                 array(
  10895.                     'exId' => $id,
  10896.                 )
  10897.             ));
  10898.         }
  10899.         if ($request->query->has('returnJson')) {
  10900.             return new JsonResponse(
  10901.                 array(
  10902.                     'success' => true,
  10903.                     'page_title' => 'Product Details',
  10904.                     'company_data' => $company_data,
  10905.                     'renderedHtml' => $html,
  10906.                     'exId' => $id,
  10907.                     'productByCodeDataObj' => $productByCodeDataObj,
  10908. //                'productData' => $productData,
  10909. //                'currInvList' => $currInvList,
  10910. //                'productList' => Inventory::ProductList($em, $companyId),
  10911. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10912. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10913. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10914. //                'unitList' => Inventory::UnitTypeList($em),
  10915. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10916. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10917. //                'warehouseList' => Inventory::WarehouseList($em),
  10918.                 )
  10919.             );
  10920.         } else {
  10921. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10922. //                ->findBy(
  10923. //                    array(
  10924. ////                        'productByCodeId' => $id,
  10925. //                    'CompanyId'=>$companyId
  10926. //                    )
  10927. //                );
  10928.             $productByCodeList = []; //called by ajax
  10929.             return $this->render('@Inventory/pages/views/product_by_code_assign_check_print.html.twig',
  10930.                 array(
  10931.                     'page_title' => 'Serial Manager',
  10932.                     'company_data' => $company_data,
  10933.                     'renderedHtml' => $html,
  10934.                     'exId' => $id,
  10935.                     'productByCodeList' => $productByCodeList,
  10936.                     'productByCodeDataObj' => $productByCodeDataObj,
  10937. //                'productByCodeData' => $productByCodeData,
  10938. //                'productData' => $productData,
  10939. //                'currInvList' => $currInvList,
  10940. //                'productList' => Inventory::ProductList($em, $companyId),
  10941. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10942. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10943. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10944. //                'unitList' => Inventory::UnitTypeList($em),
  10945. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10946. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10947. //                'warehouseList' => Inventory::WarehouseList($em),
  10948.                 )
  10949.             );
  10950.         }
  10951.     }
  10952.     public
  10953.     function TestProductByCodeCheckAssignPrintAction(Request $request$id 0)
  10954.     {
  10955.         $em $this->getDoctrine()->getManager();
  10956.         $companyId $this->getLoggedUserCompanyId($request);
  10957.         $company_data Company::getCompanyData($em$companyId);
  10958.         $data = [];
  10959.         $html '';
  10960.         $productByCodeData = [];
  10961.         $productByCodeDataObj = [];
  10962.         if ($id != 0) {
  10963.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10964.                 ->findOneBy(
  10965.                     array(
  10966.                         'productByCodeId' => $id
  10967.                     )
  10968.                 );
  10969.         } else {
  10970.             if ($request->query->has('scanCode')) {
  10971.                 $query $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10972.                     ->createQueryBuilder('p');
  10973.                 if ($request->query->has('assigned')) {
  10974.                     $query->where('p.assigned > :av')
  10975.                         ->setParameter('av'$request->query->get('assigned'));
  10976.                 } else
  10977.                     $query->where("1=0");
  10978.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  10979.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  10980.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  10981.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  10982.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  10983.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  10984.                 $query->setMaxResults(1);
  10985.                 $results $query->getQuery()->getResult();
  10986.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  10987.             } else
  10988.                 $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10989.                     ->findOneBy(
  10990.                         array(
  10991. //                        'productByCodeId' => $id,
  10992.                             'CompanyId' => $companyId
  10993.                         ), array(
  10994.                             'productByCodeId' => 'DESC'
  10995.                         )
  10996.                     );
  10997.             if ($productByCodeData)
  10998.                 $id $productByCodeData->getProductByCodeId();
  10999.         }
  11000.         if ($id != 0) {
  11001.             $productByCodeDataObj = array(
  11002.                 'sn' => $productByCodeData->getSalesCode(),
  11003.                 'imei1' => $productByCodeData->getImei1(),
  11004.                 'imei2' => $productByCodeData->getImei2(),
  11005.                 'colorId' => $productByCodeData->getColorId(),
  11006.             );
  11007.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  11008.                 ->findOneBy(
  11009.                     array(
  11010.                         'id' => $productByCodeData->getProductId()
  11011.                     )
  11012.                 );
  11013.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  11014.                 ->findBy(
  11015.                     array(
  11016.                         'productId' => $id
  11017.                     )
  11018.                 );
  11019.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  11020.                 array(
  11021.                     'page_title' => 'Details',
  11022.                     'company_data' => $company_data,
  11023.                     'productByCodeData' => $productByCodeData,
  11024.                     'productData' => $productData,
  11025.                     'currInvList' => $currInvList,
  11026.                     'exId' => $id,
  11027.                     'clientList' => Client::GetExistingClientList($em$companyId),
  11028.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  11029.                     'productList' => Inventory::ProductList($em$companyId),
  11030.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  11031.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  11032.                     'igList' => Inventory::ItemGroupList($em$companyId),
  11033.                     'unitList' => Inventory::UnitTypeList($em),
  11034.                     'brandList' => Inventory::GetBrandList($em$companyId),
  11035.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  11036.                     'warehouseList' => Inventory::WarehouseList($em),
  11037.                 )
  11038.             );
  11039.         } else {
  11040.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  11041.                 array(
  11042.                     'exId' => $id,
  11043.                 )
  11044.             );
  11045.         }
  11046.         if ($request->query->has('returnJson')) {
  11047.             return new JsonResponse(
  11048.                 array(
  11049.                     'success' => true,
  11050.                     'page_title' => 'Product Details',
  11051.                     'company_data' => $company_data,
  11052.                     'renderedHtml' => $html,
  11053.                     'exId' => $id,
  11054.                     'productByCodeDataObj' => $productByCodeDataObj,
  11055. //                'productData' => $productData,
  11056. //                'currInvList' => $currInvList,
  11057. //                'productList' => Inventory::ProductList($em, $companyId),
  11058. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11059. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11060. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11061. //                'unitList' => Inventory::UnitTypeList($em),
  11062. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11063. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11064. //                'warehouseList' => Inventory::WarehouseList($em),
  11065.                 )
  11066.             );
  11067.         } else {
  11068. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11069. //                ->findBy(
  11070. //                    array(
  11071. ////                        'productByCodeId' => $id,
  11072. //                    'CompanyId'=>$companyId
  11073. //                    )
  11074. //                );
  11075.             $productByCodeList = []; //called by ajax
  11076.             return $this->render('@Inventory/pages/views/test_product_by_code_assign_check_print.html.twig',
  11077.                 array(
  11078.                     'page_title' => ' Test Serial Manager',
  11079.                     'company_data' => $company_data,
  11080.                     'renderedHtml' => $html,
  11081.                     'exId' => $id,
  11082.                     'productByCodeList' => $productByCodeList,
  11083.                     'productByCodeDataObj' => $productByCodeDataObj,
  11084. //                'productByCodeData' => $productByCodeData,
  11085. //                'productData' => $productData,
  11086. //                'currInvList' => $currInvList,
  11087. //                'productList' => Inventory::ProductList($em, $companyId),
  11088. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11089. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11090. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11091. //                'unitList' => Inventory::UnitTypeList($em),
  11092. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11093. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11094. //                'warehouseList' => Inventory::WarehouseList($em),
  11095.                 )
  11096.             );
  11097.         }
  11098.     }
  11099.     public function DeleteProductAction(Request $request$id '')
  11100.     {
  11101.         $em $this->getDoctrine()->getManager();
  11102.         $idListArray = [];
  11103.         if ($request->isMethod('POST')) {
  11104.             if ($id == 0)
  11105.                 $id $request->request->get('productId');
  11106.             //now check the product closing , if nothing then we cna remove it
  11107.             $query_here $this->getDoctrine()
  11108.                 ->getRepository('ApplicationBundle\\Entity\\InvClosingBalance')
  11109.                 ->findBy(
  11110.                     array(
  11111.                         'productId' => $request->request->get('productId')
  11112.                     )
  11113.                 );
  11114.             if (!empty($query_here)) {
  11115.                 return new JsonResponse(
  11116.                     array(
  11117.                         'success' => false,
  11118.                     )
  11119.                 );
  11120.             } else {
  11121.                 $qry $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')->findBy(array(
  11122.                     'productId' => $id
  11123.                 ));
  11124.                 foreach ($qry as $det) {
  11125.                     //remove any barcoded products
  11126.                     $em->remove($det);
  11127.                     $em->flush();
  11128.                 }
  11129.                 $qry $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findBy(array(
  11130.                     'id' => $id
  11131.                 ));
  11132.                 foreach ($qry as $det) {
  11133.                     //remove any barcoded products
  11134.                     $em->remove($det);
  11135.                     $em->flush();
  11136.                 }
  11137.                 $qry $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')->findBy(array(
  11138.                     'productId' => $id
  11139.                 ));
  11140.                 foreach ($qry as $det) {
  11141.                     //remove any barcoded products
  11142.                     $em->remove($det);
  11143.                     $em->flush();
  11144.                 }
  11145.                 return new JsonResponse(
  11146.                     array(
  11147.                         'success' => true,
  11148.                     )
  11149.                 );
  11150.             }
  11151.         }
  11152.         return new JsonResponse(
  11153.             array(
  11154.                 'success' => false,
  11155.             )
  11156.         );
  11157.     }
  11158.     public
  11159.     function RegisterProductAction(Request $request$idListStr '')
  11160.     {
  11161.         $em $this->getDoctrine()->getManager();
  11162.         $companyId $this->getLoggedUserCompanyId($request);
  11163.         $company_data Company::getCompanyData($em$companyId);
  11164.         $session $request->getSession();
  11165. //        System::setSessionForUser($session );
  11166.         $idListArray = [];
  11167.         if ($idListStr != '')
  11168.             $idListArray explode(','$idListStr);
  11169.         $data = [];
  11170. //        if ($request->isMethod('POST')) {
  11171. //            $post = $request->request;
  11172. //            if ($request->request->get('formatId') != '') {
  11173. //                $query_here = $this->getDoctrine()
  11174. //                    ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  11175. //                    ->findOneBy(
  11176. //                        array(
  11177. //                            'formatId' => $request->request->get('formatId')
  11178. //                        )
  11179. //                    );
  11180. //                if (!empty($query_here))
  11181. //                    $new = $query_here;
  11182. //            } else
  11183. //                $new = new CheckFormat();
  11184. //            $new->setName($request->request->get('name'));
  11185. //            $new->setWidth($request->request->get('width'));
  11186. //            $new->setHeight($request->request->get('height'));
  11187. //            $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
  11188. //            $new->setCheckPayToTop($request->request->get('checkPayToTop'));
  11189. //            $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
  11190. //            $new->setCheckAmountTop($request->request->get('checkAmountTop'));
  11191. //            $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
  11192. //            $new->setCheckAiWTop($request->request->get('checkAiWTop'));
  11193. //            $new->setCheckDateLeft($request->request->get('checkDateLeft'));
  11194. //            $new->setCheckDateTop($request->request->get('checkDateTop'));
  11195. //            $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
  11196. //            $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
  11197. //            $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
  11198. //            $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
  11199. //            $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
  11200. //            $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
  11201. //            $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
  11202. //            $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
  11203. //            $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
  11204. //            $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
  11205. //            $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 1 : 0);
  11206. //            $new->setCheckImage($request->request->get('checkImage'));
  11207. //
  11208. //            $em = $this->getDoctrine()->getManager();
  11209. //            $em->persist($new);
  11210. //            $em->flush();
  11211. //
  11212. //        }
  11213. //        if (!empty($idListArray)) {
  11214. //            $query_here = $this->getDoctrine()
  11215. //                ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11216. //                ->findBy(
  11217. //                    array(
  11218. //                        'productByCodeId' => $idListArray
  11219. //                    )
  11220. //                );
  11221. //            if (!empty($query_here))
  11222. //                $data = $query_here;
  11223. //
  11224. //        }
  11225. //        else if ($request->query->has('formatId')) {
  11226. //            $query_here = $this->getDoctrine()
  11227. //                ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  11228. //                ->findOneBy(
  11229. //                    array(
  11230. //                        'formatId' => $request->query->get('formatId')
  11231. //                    )
  11232. //                );
  11233. //            if (!empty($query_here))
  11234. //                $data = $query_here;
  11235. //        }
  11236.         $data = [];
  11237.         $html '';
  11238.         $productByCodeData = [];
  11239.         if ($request->query->has('returnJson')) {
  11240.             return new JsonResponse(
  11241.                 array(
  11242.                     'success' => true,
  11243.                     'page_title' => 'Product Details',
  11244.                     'company_data' => $company_data,
  11245.                     'renderedHtml' => $html,
  11246.                     'data' => $data,
  11247.                     'idListArray' => $idListArray,
  11248. //                    'exId'=>$id,
  11249. //                'productByCodeData' => $productByCodeData,
  11250. //                'productData' => $productData,
  11251. //                'currInvList' => $currInvList,
  11252. //                'productList' => Inventory::ProductList($em, $companyId),
  11253. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11254. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11255. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11256. //                'unitList' => Inventory::UnitTypeList($em),
  11257. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11258. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11259. //                'warehouseList' => Inventory::WarehouseList($em),
  11260.                 )
  11261.             );
  11262.         } else {
  11263.             return $this->render('@Inventory/pages/input_forms/register_product.html.twig',
  11264.                 array(
  11265.                     'page_title' => 'Register Product',
  11266.                     'company_data' => $company_data,
  11267.                     'renderedHtml' => $html,
  11268. //                    'exIdList'=>$i,
  11269.                     'idListArray' => $idListArray,
  11270.                     'data' => $data,
  11271.                     'productByCodeList' => [],
  11272.                     'productByCodeData' => [],
  11273.                     'productList' => Inventory::ProductList($em$companyId),
  11274.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  11275.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  11276.                     'igList' => Inventory::ItemGroupList($em$companyId),
  11277.                     'unitList' => Inventory::UnitTypeList($em),
  11278.                     'brandList' => Inventory::GetBrandList($em$companyId),
  11279.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  11280.                     'warehouseList' => Inventory::WarehouseList($em),
  11281.                 )
  11282.             );
  11283.         }
  11284.     }
  11285.     public
  11286.     function BrandViewAction(Request $request)
  11287.     {
  11288.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  11289.             array(
  11290.                 'page_title' => 'Stock Return'
  11291.             )
  11292.         );
  11293.     }
  11294.     public
  11295.     function PrintTableDataAction(Request $request)
  11296.     {
  11297.         $em $this->getDoctrine()->getManager();
  11298.         $company_data Company::getCompanyData($em1);
  11299.         $data = [];
  11300.         $print_title "test";
  11301.         $document_mark = array(
  11302.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11303.             'copy' => ''
  11304.         );
  11305.         $mis_data = [];
  11306.         $p 1;
  11307.         return $this->render('@Inventory/pages/print/print_table_data.html.twig',
  11308.             array(
  11309.                 'page_title' => 'Data Report',
  11310.                 'data' => $data,
  11311.                 'page_header' => 'Report',
  11312.                 'print_title' => $print_title,
  11313.                 'document_type' => 'Journal voucher',
  11314.                 'document_mark_image' => $document_mark['original'],
  11315.                 'page_header_sub' => 'Add',
  11316. //                'type_list'=>$type_list,
  11317.                 'mis_data' => $mis_data,
  11318.                 'item_data' => [],
  11319.                 'received' => 2,
  11320.                 'return' => 1,
  11321.                 'total_w_vat' => 1,
  11322.                 'total_vat' => 1,
  11323.                 'total_wo_vat' => 1,
  11324.                 'invoice_id' => 'abcd1234',
  11325.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11326.                 'created_by' => 'created by',
  11327.                 'created_at' => '',
  11328.                 'red' => 0,
  11329.                 'company_name' => $company_data->getName(),
  11330.                 'company_data' => $company_data,
  11331.                 'company_address' => $company_data->getAddress(),
  11332.                 'company_image' => $company_data->getImage(),
  11333.                 'p' => $p
  11334.             )
  11335.         );
  11336.     }
  11337.     public
  11338.     function ReplacementReportAction(Request $request)
  11339.     {
  11340.         $qry_data = array(
  11341.             'warehouseId' => [0],
  11342.             'igId' => [0],
  11343.             'brandId' => [0],
  11344.             'categoryId' => [0],
  11345.             'actionTagId' => [0],
  11346.         );
  11347.         $em $this->getDoctrine()->getManager();
  11348.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  11349.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  11350.         $data_searched = [];
  11351.         $companyId $this->getLoggedUserCompanyId($request);
  11352.         $company_data Company::getCompanyData($em$companyId);
  11353.         $data = [];
  11354.         $print_title "Inventory Report";
  11355.         $document_mark = array(
  11356.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11357.             'copy' => ''
  11358.         );
  11359.         $post_data $request->request;
  11360.         $start_date $post_data->has('start_date') ? $post_data->get('start_date') : '';
  11361.         $end_date $post_data->has('end_date') ? $post_data->get('end_date') : '';
  11362.         if ($request->isMethod('POST'))
  11363.             $method 'POST';
  11364.         else
  11365.             $method 'GET';
  11366.         {
  11367. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  11368.             $data_searched Inventory::GetReplacementReportData($this->getDoctrine()->getManager(),
  11369.                 $request->request$method,
  11370.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  11371.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  11372.                 return new JsonResponse(
  11373.                     array(
  11374.                         'page_title' => 'Inventory ',
  11375.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11376.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11377.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11378.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11379.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11380.                         'action_tag' => $warehouse_action_list,
  11381.                         'start_date' => $start_date,
  11382.                         'end_date' => $end_date,
  11383.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11384.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11385.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11386.                         'data_searched' => $data_searched,
  11387.                         'success' => empty($data_searched['query_result']) ? false true
  11388.                     )
  11389.                 );
  11390.             }
  11391.             if ($request->request->get('print_data_enabled') == 1) {
  11392.                 $print_sub_title "";
  11393.                 return $this->render('@Inventory/pages/print/print_replacement_report.html.twig',
  11394.                     array(
  11395.                         'page_title' => 'Replacement Report',
  11396.                         'page_header' => 'Report',
  11397.                         'print_title' => $print_title,
  11398.                         'document_type' => 'Journal voucher',
  11399.                         'document_mark_image' => $document_mark['original'],
  11400.                         'page_header_sub' => 'Add',
  11401.                         'item_data' => [],
  11402.                         'received' => 2,
  11403.                         'return' => 1,
  11404.                         'total_w_vat' => 1,
  11405.                         'total_vat' => 1,
  11406.                         'total_wo_vat' => 1,
  11407.                         'invoice_id' => 'abcd1234',
  11408.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  11409.                         'created_by' => 'created by',
  11410.                         'created_at' => '',
  11411.                         'red' => 0,
  11412.                         'company_name' => $company_data->getName(),
  11413.                         'company_data' => $company_data,
  11414.                         'company_address' => $company_data->getAddress(),
  11415.                         'company_image' => $company_data->getImage(),
  11416.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11417.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11418.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11419.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11420.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11421.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11422.                         'action_tag' => $warehouse_action_list,
  11423.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11424.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11425.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11426.                         'start_date' => $start_date,
  11427.                         'end_date' => $end_date,
  11428.                         'data_searched' => $data_searched
  11429.                     )
  11430.                 );
  11431.             }
  11432.         }
  11433.         return $this->render('@Inventory/pages/report/replacement_report.html.twig',
  11434.             array(
  11435.                 'page_title' => 'Replacement Report',
  11436.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11437.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11438.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11439.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11440.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11441. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11442.                 'action_tag' => $warehouse_action_list,
  11443.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11444.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11445.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11446.                 'start_date' => $start_date,
  11447.                 'end_date' => $end_date,
  11448.                 'data_searched' => $data_searched,
  11449.                 'success' => empty($data_searched['query_result']) ? false true
  11450.             )
  11451.         );
  11452.     }
  11453.     public
  11454.     function InventoryViewAction(Request $request)
  11455.     {
  11456.         $qry_data = array(
  11457.             'warehouseId' => [0],
  11458.             'igId' => [0],
  11459.             'brandId' => [0],
  11460.             'categoryId' => [0],
  11461.             'actionTagId' => [0],
  11462.         );
  11463.         $em $this->getDoctrine()->getManager();
  11464.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  11465.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  11466.         $data_searched = [];
  11467.         $companyId $this->getLoggedUserCompanyId($request);
  11468.         $company_data Company::getCompanyData($em$companyId);
  11469.         $data = [];
  11470.         $print_title "Inventory Report";
  11471.         $document_mark = array(
  11472.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11473.             'copy' => ''
  11474.         );
  11475.         if ($request->isMethod('POST'))
  11476.             $method 'POST';
  11477.         else
  11478.             $method 'GET';
  11479.         {
  11480. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  11481.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  11482.                 $request->request$method,
  11483.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  11484.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  11485.                 return new JsonResponse(
  11486.                     array(
  11487.                         'page_title' => 'Inventory ',
  11488.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11489.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11490.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11491.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11492.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11493.                         'action_tag' => $warehouse_action_list,
  11494.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11495.                         'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  11496.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11497.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11498.                         'data_searched' => $data_searched,
  11499.                         'success' => empty($data_searched['query_result']) ? false true
  11500.                     )
  11501.                 );
  11502.             }
  11503.             if ($request->request->get('print_data_enabled') == 1) {
  11504.                 $print_sub_title "";
  11505.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  11506.                     array(
  11507.                         'page_title' => 'Inventory Report',
  11508.                         'page_header' => 'Report',
  11509.                         'print_title' => $print_title,
  11510.                         'document_type' => 'Journal voucher',
  11511.                         'document_mark_image' => $document_mark['original'],
  11512.                         'page_header_sub' => 'Add',
  11513.                         'item_data' => [],
  11514.                         'received' => 2,
  11515.                         'return' => 1,
  11516.                         'total_w_vat' => 1,
  11517.                         'total_vat' => 1,
  11518.                         'total_wo_vat' => 1,
  11519.                         'invoice_id' => 'abcd1234',
  11520.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  11521.                         'created_by' => 'created by',
  11522.                         'created_at' => '',
  11523.                         'red' => 0,
  11524.                         'company_name' => $company_data->getName(),
  11525.                         'company_data' => $company_data,
  11526.                         'company_address' => $company_data->getAddress(),
  11527.                         'company_image' => $company_data->getImage(),
  11528.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11529.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11530.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11531.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11532.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11533.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11534.                         'action_tag' => $warehouse_action_list,
  11535.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11536.                         'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  11537.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11538.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11539.                         'data_searched' => $data_searched
  11540.                     )
  11541.                 );
  11542.             }
  11543.         }
  11544.         return $this->render('@Inventory/pages/report/inventory_view.html.twig',
  11545.             array(
  11546.                 'page_title' => 'Inventory',
  11547.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11548.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11549.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11550.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11551.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11552. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11553.                 'action_tag' => $warehouse_action_list,
  11554.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11555.                 'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  11556.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11557.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11558.                 'data_searched' => $data_searched
  11559.             )
  11560.         );
  11561.     }
  11562.     public
  11563.     function GrnListAction(Request $request)
  11564.     {
  11565.         $q $this->getDoctrine()
  11566.             ->getRepository('ApplicationBundle\\Entity\\Grn')
  11567.             ->findBy(
  11568.                 array(
  11569.                     'status' => GeneralConstant::ACTIVE,
  11570. //                    'approved' =>  GeneralConstant::APPROVED,
  11571.                 )
  11572.             );
  11573.         $stage_list = array(
  11574.             => 'Pending',
  11575.             => 'Pending',
  11576.             => 'Complete',
  11577.             => 'Partial',
  11578.         );
  11579.         $data = [];
  11580.         foreach ($q as $entry) {
  11581.             $data[] = array(
  11582.                 'doc_date' => $entry->getGrnDate(),
  11583.                 'id' => $entry->getGrnId(),
  11584.                 'doc_hash' => $entry->getDocumentHash(),
  11585.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  11586.                 'stage' => $stage_list[$entry->getStage()]
  11587.             );
  11588.         }
  11589.         return $this->render('@Inventory/pages/views/grn_list.html.twig',
  11590.             array(
  11591.                 'page_title' => 'Grn List',
  11592.                 'data' => $data
  11593.             )
  11594.         );
  11595.     }
  11596.     public
  11597.     function ViewGrnAction(Request $request$id)
  11598.     {
  11599.         $em $this->getDoctrine()->getManager();
  11600.         $dt Inventory::GetGrnDetails($em$id);
  11601.         return $this->render(
  11602.             '@Inventory/pages/views/view_grn.html.twig',
  11603.             array(
  11604.                 'page_title' => 'View',
  11605.                 'data' => $dt,
  11606.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  11607.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11608.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11609.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11610.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  11611.                     $id,
  11612.                     $dt['created_by'],
  11613.                     $dt['edited_by'])
  11614.             )
  11615.         );
  11616.     }
  11617.     public
  11618.     function PrintGrnAction(Request $request$id)
  11619.     {
  11620.         $em $this->getDoctrine()->getManager();
  11621.         $dt Inventory::GetGrnDetails($em$id);
  11622.         $company_data Company::getCompanyData($em1);
  11623.         $document_mark = array(
  11624.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11625.             'copy' => ''
  11626.         );
  11627.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11628.             $html $this->renderView('@Inventory/pages/print/print_received_note.html.twig',
  11629.                 array(
  11630.                     //full array here
  11631.                     'pdf' => true,
  11632.                     'page_title' => 'Grn',
  11633.                     'export' => 'pdf,print',
  11634.                     'data' => $dt,
  11635.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11636.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11637.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11638.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  11639.                         $id,
  11640.                         $dt['created_by'],
  11641.                         $dt['edited_by']),
  11642.                     'document_mark_image' => $document_mark['original'],
  11643.                     'company_name' => $company_data->getName(),
  11644.                     'company_data' => $company_data,
  11645.                     'company_address' => $company_data->getAddress(),
  11646.                     'company_image' => $company_data->getImage(),
  11647.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11648.                     'red' => 0
  11649.                 )
  11650.             );
  11651.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11652. //                'orientation' => 'landscape',
  11653. //                'enable-javascript' => true,
  11654. //                'javascript-delay' => 1000,
  11655.                 'no-stop-slow-scripts' => false,
  11656.                 'no-background' => false,
  11657.                 'lowquality' => false,
  11658.                 'encoding' => 'utf-8',
  11659. //            'images' => true,
  11660. //            'cookie' => array(),
  11661.                 'dpi' => 300,
  11662.                 'image-dpi' => 300,
  11663. //                'enable-external-links' => true,
  11664. //                'enable-internal-links' => true
  11665.             ));
  11666.             return new Response(
  11667.                 $pdf_response,
  11668.                 200,
  11669.                 array(
  11670.                     'Content-Type' => 'application/pdf',
  11671.                     'Content-Disposition' => 'attachment; filename="grn.pdf"'
  11672.                 )
  11673.             );
  11674.         }
  11675.         return $this->render('@Inventory/pages/print/print_received_note.html.twig',
  11676.             array(
  11677.                 'page_title' => 'Grn',
  11678.                 'export' => 'pdf,print',
  11679.                 'data' => $dt,
  11680.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11681.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11682.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11683.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  11684.                     $id,
  11685.                     $dt['created_by'],
  11686.                     $dt['edited_by']),
  11687.                 'document_mark_image' => $document_mark['original'],
  11688.                 'company_name' => $company_data->getName(),
  11689.                 'company_data' => $company_data,
  11690.                 'company_address' => $company_data->getAddress(),
  11691.                 'company_image' => $company_data->getImage(),
  11692.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11693.                 'red' => 0
  11694.             )
  11695.         );
  11696.     }
  11697.     public
  11698.     function PrintGrnBarcodeAction(Request $request$id)
  11699.     {
  11700.         $em $this->getDoctrine()->getManager();
  11701.         $dt Inventory::GetGrnDetails($em$id);
  11702.         $company_data Company::getCompanyData($em1);
  11703.         $repeatCount 1;
  11704.         if ($request->query->has('repeatCount'))
  11705.             $repeatCount $request->query->get('repeatCount');
  11706.         $document_mark = array(
  11707.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11708.             'copy' => ''
  11709.         );
  11710.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11711.             $html $this->renderView('@Inventory/pages/print/print_grn_barcodes.html.twig',
  11712.                 array(
  11713.                     //full array here
  11714.                     'pdf' => true,
  11715.                     'page_title' => 'Grn Barcodes',
  11716.                     'export' => 'print',
  11717.                     'data' => $dt,
  11718.                     'repeatCount' => $repeatCount,
  11719.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11720.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11721.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11722.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  11723.                         $id,
  11724.                         $dt['created_by'],
  11725.                         $dt['edited_by']),
  11726.                     'document_mark_image' => $document_mark['original'],
  11727.                     'company_name' => $company_data->getName(),
  11728.                     'company_data' => $company_data,
  11729.                     'company_address' => $company_data->getAddress(),
  11730.                     'company_image' => $company_data->getImage(),
  11731.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11732.                     'red' => 0
  11733.                 )
  11734.             );
  11735.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11736. //                'orientation' => 'landscape',
  11737.                 'enable-javascript' => true,
  11738. //                'javascript-delay' => 1000,
  11739.                 'no-stop-slow-scripts' => false,
  11740.                 'no-background' => false,
  11741.                 'lowquality' => false,
  11742.                 'encoding' => 'utf-8',
  11743. //            'images' => true,
  11744. //            'cookie' => array(),
  11745.                 'dpi' => 300,
  11746.                 'image-dpi' => 300,
  11747. //                'enable-external-links' => true,
  11748. //                'enable-internal-links' => true
  11749.             ));
  11750.             return new Response(
  11751.                 $pdf_response,
  11752.                 200,
  11753.                 array(
  11754.                     'Content-Type' => 'application/pdf',
  11755.                     'Content-Disposition' => 'attachment; filename="grn_barcodes.pdf"'
  11756.                 )
  11757.             );
  11758.         }
  11759.         return $this->render('@Inventory/pages/print/print_grn_barcodes.html.twig',
  11760.             array(
  11761.                 'page_title' => 'Grn barcodes',
  11762. //                'export'=>'pdf,print',
  11763.                 'data' => $dt,
  11764.                 'repeatCount' => $repeatCount,
  11765.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11766.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11767.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11768.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  11769.                     $id,
  11770.                     $dt['created_by'],
  11771.                     $dt['edited_by']),
  11772.                 'document_mark_image' => $document_mark['original'],
  11773.                 'company_name' => $company_data->getName(),
  11774.                 'company_data' => $company_data,
  11775.                 'company_address' => $company_data->getAddress(),
  11776.                 'company_image' => $company_data->getImage(),
  11777.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11778.                 'red' => 0
  11779.             )
  11780.         );
  11781.     }
  11782.     public function GenerateBarcodeAction(Request $request$type$id$item_id)
  11783.     {
  11784.         $em $this->getDoctrine()->getManager();
  11785.         $repeatCount 1;
  11786.         $spec_item_id 0;
  11787.         $skip_ids = [];
  11788.         $clearUnnecessaryOnly 0;
  11789.         if ($request->query->has('skipIds'))
  11790.             $skip_ids $request->query->get('skipIds');
  11791.         if ($request->query->has('clearUnnecessaryOnly'))
  11792.             $clearUnnecessaryOnly $request->query->get('clearUnnecessaryOnly');
  11793.         if ($type == 'srcv') {
  11794.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')->findOneBy(
  11795.                 array(
  11796.                     'stockReceivedNoteId' => $id
  11797.                 )
  11798.             );
  11799.             if ($item_id == '_single_') {
  11800.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findBy(
  11801.                     array(
  11802.                         'stockReceivedNoteId' => $id,
  11803. //                        'id' => $item_id
  11804.                     )
  11805.                 );
  11806.             } else {
  11807.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findBy(
  11808.                     array(
  11809.                         'stockReceivedNoteId' => $id,
  11810.                         'id' => $item_id
  11811.                     )
  11812.                 );
  11813.             }
  11814.             $inv_acc_data = [
  11815.                 'fa_amount' => 0,
  11816.                 'tg_amount' => 0,
  11817.             ];
  11818.             $inv_acc_data_by_head = [
  11819.             ];
  11820.             $new_non_delivered_sales_code_range = [];
  11821.             foreach ($doc_item_data as $entry) {
  11822.                 //adding transaction
  11823.                 $sales_code_range_ser = [];
  11824.                 if (in_array($entry->getId(), $skip_ids))
  11825.                     continue;
  11826.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  11827.                     ->findOneBy(
  11828.                         array(
  11829.                             'id' => $entry->getProductId()
  11830.                         )
  11831.                     );
  11832.                 $stitem $em->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  11833.                     ->findOneBy(
  11834.                         array(
  11835.                             'id' => $entry->getStockTransferItemId(),
  11836.                             'productId' => $entry->getProductId()
  11837.                         )
  11838.                     );
  11839.                 if ($product) {
  11840.                     if ($product->getHasSerial() == 1) {
  11841.                         //clear if exists
  11842.                         if ($clearUnnecessaryOnly == 1) {
  11843.                             $get_kids_sql "DELETE FROM product_by_code
  11844.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  11845. //                $get_kids_sql .=' ORDER BY name ASC';
  11846.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  11847.                             $em->flush();
  11848.                         } else {
  11849.                             $get_kids_sql "DELETE FROM product_by_code
  11850.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  11851. //                $get_kids_sql .=' ORDER BY name ASC';
  11852.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  11853.                             $em->flush();
  11854.                         }
  11855. //                        $check_here = $stmt;
  11856.                         //now addng product by code
  11857.                         $sales_code_range = [];
  11858.                         if ($doc_data->getType() == || $doc_data->getType() == 4) {
  11859. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  11860. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  11861.                             $product_action_tag_id $entry->getWarehouseActionId();
  11862.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getQty(),
  11863.                                 $doc_data->getStockReceivedNoteDate(), $entry->getWarrantyMon(), 0$doc_data->getCompanyId(), $entry->getWarehouseId(),
  11864.                                 $entry->getWarehouseActionId(), $entry->getPurchaseCodeRange(), nullnullnullnull$doc_data->getStockReceivedNoteId()
  11865.                             );
  11866.                             $sales_code_range $barcodeData['sales_code_range'];
  11867.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  11868.                             $em->flush();
  11869.                         }
  11870. //                        else {
  11871. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11872. //
  11873. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11874. //                            } else {
  11875. //
  11876. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11877. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  11878. //                                $sales_code_range = json_decode($json_without_bigints, true);
  11879. //                            }
  11880. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11881. //
  11882. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11883. //                            } else {
  11884. //
  11885. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11886. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  11887. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  11888. //                            }
  11889. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  11890. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  11891. //                            $new_non_delivered_sales_code_range = [];
  11892. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  11893. //                                if (!(in_array($ndsc, $sales_code_range)))
  11894. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  11895. //                            }
  11896. //                            if ($sales_code_range != null) {
  11897. //                                foreach ($sales_code_range as $ind => $dt) {
  11898. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11899. //                                        ->findOneBy(
  11900. //                                            array(
  11901. //                                                'salesCode' => [$dt],
  11902. //                                                'productId' => $entry->getProductId()
  11903. //                                            )
  11904. //                                        );
  11905. //
  11906. //                                    if ($np) {
  11907. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  11908. //                                        $np->setProductId($entry->getProductId());
  11909. //                                        $np->setWarehouseId($entry->getWarehouseId());
  11910. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  11911. //                                        $np->setPosition(1);//in warehouse
  11912. //                                        $np->setStockReceivedNoteId($id);
  11913. //
  11914. //
  11915. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  11916. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  11917. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  11918. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  11919. //                                            'direction' => 'in',
  11920. //                                            'warehouseId' => $entry->getWarehouseId(),
  11921. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  11922. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  11923. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  11924. //                                        );
  11925. //                                        $np->setTransactionHistory(json_encode(
  11926. //                                            $trans_history
  11927. //                                        ));
  11928. //
  11929. //
  11930. //                                        $em->persist($np);
  11931. //                                        $em->flush();
  11932. //                                    }
  11933. //                                }
  11934. //                            }
  11935. //                        }
  11936.                     }
  11937.                 }
  11938.                 //adding transaction
  11939.                 if ($stitem) {
  11940.                     $stitem->setNonDeliveredSalesCodeRange(json_encode($new_non_delivered_sales_code_range));
  11941.                 }
  11942.                 $spec_item_id $entry->getId();
  11943.                 if ($item_id == '_single_') {
  11944.                     break;
  11945.                 }
  11946.             }
  11947.         }
  11948.         if ($type == 'irr') {
  11949.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacement')->findOneBy(
  11950.                 array(
  11951.                     'itemReceivedAndReplacementId' => $id
  11952.                 )
  11953.             );
  11954.             if ($item_id == '_single_') {
  11955.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacementItem')->findBy(
  11956.                     array(
  11957.                         'itemReceivedAndReplacementId' => $id,
  11958. //                        'id' => $item_id
  11959.                     )
  11960.                 );
  11961.             } else {
  11962.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacementItem')->findBy(
  11963.                     array(
  11964.                         'itemReceivedAndReplacementId' => $id,
  11965.                         'id' => $item_id
  11966.                     )
  11967.                 );
  11968.             }
  11969.             $inv_acc_data = [
  11970.                 'fa_amount' => 0,
  11971.                 'tg_amount' => 0,
  11972.             ];
  11973.             $inv_acc_data_by_head = [
  11974.             ];
  11975.             $new_non_delivered_sales_code_range = [];
  11976.             foreach ($doc_item_data as $entry) {
  11977.                 //adding transaction
  11978.                 $sales_code_range_ser = [];
  11979.                 if (in_array($entry->getId(), $skip_ids))
  11980.                     continue;
  11981.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  11982.                     ->findOneBy(
  11983.                         array(
  11984.                             'id' => $entry->getReceivedProductId()
  11985.                         )
  11986.                     );
  11987.                 if ($product) {
  11988.                     if ($product->getHasSerial() == 1) {
  11989.                         //clear if exists
  11990. //                        if($clearUnnecessaryOnly==1) {
  11991. //                            $get_kids_sql = "DELETE FROM product_by_code
  11992. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  11993. ////                $get_kids_sql .=' ORDER BY name ASC';
  11994. //
  11995. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  11996. //                            
  11997. //                            $em->flush();
  11998. //                        }
  11999. //                        else{
  12000. //                            $get_kids_sql = "DELETE FROM product_by_code
  12001. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12002. ////                $get_kids_sql .=' ORDER BY name ASC';
  12003. //
  12004. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12005. //                            
  12006. //                            $em->flush();
  12007. //                        }
  12008. //                        $check_here = $stmt;
  12009.                         //now addng product by code
  12010.                         $sales_code_range = [];
  12011.                         if ($entry->getReceivedQty() > 0) {
  12012. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  12013. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  12014. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  12015.                             $barcodeData Inventory::GenerateBarcode($em$entry->getReceivedProductId(), $entry->getReceivedQty(),
  12016.                                 $doc_data->getItemReceivedAndReplacementDate(), 00$doc_data->getCompanyId(), $entry->getReceivedWarehouseId(),
  12017.                                 $entry->getReceivedWarehouseActionId(), nullnullnullnullnullnullnullnull$doc_data->getItemReceivedAndReplacementId()
  12018.                             );
  12019.                             $sales_code_range $barcodeData['sales_code_range'];
  12020.                             $entry->setReceivedCodeRange(json_encode($sales_code_range));
  12021.                             $em->flush();
  12022.                         }
  12023. //                        else {
  12024. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12025. //
  12026. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12027. //                            } else {
  12028. //
  12029. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12030. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  12031. //                                $sales_code_range = json_decode($json_without_bigints, true);
  12032. //                            }
  12033. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12034. //
  12035. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12036. //                            } else {
  12037. //
  12038. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12039. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  12040. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  12041. //                            }
  12042. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  12043. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  12044. //                            $new_non_delivered_sales_code_range = [];
  12045. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  12046. //                                if (!(in_array($ndsc, $sales_code_range)))
  12047. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  12048. //                            }
  12049. //                            if ($sales_code_range != null) {
  12050. //                                foreach ($sales_code_range as $ind => $dt) {
  12051. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12052. //                                        ->findOneBy(
  12053. //                                            array(
  12054. //                                                'salesCode' => [$dt],
  12055. //                                                'productId' => $entry->getProductId()
  12056. //                                            )
  12057. //                                        );
  12058. //
  12059. //                                    if ($np) {
  12060. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  12061. //                                        $np->setProductId($entry->getProductId());
  12062. //                                        $np->setWarehouseId($entry->getWarehouseId());
  12063. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  12064. //                                        $np->setPosition(1);//in warehouse
  12065. //                                        $np->setStockReceivedNoteId($id);
  12066. //
  12067. //
  12068. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  12069. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  12070. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  12071. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  12072. //                                            'direction' => 'in',
  12073. //                                            'warehouseId' => $entry->getWarehouseId(),
  12074. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  12075. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  12076. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  12077. //                                        );
  12078. //                                        $np->setTransactionHistory(json_encode(
  12079. //                                            $trans_history
  12080. //                                        ));
  12081. //
  12082. //
  12083. //                                        $em->persist($np);
  12084. //                                        $em->flush();
  12085. //                                    }
  12086. //                                }
  12087. //                            }
  12088. //                        }
  12089.                     }
  12090.                 }
  12091.                 //adding transaction
  12092.                 $spec_item_id $entry->getId();
  12093.                 if ($item_id == '_single_') {
  12094.                     break;
  12095.                 }
  12096.             }
  12097.         }
  12098.         if ($type == 'prdcn') {
  12099.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\Production')->findOneBy(
  12100.                 array(
  12101.                     'productionId' => $id
  12102.                 )
  12103.             );
  12104.             if ($item_id == '_single_') {
  12105.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findBy(
  12106.                     array(
  12107.                         'productionId' => $id,
  12108. //                        'id' => $item_id
  12109.                     )
  12110.                 );
  12111.             } else {
  12112.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findBy(
  12113.                     array(
  12114.                         'productionId' => $id,
  12115.                         'id' => $item_id
  12116.                     )
  12117.                 );
  12118.             }
  12119.             $inv_acc_data = [
  12120.                 'fa_amount' => 0,
  12121.                 'tg_amount' => 0,
  12122.             ];
  12123.             $inv_acc_data_by_head = [
  12124.             ];
  12125.             $new_non_delivered_sales_code_range = [];
  12126.             foreach ($doc_item_data as $entry) {
  12127.                 //adding transaction
  12128.                 $sales_code_range_ser = [];
  12129.                 if (in_array($entry->getId(), $skip_ids))
  12130.                     continue;
  12131.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12132.                     ->findOneBy(
  12133.                         array(
  12134.                             'id' => $entry->getProductId()
  12135.                         )
  12136.                     );
  12137.                 if ($product) {
  12138.                     if ($product->getHasSerial() == 1) {
  12139.                         //clear if exists
  12140. //                        if($clearUnnecessaryOnly==1) {
  12141. //                            $get_kids_sql = "DELETE FROM product_by_code
  12142. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12143. ////                $get_kids_sql .=' ORDER BY name ASC';
  12144. //
  12145. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12146. //                            
  12147. //                            $em->flush();
  12148. //                        }
  12149. //                        else{
  12150. //                            $get_kids_sql = "DELETE FROM product_by_code
  12151. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12152. ////                $get_kids_sql .=' ORDER BY name ASC';
  12153. //
  12154. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12155. //                            
  12156. //                            $em->flush();
  12157. //                        }
  12158. //                        $check_here = $stmt;
  12159.                         //now addng product by code
  12160.                         $sales_code_range = [];
  12161.                         if ($entry->getProducedQty() > 0) {
  12162. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  12163. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  12164. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  12165.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getProducedQty(),
  12166.                                 $doc_data->getProductionDate(), 00$doc_data->getCompanyId(), $entry->getWarehouseId(),
  12167.                                 $entry->getProducedItemActionTagId(), nullnullnullnullnullnullnull$doc_data->getProductionId(), null
  12168.                             );
  12169.                             $sales_code_range $barcodeData['sales_code_range'];
  12170.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  12171.                             $em->flush();
  12172.                         }
  12173. //                        else {
  12174. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12175. //
  12176. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12177. //                            } else {
  12178. //
  12179. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12180. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  12181. //                                $sales_code_range = json_decode($json_without_bigints, true);
  12182. //                            }
  12183. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12184. //
  12185. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12186. //                            } else {
  12187. //
  12188. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12189. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  12190. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  12191. //                            }
  12192. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  12193. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  12194. //                            $new_non_delivered_sales_code_range = [];
  12195. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  12196. //                                if (!(in_array($ndsc, $sales_code_range)))
  12197. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  12198. //                            }
  12199. //                            if ($sales_code_range != null) {
  12200. //                                foreach ($sales_code_range as $ind => $dt) {
  12201. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12202. //                                        ->findOneBy(
  12203. //                                            array(
  12204. //                                                'salesCode' => [$dt],
  12205. //                                                'productId' => $entry->getProductId()
  12206. //                                            )
  12207. //                                        );
  12208. //
  12209. //                                    if ($np) {
  12210. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  12211. //                                        $np->setProductId($entry->getProductId());
  12212. //                                        $np->setWarehouseId($entry->getWarehouseId());
  12213. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  12214. //                                        $np->setPosition(1);//in warehouse
  12215. //                                        $np->setStockReceivedNoteId($id);
  12216. //
  12217. //
  12218. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  12219. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  12220. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  12221. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  12222. //                                            'direction' => 'in',
  12223. //                                            'warehouseId' => $entry->getWarehouseId(),
  12224. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  12225. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  12226. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  12227. //                                        );
  12228. //                                        $np->setTransactionHistory(json_encode(
  12229. //                                            $trans_history
  12230. //                                        ));
  12231. //
  12232. //
  12233. //                                        $em->persist($np);
  12234. //                                        $em->flush();
  12235. //                                    }
  12236. //                                }
  12237. //                            }
  12238. //                        }
  12239.                     }
  12240.                 }
  12241.                 //adding transaction
  12242.                 $spec_item_id $entry->getId();
  12243.                 if ($item_id == '_single_') {
  12244.                     break;
  12245.                 }
  12246.             }
  12247.         }
  12248.         return new JsonResponse(array(
  12249.             'success' => $spec_item_id != true false,
  12250.             'skipIds' => [],
  12251.             'spec_item_id' => $spec_item_id
  12252.         ));
  12253. //        return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12254. //            array(
  12255. //                'page_title' => 'Srcv barcodes',
  12256. ////                'export'=>'pdf,print',
  12257. //                'data' => $dt,
  12258. //                'repeatCount' => $repeatCount,
  12259. //                'item_id' => $item_id,
  12260. //                'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12261. //                    $id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12262. //                'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12263. //                    array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12264. //                    $id,
  12265. //                    $dt['created_by'],
  12266. //                    $dt['edited_by']),
  12267. //                'document_mark_image' => $document_mark['original'],
  12268. //                                    'company_name' => $company_data->getName(),
  12269. //                    'company_data'=>$company_data,
  12270. //                'company_address' => $company_data->getAddress(),
  12271. //                'company_image' => $company_data->getImage(),
  12272. //                'invoice_footer' => $company_data->getInvoiceFooter(),
  12273. //                'red' => 0
  12274. //
  12275. //            )
  12276. //        );
  12277.     }
  12278.     public
  12279.     function PrintLabelAction(Request $request$id)
  12280.     {
  12281.         $em $this->getDoctrine()->getManager();
  12282. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12283.         $repeatCount 1;
  12284.         $assignProductId '';
  12285.         $productByCodeIds = [];
  12286.         $print_selection_type 1;
  12287.         $print_selection_string 1;
  12288.         $assignLabelFormatId 0;
  12289.         $assignColorId 0;
  12290.         $assignProductionScheduleId 0;
  12291.         $warehouseId '';
  12292.         $warehouseActionId '';
  12293.         $toAssignPosition '';
  12294.         $printFlag $request->request->has('printFlag') ? $request->request->get('printFlag') : 1;
  12295.         $returnJson $request->request->has('returnJson') ? $request->request->get('returnJson') : 0;
  12296.         if ($returnJson == 1)
  12297.             $printFlag 0;
  12298.         $companyId $this->getLoggedUserCompanyId($request);
  12299.         if ($request->query->has('repeatCount'))
  12300.             $repeatCount $request->query->get('repeatCount');
  12301.         if ($request->request->has('print_selection_type'))
  12302.             $print_selection_type $request->request->get('print_selection_type');
  12303.         if ($request->request->has('print_selection_string'))
  12304.             $print_selection_string $request->request->get('print_selection_string');
  12305.         if ($request->request->has('productByCodeIds'))
  12306.             $productByCodeIds json_decode($request->request->get('productByCodeIds'), true);
  12307.         if ($request->request->has('formatId'))
  12308.             $assignLabelFormatId $request->request->get('formatId');
  12309.         if ($printFlag == 0) {
  12310.             if ($request->request->has('productSelector'))
  12311.                 $assignProductId $request->request->get('productSelector');
  12312.             if ($request->request->has('colorId'))
  12313.                 $assignColorId $request->request->get('colorId');
  12314.             if ($request->request->has('productionScheduleId'))
  12315.                 $assignProductionScheduleId $request->request->get('productionScheduleId');
  12316.             if ($request->request->has('warehouseId'))
  12317.                 $warehouseId $request->request->get('warehouseId');
  12318.             if ($request->request->has('warehouseActionId'))
  12319.                 $warehouseActionId $request->request->get('warehouseActionId');
  12320.             if ($request->request->has('position'))
  12321.                 $toAssignPosition $request->request->get('position');
  12322.             if ($assignColorId == '')
  12323.                 $assignColorId 0;
  12324.         }
  12325.         if ($productByCodeIds == null)
  12326.             $productByCodeIds = [];
  12327.         $productByCodeData = [];
  12328.         $productList = [];
  12329.         $productIds = [];
  12330.         if ($print_selection_type == 2) {
  12331.             //range
  12332.             $productByCodeIds Inventory::getIdsFromIdSelectionStr($print_selection_string);
  12333.         }
  12334.         $labelData = [
  12335.             'formatId' => 0
  12336.         ];
  12337.         $formatId 0;
  12338.         if (!empty($productByCodeIds)) {
  12339.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12340.                 ->findBy(
  12341.                     array(
  12342.                         'productByCodeId' => $productByCodeIds
  12343.                     )
  12344.                 );
  12345.             foreach ($productByCodeData as $d) {
  12346.                 if ($d->getStage() < 10$d->setStage(11);
  12347.                 if ($assignProductId != '') {
  12348.                     $d->setProductId($assignProductId);
  12349.                 }
  12350.                 if ($assignColorId != 0) {
  12351.                     $d->setColorId($assignColorId);
  12352.                 } else {
  12353.                     $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12354.                         ->findOneBy(
  12355.                             array(
  12356.                                 'id' => $assignProductId
  12357.                             )
  12358.                         );
  12359.                     if ($productData) {
  12360.                         $d->setColorId($productData->getDefaultColorId());
  12361.                     }
  12362.                 }
  12363.                 if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  12364.                     $d->setDefaultLabelFormatId($assignLabelFormatId);
  12365.                     $d->setDeviceLabelFormatId($assignLabelFormatId);
  12366.                 }
  12367.                 $toAssignPosition != '' $d->setPosition($toAssignPosition) : '';
  12368.                 $warehouseId != '' $d->setWarehouseId($warehouseId) : '';
  12369.                 $warehouseActionId != '' $d->setWarehouseActionId($warehouseActionId) : '';
  12370.                 if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  12371.                     $d->setProductionScheduleId($assignProductionScheduleId);
  12372.                     $productionSchedule $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  12373.                         ->findOneBy(
  12374.                             array(
  12375.                                 'productionScheduleId' => $assignProductionScheduleId
  12376.                             )
  12377.                         );
  12378.                     if ($productionSchedule) {
  12379.                         if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  12380.                             //becuase it will assigned at previous lines
  12381.                         } else {
  12382.                             $d->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  12383.                             $d->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  12384.                         }
  12385.                         $d->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  12386.                         $d->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  12387.                     }
  12388.                 }
  12389.                 $em->flush();
  12390.                 if ($d->getProductId() != '' || $d->getProductId() != null)
  12391.                     $productIds[] = $d->getProductId();
  12392.                 $formatId $d->getDeviceLabelFormatId();
  12393.             }
  12394.         }
  12395.         $labelFormatHere $em->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  12396.             ->findOneBy(
  12397.                 array(
  12398.                     'formatId' => $formatId,
  12399. //                        'CompanyId' => $companyId
  12400.                 )
  12401.             );
  12402.         if ($labelFormatHere) {
  12403.             $formatData json_decode($labelFormatHere->getFormatData(), true);
  12404.             if ($formatData == null$formatData = [];
  12405.             $labelData = array(
  12406.                 'id' => $labelFormatHere->getFormatId(),
  12407.                 'formatId' => $labelFormatHere->getFormatId(),
  12408.                 'labelType' => $labelFormatHere->getLabelType(),
  12409.                 'name' => $labelFormatHere->getName(),
  12410.                 'width' => $labelFormatHere->getWidth(),
  12411.                 'pageWidth' => $labelFormatHere->getPageWidth(),
  12412.                 'height' => $labelFormatHere->getheight(),
  12413.                 'pageHeight' => $labelFormatHere->getPageHeight(),
  12414.                 'formatData' => $formatData,
  12415.             );
  12416.         }
  12417.         $productList Inventory::ProductList($em$this->getLoggedUserCompanyId($request), 10''$productIds);
  12418.         $company_data Company::getCompanyData($em1);
  12419.         $document_mark = array(
  12420.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12421.             'copy' => ''
  12422.         );
  12423.         $dt $productByCodeData;
  12424.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12425.             $html $this->renderView('@Inventory/pages/print/print_label.html.twig',
  12426.                 array(
  12427.                     //full array here
  12428.                     'pdf' => true,
  12429.                     'page_title' => 'Device Labels',
  12430.                     'export' => 'print',
  12431.                     'repeatCount' => $repeatCount,
  12432.                     'labelData' => $labelData,
  12433.                     'brandList' => Inventory::GetBrandList($em$companyId),
  12434. //                    'item_id' => $item_id,
  12435.                     'data' => $dt,
  12436.                     'productList' => $productList,
  12437.                     'approval_data' => [],
  12438.                     'document_log' => [],
  12439.                     'document_mark_image' => $document_mark['original'],
  12440.                     'company_name' => $company_data->getName(),
  12441.                     'company_data' => $company_data,
  12442.                     'company_address' => $company_data->getAddress(),
  12443.                     'company_image' => $company_data->getImage(),
  12444.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12445.                     'red' => 0
  12446.                 )
  12447.             );
  12448.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12449. //                'orientation' => 'landscape',
  12450.                 'enable-javascript' => true,
  12451. //                'javascript-delay' => 1000,
  12452.                 'no-stop-slow-scripts' => false,
  12453.                 'no-background' => false,
  12454.                 'lowquality' => false,
  12455.                 'encoding' => 'utf-8',
  12456. //            'images' => true,
  12457. //            'cookie' => array(),
  12458.                 'dpi' => 300,
  12459.                 'image-dpi' => 300,
  12460. //                'enable-external-links' => true,
  12461. //                'enable-internal-links' => true
  12462.             ));
  12463.             return new Response(
  12464.                 $pdf_response,
  12465.                 200,
  12466.                 array(
  12467.                     'Content-Type' => 'application/pdf',
  12468.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  12469.                 )
  12470.             );
  12471.         }
  12472.         $url $this->generateUrl(
  12473.             'print_label'
  12474.         );
  12475.         if ($returnJson == && $printFlag == 0) {
  12476. //                    $dr = $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findBy(
  12477. //                        array(
  12478. //                            'salesOrderId' => $orderId, ///material
  12479. //
  12480. //                        )
  12481. //                    );
  12482.             return new JsonResponse(array(
  12483.                 'success' => true,
  12484. //                        'documentHash' => $order->getDocumentHash(),
  12485. //                'documentId' => $receiptId,
  12486. //                'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
  12487. //
  12488. //                'viewUrl' => $url . "/" . $receiptId,
  12489.             ));
  12490.         } else return $this->render('@Inventory/pages/print/print_label.html.twig',
  12491.             array(
  12492.                 'page_title' => 'Product Labels',
  12493. //                'export'=>'pdf,print',
  12494.                 'data' => $dt,
  12495.                 'productList' => $productList,
  12496.                 'repeatCount' => $repeatCount,
  12497. //                'item_id' => $item_id,
  12498.                 'labelData' => $labelData,
  12499.                 'brandList' => Inventory::GetBrandList($em$companyId),
  12500.                 'approval_data' => [],
  12501.                 'document_log' => [],
  12502.                 'document_mark_image' => $document_mark['original'],
  12503.                 'company_name' => $company_data->getName(),
  12504.                 'company_data' => $company_data,
  12505.                 'company_address' => $company_data->getAddress(),
  12506.                 'company_image' => $company_data->getImage(),
  12507.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12508.                 'red' => 0
  12509.             )
  12510.         );
  12511.     }
  12512.     public
  12513.     function PrintCartonLabelAction(Request $request$id)
  12514.     {
  12515.         $em $this->getDoctrine()->getManager();
  12516. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12517.         $repeatCount 1;
  12518.         $assignProductId '';
  12519.         $productByCodeIds = [];
  12520.         $cartonId 0;
  12521.         if ($id != 0)
  12522.             $cartonId $id;
  12523.         $colorText '';
  12524.         $weightText '';
  12525.         if ($request->query->has('repeatCount'))
  12526.             $repeatCount $request->query->get('repeatCount');
  12527.         if ($request->request->has('printCartonId'))
  12528.             $cartonId $request->request->get('printCartonId');
  12529.         if ($request->request->has('printCartonColorText'))
  12530.             $colorText $request->request->get('printCartonColorText');
  12531.         if ($request->request->has('printCartonWeightText'))
  12532.             $weightText $request->request->get('printCartonWeightText');
  12533.         $labelData = [
  12534.             'formatId' => 0
  12535.         ];
  12536.         if ($productByCodeIds == null)
  12537.             $productByCodeIds = [];
  12538.         $productByCodeData = [];
  12539.         $cartonData = [];
  12540.         $product = [];
  12541.         if ($cartonId != 0) {
  12542.             $cartonData $em->getRepository('ApplicationBundle\\Entity\\Carton')
  12543.                 ->findOneBy(
  12544.                     array(
  12545.                         'id' => $cartonId
  12546.                     )
  12547.                 );
  12548.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12549.                 ->findBy(
  12550.                     array(
  12551.                         'cartonId' => $cartonId
  12552.                     )
  12553.                 );
  12554. //            if(!empty($productByCodeData))
  12555. //                $product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12556. //                ->findOneBy(
  12557. //                    array(
  12558. //                        'id' => $productByCodeData[0]->getProductId()
  12559. //                    )
  12560. //                );
  12561. //            else
  12562.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12563.                 ->findOneBy(
  12564.                     array(
  12565.                         'id' => $cartonData->getProductId()
  12566.                     )
  12567.                 );
  12568.             $formatId $cartonData->getCartonLabelFormatId();
  12569.             $labelFormatHere $em->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  12570.                 ->findOneBy(
  12571.                     array(
  12572.                         'formatId' => $formatId,
  12573. //                        'CompanyId' => $companyId
  12574.                     )
  12575.                 );
  12576.             if ($labelFormatHere) {
  12577.                 $formatData json_decode($labelFormatHere->getFormatData(), true);
  12578.                 if ($formatData == null$formatData = [];
  12579.                 $labelData = array(
  12580.                     'id' => $labelFormatHere->getFormatId(),
  12581.                     'formatId' => $labelFormatHere->getFormatId(),
  12582.                     'labelType' => $labelFormatHere->getLabelType(),
  12583.                     'name' => $labelFormatHere->getName(),
  12584.                     'width' => $labelFormatHere->getWidth(),
  12585.                     'pageWidth' => $labelFormatHere->getPageWidth(),
  12586.                     'height' => $labelFormatHere->getheight(),
  12587.                     'pageHeight' => $labelFormatHere->getPageHeight(),
  12588.                     'formatData' => $formatData,
  12589.                 );
  12590.             }
  12591.         }
  12592.         $company_data Company::getCompanyData($em1);
  12593.         $document_mark = array(
  12594.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12595.             'copy' => ''
  12596.         );
  12597.         $dt $productByCodeData;
  12598.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12599.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  12600.                 array(
  12601.                     //full array here
  12602.                     'pdf' => true,
  12603.                     'page_title' => 'Carton Labels',
  12604.                     'export' => 'print',
  12605.                     'labelData' => $labelData,
  12606.                     'repeatCount' => $repeatCount,
  12607. //                    'item_id' => $item_id,
  12608.                     'data' => $dt,
  12609.                     'cartonData' => $cartonData,
  12610.                     'product' => $product,
  12611.                     'colorText' => $colorText,
  12612.                     'weightText' => $weightText,
  12613.                     'approval_data' => [],
  12614.                     'document_log' => [],
  12615.                     'document_mark_image' => $document_mark['original'],
  12616.                     'company_name' => $company_data->getName(),
  12617.                     'company_data' => $company_data,
  12618.                     'company_address' => $company_data->getAddress(),
  12619.                     'company_image' => $company_data->getImage(),
  12620.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12621.                     'red' => 0
  12622.                 )
  12623.             );
  12624.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12625. //                'orientation' => 'landscape',
  12626.                 'enable-javascript' => true,
  12627. //                'javascript-delay' => 1000,
  12628.                 'no-stop-slow-scripts' => false,
  12629.                 'no-background' => false,
  12630.                 'lowquality' => false,
  12631.                 'encoding' => 'utf-8',
  12632. //            'images' => true,
  12633. //            'cookie' => array(),
  12634.                 'dpi' => 300,
  12635.                 'image-dpi' => 300,
  12636. //                'enable-external-links' => true,
  12637. //                'enable-internal-links' => true
  12638.             ));
  12639.             return new Response(
  12640.                 $pdf_response,
  12641.                 200,
  12642.                 array(
  12643.                     'Content-Type' => 'application/pdf',
  12644.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  12645.                 )
  12646.             );
  12647.         }
  12648.         if ($request->query->has('previewOnly')) {
  12649.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  12650.                 array(
  12651.                     'page_title' => 'Carton Labels',
  12652. //                'export'=>'pdf,print',
  12653.                     'data' => $dt,
  12654.                     'skip_parameters' => 1,
  12655.                     'labelData' => $labelData,
  12656.                     'cartonData' => $cartonData,
  12657.                     'product' => $product,
  12658.                     'colorText' => $colorText,
  12659.                     'weightText' => $weightText,
  12660.                     'repeatCount' => $repeatCount,
  12661. //                'item_id' => $item_id,
  12662.                     'approval_data' => [],
  12663.                     'document_log' => [],
  12664.                     'document_mark_image' => $document_mark['original'],
  12665.                     'company_name' => $company_data->getName(),
  12666.                     'company_data' => $company_data,
  12667.                     'company_address' => $company_data->getAddress(),
  12668.                     'company_image' => $company_data->getImage(),
  12669.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12670.                     'red' => 0
  12671.                 )
  12672.             );
  12673.             if ($request->query->has('returnJson')) {
  12674.                 return new JsonResponse(
  12675.                     array(
  12676.                         'success' => true,
  12677.                         'page_title' => 'Product Details',
  12678.                         'company_data' => $company_data,
  12679.                         'renderedHtml' => $html,
  12680. //                'productData' => $productData,
  12681. //                'currInvList' => $currInvList,
  12682. //                'productList' => Inventory::ProductList($em, $companyId),
  12683. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  12684. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  12685. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  12686. //                'unitList' => Inventory::UnitTypeList($em),
  12687. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  12688. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  12689. //                'warehouseList' => Inventory::WarehouseList($em),
  12690.                     )
  12691.                 );
  12692.             }
  12693.         }
  12694.         return $this->render('@Inventory/pages/print/print_carton_label.html.twig',
  12695.             array(
  12696.                 'page_title' => 'Carton Labels',
  12697. //                'export'=>'pdf,print',
  12698.                 'data' => $dt,
  12699.                 'cartonData' => $cartonData,
  12700.                 'product' => $product,
  12701. //                'productByCodeData' => $productByCodeData,
  12702.                 'colorText' => $colorText,
  12703.                 'weightText' => $weightText,
  12704.                 'repeatCount' => $repeatCount,
  12705.                 'labelData' => $labelData,
  12706. //                'item_id' => $item_id,
  12707.                 'approval_data' => [],
  12708.                 'document_log' => [],
  12709.                 'document_mark_image' => $document_mark['original'],
  12710.                 'company_name' => $company_data->getName(),
  12711.                 'company_data' => $company_data,
  12712.                 'company_address' => $company_data->getAddress(),
  12713.                 'company_image' => $company_data->getImage(),
  12714.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12715.                 'red' => 0
  12716.             )
  12717.         );
  12718.     }
  12719.     public function AssignInfoToProductByCodeAction(Request $request$id)
  12720.     {
  12721.         $em $this->getDoctrine()->getManager();
  12722.         $companyId $this->getLoggedUserCompanyId($request);
  12723. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12724.         $cartonId '';
  12725.         $passStatus 5;
  12726.         $assignProductId '';
  12727.         $assignProductionId '';
  12728.         $assignProductionScheduleId '';
  12729.         $gbWeightGm '';
  12730.         $dvWeightGm '';
  12731.         $cartonWeightGm '';
  12732.         if ($request->request->has('cartonId'))
  12733.             $cartonId $request->request->get('cartonId');
  12734.         if ($request->request->has('passStatus'))
  12735.             $passStatus $request->request->get('passStatus');
  12736.         if ($request->request->has('productByCodeId'))
  12737.             $id $request->request->get('productByCodeId');
  12738.         if ($request->request->has('productId'))
  12739.             $assignProductId $request->request->get('productId');
  12740.         if ($request->request->has('productionId'))
  12741.             $assignProductionId $request->request->get('productionId');
  12742.         if ($request->request->has('productionScheduleId'))
  12743.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  12744.         if ($request->request->has('gbWeightGm'))
  12745.             $gbWeightGm $request->request->get('gbWeightGm');
  12746.         if ($request->request->has('dvWeightGm'))
  12747.             $dvWeightGm $request->request->get('dvWeightGm');
  12748.         if ($request->request->has('cartonWeightGm'))
  12749.             $cartonWeightGm $request->request->get('cartonWeightGm');
  12750.         $cartonAssignedAlready 0;
  12751.         $otherData = array(
  12752.             'currentCartonBalance' => 0,
  12753.             'currentCartonCapacity' => 0,
  12754.             'currentCartonAssigned' => 0,
  12755.             'currentCartonFull' => 0,
  12756.         );
  12757.         if ($id != && $id != '') {
  12758.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12759.                 ->findOneBy(
  12760.                     array(
  12761.                         'productByCodeId' => $id
  12762.                     )
  12763.                 );
  12764.             if ($assignProductId != ''$productByCodeData->setProductId($assignProductId);
  12765.             if ($productByCodeData->getCartonId() != '' || $productByCodeData->getCartonId() != null)
  12766.                 $cartonAssignedAlready 1;
  12767.             else if ($cartonId != ''$productByCodeData->setCartonId($cartonId);
  12768.             if ($dvWeightGm != ''$productByCodeData->setSingleWeightGm($dvWeightGm);
  12769.             if ($gbWeightGm != '') {
  12770.                 $productByCodeData->setPackagedWeightGm($gbWeightGm);
  12771.             }
  12772.             $colorText '_NA_';
  12773.             if ($passStatus != 5$productByCodeData->setStage($passStatus);
  12774.             $productByCodeData->setCompanyId($companyId);
  12775.             if ($assignProductionId != '') {
  12776.                 $productByCodeData->setProductionId($assignProductionId);
  12777.                 $productionData $em->getRepository('ApplicationBundle\\Entity\\Production')
  12778.                     ->findOneBy(
  12779.                         array(
  12780.                             'productionId' => $assignProductionId
  12781.                         )
  12782.                     );
  12783.                 if ($assignProductId != '' && $assignProductId != null && $assignProductId != 0)
  12784.                     $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  12785.                         array(
  12786.                             'productionId' => $assignProductionId,
  12787.                             'productId' => $assignProductId,
  12788.                             'type' => 1,
  12789.                         )
  12790.                     );
  12791.                 else
  12792.                     $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  12793.                         array(
  12794.                             'productionId' => $assignProductionId,
  12795. //                            'productId' => $assignProductId,
  12796.                             'type' => 1,
  12797.                         )
  12798.                     );
  12799.                 $assignProductionScheduleId $productionData->getProductionScheduleId();
  12800.                 if ($productionItemData) {
  12801.                     $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  12802.                     $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  12803.                     $productByCodeData->setPosition(1);//in inventory
  12804.                     $productByCodeData->setSerialAssigned(1);
  12805.                     $productByCodeData->setColorId($productionItemData->getColorId());
  12806.                     $productByCodeData->setColorText($productionItemData->getColorText());
  12807.                     $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  12808.                     $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  12809.                     if ($passStatus == 1)//passed
  12810.                     {
  12811. //                    $transDate = new \DateTime();
  12812. //                    Inventory::addItemToInventoryCompact($em,
  12813. //                        $productionItemData->getProductId(),
  12814. //                        $productionItemData->getWarehouseId(),
  12815. //                        $productionItemData->getWarehouseId(),
  12816. //                        $productionData->getProducedItemActionTagId(),
  12817. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  12818. //                        $transDate,
  12819. //                        1,
  12820. //                        1,
  12821. //                        $entry['valueAdd'],
  12822. //                        $entry['valueSub'],
  12823. //                        $entry['price'],
  12824. //                        $this->getLoggedUserCompanyId($request),
  12825. //                        0,
  12826. //                        $entry['entity'],
  12827. //                        $entry['entityId'],
  12828. //                        $entry['entityDocHash']
  12829. //                    );
  12830.                     }
  12831.                     $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  12832.                     if ($transHistory == null)
  12833.                         $transHistory = [];
  12834.                     $transHistory[] = array(
  12835.                         'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  12836.                         'direction' => 'in',
  12837.                         'warehouseId' => $productionItemData->getWarehouseId(),
  12838.                         'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  12839.                         'fromWarehouseId' => 0,
  12840.                         'fromWarehouseActionId' => //stock of goods
  12841.                     );
  12842.                     $productByCodeData->setTransactionHistory(json_encode($transHistory));
  12843.                 }
  12844.             }
  12845.             if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  12846.                 $productByCodeData->setProductionScheduleId($assignProductionScheduleId);
  12847.                 $productionSchedule $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  12848.                     ->findOneBy(
  12849.                         array(
  12850.                             'productionScheduleId' => $assignProductionScheduleId
  12851.                         )
  12852.                     );
  12853.                 if ($productionSchedule) {
  12854.                     $productByCodeData->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  12855.                     $productByCodeData->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  12856.                     $productByCodeData->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  12857.                     $productByCodeData->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  12858.                     if ($productByCodeData->getProductionId() == null || $productByCodeData->getProductionId() == '' || $productByCodeData->getProductionId() == 0) {
  12859.                         $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  12860.                             array(
  12861.                                 'productionScheduleId' => $assignProductionScheduleId,
  12862.                                 'productId' => $productionSchedule->getProducedProductId(),
  12863.                                 'type' => 1,
  12864.                             )
  12865.                         );
  12866. //                        $assignProductionScheduleId=$productionData->getProductionScheduleId();
  12867.                         if ($productionItemData) {
  12868.                             $productByCodeData->setProductionId($productionItemData->getProductionId());
  12869.                             $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  12870.                             $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  12871.                             $productByCodeData->setPosition(1);//in inventory
  12872.                             $productByCodeData->setSerialAssigned(1);
  12873.                             $productByCodeData->setColorId($productionItemData->getColorId());
  12874.                             $productByCodeData->setColorText($productionItemData->getColorText());
  12875.                             $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  12876.                             $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  12877.                             if ($passStatus == 1)//passed
  12878.                             {
  12879. //                    $transDate = new \DateTime();
  12880. //                    Inventory::addItemToInventoryCompact($em,
  12881. //                        $productionItemData->getProductId(),
  12882. //                        $productionItemData->getWarehouseId(),
  12883. //                        $productionItemData->getWarehouseId(),
  12884. //                        $productionData->getProducedItemActionTagId(),
  12885. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  12886. //                        $transDate,
  12887. //                        1,
  12888. //                        1,
  12889. //                        $entry['valueAdd'],
  12890. //                        $entry['valueSub'],
  12891. //                        $entry['price'],
  12892. //                        $this->getLoggedUserCompanyId($request),
  12893. //                        0,
  12894. //                        $entry['entity'],
  12895. //                        $entry['entityId'],
  12896. //                        $entry['entityDocHash']
  12897. //                    );
  12898.                             }
  12899.                             $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  12900.                             if ($transHistory == null)
  12901.                                 $transHistory = [];
  12902.                             $transHistory[] = array(
  12903.                                 'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  12904.                                 'direction' => 'in',
  12905.                                 'warehouseId' => $productionItemData->getWarehouseId(),
  12906.                                 'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  12907.                                 'fromWarehouseId' => 0,
  12908.                                 'fromWarehouseActionId' => //stock of goods
  12909.                             );
  12910.                             $productByCodeData->setTransactionHistory(json_encode($transHistory));
  12911.                         }
  12912.                     }
  12913.                 }
  12914.             }
  12915. //                $productByCodeData->setPurchaseWarrantyLastDate($new_pwld);
  12916.             $em->flush();
  12917.             //now adding carton
  12918.         }
  12919.         if ($cartonId != '') {
  12920.             $carton $em->getRepository('ApplicationBundle\\Entity\\Carton')
  12921.                 ->findOneBy(
  12922.                     array(
  12923.                         'id' => $cartonId
  12924.                     )
  12925.                 );
  12926.             if ($cartonWeightGm != ''$carton->setCartonWeightGm($cartonWeightGm);
  12927.             $otherData['currentCartonCapacity'] = $carton->getCartonCapacityCount();
  12928.             if ($cartonAssignedAlready == 0)
  12929.                 $carton->setCartonAssignedCount(($carton->getCartonAssignedCount()) + 1);
  12930.             $otherData['currentCartonAssigned'] = $carton->getCartonAssignedCount();
  12931.             $otherData['currentCartonBalance'] = $otherData['currentCartonCapacity'] - $otherData['currentCartonAssigned'];
  12932.             if ($otherData['currentCartonAssigned'] >= $otherData['currentCartonCapacity'])
  12933.                 $otherData['currentCartonFull'] = 1;
  12934.             $em->flush();
  12935.         }
  12936.         if ($cartonId != '') {
  12937. //                    if($cartonAssignedAlready==1)
  12938. //                    {
  12939.             $productByCodeDataListForThisCarton $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12940.                 ->findBy(
  12941.                     array(
  12942.                         'cartonId' => $cartonId
  12943.                     )
  12944.                 );
  12945.             $carton $em->getRepository('ApplicationBundle\\Entity\\Carton')
  12946.                 ->findOneBy(
  12947.                     array(
  12948.                         'id' => $cartonId
  12949.                     )
  12950.                 );
  12951.             $total_carton_predicted_weight 0;
  12952.             $colorTextList = [];
  12953.             $cartonProductByCodeIds = [];
  12954.             foreach ($productByCodeDataListForThisCarton as $pikamaster) {
  12955.                 if (!in_array($pikamaster->getProductByCodeId(), $cartonProductByCodeIds))
  12956.                     $cartonProductByCodeIds[] = $pikamaster->getProductByCodeId();
  12957.                 if (!in_array($pikamaster->getColorText(), $colorTextList) && $pikamaster->getColorText() != null)
  12958.                     $colorTextList[] = $pikamaster->getColorText();
  12959.                 $total_carton_predicted_weight += ($pikamaster->getPackagedWeightGm());
  12960.                 if ($passStatus != 5)
  12961.                     if ($pikamaster->getStage() < $passStatus)
  12962.                         $pikamaster->setStage($passStatus);
  12963.             }
  12964.             if ($carton)
  12965.                 $carton->setCartonCalculatedWeightGm($total_carton_predicted_weight);
  12966.             if ($passStatus != 5)
  12967.                 $carton->setStage($passStatus);
  12968.             $carton->setColors(implode(','$colorTextList));
  12969.             $carton->setCartonProductByCodeIds(json_encode($cartonProductByCodeIds));
  12970.             $em->flush();
  12971.         }
  12972.         return new JsonResponse(array(
  12973.             'success' => true,
  12974.             'otherData' => $otherData,
  12975.         ));
  12976.     }
  12977.     public function RefreshCartonListAction(Request $request$id)
  12978.     {
  12979.         $em $this->getDoctrine()->getManager();
  12980. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12981.         $cartonListArray = [];
  12982.         $cartonList = [];
  12983.         $assignableCartonList = [];
  12984.         $assignableCartonListArray = [];
  12985.         $assignable 0;
  12986.         $cartonId '';
  12987.         $passStatus 5;
  12988.         $assignProductId '';
  12989.         $assignProductionId '';
  12990.         $assignProductionScheduleId '';
  12991.         if ($request->request->has('productionId'))
  12992.             $assignProductionId $request->request->get('productionId');
  12993.         if ($request->request->has('productionScheduleId'))
  12994.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  12995.         if ($request->request->has('assignable'))
  12996.             $assignable $request->request->get('assignable');
  12997.         $cartonAssignedAlready 0;
  12998.         $otherData = array(
  12999.             'currentCartonBalance' => 0,
  13000.             'currentCartonCapacity' => 0,
  13001.             'currentCartonAssigned' => 0,
  13002.             'currentCartonFull' => 0,
  13003.         );
  13004.         //1st get all cartons for this production id
  13005.         $cartonList $em->getRepository('ApplicationBundle\\Entity\\Carton')
  13006.             ->findBy(
  13007.                 array(
  13008. //                    'productionId' => $assignProductionId,
  13009.                     'productionScheduleId' => $assignProductionScheduleId
  13010.                 )
  13011.             );
  13012.         $foundAssignable 0;
  13013.         $setId 0;
  13014.         $lastdmySer '';
  13015.         foreach ($cartonList as $carton) {
  13016.             $cartonData = array(
  13017.                 'id' => $carton->getId(),
  13018.                 'name' => $carton->getCartonNumber(),
  13019.                 'colors' => $carton->getColors(),
  13020.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  13021.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  13022.             );
  13023.             $cartonListArray[] = $cartonData;
  13024.             $cartonList[$cartonData['id']] = $cartonData;
  13025.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  13026.                 $foundAssignable 1;
  13027.                 $setId $cartonData['id'];
  13028.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  13029.                 $assignableCartonListArray[] = $cartonData;
  13030.             }
  13031.         }
  13032.         if ($assignable == && $foundAssignable == 0) {
  13033. //            $productionData = $em->getRepository('ApplicationBundle\\Entity\\Production')
  13034. //                ->findOneBy(
  13035. //                    array(
  13036. //                        'productionId' => $assignProductionId
  13037. //                    )
  13038. //                );
  13039.             $productionScheduleData $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  13040.                 ->findOneBy(
  13041.                     array(
  13042.                         'productionScheduleId' => $assignProductionScheduleId
  13043.                     )
  13044.                 );
  13045.             $productId 0;
  13046.             $product = [];
  13047.             $productModel '';
  13048.             if ($productionScheduleData)
  13049.                 $productId $productionScheduleData->getProducedProductId();
  13050. //            $productionItem = $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')
  13051. //                ->findOneBy(
  13052. //                    array(
  13053. //                        'productionId' => $assignProductionId,
  13054. //                        'type' => 1
  13055. //                    )
  13056. //                );
  13057.             if ($productId != 0) {
  13058. //                    $productId = $productionItem->getProductId();
  13059.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  13060.                     ->findOneBy(
  13061.                         array(
  13062.                             'id' => $productId,
  13063.                         )
  13064.                     );
  13065.                 $productModel $product->getModelNo();
  13066.             }
  13067.             $carton = new Carton();
  13068.             $carton_capacity $productionScheduleData->getCartonCapacity();
  13069.             $carton->setProductId($productId);
  13070.             $carton->setProductionId($assignProductionId);
  13071.             $carton->setProductionScheduleId($assignProductionScheduleId);
  13072.             if ($productionScheduleData) {
  13073.                 $carton->setCartonLabelFormatId($productionScheduleData->getCartonLabelFormatId());
  13074.             }
  13075.             $carton->setCartonCapacityCount($carton_capacity == null $carton_capacity);
  13076.             $carton->setCartonAssignedCount(0);
  13077.             $carton->setCompanyId($this->getLoggedUserCompanyId($request));
  13078.             $today = new \DateTime();
  13079.             $dmy $productModel '-' . ($today->format('m')) . '-' . ($today->format('Y')) . '-' $productionScheduleData->getBatchNumber();
  13080.             $ser 0;
  13081.             $carton->setCartonNumberDmy($dmy);
  13082.             $carton->setCartonNumberLastSer(* (($today->format('h')) . '' . ($today->format('i'))));
  13083.             $carton->setCartonNumber($dmy '-' . ($today->format('h')) . '' . ($today->format('i')));
  13084.             $em->persist($carton);
  13085.             $em->flush();
  13086.             $cartonData = array(
  13087.                 'id' => $carton->getId(),
  13088.                 'name' => $carton->getCartonNumber(),
  13089.                 'colors' => $carton->getColors(),
  13090.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  13091.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  13092.             );
  13093.             $cartonListArray[] = $cartonData;
  13094.             $cartonList[$cartonData['id']] = $cartonData;
  13095.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  13096.                 $foundAssignable 1;
  13097.                 $setId $cartonData['id'];
  13098.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  13099.                 $assignableCartonListArray[] = $cartonData;
  13100.             }
  13101.         }
  13102.         return new JsonResponse(array(
  13103.             'success' => true,
  13104.             'cartonList' => $cartonList,
  13105.             'cartonListArray' => $cartonListArray,
  13106.             'assignableCartonList' => $assignableCartonList,
  13107.             'assignableCartonListArray' => $assignableCartonListArray,
  13108.             'setId' => $setId,
  13109.         ));
  13110.     }
  13111.     public
  13112.     function PrintDrBarcodeAction(Request $request$id$item_id)
  13113.     {
  13114.         $em $this->getDoctrine()->getManager();
  13115.         $dt Inventory::GetDrDetails($em$id$item_id);
  13116.         $repeatCount 1;
  13117.         if ($request->query->has('repeatCount'))
  13118.             $repeatCount $request->query->get('repeatCount');
  13119.         $company_data Company::getCompanyData($em1);
  13120.         $document_mark = array(
  13121.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13122.             'copy' => ''
  13123.         );
  13124.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13125.             $html $this->renderView('@Inventory/pages/print/print_dr_barcodes.html.twig',
  13126.                 array(
  13127.                     //full array here
  13128.                     'pdf' => true,
  13129.                     'page_title' => 'Challan Barcodes',
  13130.                     'export' => 'print',
  13131.                     'repeatCount' => $repeatCount,
  13132.                     'item_id' => $item_id,
  13133.                     'data' => $dt,
  13134.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13135.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13136.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13137.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  13138.                         $id,
  13139.                         $dt['created_by'],
  13140.                         $dt['edited_by']),
  13141.                     'document_mark_image' => $document_mark['original'],
  13142.                     'company_name' => $company_data->getName(),
  13143.                     'company_data' => $company_data,
  13144.                     'company_address' => $company_data->getAddress(),
  13145.                     'company_image' => $company_data->getImage(),
  13146.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13147.                     'red' => 0
  13148.                 )
  13149.             );
  13150.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13151. //                'orientation' => 'landscape',
  13152.                 'enable-javascript' => true,
  13153. //                'javascript-delay' => 1000,
  13154.                 'no-stop-slow-scripts' => false,
  13155.                 'no-background' => false,
  13156.                 'lowquality' => false,
  13157.                 'encoding' => 'utf-8',
  13158. //            'images' => true,
  13159. //            'cookie' => array(),
  13160.                 'dpi' => 300,
  13161.                 'image-dpi' => 300,
  13162. //                'enable-external-links' => true,
  13163. //                'enable-internal-links' => true
  13164.             ));
  13165.             return new Response(
  13166.                 $pdf_response,
  13167.                 200,
  13168.                 array(
  13169.                     'Content-Type' => 'application/pdf',
  13170.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  13171.                 )
  13172.             );
  13173.         }
  13174.         return $this->render('@Inventory/pages/print/print_dr_barcodes.html.twig',
  13175.             array(
  13176.                 'page_title' => 'Challan barcodes',
  13177. //                'export'=>'pdf,print',
  13178.                 'data' => $dt,
  13179.                 'repeatCount' => $repeatCount,
  13180.                 'item_id' => $item_id,
  13181.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13182.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13183.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13184.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  13185.                     $id,
  13186.                     $dt['created_by'],
  13187.                     $dt['edited_by']),
  13188.                 'document_mark_image' => $document_mark['original'],
  13189.                 'company_name' => $company_data->getName(),
  13190.                 'company_data' => $company_data,
  13191.                 'company_address' => $company_data->getAddress(),
  13192.                 'company_image' => $company_data->getImage(),
  13193.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13194.                 'red' => 0
  13195.             )
  13196.         );
  13197.     }
  13198.     public
  13199.     function PrintIrrBarcodeAction(Request $request$id$item_id)
  13200.     {
  13201.         $em $this->getDoctrine()->getManager();
  13202.         $dt Inventory::GetIrrDetails($em$id$item_id);
  13203.         $repeatCount 1;
  13204.         if ($request->query->has('repeatCount'))
  13205.             $repeatCount $request->query->get('repeatCount');
  13206.         $company_data Company::getCompanyData($em1);
  13207.         $document_mark = array(
  13208.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13209.             'copy' => ''
  13210.         );
  13211.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13212.             $html $this->renderView('@Inventory/pages/print/print_irr_barcodes.html.twig',
  13213.                 array(
  13214.                     //full array here
  13215.                     'pdf' => true,
  13216.                     'page_title' => 'Sales Return Barcodes',
  13217.                     'export' => 'print',
  13218.                     'repeatCount' => $repeatCount,
  13219.                     'item_id' => $item_id,
  13220.                     'data' => $dt,
  13221.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13222.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13223.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13224.                         array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13225.                         $id,
  13226.                         $dt['created_by'],
  13227.                         $dt['edited_by']),
  13228.                     'document_mark_image' => $document_mark['original'],
  13229.                     'company_name' => $company_data->getName(),
  13230.                     'company_data' => $company_data,
  13231.                     'company_address' => $company_data->getAddress(),
  13232.                     'company_image' => $company_data->getImage(),
  13233.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13234.                     'red' => 0
  13235.                 )
  13236.             );
  13237.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13238. //                'orientation' => 'landscape',
  13239.                 'enable-javascript' => true,
  13240. //                'javascript-delay' => 1000,
  13241.                 'no-stop-slow-scripts' => false,
  13242.                 'no-background' => false,
  13243.                 'lowquality' => false,
  13244.                 'encoding' => 'utf-8',
  13245. //            'images' => true,
  13246. //            'cookie' => array(),
  13247.                 'dpi' => 300,
  13248.                 'image-dpi' => 300,
  13249. //                'enable-external-links' => true,
  13250. //                'enable-internal-links' => true
  13251.             ));
  13252.             return new Response(
  13253.                 $pdf_response,
  13254.                 200,
  13255.                 array(
  13256.                     'Content-Type' => 'application/pdf',
  13257.                     'Content-Disposition' => 'attachment; filename="irr_barcodes.pdf"'
  13258.                 )
  13259.             );
  13260.         }
  13261.         return $this->render('@Inventory/pages/print/print_irr_barcodes.html.twig',
  13262.             array(
  13263.                 'page_title' => 'Sales Return barcodes',
  13264. //                'export'=>'pdf,print',
  13265.                 'data' => $dt,
  13266.                 'repeatCount' => $repeatCount,
  13267.                 'item_id' => $item_id,
  13268.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13269.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13270.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13271.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13272.                     $id,
  13273.                     $dt['created_by'],
  13274.                     $dt['edited_by']),
  13275.                 'document_mark_image' => $document_mark['original'],
  13276.                 'company_name' => $company_data->getName(),
  13277.                 'company_data' => $company_data,
  13278.                 'company_address' => $company_data->getAddress(),
  13279.                 'company_image' => $company_data->getImage(),
  13280.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13281.                 'red' => 0
  13282.             )
  13283.         );
  13284.     }
  13285.     public
  13286.     function PrintSrcvBarcodeAction(Request $request$id$item_id)
  13287.     {
  13288.         $em $this->getDoctrine()->getManager();
  13289.         $dt Inventory::GetSrcvDetails($em$id$item_id);
  13290.         $repeatCount 1;
  13291.         if ($request->query->has('repeatCount'))
  13292.             $repeatCount $request->query->get('repeatCount');
  13293.         $company_data Company::getCompanyData($em1);
  13294.         $document_mark = array(
  13295.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13296.             'copy' => ''
  13297.         );
  13298.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13299.             $html $this->renderView('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  13300.                 array(
  13301.                     //full array here
  13302.                     'pdf' => true,
  13303.                     'page_title' => 'Grn Barcodes',
  13304.                     'export' => 'print',
  13305.                     'repeatCount' => $repeatCount,
  13306.                     'item_id' => $item_id,
  13307.                     'data' => $dt,
  13308.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13309.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13310.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13311.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13312.                         $id,
  13313.                         $dt['created_by'],
  13314.                         $dt['edited_by']),
  13315.                     'document_mark_image' => $document_mark['original'],
  13316.                     'company_name' => $company_data->getName(),
  13317.                     'company_data' => $company_data,
  13318.                     'company_address' => $company_data->getAddress(),
  13319.                     'company_image' => $company_data->getImage(),
  13320.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13321.                     'red' => 0
  13322.                 )
  13323.             );
  13324.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13325. //                'orientation' => 'landscape',
  13326.                 'enable-javascript' => true,
  13327. //                'javascript-delay' => 1000,
  13328.                 'no-stop-slow-scripts' => false,
  13329.                 'no-background' => false,
  13330.                 'lowquality' => false,
  13331.                 'encoding' => 'utf-8',
  13332. //            'images' => true,
  13333. //            'cookie' => array(),
  13334.                 'dpi' => 300,
  13335.                 'image-dpi' => 300,
  13336. //                'enable-external-links' => true,
  13337. //                'enable-internal-links' => true
  13338.             ));
  13339.             return new Response(
  13340.                 $pdf_response,
  13341.                 200,
  13342.                 array(
  13343.                     'Content-Type' => 'application/pdf',
  13344.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  13345.                 )
  13346.             );
  13347.         }
  13348.         return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  13349.             array(
  13350.                 'page_title' => 'Srcv barcodes',
  13351. //                'export'=>'pdf,print',
  13352.                 'data' => $dt,
  13353.                 'repeatCount' => $repeatCount,
  13354.                 'item_id' => $item_id,
  13355.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13356.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13357.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13358.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13359.                     $id,
  13360.                     $dt['created_by'],
  13361.                     $dt['edited_by']),
  13362.                 'document_mark_image' => $document_mark['original'],
  13363.                 'company_name' => $company_data->getName(),
  13364.                 'company_data' => $company_data,
  13365.                 'company_address' => $company_data->getAddress(),
  13366.                 'company_image' => $company_data->getImage(),
  13367.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13368.                 'red' => 0
  13369.             )
  13370.         );
  13371.     }
  13372. //product by code
  13373.     public function ImeiListExcelUploadAction(Request $request)
  13374.     {
  13375.         $lastIndex $request->request->get('lastIndex'0);
  13376.         if ($request->isMethod('POST')) {
  13377.             $post $request->request;
  13378.             if ($request->request->has('chunkData')) {
  13379.                 //now getting the relevant checks
  13380.                 $check_list = [];
  13381.                 $csv_data $request->request->get('chunkData', []);
  13382.                 $em $this->getDoctrine()->getManager();
  13383.                 foreach ($csv_data as $ind => $data_row) {
  13384. //                    if ($ind == 1)
  13385. //                        continue;
  13386.                     $np $this->getDoctrine()
  13387.                         ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  13388.                         ->findOneBy(
  13389.                             array(
  13390.                                 'salesCode' => isset($data_row[4]) ? $data_row[4] : 0,
  13391. //                    'approved' =>  GeneralConstant::APPROVED,
  13392.                             )
  13393.                         );
  13394.                     if (!$np)
  13395.                         $np = new ProductByCode();
  13396. //                    $np = new ProductByCode();
  13397.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  13398.                     if (isset($data_row[1])) $np->setProductId($data_row[1]);
  13399.                     if (isset($data_row[0])) $np->setLcNumber($data_row[0]);
  13400.                     if (isset($data_row[2])) $np->setCartonNumber($data_row[2]);
  13401.                     if (isset($data_row[3])) $np->setSerialNo($data_row[3]);
  13402.                     $np->setSerialAssigned(isset($data_row[10]) ? $data_row[10] : 0);
  13403.                     if (isset($data_row[4])) $np->setImei1($data_row[4]);
  13404.                     if (isset($data_row[5])) $np->setImei2($data_row[5]);
  13405.                     if (isset($data_row[6])) $np->setImei3($data_row[6]);
  13406.                     if (isset($data_row[7])) $np->setImei4($data_row[7]);
  13407.                     if (isset($data_row[8])) $np->setBtMac($data_row[8]);
  13408.                     if (isset($data_row[9])) $np->setWlanMac($data_row[9]);
  13409.                     $np->setWarehouseId(isset($data_row[11]) ? $data_row[11] : 0);
  13410.                     $np->setWarehouseActionId(isset($data_row[12]) ? $data_row[12] : 0);
  13411.                     $np->setPosition(isset($data_row[13]) ? $data_row[13] : 0);//in inventory
  13412.                     $np->setPurchaseOrderId(0);
  13413.                     $np->setGrnId(0);
  13414.                     $np->setStage(0);
  13415.                     if (isset($data_row[3])) $np->setSalesCodeRange(json_encode([$data_row[3]]));
  13416. //                $np->setSalesCode($data_row[3]);
  13417.                     if (isset($data_row[4])) $np->setSalesCode($data_row[4]); //IMEI
  13418.                     $np->setSalesCodeSer(0);
  13419.                     $np->setSalesCodeDmy('');
  13420.                     $np->setPurchaseCodeRange("");
  13421.                     $np->setPurchaseReceiptDate(null);
  13422.                     $np->setLastInDate(null);
  13423.                     $np->setStatus(GeneralConstant::ACTIVE);
  13424.                     $np->setTransactionHistory(json_encode([
  13425.                         ]
  13426.                     ));
  13427.                     $np->setPurchaseWarrantyLastDate(null);
  13428.                     $em->persist($np);
  13429.                     $em->flush();
  13430.                 }
  13431.                 return new JsonResponse(array(
  13432.                     "success" => true,
  13433.                     "lastIndex" => $lastIndex,
  13434.                     "file_path" => '',
  13435.                     "csv_data" => $csv_data,
  13436.                     //                "debug_data"=>System::encryptSignature($r)
  13437.                 ));
  13438.             } else {
  13439.                 $path "";
  13440.                 $file_path "";
  13441.                 //            var_dump($request->files);
  13442.                 //        var_dump($request->getFile());
  13443.                 foreach ($request->files as $uploadedFile) {
  13444.                     //            if($uploadedFile->getImage())
  13445.                     //                var_dump($uploadedFile->getFile());
  13446.                     //                var_dump($uploadedFile);
  13447.                     if ($uploadedFile != null) {
  13448.                         $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  13449.                         $path $fileName;
  13450.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  13451.                         if (!file_exists($upl_dir)) {
  13452.                             mkdir($upl_dir0777true);
  13453.                         }
  13454.                         $file $uploadedFile->move($upl_dir$path);
  13455.                     }
  13456.                 }
  13457.                 //        print_r($file);
  13458.                 if ($path != "")
  13459.                     $file_path 'uploads/FileUploads/' $path;
  13460.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  13461.                 //
  13462.                 //            $img_file = file_get_contents($g_path);
  13463.                 //            $r=base64_encode($img_file);
  13464.                 $row 1;
  13465.                 $csv_data = [];
  13466.                 if (($handle fopen($g_path"r")) !== FALSE) {
  13467.                     while (($data fgetcsv($handle1000",")) !== FALSE) {
  13468.                         $num count($data);
  13469.                         $csv_data[$row] = $data;
  13470.                         //                    echo "<p> $num fields in line $row: <br /></p>\n";
  13471.                         $row++;
  13472.                         //                    for ($c=0; $c < $num; $c++) {
  13473.                         //                        echo $data[$c] . "<br />\n";
  13474.                         //                    }
  13475.                     }
  13476.                     fclose($handle);
  13477.                 }
  13478.                 //now getting the relevant checks
  13479.                 $check_list = [];
  13480.                 $em $this->getDoctrine()->getManager();
  13481.                 foreach ($csv_data as $ind => $data_row) {
  13482.                     if ($ind == 1)
  13483.                         continue;
  13484.                     $np = new ProductByCode();
  13485.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  13486.                     $np->setProductId($data_row[1]);
  13487.                     $np->setLcNumber($data_row[0]);
  13488.                     $np->setCartonNumber($data_row[2]);
  13489.                     $np->setSerialNo($data_row[3]);
  13490.                     $np->setSerialAssigned(0);
  13491.                     $np->setImei1($data_row[4]);
  13492.                     $np->setImei2($data_row[5]);
  13493.                     $np->setImei3($data_row[6]);
  13494.                     $np->setImei4($data_row[7]);
  13495.                     $np->setBtMac($data_row[8]);
  13496.                     $np->setWlanMac($data_row[9]);
  13497.                     $np->setWarehouseId(0);
  13498.                     $np->setWarehouseActionId(0);
  13499.                     $np->setPosition(0);//in inventory
  13500.                     $np->setPurchaseOrderId(0);
  13501.                     $np->setGrnId(0);
  13502.                     $np->setStage(0);
  13503.                     $np->setSalesCodeRange(json_encode([$data_row[3]]));
  13504. //                $np->setSalesCode($data_row[3]);
  13505.                     $np->setSalesCode($data_row[4]); //IMEI
  13506.                     $np->setSalesCodeSer(0);
  13507.                     $np->setSalesCodeDmy('');
  13508.                     $np->setPurchaseCodeRange("");
  13509.                     $np->setPurchaseReceiptDate(null);
  13510.                     $np->setLastInDate(null);
  13511.                     $np->setStatus(GeneralConstant::ACTIVE);
  13512.                     $np->setTransactionHistory(json_encode([
  13513.                         ]
  13514.                     ));
  13515.                     $np->setPurchaseWarrantyLastDate(null);
  13516.                     $em->persist($np);
  13517.                     $em->flush();
  13518.                 }
  13519.                 return new JsonResponse(array(
  13520.                     "success" => true,
  13521.                     "lastIndex" => $lastIndex,
  13522.                     "file_path" => $file_path,
  13523.                     "csv_data" => $csv_data,
  13524.                     //                "debug_data"=>System::encryptSignature($r)
  13525.                 ));
  13526.             }
  13527.         }
  13528.         return new JsonResponse(array(
  13529.             "success" => false,
  13530.             "file_path" => '',
  13531.             "csv_data" => [],
  13532.             "lastIndex" => $lastIndex,
  13533.         ));
  13534.     }
  13535.     public
  13536.     function ProductByCodeListAction(Request $request)
  13537.     {
  13538.         $em $this->getDoctrine()->getManager();
  13539.         $companyId $this->getLoggedUserCompanyId($request);
  13540.         $listData Inventory::GetProductListForProductByCodeListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  13541.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  13542.             if ($request->query->has('dataTableQry')) {
  13543.                 return new JsonResponse(
  13544.                     $listData
  13545.                 );
  13546.             }
  13547.         }
  13548.         $q = [];
  13549. //        $q = $this->getDoctrine()
  13550. //            ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  13551. //            ->findBy(
  13552. //                array(
  13553. //                    'status' => GeneralConstant::ACTIVE,
  13554. ////                    'approved' =>  GeneralConstant::APPROVED,
  13555. //                )
  13556. //
  13557. //            );
  13558.         //temp start
  13559. //        foreach($q as $np) {
  13560. //            if($np->getPosition()==1) {   /// only starting ones or in warehouse ones
  13561. //                $temp_obj = json_decode($np->getTransactionHistory());
  13562. //                if ($temp_obj != null) {
  13563. //                    $transHistory = [];
  13564. //                    $transHistory[] = $temp_obj;
  13565. //                    $np->setTransactionHistory(json_encode($transHistory));
  13566. //                }
  13567. //            }
  13568. //            $em->flush();
  13569. //        }
  13570.         ///temp end
  13571.         $stage_list = array(
  13572.             => 'Pending',
  13573.             => 'Pending',
  13574.             => 'Complete',
  13575.             => 'Partial',
  13576.         );
  13577.         $data = [];
  13578. //        foreach($q as $entry)
  13579. //        {
  13580. //            $data[]=array(
  13581. //                'doc_date'=>$entry->getStockRequisitionDate(),
  13582. //                'id'=>$entry->getStockRequisitionId(),
  13583. //                'doc_hash'=>$entry->getDocumentHash(),
  13584. //                'approval_status'=>GeneralConstant::$approvalStatus[$entry->getApproved()],
  13585. //                'stage'=>$stage_list[$entry->getStage()]
  13586. //
  13587. //            );
  13588. //        }
  13589.         return $this->render('@Inventory/pages/views/product_by_code_list.html.twig',
  13590.             array(
  13591.                 'page_title' => 'Product List',
  13592.                 'data' => $q,
  13593. //                'listData' => $listData,
  13594.                 'products' => Inventory::ProductList($em),
  13595.                 'warehouseList' => Inventory::WarehouseList($em)
  13596.             )
  13597.         );
  13598.     }
  13599. //SR
  13600.     public
  13601.     function SrListAction(Request $request)
  13602.     {
  13603.         $q $this->getDoctrine()
  13604.             ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  13605.             ->findBy(
  13606.                 array(
  13607.                     'status' => GeneralConstant::ACTIVE,
  13608. //                    'approved' =>  GeneralConstant::APPROVED,
  13609.                 )
  13610.                 ,
  13611.                 array(
  13612.                     'stockRequisitionDate' => 'DESC'
  13613.                 )
  13614.             );
  13615.         $stage_list = array(
  13616.             => 'Pending',
  13617.             => 'Pending',
  13618.             => 'Complete',
  13619.             => 'Partial',
  13620.         );
  13621.         $data = [];
  13622.         foreach ($q as $entry) {
  13623.             $data[] = array(
  13624.                 'doc_date' => $entry->getStockRequisitionDate(),
  13625.                 'id' => $entry->getStockRequisitionId(),
  13626.                 'doc_hash' => $entry->getDocumentHash(),
  13627.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13628.                 'stage' => $stage_list[$entry->getStage()],
  13629.                 'indentTagged' => $entry->getIndentTagged(),
  13630.                 'srIds' => $entry->getSrIds(),
  13631.                 'irIds' => $entry->getIrIds(),
  13632.                 'prIds' => $entry->getPrIds(),
  13633.                 'poIds' => $entry->getPoIds(),
  13634.             );
  13635.         }
  13636.         return $this->render('@Inventory/pages/views/sr_list.html.twig',
  13637.             array(
  13638.                 'page_title' => 'Stock Requisition List',
  13639.                 'data' => $data
  13640.             )
  13641.         );
  13642.     }
  13643.     public
  13644.     function ViewSrAction(Request $request$id)
  13645.     {
  13646.         $em $this->getDoctrine()->getManager();
  13647.         $dt Inventory::GetSrDetails($em$id);
  13648.         return $this->render(
  13649.             '@Inventory/pages/views/view_stock_requisition.html.twig',
  13650.             array(
  13651.                 'page_title' => 'Stock requisition',
  13652.                 'data' => $dt,
  13653.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13654.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13655.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13656.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13657.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13658.                     $id,
  13659.                     $dt['created_by'],
  13660.                     $dt['edited_by'])
  13661.             )
  13662.         );
  13663.     }
  13664.     public
  13665.     function PrintSrAction(Request $request$id)
  13666.     {
  13667.         $em $this->getDoctrine()->getManager();
  13668.         $dt Inventory::GetSrDetails($em$id);
  13669.         $company_data Company::getCompanyData($em1);
  13670.         $document_mark = array(
  13671.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13672.             'copy' => ''
  13673.         );
  13674.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13675.             $html $this->renderView('@Inventory/pages/print/print_sr.html.twig',
  13676.                 array(
  13677.                     //full array here
  13678.                     'pdf' => true,
  13679.                     'page_title' => 'Stock Requisition',
  13680.                     'export' => 'pdf,print',
  13681.                     'data' => $dt,
  13682.                     'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13683.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13684.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13685.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13686.                         array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13687.                         $id,
  13688.                         $dt['created_by'],
  13689.                         $dt['edited_by']),
  13690.                     'document_mark_image' => $document_mark['original'],
  13691.                     'company_name' => $company_data->getName(),
  13692.                     'company_data' => $company_data,
  13693.                     'company_address' => $company_data->getAddress(),
  13694.                     'company_image' => $company_data->getImage(),
  13695.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13696.                     'red' => 0
  13697.                 )
  13698.             );
  13699.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13700.                 //     'orientation' => 'landscape',
  13701.                 //     'enable-javascript' => true,
  13702.                 //     'javascript-delay' => 1000,
  13703.                 'no-stop-slow-scripts' => false,
  13704.                 'no-background' => false,
  13705.                 'lowquality' => false,
  13706.                 'encoding' => 'utf-8',
  13707.                 //    'images' => true,
  13708.                 //    'cookie' => array(),
  13709.                 'dpi' => 300,
  13710.                 'image-dpi' => 300,
  13711.                 //    'enable-external-links' => true,
  13712.                 //    'enable-internal-links' => true
  13713.             ));
  13714.             return new Response(
  13715.                 $pdf_response,
  13716.                 200,
  13717.                 array(
  13718.                     'Content-Type' => 'application/pdf',
  13719.                     'Content-Disposition' => 'attachment; filename="stock_requisition_' $id '.pdf"'
  13720.                 )
  13721.             );
  13722.         }
  13723.         return $this->render('@Inventory/pages/print/print_sr.html.twig',
  13724.             array(
  13725.                 'page_title' => 'Stock Requisition',
  13726.                 'export' => 'pdf,print',
  13727.                 'data' => $dt,
  13728.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13729.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13730.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13731.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13732.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13733.                     $id,
  13734.                     $dt['created_by'],
  13735.                     $dt['edited_by']),
  13736.                 'document_mark_image' => $document_mark['original'],
  13737.                 'company_name' => $company_data->getName(),
  13738.                 'company_data' => $company_data,
  13739.                 'company_address' => $company_data->getAddress(),
  13740.                 'company_image' => $company_data->getImage(),
  13741.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13742.                 'red' => 0
  13743.             )
  13744.         );
  13745.     }
  13746. //IR
  13747.     public
  13748.     function IrListAction(Request $request)
  13749.     {
  13750.         $q $this->getDoctrine()
  13751.             ->getRepository('ApplicationBundle\\Entity\\StoreRequisition')
  13752.             ->findBy(
  13753.                 array(
  13754.                     'status' => GeneralConstant::ACTIVE,
  13755. //                    'approved' =>  GeneralConstant::APPROVED,
  13756.                 ),
  13757.                 array(
  13758.                     'storeRequisitionDate' => 'DESC'
  13759.                 )
  13760.             );
  13761.         $stage_list = array(
  13762.             => 'Pending',
  13763.             => 'Pending',
  13764.             => 'Complete',
  13765.             => 'Partial',
  13766.         );
  13767.         $data = [];
  13768.         foreach ($q as $entry) {
  13769.             $data[] = array(
  13770.                 'doc_date' => $entry->getStoreRequisitionDate(),
  13771.                 'id' => $entry->getStoreRequisitionId(),
  13772.                 'doc_hash' => $entry->getDocumentHash(),
  13773.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13774.                 'stage' => $stage_list[$entry->getStage()],
  13775.                 'prTagged' => $entry->getIndentTagged(),
  13776.                 'srIds' => $entry->getSrIds(),
  13777.                 'irIds' => $entry->getIrIds(),
  13778.                 'prIds' => $entry->getPrIds(),
  13779.                 'poIds' => $entry->getPoIds(),
  13780.             );
  13781.         }
  13782.         return $this->render('@Inventory/pages/views/ir_list.html.twig',
  13783.             array(
  13784.                 'page_title' => 'Indent Requisition List',
  13785.                 'data' => $data
  13786.             )
  13787.         );
  13788.     }
  13789.     public
  13790.     function ViewIrAction(Request $request$id)
  13791.     {
  13792.         $em $this->getDoctrine()->getManager();
  13793.         $dt Inventory::GetIrDetails($em$id);
  13794.         return $this->render(
  13795.             '@Inventory/pages/views/view_indent_requisition.html.twig',
  13796.             array(
  13797.                 'page_title' => 'Indent',
  13798.                 'data' => $dt,
  13799.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13800.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13801.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13802.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13803.                     $id,
  13804.                     $dt['created_by'],
  13805.                     $dt['edited_by'])
  13806.             )
  13807.         );
  13808.     }
  13809.     public
  13810.     function PrintIrAction(Request $request$id)
  13811.     {
  13812.         $em $this->getDoctrine()->getManager();
  13813.         $dt Inventory::GetIrDetails($em$id);
  13814.         $company_data Company::getCompanyData($em1);
  13815.         $document_mark = array(
  13816.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13817.             'copy' => ''
  13818.         );
  13819.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13820.             $html $this->renderView('@Inventory/pages/print/print_ir.html.twig',
  13821.                 array(
  13822.                     //full array here
  13823.                     'pdf' => true,
  13824.                     'page_title' => 'Indent Requisition',
  13825.                     'export' => 'pdf,print',
  13826.                     'data' => $dt,
  13827.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13828.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13829.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13830.                         array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13831.                         $id,
  13832.                         $dt['created_by'],
  13833.                         $dt['edited_by']),
  13834.                     'document_mark_image' => $document_mark['original'],
  13835.                     'company_name' => $company_data->getName(),
  13836.                     'company_data' => $company_data,
  13837.                     'company_address' => $company_data->getAddress(),
  13838.                     'company_image' => $company_data->getImage(),
  13839.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13840.                     'red' => 0
  13841.                 )
  13842.             );
  13843.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13844. //                'orientation' => 'landscape',
  13845. //                'enable-javascript' => true,
  13846. //                'javascript-delay' => 1000,
  13847.                 'no-stop-slow-scripts' => false,
  13848.                 'no-background' => false,
  13849.                 'lowquality' => false,
  13850.                 'encoding' => 'utf-8',
  13851. //            'images' => true,
  13852. //            'cookie' => array(),
  13853.                 'dpi' => 300,
  13854.                 'image-dpi' => 300,
  13855. //                'enable-external-links' => true,
  13856. //                'enable-internal-links' => true
  13857.             ));
  13858.             return new Response(
  13859.                 $pdf_response,
  13860.                 200,
  13861.                 array(
  13862.                     'Content-Type' => 'application/pdf',
  13863.                     'Content-Disposition' => 'attachment; filename="indent_' $id '.pdf"'
  13864.                 )
  13865.             );
  13866.         }
  13867.         return $this->render('@Inventory/pages/print/print_ir.html.twig',
  13868.             array(
  13869.                 'page_title' => 'Indent Requisition',
  13870.                 'export' => 'pdf,print',
  13871.                 'data' => $dt,
  13872.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13873.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13874.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13875.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13876.                     $id,
  13877.                     $dt['created_by'],
  13878.                     $dt['edited_by']),
  13879.                 'document_mark_image' => $document_mark['original'],
  13880.                 'company_name' => $company_data->getName(),
  13881.                 'company_data' => $company_data,
  13882.                 'company_address' => $company_data->getAddress(),
  13883.                 'company_image' => $company_data->getImage(),
  13884.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13885.                 'red' => 0
  13886.             )
  13887.         );
  13888.     }
  13889. //PR
  13890.     public
  13891.     function PrListAction(Request $request)
  13892.     {
  13893.         $q $this->getDoctrine()
  13894.             ->getRepository('ApplicationBundle\\Entity\\PurchaseRequisition')
  13895.             ->findBy(
  13896.                 array(
  13897.                     'status' => GeneralConstant::ACTIVE,
  13898. //                    'approved' =>  GeneralConstant::APPROVED,
  13899.                 ),
  13900.                 array(
  13901.                     'purchaseRequisitionDate' => 'DESC'
  13902.                 )
  13903.             );
  13904.         $stage_list = array(
  13905.             => 'Pending',
  13906.             => 'Pending',
  13907.             => 'Complete',
  13908.             => 'Partial',
  13909.         );
  13910.         $data = [];
  13911.         foreach ($q as $entry) {
  13912.             $data[] = array(
  13913.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  13914.                 'id' => $entry->getPurchaseRequisitionId(),
  13915.                 'doc_hash' => $entry->getDocumentHash(),
  13916.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13917.                 'acquisition_status' => $entry->getAcquisitionStatus(),
  13918.                 'acquisition_start_date' => $entry->getAcquisitionStartDate(),
  13919.                 'acquisition_end_date' => $entry->getAcquisitionEndDate(),
  13920.                 'acquisition_method' => $entry->getquotationAcquisitionMethod(),
  13921.                 'poTagged' => $entry->getPoTagged(),
  13922.                 'typeHash' => $entry->getTypehash(),
  13923.                 'srIds' => $entry->getSrIds(),
  13924.                 'irIds' => $entry->getIrIds(),
  13925.                 'prIds' => $entry->getPrIds(),
  13926.                 'poIds' => $entry->getPoIds(),
  13927.             );
  13928.         }
  13929.         return $this->render('@Inventory/pages/views/pr_list.html.twig',
  13930.             array(
  13931.                 'page_title' => 'Purchase Requisition List',
  13932.                 'data' => $data
  13933.             )
  13934.         );
  13935.     }
  13936.     public
  13937.     function ServiceRequisitionListAction(Request $request)
  13938.     {
  13939.         $q $this->getDoctrine()
  13940.             ->getRepository('ApplicationBundle\\Entity\\PurchaseRequisition')
  13941.             ->findBy(
  13942.                 array(
  13943.                     'status' => GeneralConstant::ACTIVE,
  13944. //                    'approved' =>  GeneralConstant::APPROVED,
  13945.                 ),
  13946.                 array(
  13947.                     'purchaseRequisitionDate' => 'DESC'
  13948.                 )
  13949.             );
  13950.         $stage_list = array(
  13951.             => 'Pending',
  13952.             => 'Pending',
  13953.             => 'Complete',
  13954.             => 'Partial',
  13955.         );
  13956.         $data = [];
  13957.         foreach ($q as $entry) {
  13958.             $data[] = array(
  13959.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  13960.                 'id' => $entry->getPurchaseRequisitionId(),
  13961.                 'doc_hash' => $entry->getDocumentHash(),
  13962.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13963.                 'poTagged' => $entry->getPoTagged(),
  13964.                 'typeHash' => $entry->getTypehash(),
  13965.                 'srIds' => $entry->getSrIds(),
  13966.                 'irIds' => $entry->getIrIds(),
  13967.                 'prIds' => $entry->getPrIds(),
  13968.                 'poIds' => $entry->getPoIds(),
  13969.             );
  13970.         }
  13971.         return $this->render('@Inventory/pages/views/service_requisition_list.html.twig',
  13972.             array(
  13973.                 'page_title' => 'Service Requisition List',
  13974.                 'data' => $data
  13975.             )
  13976.         );
  13977.     }
  13978.     public
  13979.     function ViewPrAction(Request $request$id)
  13980.     {
  13981.         $em $this->getDoctrine()->getManager();
  13982.         $dt Inventory::GetPrDetails($em$id);
  13983.         $companyId $this->getLoggedUserCompanyId($request);
  13984.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  13985.             array(
  13986.                 'page_title' => 'Purchase Requisition',
  13987.                 'data' => $dt,
  13988.                 'branchList' => Client::BranchList($em$companyId),
  13989.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  13990.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13991.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13992.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13993.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13994.                     $id,
  13995.                     $dt['created_by'],
  13996.                     $dt['edited_by'])
  13997.             )
  13998.         );
  13999.     }
  14000.     public
  14001.     function ViewServiceRequisitionAction(Request $request$id)
  14002.     {
  14003.         $em $this->getDoctrine()->getManager();
  14004.         $dt Inventory::GetPrDetails($em$id);
  14005.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  14006.             array(
  14007.                 'page_title' => 'Service Requisition',
  14008.                 'data' => $dt,
  14009.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14010.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14011.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14012.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14013.                     $id,
  14014.                     $dt['created_by'],
  14015.                     $dt['edited_by'])
  14016.             )
  14017.         );
  14018.     }
  14019.     public
  14020.     function PrintPrAction(Request $request$id)
  14021.     {
  14022.         $em $this->getDoctrine()->getManager();
  14023.         $dt Inventory::GetPrDetails($em$id);
  14024.         $companyId $this->getLoggedUserCompanyId($request);
  14025.         $company_data Company::getCompanyData($em$companyId);
  14026.         $document_mark = array(
  14027.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  14028.             'copy' => ''
  14029.         );
  14030.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  14031.             $html $this->renderView('@Inventory/pages/print/print_pr.html.twig',
  14032.                 array(
  14033.                     //full array here
  14034.                     'pdf' => true,
  14035.                     'page_title' => 'Purchase Requisition',
  14036.                     'export' => 'pdf,print',
  14037.                     'data' => $dt,
  14038.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14039.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14040.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14041.                         array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14042.                         $id,
  14043.                         $dt['created_by'],
  14044.                         $dt['edited_by']),
  14045.                     'document_mark_image' => $document_mark['original'],
  14046.                     'branchList' => Client::BranchList($em$companyId),
  14047.                     'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  14048.                     'company_name' => $company_data->getName(),
  14049.                     'company_data' => $company_data,
  14050.                     'company_address' => $company_data->getAddress(),
  14051.                     'company_image' => $company_data->getImage(),
  14052.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  14053.                     'red' => 0
  14054.                 )
  14055.             );
  14056.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  14057. //                'orientation' => 'landscape',
  14058. //                'enable-javascript' => true,
  14059. //                'javascript-delay' => 1000,
  14060.                 'no-stop-slow-scripts' => false,
  14061.                 'no-background' => false,
  14062.                 'lowquality' => false,
  14063.                 'encoding' => 'utf-8',
  14064. //            'images' => true,
  14065. //            'cookie' => array(),
  14066.                 'dpi' => 300,
  14067.                 'image-dpi' => 300,
  14068. //                'enable-external-links' => true,
  14069. //                'enable-internal-links' => true
  14070.             ));
  14071.             return new Response(
  14072.                 $pdf_response,
  14073.                 200,
  14074.                 array(
  14075.                     'Content-Type' => 'application/pdf',
  14076.                     'Content-Disposition' => 'attachment; filename="purchase_requisition_' $id '.pdf"'
  14077.                 )
  14078.             );
  14079.         }
  14080.         return $this->render('@Inventory/pages/print/print_pr.html.twig',
  14081.             array(
  14082.                 'page_title' => 'Purchase Requisition',
  14083.                 'export' => 'pdf,print',
  14084.                 'data' => $dt,
  14085.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14086.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14087.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14088.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14089.                     $id,
  14090.                     $dt['created_by'],
  14091.                     $dt['edited_by']),
  14092.                 'document_mark_image' => $document_mark['original'],
  14093.                 'company_name' => $company_data->getName(),
  14094.                 'company_data' => $company_data,
  14095.                 'branchList' => Client::BranchList($em$companyId),
  14096.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  14097.                 'company_address' => $company_data->getAddress(),
  14098.                 'company_image' => $company_data->getImage(),
  14099.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  14100.                 'red' => 0
  14101.             )
  14102.         );
  14103.     }
  14104.     public
  14105.     function CreateSecondaryDeliveryReceiptAction(Request $request)
  14106.     {
  14107.         $em $this->getDoctrine()->getManager();
  14108.         $companyId $this->getLoggedUserCompanyId($request);
  14109.         $userBranchIdList $request->getSession()->get('branchIdList');
  14110.         if ($userBranchIdList == null$userBranchIdList = [];
  14111.         $userBranchId $request->getSession()->get('branchId');
  14112.         if ($request->isMethod('POST')) {
  14113.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  14114.             $dochash $request->request->get('docHash'); //change
  14115.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14116.             $approveRole 1;  //created
  14117.             $approveHash $request->request->get('approvalHash');
  14118.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  14119.                 $loginId$approveRole$approveHash)
  14120.             ) {
  14121.                 $this->addFlash(
  14122.                     'error',
  14123.                     'Sorry Couldnot insert Data.'
  14124.                 );
  14125.             } else {
  14126.                 $receiptId SalesOrderM::CreateNewSecondaryDeliveryReceipt($this->getDoctrine()->getManager(), $request->request,
  14127.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  14128.                     $this->getLoggedUserCompanyId($request));
  14129.                 //now add Approval info
  14130.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14131.                 $approveRole 1;  //created
  14132.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  14133.                     $receiptId,
  14134.                     $loginId,
  14135.                     $approveRole,
  14136.                     $request->request->get('approvalHash'));
  14137.                 $options = array(
  14138.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  14139.                     'notification_server' => $this->container->getParameter('notification_server'),
  14140.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  14141.                     'url' => $this->generateUrl(
  14142.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  14143.                         ['entity_view_route_path_name']
  14144.                     )
  14145.                 );
  14146.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  14147.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  14148.                     $receiptId,
  14149.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  14150.                 );
  14151.                 $this->addFlash(
  14152.                     'success',
  14153.                     'New Delivery Receipt Created'
  14154.                 );
  14155.                 $url $this->generateUrl(
  14156.                     'view_delivery_receipt'
  14157.                 );
  14158.                 return $this->redirect($url "/" $receiptId);
  14159.             }
  14160.         }
  14161.         $debugData = [];
  14162. //        $dr_data=$em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findOneBy(
  14163. //            array(
  14164. //                'deliveryReceiptId'=>$dr_id
  14165. //            )
  14166. //        );
  14167.         $new_swld = new \DateTime('2017-07-09');
  14168. //        if ($entry->getWarranty() > 0)
  14169. //            $new_swld->modify('+' . $entry->getWarranty() . ' month');
  14170.         $debugData[] = $new_swld->format('Y-m-d');
  14171.         $debugData[] = $new_swld;
  14172. //        $debugData[]=$dr_data->getDeliveryReceiptDate();
  14173.         $debugData[] = '+' '1' ' month';
  14174.         $branchList Client::BranchList($em$companyId, [], $userBranchIdList);
  14175.         $warehouseIds = [];
  14176.         foreach ($branchList as $br) {
  14177.             $warehouseIds[] = $br['warehouseId'];
  14178.         }
  14179.         return $this->render('@Inventory/pages/input_forms/secondaryDeliveryReceipt.html.twig',
  14180.             array(
  14181.                 'page_title' => 'New Delivery Receipt',
  14182.                 'ExistingClients' => Accounts::getClientLedgerHeads($em),
  14183.                 'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($em),
  14184.                 'ClientList' => SalesOrderM::GetSecondaryClientList($em),
  14185.                 'warehouse' => Inventory::WarehouseList($em$companyId$warehouseIds),
  14186.                 'salesOrders' => SalesOrderM::SecondarySalesOrderListPendingDelivery($em$warehouseIds),
  14187.                 'salesOrdersArray' => SalesOrderM::SecondarySalesOrderListPendingDeliveryArray($em$warehouseIds),
  14188.                 'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
  14189.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
  14190.                 'debugData' => $debugData,
  14191.             )
  14192.         );
  14193.     }
  14194.     public function AddUnitTypeAction(Request $request$id 0)
  14195.     {
  14196.         $em $this->getDoctrine()->getManager();
  14197.         $unitType $id != $em->getRepository(UnitType::class)->find($id) : null;
  14198.         if ($request->isMethod('POST')) {
  14199.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14200.             Inventory::CreateUnitType($em$id$request->request$loginId);
  14201.             $this->addFlash(
  14202.                 'success',
  14203.                 $id != 'Unit Type Updated' 'Unit Type Added'
  14204.             );
  14205.             $unitType $id != $em->getRepository(UnitType::class)->find($id) : null;
  14206.         }
  14207.         $unitTypeDetails $em->getRepository(UnitType::class)->findBy(array(), array('name' => 'ASC'));
  14208.         $existingConversionMap = [];
  14209.         if ($unitType && $unitType->getConversion() != '') {
  14210.             $existingConversionMap json_decode($unitType->getConversion(), true);
  14211.             if ($existingConversionMap == null) {
  14212.                 $existingConversionMap = [];
  14213.             }
  14214.         }
  14215.         return $this->render('@Inventory/pages/input_forms/addUnitType.html.twig',
  14216.             array(
  14217.                 'page_title' => $id != 'Edit Unit Type' 'Add Unit Type',
  14218.                 'ex_id' => $id,
  14219.                 'ex_det' => $unitType,
  14220.                 'existingConversionMap' => $existingConversionMap,
  14221.                 'unitTypeDetails' => $unitTypeDetails,
  14222.                 'unitTypeRecords' => $unitTypeDetails
  14223.             )
  14224.         );
  14225.     }
  14226.     public function AddCurrencyAction(Request $request$id 0)
  14227.     {
  14228.         $em $this->getDoctrine()->getManager();
  14229.         $currency $id != $em->getRepository(Currencies::class)->find($id) : null;
  14230.         if ($request->isMethod('POST')) {
  14231.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14232.             Inventory::CreateCurrency($em$id$request->request$loginId);
  14233.             $this->addFlash(
  14234.                 'success',
  14235.                 $id != 'Currency Updated' 'Currency Added'
  14236.             );
  14237.             $currency $id != $em->getRepository(Currencies::class)->find($id) : null;
  14238.         }
  14239.         $currencyDetails $em->getRepository(Currencies::class)->findBy(array(), array('code' => 'ASC'));
  14240.         $existingConversionMap = [];
  14241.         if ($currency && $currency->getConversionData() != '') {
  14242.             $existingConversionMap json_decode($currency->getConversionData(), true);
  14243.             if ($existingConversionMap == null) {
  14244.                 $existingConversionMap = [];
  14245.             }
  14246.         }
  14247.         return $this->render('@Inventory/pages/input_forms/addCurrency.html.twig',
  14248.             array(
  14249.                 'page_title' => $id != 'Edit Currency' 'Add Currency',
  14250.                 'ex_id' => $id,
  14251.                 'ex_det' => $currency,
  14252.                 'existingConversionMap' => $existingConversionMap,
  14253.                 'currencyDetails' => $currencyDetails,
  14254.                 'currencyRecords' => $currencyDetails
  14255.             )
  14256.         );
  14257.     }
  14258.     public
  14259.     function SubcategoryListAction()
  14260.     {
  14261.         return $this->render('@Inventory/pages/input_forms/subCategoryList.html.twig',
  14262.             array(
  14263.                 'page_title' => 'Sub Category List',
  14264.             )
  14265.         );
  14266.     }
  14267. //    public function getInventoryProductList(Request $request)
  14268. //    {
  14269. //        $em = $this->getDoctrine()->getManager();
  14270. //
  14271. //        $page = (int) $request->query->get('page', 1);     // Default page = 1
  14272. //        $limit = (int) $request->query->get('limit', 10);   // Default limit = 10
  14273. //        $offset = ($page - 1) * $limit;
  14274. //
  14275. //        // First, get the total count of products
  14276. //        $totalQuery = $em->createQueryBuilder()
  14277. //            ->select('COUNT(i.id)')
  14278. //            ->from('ApplicationBundle:InventoryStorage', 'i')
  14279. //            ->where('i.qty > :minQty')
  14280. //            ->setParameter('minQty', 0)
  14281. //            ->getQuery();
  14282. //
  14283. //        $totalRecords = (int) $totalQuery->getSingleScalarResult();
  14284. //        $totalPages = $limit > 0 ? (int) ceil($totalRecords / $limit) : 1;
  14285. //
  14286. //        // Then, get the paginated data
  14287. //        $qb = $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->createQueryBuilder('i')
  14288. //            ->select([
  14289. //                'i.productId AS productId',
  14290. //                'COALESCE(ig.name, \'\') AS itemGroupName',
  14291. //                'COALESCE(w.name, \'\') AS wareHouseName',
  14292. //                'i.qty AS quantity',
  14293. //                'COALESCE(b.name, \'\') AS brandName',
  14294. //                'COALESCE(u.name, \'\') AS UnitName',
  14295. //                'COALESCE(c.name, \'\') AS color',
  14296. //                'COALESCE(s.name, \'\') AS size',
  14297. //                'COALESCE(i.salesPrice, 0) AS salesPrice',
  14298. //                'COALESCE(p.name, \'\') AS productName'
  14299. //            ])
  14300. //            ->leftJoin('ApplicationBundle:InvProducts', 'p', 'WITH', 'i.productId = p.id')
  14301. //            ->leftJoin('ApplicationBundle:InvItemGroup', 'ig', 'WITH', 'i.igId = ig.id')
  14302. //            ->leftJoin('ApplicationBundle:Warehouse', 'w', 'WITH', 'i.warehouseId = w.id')
  14303. //            ->leftJoin('ApplicationBundle:BrandCompany', 'b', 'WITH', 'i.brandId = b.id')
  14304. //            ->leftJoin('ApplicationBundle:UnitType', 'u', 'WITH', 'i.unitTypeId = u.id')
  14305. //            ->leftJoin('ApplicationBundle:Colors', 'c', 'WITH', 'i.color = c.id')
  14306. //            ->leftJoin('ApplicationBundle:ProductSizes', 's', 'WITH', 'i.size = s.id')
  14307. //            ->where('i.qty > :minQty')
  14308. //            ->setParameter('minQty', 0)
  14309. //            ->setFirstResult($offset)
  14310. //            ->setMaxResults($limit);
  14311. //
  14312. //        $inventoryData = $qb->getQuery()->getResult();
  14313. //
  14314. //        return $this->json([
  14315. //            'page' => $page,
  14316. //            'limit' => $limit,
  14317. //            'totalRecords' => $totalRecords,
  14318. //            'totalPages' => $totalPages,
  14319. //            'data' => $inventoryData,
  14320. //        ]);
  14321. //    }
  14322.     public function getInventoryProductList(Request $request)
  14323.     {
  14324.         $em $this->getDoctrine()->getManager();
  14325.         $page = (int)$request->query->get('page'1);
  14326.         $limit = (int)$request->query->get('limit'10);
  14327.         $offset = ($page 1) * $limit;
  14328.         $totalQuery $em->createQueryBuilder()
  14329.             ->select('COUNT(i.id)')
  14330.             ->from('ApplicationBundle:InventoryStorage''i')
  14331.             ->where('i.qty > :minQty')
  14332.             ->setParameter('minQty'0)
  14333.             ->getQuery();
  14334.         $totalRecords = (int)$totalQuery->getSingleScalarResult();
  14335.         $totalPages $limit ? (int)ceil($totalRecords $limit) : 1;
  14336.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14337.         $qb $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->createQueryBuilder('i')
  14338.             ->select([
  14339.                 'i.productId AS productId',
  14340.                 'COALESCE(ig.name, \'\') AS itemGroupName',
  14341.                 'COALESCE(w.name, \'\') AS wareHouseName',
  14342.                 'COALESCE(wa.name, \'\') AS subWareHouseName',
  14343.                 'i.qty AS quantity',
  14344.                 'i.qty AS lastSold',
  14345.                 'i.qty AS lastPurchase',
  14346.                 'COALESCE(b.name, \'\') AS brandName',
  14347.                 'COALESCE(u.name, \'\') AS UnitName',
  14348.                 'COALESCE(c.name, \'\') AS color',
  14349.                 'COALESCE(s.name, \'\') AS size',
  14350.                 'COALESCE(i.purchasePrice, 0) AS purchasePrice',
  14351.                 'COALESCE(i.salesPrice, 0) AS salesPrice',
  14352.                 'COALESCE(p.name, \'\') AS productName',
  14353.                 'COALESCE(p.productCode, \'\') AS productCode',
  14354.                 "CASE 
  14355.                 WHEN p.images IS NOT NULL AND p.images <> '' 
  14356.                 THEN p.images 
  14357.                 ELSE '$defaultImage
  14358.             END AS image"
  14359.             ])
  14360.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  14361.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''i.igId = ig.id')
  14362.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''i.warehouseId = w.id')
  14363.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''i.actionTagId = wa.id')
  14364.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''i.brandId = b.id')
  14365.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''i.unitTypeId = u.id')
  14366.             ->leftJoin('ApplicationBundle:Colors''c''WITH''i.color = c.id')
  14367.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''i.size = s.id')
  14368.             ->where('i.qty > :minQty')
  14369.             ->setParameter('minQty'0)
  14370.             ->setFirstResult($offset)
  14371.             ->setMaxResults($limit);
  14372.         $inventoryData $qb->getQuery()->getResult();
  14373.         return $this->json([
  14374.             'page' => $page,
  14375.             'limit' => $limit,
  14376.             'totalRecords' => $totalRecords,
  14377.             'totalPages' => $totalPages,
  14378.             'data' => $inventoryData,
  14379.         ]);
  14380.     }
  14381.     public function CreateStockTransferForAppAction(Request $request)
  14382.     {
  14383.         $em $this->getDoctrine()->getManager();
  14384.         $companyId $this->getLoggedUserCompanyId($request);
  14385.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  14386.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  14387.         if ($request->isMethod('POST')) {
  14388.             $em $this->getDoctrine()->getManager();
  14389.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  14390.             $dochash $request->request->get('docHash'); //change
  14391.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14392.             $approveRole $request->request->get('approvalRole');
  14393.             $approveHash $request->request->get('approvalHash');
  14394.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  14395.                 $loginId$approveRole$approveHash)
  14396.             ) {
  14397.                 $this->addFlash(
  14398.                     'error',
  14399.                     'Sorry Couldnot insert Data.'
  14400.                 );
  14401.             } else {
  14402.                 if ($request->request->has('check_allowed'))
  14403.                     $check_allowed 1;
  14404.                 $StID Inventory::CreateNewStockTransferForAPP(
  14405.                     $this->getDoctrine()->getManager(),
  14406.                     $request->request,
  14407.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  14408.                     $this->getLoggedUserCompanyId($request)
  14409.                 );
  14410.                 //now add Approval info
  14411.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14412.                 $approveRole 1;  //created
  14413.                 $options = array(
  14414.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  14415.                     'notification_server' => $this->container->getParameter('notification_server'),
  14416.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  14417.                     'url' => $this->generateUrl(
  14418.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  14419.                         ['entity_view_route_path_name']
  14420.                     )
  14421.                 );
  14422.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  14423.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  14424.                     $StID,
  14425.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  14426.                 );
  14427.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  14428.                     $loginId,
  14429.                     $approveRole,
  14430.                     $request->request->get('approvalHash'));
  14431.                 $this->addFlash(
  14432.                     'success',
  14433.                     'Stock Transfer Added.'
  14434.                 );
  14435.                 $url $this->generateUrl(
  14436.                     'view_st'
  14437.                 );
  14438. //                return $this->redirect($url . "/" . $StID);
  14439.                 return $this->json(['success' => true]);
  14440.             }
  14441.         }
  14442.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  14443.             array(
  14444.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  14445.             )
  14446.         );
  14447.         $INVLIST = [];
  14448.         foreach ($slotList as $slot) {
  14449.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  14450.         }
  14451.         return $this->json(['success' => true]);
  14452. //       return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  14453. //           array(
  14454. //         'page_title' => 'Stock Transfer Note',
  14455. //               'warehouseList' => Inventory::WarehouseList($em),
  14456. //        'warehouseListArray' => Inventory::WarehouseListArray($em),
  14457. //               'colorList' => Inventory::GetColorList($em),
  14458. //               'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  14459. //                'srList' => [],
  14460. //               'warehouseActionList' => $warehouse_action_list,
  14461. //                'warehouseActionListArray' => $warehouse_action_list_array,
  14462. //                'item_list' => Inventory::ItemGroupList($em),
  14463. //                'item_list_array' => Inventory::ItemGroupListArray($em),
  14464. //               'category_list_array' => Inventory::ProductCategoryListArray($em),
  14465. //              'product_list_array' => Inventory::ProductListDetailedArray($em),
  14466. ////               'product_list_array' => [],
  14467. //               'product_list' => Inventory::ProductList($em, $companyId),
  14468. ////                'product_list' => [],
  14469. //               'prefix_list' => array(
  14470. //                   [
  14471. //                       'id' => 1,
  14472. //                       'value' => 'GN',
  14473. //                        'text' => 'GN'
  14474. //
  14475. //                   ]
  14476. //              ),
  14477. //              'assoc_list' => array(
  14478. //                  [
  14479. //                       'id' => 1,
  14480. //                        'value' => 1,
  14481. //                        'text' => 'GN'
  14482. //
  14483. //                  ]
  14484. //               ),
  14485. //              'INVLIST' => $INVLIST
  14486. //           )
  14487. //      );
  14488.     }
  14489.     public function getWarehouseList(Request $request)
  14490.     {
  14491.         $em $this->getDoctrine()->getManager();
  14492.         $warehouses $em->getRepository('ApplicationBundle\\Entity\\Warehouse')
  14493.             ->createQueryBuilder('w')
  14494.             ->select('w.id''w.name')
  14495.             ->orderBy('w.name''ASC')
  14496.             ->getQuery()
  14497.             ->getResult();
  14498.         return $this->json($warehouses);
  14499.     }
  14500.     public function getSubWarehouseList(Request $request)
  14501.     {
  14502.         $em $this->getDoctrine()->getManager();
  14503.         $warehouses $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')
  14504.             ->createQueryBuilder('w')
  14505.             ->select('w.id''w.name')
  14506. //            ->orderBy('w.name', 'ASC')
  14507.             ->getQuery()
  14508.             ->getResult();
  14509.         return $this->json($warehouses);
  14510.     }
  14511.     public function getStockReceiveList(Request $request)
  14512.     {
  14513.         $list GeneralConstant::$stockReceiveType;
  14514.         return $this->json($list);
  14515.     }
  14516.     public function getOrderListByStockReceiveId(Request $request)
  14517.     {
  14518.         $em $this->getDoctrine()->getManager();
  14519.         $typeName $request->request->get('type');
  14520.         $typeId $request->request->get('id');
  14521.         $document null;
  14522.         if ($typeName == 'From Stock Transfer' || $typeId == 1) {
  14523.             $document $em->getRepository('ApplicationBundle\\Entity\\StockTransfer')->createQueryBuilder('s')->select('s.stockTransferId''s.documentHash')->where('s.approved !=1')->getQuery()->getResult();
  14524.         } else if ($typeName == 'For Stock In' || $typeId == 3) {
  14525.             $document $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->createQueryBuilder('a')->select('a.accountsHeadId''a.name')->getQuery()->getResult();
  14526.         } else if ($typeName == 'For Opening Entity' || $typeId == 4) {
  14527.             $document $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')
  14528.                 ->createQueryBuilder('w')
  14529.                 ->select('w.id''w.name')
  14530.                 ->getQuery()
  14531.                 ->getResult();
  14532.         }
  14533.         return $this->json($document);
  14534.     }
  14535.     public function GetProductFromInvStorage(Request $request)
  14536.     {
  14537.         $em $this->getDoctrine()->getManager();
  14538.         $searchTerm trim($request->get('name'));
  14539.         // Fetch all or filtered products
  14540.         if ($searchTerm) {
  14541.             $products $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  14542.                 ->createQueryBuilder('p')
  14543.                 ->where('p.name LIKE :term')
  14544.                 ->setParameter('term''%' $searchTerm '%')
  14545.                 ->getQuery()
  14546.                 ->getResult();
  14547.         } else {
  14548.             $products $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findAll();
  14549.         }
  14550.         $response = [];
  14551.         foreach ($products as $product) {
  14552.             // All InventoryStorage entries for the product
  14553.             $invStorageItems $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy([
  14554.                 'productId' => $product->getId()
  14555.             ]);
  14556.             $inventoryList = [];
  14557.             foreach ($invStorageItems as $item) {
  14558.                 $warehouse $em->getRepository('ApplicationBundle\\Entity\\Warehouse')->find($item->getWarehouseId());
  14559.                 $subWarehouse $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')->find($item->getActionTagId());
  14560.                 $inventoryList[] = [
  14561.                     'warehouse_id' => $item->getWarehouseId(),
  14562.                     'warehouse_name' => $warehouse $warehouse->getName() : '',
  14563.                     'sub_warehouse_id' => $item->getActionTagId(),
  14564.                     'sub_warehouse_name' => $subWarehouse $subWarehouse->getName() : '',
  14565.                     'quantity' => $item->getQty(),
  14566.                     'lastSold' => $item->getNonInvoicedQty(),
  14567.                     'lastPurchase' => $item->getPhysicalQty(),
  14568.                     'purchasePrice' => $item->getPurchasePrice(),
  14569.                     'salesPrice' => $item->getSalesPrice(),
  14570.                     'brandName' => $item->getBrandId(),
  14571.                     'unitName' => 'pcs'// Optional: Resolve via Unit table
  14572.                 ];
  14573.             }
  14574.             $response[] = [
  14575.                 'productId' => $product->getId(),
  14576.                 'itemGroupName' => $product->getIgId(),
  14577.                 'productName' => $product->getName(),
  14578.                 'productCode' => $product->getProductCode(),
  14579.                 'color' => $product->getColors(),
  14580.                 'size' => $product->getSizes(),
  14581.                 'image' => $product->getDefaultImage(),
  14582.                 'inventory' => $inventoryList
  14583.             ];
  14584.         }
  14585.         return new JsonResponse($response);
  14586.     }
  14587.     public function getProductByDocumentId(Request $request)
  14588.     {
  14589.         $em $this->getDoctrine()->getManager();
  14590.         $documentId $request->request->get('documentId');
  14591.         $accountsHeadId $request->request->get('accountsHeadId');
  14592.         if ($documentId) {
  14593.             $productIdRows $em->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  14594.                 ->createQueryBuilder('s')
  14595.                 ->select('s.productId')
  14596.                 ->where('s.stockTransferId = :documentId')
  14597.                 ->setParameter('documentId'$documentId)
  14598.                 ->getQuery()
  14599.                 ->getResult();
  14600.             $fromWarehouseRow $em->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  14601.                 ->createQueryBuilder('s')
  14602.                 ->select('s.warehouseId''s.toWarehouseId''s.warehouseActionId''s.toWarehouseActionId''s.qty''s.price')
  14603.                 ->where('s.stockTransferId = :documentId')
  14604.                 ->setParameter('documentId'$documentId)
  14605.                 ->setMaxResults(1)
  14606.                 ->getQuery()
  14607.                 ->getOneOrNullResult();
  14608.             $productIds array_map(function ($row) {
  14609.                 return $row['productId'];
  14610.             }, $productIdRows);
  14611.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findBy([
  14612.                 'id' => $productIds
  14613.             ]);
  14614.             $productData array_map(function ($p) {
  14615.                 return [
  14616.                     'id' => $p->getId(),
  14617.                     'name' => $p->getName(),
  14618.                     'modelNo' => $p->getModelNo(),
  14619.                     'sku' => $p->getSkuCode(),
  14620.                     'productCode' => $p->getProductCode(),
  14621.                     'purchasePrice' => $p->getPurchasePrice(),
  14622.                     'salesPrice' => $p->getSalesPrice(),
  14623.                     'purchasePriceWoExpense' => $p->getPurchasePriceWoExpense(),
  14624.                     'qty' => $p->getQty(),
  14625.                     'nonInvoicedQty' => $p->getNonInvoicedQty(),
  14626.                     'nonSalesInvoicedQty' => $p->getNonSalesInvoicedQty(),
  14627.                     'unitTypeId' => $p->getUnitTypeId(),
  14628.                     'dimension' => $p->getDimension(),
  14629.                     'dimensionUnitTypeId' => $p->getDimensionUnitTypeId(),
  14630.                     'weight' => $p->getWeight(),
  14631.                     'categoryId' => $p->getCategoryId(),
  14632.                     'subCategoryId' => $p->getSubCategoryId(),
  14633.                     'brandCompany' => $p->getBrandCompany(),
  14634.                     'warehouseId' => $p->getWarehouseId(),
  14635.                     'reorderLevel' => $p->getReorderLevel(),
  14636.                     'defaultImage' => $p->getDefaultImage(),
  14637.                     'status' => $p->getStatus()
  14638.                 ];
  14639.             }, $product);
  14640.             return $this->json([
  14641.                 'warehouseId' => $fromWarehouseRow['warehouseId'],
  14642.                 'toWarehouseId' => $fromWarehouseRow['toWarehouseId'],
  14643.                 'warehouseActionId' => $fromWarehouseRow['warehouseActionId'],
  14644.                 'toWarehouseActionId' => $fromWarehouseRow['toWarehouseActionId'],
  14645.                 'quantity' => $fromWarehouseRow['qty'],
  14646.                 'price' => $fromWarehouseRow['price'],
  14647.                 'products' => $productData
  14648.             ]);
  14649.         } else if ($accountsHeadId) {
  14650.             $products $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findAll();
  14651.             $productData array_map(function ($p) {
  14652.                 return [
  14653.                     'id' => $p->getId(),
  14654.                     'name' => $p->getName(),
  14655.                     'modelNo' => $p->getModelNo(),
  14656.                     'sku' => $p->getSkuCode(),
  14657.                     'productCode' => $p->getProductCode(),
  14658.                     'purchasePrice' => $p->getPurchasePrice(),
  14659.                     'salesPrice' => $p->getSalesPrice(),
  14660.                     'purchasePriceWoExpense' => $p->getPurchasePriceWoExpense(),
  14661.                     'qty' => $p->getQty(),
  14662.                     'nonInvoicedQty' => $p->getNonInvoicedQty(),
  14663.                     'nonSalesInvoicedQty' => $p->getNonSalesInvoicedQty(),
  14664.                     'unitTypeId' => $p->getUnitTypeId(),
  14665.                     'dimension' => $p->getDimension(),
  14666.                     'dimensionUnitTypeId' => $p->getDimensionUnitTypeId(),
  14667.                     'weight' => $p->getWeight(),
  14668.                     'categoryId' => $p->getCategoryId(),
  14669.                     'subCategoryId' => $p->getSubCategoryId(),
  14670.                     'brandCompany' => $p->getBrandCompany(),
  14671.                     'warehouseId' => $p->getWarehouseId(),
  14672.                     'reorderLevel' => $p->getReorderLevel(),
  14673.                     'defaultImage' => $p->getDefaultImage(),
  14674.                     'status' => $p->getStatus()
  14675.                 ];
  14676.             }, $products);
  14677.             return $this->json($productData);
  14678.         } else {
  14679.             return new JsonResponse([
  14680.                 "status" => false,
  14681.                 "message" => "Please insert valid documentId or accountsHead!"
  14682.             ]);
  14683.         }
  14684.     }
  14685.     public function getQuantityBasedOnSubWareHouse(Request $request)
  14686.     {
  14687.         $em $this->getDoctrine()->getManager();
  14688.         $productId $request->get('product_id');
  14689.         $productName trim($request->get('product_name'));
  14690.         $warehouseId $request->get('warehouse_id');
  14691.         $warehouseActionId $request->get('warehouse_action_id');
  14692.         if (!$productId && $productName) {
  14693.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  14694.                 ->createQueryBuilder('p')
  14695.                 ->where('p.name LIKE :name')
  14696.                 ->setParameter('name''%' $productName '%')
  14697.                 ->setMaxResults(1)
  14698.                 ->getQuery()
  14699.                 ->getOneOrNullResult();
  14700.             if ($product) {
  14701.                 $productId $product->getId();
  14702.             }
  14703.         }
  14704.         if (!$productId || !$warehouseId || !$warehouseActionId) {
  14705.             return new JsonResponse(['error' => 'Product ID, Warehouse ID, and Action Tag ID are required'], 400);
  14706.         }
  14707.         $criteria = [
  14708.             'productId' => $productId,
  14709.             'warehouseId' => $warehouseId,
  14710.             'actionTagId' => $warehouseActionId,
  14711.         ];
  14712.         $invStorageItems $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy($criteria);
  14713.         if (empty($invStorageItems)) {
  14714.             return new JsonResponse([
  14715.                 'product_id' => $productId,
  14716.                 'quantities' => []
  14717.             ]);
  14718.         }
  14719.         $totalQty 0;
  14720.         $totalNonInvoicedQty 0;
  14721.         $totalPhysicalQty 0;
  14722.         $purchasePrice null;
  14723.         $salesPrice null;
  14724.         foreach ($invStorageItems as $item) {
  14725.             $totalQty += $item->getQty();
  14726.             $totalNonInvoicedQty += $item->getNonInvoicedQty();
  14727.             $totalPhysicalQty += $item->getPhysicalQty();
  14728.             $purchasePrice $item->getPurchasePrice();
  14729.             $salesPrice $item->getSalesPrice();
  14730.         }
  14731.         $subWarehouse $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')->find($warehouseActionId);
  14732.         $quantitiesBySubWarehouse = [[
  14733.             'action_tag_id' => $warehouseActionId,
  14734.             'sub_warehouse' => $subWarehouse $subWarehouse->getName() : '',
  14735.             'qty' => $totalQty,
  14736.             'non_invoiced_qty' => $totalNonInvoicedQty,
  14737.             'physical_qty' => $totalPhysicalQty,
  14738.             'purchase_price' => $purchasePrice,
  14739.             'sales_price' => $salesPrice,
  14740.         ]];
  14741.         return new JsonResponse([
  14742.             'product_id' => $productId,
  14743.             'quantities' => $quantitiesBySubWarehouse
  14744.         ]);
  14745.     }
  14746.     public function getPriceByWareHouseId(Request $request)
  14747.     {
  14748.         $em $this->getDoctrine()->getManager();
  14749.         $warehouseId $request->request->get('warehouseId');
  14750.         $productId $request->request->get('productId');
  14751.         $actionTagId $request->request->get('actionTagId');
  14752.         $unitPrice $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->createQueryBuilder('st')
  14753.             ->select('st.purchasePrice AS purchasePrice')
  14754.             ->where('st.productId = :productId')
  14755.             ->andWhere('st.warehouseId = :warehouseId')
  14756.             ->andWhere('st.actionTagId = :actionTagId')
  14757.             ->setParameter('productId'$productId)
  14758.             ->setParameter('warehouseId'$warehouseId)
  14759.             ->setParameter('actionTagId'$actionTagId)
  14760.             ->setMaxResults(1)
  14761.             ->getQuery()
  14762.             ->getOneOrNullResult();
  14763.         return new JsonResponse([
  14764.             'purchasePrice' => $unitPrice $unitPrice['purchasePrice'] : null
  14765.         ]);
  14766.     }
  14767.     public function getStockTransferList(Request $request)
  14768.     {
  14769.         $em $this->getDoctrine()->getManager();
  14770.         $warehouses $em->getRepository('ApplicationBundle\\Entity\\StockTransfer')
  14771.             ->createQueryBuilder('s')
  14772.             ->select('s.stockTransferId''s.documentHash')
  14773. //            ->orderBy('s.name', 'ASC')
  14774.             ->getQuery()
  14775.             ->getResult();
  14776.         return $this->json($warehouses);
  14777.     }
  14778.     public function stockTransferItemList(Request $request)
  14779.     {
  14780.         $em $this->getDoctrine()->getManager();
  14781.         $stockTransferId $request->query->get('stockTransferId');
  14782.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14783.         $qb $em->createQueryBuilder();
  14784.         $qb->select(
  14785.             'sti.id AS id',
  14786.             'sti.productId AS productId',
  14787.             'sti.stockTransferId AS stockTransferId',
  14788.             'p.name AS productName',
  14789.             'sti.price AS price',
  14790.             'p.images AS images',
  14791.             'ig.name AS itemGroupName',
  14792.             'w.name AS wareHouseName',
  14793.             'sti.warehouseId AS warehouseId',
  14794.             'wa.name AS subWareHouseName',
  14795.             'sti.warehouseActionId AS warehouseActionId',
  14796.             'sti.qty AS quantity',
  14797.             'b.name AS brandName',
  14798.             'u.name AS UnitName',
  14799.             'c.name AS color',
  14800.             's.name AS size'
  14801.         )
  14802.             ->from('ApplicationBundle:StockTransferItem''sti')
  14803.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''sti.productId = p.id')
  14804.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''p.igId = ig.id')
  14805.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''sti.warehouseId = w.id')
  14806.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''sti.warehouseActionId = wa.id')
  14807.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''p.brandCompany = b.id')
  14808.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''p.unitTypeId = u.id')
  14809.             ->leftJoin('ApplicationBundle:Colors''c''WITH''sti.colorId = c.id')
  14810.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''sti.sizeId = s.id')
  14811.             ->where('sti.stockTransferId = :stockTransferId')
  14812.             ->setParameter('stockTransferId'$stockTransferId);
  14813.         $results $qb->getQuery()->getResult();
  14814.         $response = [];
  14815.         foreach ($results as $item) {
  14816.             $response[] = [
  14817.                 'id' => $item['id'],
  14818.                 'stockTransferId' => $item['stockTransferId'],
  14819.                 'productId' => (int)$item['productId'],
  14820.                 'itemGroupName' => $item['itemGroupName'] ?? '',
  14821.                 'wareHouseName' => $item['wareHouseName'] ?? '',
  14822.                 'wareHouseId' => $item['warehouseId'] ?? '',
  14823.                 'subWareHouseName' => $item['subWareHouseName'] ?? '',
  14824.                 'subWareHouseId' => $item['warehouseActionId'] ?? '',
  14825.                 'quantity' => (int)$item['quantity'],
  14826.                 'brandName' => $item['brandName'] ?? '',
  14827.                 'UnitName' => $item['UnitName'] ?? '',
  14828.                 'color' => $item['color'] ?? '',
  14829.                 'size' => $item['size'] ?? '',
  14830.                 'price' => (float)$item['price'],
  14831.                 'productName' => $item['productName'] ?? '',
  14832.                 'image' => !empty($item['images']) ? $item['images'] : $defaultImage,
  14833.             ];
  14834.         }
  14835.         return $this->json($response);
  14836.     }
  14837.     public function inventoryStorageFilter(Request $request)
  14838.     {
  14839.         $em $this->getDoctrine()->getManager();
  14840.         $qb $em->createQueryBuilder();
  14841.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14842.         $qb->select(
  14843.             'i.productId',
  14844.             'ig.name AS itemGroupName',
  14845.             'w.name AS wareHouseName',
  14846.             'wa.name AS subWareHouseName',
  14847.             'i.qty AS quantity',
  14848.             'b.name AS brandName',
  14849.             'u.name AS UnitName',
  14850.             'c.name AS color',
  14851.             's.name AS size',
  14852.             'i.purchasePrice AS price',
  14853.             'p.name AS productName',
  14854.             'p.images'
  14855.         )
  14856.             ->from('ApplicationBundle:InventoryStorage''i')
  14857.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  14858.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''i.igId = ig.id')
  14859.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''i.warehouseId = w.id')
  14860.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''i.brandId = b.id')
  14861.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''i.unitTypeId = u.id')
  14862.             ->leftJoin('ApplicationBundle:Colors''c''WITH''i.color = c.id')
  14863.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''i.size = s.id')
  14864.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''i.actionTagId = wa.id');
  14865.         // Define available filters with their mappings
  14866.         $filters = [
  14867.             'itemGroup' => 'ig.id',
  14868.             'category' => 'p.categoryId',
  14869.             'warehouse' => 'w.id',
  14870.             'storageType' => 'i.actionTagId',
  14871.             'brand' => 'b.id',
  14872.             'color' => 'c.id',
  14873.             'colorCode' => 'c.hexCode',
  14874.             'size' => 's.id',
  14875.         ];
  14876.         foreach ($filters as $param => $field) {
  14877.             $value $request->query->get($param);
  14878.             if ($value !== null) {
  14879.                 $values array_map('trim'explode(','$value));
  14880.                 if (count($values) > 1) {
  14881.                     $qb->andWhere($qb->expr()->in($field":$param"))
  14882.                         ->setParameter($param$values);
  14883.                 } else {
  14884.                     $qb->andWhere("$field = :$param")
  14885.                         ->setParameter($param$values[0]);
  14886.                 }
  14887.             }
  14888.         }
  14889.         $rawResult $qb->getQuery()->getArrayResult();
  14890.         $finalResult = [];
  14891.         foreach ($rawResult as $row) {
  14892.             $finalResult[] = [
  14893.                 'productId' => $row['productId'],
  14894.                 'itemGroupName' => $row['itemGroupName'],
  14895.                 'wareHouseName' => $row['wareHouseName'],
  14896.                 'subWareHouseName' => $row['subWareHouseName'],
  14897.                 'quantity' => $row['quantity'],
  14898.                 'brandName' => $row['brandName'],
  14899.                 'UnitName' => $row['UnitName'],
  14900.                 'color' => $row['color'] ?? '',
  14901.                 'size' => $row['size'] ?? '',
  14902.                 'price' => $row['price'],
  14903.                 'productName' => $row['productName'],
  14904.                 'image' => !empty($row['images']) ? $row['images'] : $defaultImage,
  14905.             ];
  14906.         }
  14907.         // Check if finalResult is empty
  14908.         if (empty($finalResult)) {
  14909.             return $this->json([
  14910.                 'success' => false,
  14911.                 'message' => 'No inventory items found matching your criteria'
  14912.             ]);
  14913.         }
  14914.         return $this->json([
  14915.             'success' => true,
  14916.             'data' => $finalResult
  14917.         ]);
  14918.     }
  14919. //    public function inventoryStorageFilter(Request $request)
  14920. //    {
  14921. //        $em = $this->getDoctrine()->getManager();
  14922. //        $qb = $em->createQueryBuilder();
  14923. //        $defaultImage = 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14924. //
  14925. //        $qb->select(
  14926. //            'i.productId',
  14927. //            'ig.name AS itemGroupName',
  14928. //            'w.name AS wareHouseName',
  14929. //            'wa.name AS subWareHouseName',
  14930. //            'i.qty AS quantity',
  14931. //            'b.name AS brandName',
  14932. //            'u.name AS UnitName',
  14933. //            'c.name AS color',
  14934. //            's.name AS size',
  14935. //            'i.purchasePrice AS price',
  14936. //            'p.name AS productName',
  14937. //            'p.images'
  14938. //        )
  14939. //            ->from('ApplicationBundle:InventoryStorage', 'i')
  14940. //            ->leftJoin('ApplicationBundle:InvProducts', 'p', 'WITH', 'i.productId = p.id')
  14941. //            ->leftJoin('ApplicationBundle:InvItemGroup', 'ig', 'WITH', 'i.igId = ig.id')
  14942. //            ->leftJoin('ApplicationBundle:Warehouse', 'w', 'WITH', 'i.warehouseId = w.id')
  14943. //            ->leftJoin('ApplicationBundle:BrandCompany', 'b', 'WITH', 'i.brandId = b.id')
  14944. //            ->leftJoin('ApplicationBundle:UnitType', 'u', 'WITH', 'i.unitTypeId = u.id')
  14945. //            ->leftJoin('ApplicationBundle:Colors', 'c', 'WITH', 'i.color = c.id')
  14946. //            ->leftJoin('ApplicationBundle:ProductSizes', 's', 'WITH', 'i.size = s.id')
  14947. //            ->leftJoin('ApplicationBundle:WarehouseAction', 'wa', 'WITH', 'i.actionTagId = wa.id');
  14948. //
  14949. //        // Define available filters with their mappings
  14950. //        $filters = [
  14951. //            'itemGroup'    => 'ig.id',
  14952. //            'category'     => 'p.categoryId',
  14953. //            'warehouse'    => 'w.id',
  14954. //            'storageType'  => 'i.actionTagId',
  14955. //            'brand'        => 'b.id',
  14956. //            'color'        => 'c.id',
  14957. //            'colorCode'    => 'c.hexCode',
  14958. //            'size'         => 's.id',
  14959. //        ];
  14960. //
  14961. //        foreach ($filters as $param => $field) {
  14962. //            $value = $request->query->get($param);
  14963. //
  14964. //            if ($value !== null) {
  14965. //                $values = array_map('trim', explode(',', $value)); // handle multiple
  14966. //                if (count($values) > 1) {
  14967. //                    $qb->andWhere($qb->expr()->in($field, ":$param"))
  14968. //                        ->setParameter($param, $values);
  14969. //                } else {
  14970. //                    $qb->andWhere("$field = :$param")
  14971. //                        ->setParameter($param, $values[0]);
  14972. //                }
  14973. //            }
  14974. //        }
  14975. //
  14976. //        $rawResult = $qb->getQuery()->getArrayResult();
  14977. //
  14978. //        // Now process for validation (color, size, images)
  14979. //        $finalResult = [];
  14980. //
  14981. //        foreach ($rawResult as $row) {
  14982. //            $finalResult[] = [
  14983. //                'productId'     => $row['productId'],
  14984. //                'itemGroupName' => $row['itemGroupName'],
  14985. //                'wareHouseName' => $row['wareHouseName'],
  14986. //                'subWareHouseName' => $row['subWareHouseName'],
  14987. //                'quantity'      => $row['quantity'],
  14988. //                'brandName'     => $row['brandName'],
  14989. //                'UnitName'      => $row['UnitName'],
  14990. //                'color'         => $row['color'] ?? '',
  14991. //                'size'          => $row['size'] ?? '',
  14992. //                'price'         => $row['price'],
  14993. //                'productName'   => $row['productName'],
  14994. //                'image'         => !empty($row['images']) ? $row['images'] : $defaultImage,
  14995. //            ];
  14996. //        }
  14997. //
  14998. //
  14999. //
  15000. //        return $this->json($finalResult);
  15001. //    }
  15002.     public function getItemGroupList()
  15003.     {
  15004.         $em $this->getDoctrine()->getManager();
  15005.         $itemGroups $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')
  15006.             ->createQueryBuilder('ig')
  15007.             ->select('ig.id''ig.name')
  15008.             ->getQuery()
  15009.             ->getResult();
  15010.         return $this->json($itemGroups);
  15011.     }
  15012.     public function getProductCategoryList()
  15013.     {
  15014.         $em $this->getDoctrine()->getManager();
  15015.         $categories $em->getRepository('ApplicationBundle\\Entity\\InvProductCategories')
  15016.             ->createQueryBuilder('pc')
  15017.             ->select('pc.id''pc.name')
  15018.             ->getQuery()
  15019.             ->getResult();
  15020.         return $this->json($categories);
  15021.     }
  15022.     public function getBrandList()
  15023.     {
  15024.         $em $this->getDoctrine()->getManager();
  15025.         $brands $em->getRepository('ApplicationBundle\\Entity\\BrandCompany')
  15026.             ->createQueryBuilder('b')
  15027.             ->select('b.id''b.name')
  15028.             ->getQuery()
  15029.             ->getResult();
  15030.         return $this->json($brands);
  15031.     }
  15032.     public function getColorList()
  15033.     {
  15034.         $em $this->getDoctrine()->getManager();
  15035.         $colors $em->getRepository('ApplicationBundle\\Entity\\Colors')
  15036.             ->createQueryBuilder('c')
  15037.             ->select('c.id''c.name')
  15038.             ->getQuery()
  15039.             ->getResult();
  15040.         return $this->json($colors);
  15041.     }
  15042.     public function getColorCodeList()
  15043.     {
  15044.         $em $this->getDoctrine()->getManager();
  15045.         $colorCodes $em->getRepository('ApplicationBundle\\Entity\\Colors')
  15046.             ->createQueryBuilder('c')
  15047.             ->select('c.id''c.hexCode')
  15048.             ->getQuery()
  15049.             ->getResult();
  15050.         return $this->json($colorCodes);
  15051.     }
  15052.     public function getSizeList()
  15053.     {
  15054.         $em $this->getDoctrine()->getManager();
  15055.         $sizes $em->getRepository('ApplicationBundle\\Entity\\ProductSizes')
  15056.             ->createQueryBuilder('s')
  15057.             ->select('s.id''s.name')
  15058.             ->getQuery()
  15059.             ->getResult();
  15060.         if (empty($sizes)) {
  15061.             return $this->json([
  15062.                 'success' => false,
  15063.                 'message' => 'No data found'
  15064.             ]);
  15065.         }
  15066.         return $this->json($sizes);
  15067.     }
  15068.     public function productCodeList()
  15069.     {
  15070.         $em $this->getDoctrine()->getManager();
  15071.         $productCode $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  15072.             ->createQueryBuilder('p')
  15073.             ->select('p.productByCodeId''p.productId''p.salesCode')
  15074.             ->getQuery()
  15075.             ->getResult();
  15076.         if (empty($productCode)) {
  15077.             return $this->json([
  15078.                 'success' => false,
  15079.                 'message' => 'No data found'
  15080.             ]);
  15081.         }
  15082.         return $this->json($productCode);
  15083.     }
  15084.     public function getItemInOutHistory(Request $request)
  15085.     {
  15086.         $em $this->getDoctrine()->getManager();
  15087.         $qb $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')->createQueryBuilder('i')
  15088.             ->select([
  15089.                 'i.productId AS productId',
  15090.                 'i.transactionType AS transactionType',
  15091.                 'i.transactionDate AS transactionDate',
  15092.                 'toWarehouse.name AS toWarehouseId',
  15093.                 'toSubWarehouse.name AS toSubWarehouseId',
  15094.                 'fromWarehouse.name AS fromWarehouseId',
  15095.                 'fromSubWarehouse.name AS fromSubWarehouseId',
  15096.                 'i.qty AS quantity',
  15097.                 'i.entityDocHash AS document',
  15098.                 'i.entity AS entity',
  15099.                 'i.entityId AS entityId',
  15100.                 'p.name AS productName',
  15101.             ])
  15102.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  15103.             ->leftJoin('ApplicationBundle:Warehouse''toWarehouse''WITH''i.warehouseId = toWarehouse.id')
  15104.             ->leftJoin('ApplicationBundle:WarehouseAction''toSubWarehouse''WITH''i.actionTagId = toSubWarehouse.id')
  15105.             ->leftJoin('ApplicationBundle:Warehouse''fromWarehouse''WITH''i.fromWarehouseId = fromWarehouse.id')
  15106.             ->leftJoin('ApplicationBundle:WarehouseAction''fromSubWarehouse''WITH''i.fromActionTagId = fromSubWarehouse.id');
  15107.         // Parse dd-mm-yyyy to Y-m-d
  15108.         $startDateStr $request->query->get('startDate');
  15109.         $endDateStr $request->query->get('endDate');
  15110.         if ($startDateStr && $endDateStr) {
  15111.             try {
  15112.                 $startDate = \DateTime::createFromFormat('d-m-Y'$startDateStr)->setTime(000);
  15113.                 $endDate = \DateTime::createFromFormat('d-m-Y'$endDateStr)->setTime(235959);
  15114.                 $qb->andWhere('i.transactionDate BETWEEN :startDate AND :endDate')
  15115.                     ->setParameter('startDate'$startDate)
  15116.                     ->setParameter('endDate'$endDate);
  15117.             } catch (\Exception $e) {
  15118.                 return $this->json(['error' => 'Invalid date format. Use dd-mm-yyyy.'], 400);
  15119.             }
  15120.         }
  15121.         $results $qb->getQuery()->getResult();
  15122.         $data array_map(function ($item) {
  15123.             return [
  15124.                 'productId' => $item['productId'],
  15125.                 'transactionType' => $item['transactionType'] == 'IN' 'OUT',
  15126.                 'transactionDate' => $item['transactionDate']->format('Y-m-d'),
  15127.                 'toWarehouseId' => $item['toWarehouseId'] ?? '',
  15128.                 'toSubWarehouseId' => $item['toSubWarehouseId'] ?? '',
  15129.                 'toSubWarehouseShortName' => $item['toSubWarehouseId'] ?? '',
  15130.                 'fromWarehouseId' => $item['fromWarehouseId'] ?? '',
  15131.                 'fromSubWarehouseId' => $item['fromSubWarehouseId'] ?? '',
  15132.                 'fromSubWarehouseShortName' => $item['fromSubWarehouseId'] ?? '',
  15133.                 'quantity' => $item['quantity'],
  15134.                 'document' => !empty($item['document']) ? $item['document'] : 0,
  15135.                 'entity' => !empty($item['entity']) ? $item['entity'] : 0,
  15136.                 'entityId' => !empty($item['entityId']) ? $item['entityId'] : 0,
  15137.                 'productName' => $item['productName'],
  15138.             ];
  15139.         }, $results);
  15140.         return $this->json($data);
  15141.     }
  15142.     public function CreateStockReceivedNoteForApp(Request $request$id 0)
  15143.     {
  15144.         $em $this->getDoctrine()->getManager();
  15145.         $companyId $this->getLoggedUserCompanyId($request);
  15146.         $extDocData = [];
  15147.         $userId $request->getSession()->get(UserConstants::USER_ID);
  15148.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  15149.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  15150. //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  15151.         $userBranchIdList $request->getSession()->get('branchIdList');
  15152.         if ($userBranchIdList == null$userBranchIdList = [];
  15153.         $userBranchId $request->getSession()->get('branchId');
  15154.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  15155.             $em $this->getDoctrine()->getManager();
  15156.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //change
  15157.             $dochash $request->request->get('docHash'); //change
  15158.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  15159.             $approveRole $request->request->get('approvalRole');
  15160.             $approveHash $request->request->get('approvalHash');
  15161.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  15162.                 $loginId$approveRole$approveHash$id)
  15163.             ) {
  15164.                 if ($request->request->has('returnJson')) {
  15165.                     return new JsonResponse(array(
  15166.                         'success' => false,
  15167.                         'documentHash' => 0,
  15168.                         'documentId' => 0,
  15169.                         'billIds' => [],
  15170.                         'drIds' => [],
  15171.                         'pmntTransIds' => [],
  15172.                         'viewUrl' => '',
  15173.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  15174.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  15175.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  15176.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  15177.                     ));
  15178.                 } else
  15179.                     $this->addFlash(
  15180.                         'error',
  15181.                         'Sorry Could not insert Data.'
  15182.                     );
  15183.             } else {
  15184.                 if ($request->request->has('check_allowed'))
  15185.                     $check_allowed 1;
  15186.                 $StID Inventory::CreateNewStockReceivedNoteForApp(
  15187.                     $this->getDoctrine()->getManager(),
  15188.                     $request->request,
  15189.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  15190.                     $this->getLoggedUserCompanyId($request)
  15191.                 );
  15192.                 //now add Approval info
  15193.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  15194.                 $approveRole 1;  //created
  15195.                 $options = array(
  15196.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  15197.                     'notification_server' => $this->container->getParameter('notification_server'),
  15198.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  15199.                     'url' => $this->generateUrl(
  15200.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  15201.                         ['entity_view_route_path_name']
  15202.                     )
  15203.                 );
  15204.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  15205.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  15206.                     $StID,
  15207.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  15208.                 );
  15209.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  15210.                     $loginId,
  15211.                     $approveRole,
  15212.                     $request->request->get('approvalHash'));
  15213.                 $url $this->generateUrl(
  15214.                     'view_srcv'
  15215.                 );
  15216.                 if ($request->request->has('returnJson')) {
  15217.                     return new JsonResponse(array(
  15218.                         'success' => true,
  15219.                         'documentHash' => $dochash,
  15220.                         'documentId' => $StID,
  15221. //                        'viewUrl' => $url . "/" . $StID,
  15222.                     ));
  15223.                 } else {
  15224.                     $this->addFlash(
  15225.                         'success',
  15226.                         'Stock Received Note Added.'
  15227.                     );
  15228.                     return $this->redirect($url "/" $StID);
  15229.                 }
  15230.             }
  15231.         }
  15232.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  15233.             array(
  15234.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  15235.             )
  15236.         );
  15237.         if ($id == 0) {
  15238.         } else {
  15239.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')->findOneBy(
  15240.                 array(
  15241.                     'salesOrderId' => $id///material
  15242.                 )
  15243.             );
  15244.             //now if its not editable, redirect to view
  15245.             if ($extDoc) {
  15246.                 if ($extDoc->getEditFlag() != 1) {
  15247.                     $url $this->generateUrl(
  15248.                         'view_srcv'
  15249.                     );
  15250.                     return $this->redirect($url "/" $id);
  15251.                 } else {
  15252.                     $extDocData $extDoc;
  15253.                     $extDocDataDetails $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findOneBy(
  15254.                         array(
  15255.                             'stockReceivedNoteId' => $id///material
  15256.                         )
  15257.                     );
  15258.                 }
  15259.             } else {
  15260.             }
  15261.         }
  15262.         $INVLIST = [];
  15263.         foreach ($slotList as $slot) {
  15264.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  15265.         }
  15266.         $dataArray = array(
  15267.             'page_title' => 'Stock Received Note',
  15268. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  15269.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  15270.             'users' => Users::getUserListById($em),
  15271.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  15272.             'warehouseList' => Inventory::WarehouseList($em),
  15273.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  15274.             'warehouseActionList' => $warehouse_action_list,
  15275.             'warehouseActionListArray' => $warehouse_action_list_array,
  15276.             'extDocData' => $extDocData,
  15277.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  15278.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  15279.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  15280.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  15281. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  15282. //            'product_list' => Inventory::ProductList($em, $companyId),
  15283.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  15284.             'prefix_list' => array(
  15285.                 [
  15286.                     'id' => 1,
  15287.                     'value' => 'GN',
  15288.                     'text' => 'GN'
  15289.                 ]
  15290.             ),
  15291.             'assoc_list' => array(
  15292.                 [
  15293.                     'id' => 1,
  15294.                     'value' => 1,
  15295.                     'text' => 'GN'
  15296.                 ]
  15297.             ),
  15298.             'INVLIST' => $INVLIST,
  15299.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  15300.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  15301.             'userBranchIdList' => $userBranchIdList,
  15302.             'userBranchId' => $userBranchId,
  15303. //            'headList' => Accounts::HeadList($em),
  15304.         );
  15305.         //json
  15306.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  15307.         {
  15308.             $dataArray['success'] = true;
  15309.             return new JsonResponse(
  15310.                 $dataArray
  15311.             );
  15312.         }
  15313.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  15314.             $dataArray
  15315.         );
  15316.     }
  15317.     public function RefreshTaskOnSessionAction(Request $request)
  15318.     {
  15319.         $session $request->getSession();
  15320.         $em $this->getDoctrine()->getManager();
  15321.         $currentPlanningItemId 0;
  15322.         $currentTaskId 0;
  15323.         $taskActualStartTs 0;
  15324.         $currentTask $em->getRepository('ApplicationBundle\\Entity\\TaskLog')
  15325.             ->findOneBy(
  15326.                 array(
  15327.                     'userId' => $session->get(UserConstants::USER_ID),
  15328.                     'workingStatus' => 1
  15329.                 )
  15330.             );
  15331.         if ($currentTask) {
  15332.             $currentTaskId $currentTask->getId();
  15333.             $currentPlanningItemId $currentTask->getPlanningItemId();
  15334.             $taskActualStartTs $currentTask->getActualStartTs();
  15335.         }
  15336.         $session->set(UserConstants::USER_CURRENT_TASK_ID$currentTaskId);
  15337.         $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$currentPlanningItemId);
  15338.         return new JsonResponse(
  15339.             array(
  15340.                 'currentPlanningItemId' => $currentPlanningItemId,
  15341.                 'currentTaskId' => $currentTaskId,
  15342.                 'taskActualStartTs' => $taskActualStartTs,
  15343.             )
  15344.         );
  15345.     }
  15346.     private function getProductFormDefaults($em$companyId$loginId)
  15347.     {
  15348.         $defaults = array(
  15349.             'unitTypeId' => 0,
  15350.             'defaultTaxConfigId' => 0,
  15351.             'defaultPurchaseTaxConfigId' => 0,
  15352.             'defaultPurchaseActionTagId' => 0
  15353.         );
  15354.         if ($loginId != '' && $loginId != null) {
  15355.             $pref $em->getRepository('ApplicationBundle\\Entity\\InvProductFormPreference')->findOneBy(array(
  15356.                 'companyId' => $companyId,
  15357.                 'loginId' => $loginId
  15358.             ));
  15359.             if ($pref) {
  15360.                 $defaults['unitTypeId'] = (int) $pref->getUnitTypeId();
  15361.                 $defaults['defaultTaxConfigId'] = (int) $pref->getDefaultTaxConfigId();
  15362.                 $defaults['defaultPurchaseTaxConfigId'] = (int) $pref->getDefaultPurchaseTaxConfigId();
  15363.                 $defaults['defaultPurchaseActionTagId'] = (int) $pref->getDefaultPurchaseActionTagId();
  15364.             }
  15365.         }
  15366.         if ($defaults['unitTypeId'] == 0) {
  15367.             $defaults['unitTypeId'] = $this->resolveDefaultPcsUnitTypeId($em);
  15368.         }
  15369.         if ($defaults['defaultTaxConfigId'] == || $defaults['defaultPurchaseTaxConfigId'] == || $defaults['defaultPurchaseActionTagId'] == 0) {
  15370.             $defaultItemGroup $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(array(
  15371.                 'CompanyId' => $companyId,
  15372.                 'status' => GeneralConstant::ACTIVE
  15373.             ));
  15374.             if ($defaultItemGroup) {
  15375.                 if ($defaults['defaultTaxConfigId'] == 0) {
  15376.                     $defaults['defaultTaxConfigId'] = (int) $defaultItemGroup->getDefaultTaxConfigId();
  15377.                 }
  15378.                 if ($defaults['defaultPurchaseTaxConfigId'] == 0) {
  15379.                     $defaults['defaultPurchaseTaxConfigId'] = (int) $defaultItemGroup->getDefaultPurchaseTaxConfigId();
  15380.                 }
  15381.                 if ($defaults['defaultPurchaseActionTagId'] == 0) {
  15382.                     $defaults['defaultPurchaseActionTagId'] = (int) $defaultItemGroup->getDefaultPurchaseActionTagId();
  15383.                 }
  15384.                 if ($defaults['unitTypeId'] == 0) {
  15385.                     $defaults['unitTypeId'] = (int) $defaultItemGroup->getUnitTypeId();
  15386.                 }
  15387.             }
  15388.         }
  15389.         return $defaults;
  15390.     }
  15391.     private function resolveDefaultPcsUnitTypeId($em)
  15392.     {
  15393.         $unitTypes Inventory::UnitTypeList($em);
  15394.         foreach ($unitTypes as $unitType) {
  15395.             $name = isset($unitType['name']) ? strtoupper(trim($unitType['name'])) : '';
  15396.             $suffix = isset($unitType['classSuffix']) ? strtoupper(trim($unitType['classSuffix'])) : '';
  15397.             if ($name === 'PCS' || $suffix === 'PCS') {
  15398.                 return (int) $unitType['id'];
  15399.             }
  15400.         }
  15401.         foreach ($unitTypes as $unitType) {
  15402.             if (isset($unitType['id']) && $unitType['id'] != && $unitType['id'] != '') {
  15403.                 return (int) $unitType['id'];
  15404.             }
  15405.         }
  15406.         return 0;
  15407.     }
  15408.     private function saveProductFormDefaults($em$companyId$loginId$savedEntityRequest $request)
  15409.     {
  15410.         if ($loginId == '' || $loginId == null) {
  15411.             return;
  15412.         }
  15413.         $unitTypeId 0;
  15414.         $defaultTaxConfigId 0;
  15415.         $defaultPurchaseTaxConfigId 0;
  15416.         $defaultPurchaseActionTagId 0;
  15417.         if ($savedEntity) {
  15418.             if (method_exists($savedEntity'getUnitTypeId')) {
  15419.                 $unitTypeId = (int) $savedEntity->getUnitTypeId();
  15420.             }
  15421.             if (method_exists($savedEntity'getDefaultTaxConfigId')) {
  15422.                 $defaultTaxConfigId = (int) $savedEntity->getDefaultTaxConfigId();
  15423.             }
  15424.             if (method_exists($savedEntity'getDefaultPurchaseTaxConfigId')) {
  15425.                 $defaultPurchaseTaxConfigId = (int) $savedEntity->getDefaultPurchaseTaxConfigId();
  15426.             }
  15427.             if (method_exists($savedEntity'getDefaultPurchaseActionTagId')) {
  15428.                 $defaultPurchaseActionTagId = (int) $savedEntity->getDefaultPurchaseActionTagId();
  15429.             }
  15430.         }
  15431.         if ($unitTypeId == 0) {
  15432.             $unitTypeId = (int) $request->request->get('unitTypeId'0);
  15433.         }
  15434.         if ($defaultTaxConfigId == 0) {
  15435.             $defaultTaxConfigId = (int) $request->request->get('defaultTaxConfigId'0);
  15436.             if ($defaultTaxConfigId == 0) {
  15437.                 $taxConfigIds $request->request->get('taxConfigIds', array());
  15438.                 if (!empty($taxConfigIds)) {
  15439.                     $defaultTaxConfigId = (int) $taxConfigIds[0];
  15440.                 }
  15441.             }
  15442.         }
  15443.         if ($defaultPurchaseTaxConfigId == 0) {
  15444.             $defaultPurchaseTaxConfigId = (int) $request->request->get('defaultPurchaseTaxConfigId'0);
  15445.             if ($defaultPurchaseTaxConfigId == 0) {
  15446.                 $purchaseTaxConfigIds $request->request->get('purchaseTaxConfigIds', array());
  15447.                 if (!empty($purchaseTaxConfigIds)) {
  15448.                     $defaultPurchaseTaxConfigId = (int) $purchaseTaxConfigIds[0];
  15449.                 }
  15450.             }
  15451.         }
  15452.         if ($defaultPurchaseActionTagId == 0) {
  15453.             $defaultPurchaseActionTagId = (int) $request->request->get('defaultPurchaseActionTagId'0);
  15454.         }
  15455.         $pref $em->getRepository('ApplicationBundle\\Entity\\InvProductFormPreference')->findOneBy(array(
  15456.             'companyId' => $companyId,
  15457.             'loginId' => $loginId
  15458.         ));
  15459.         if (!$pref) {
  15460.             $pref = new \ApplicationBundle\Entity\InvProductFormPreference();
  15461.             $pref->setCompanyId($companyId);
  15462.             $pref->setLoginId($loginId);
  15463.             $em->persist($pref);
  15464.         }
  15465.         $pref->setUnitTypeId($unitTypeId);
  15466.         $pref->setDefaultTaxConfigId($defaultTaxConfigId);
  15467.         $pref->setDefaultPurchaseTaxConfigId($defaultPurchaseTaxConfigId);
  15468.         $pref->setDefaultPurchaseActionTagId($defaultPurchaseActionTagId);
  15469.         $em->flush();
  15470.     }
  15471.     // ─────────────────────────────────────────────────────────
  15472.     // S2.2 — EPC Category catalog
  15473.     // ─────────────────────────────────────────────────────────
  15474.     public function EpcCategoryListAction(Request $request)
  15475.     {
  15476.         $em $this->getDoctrine()->getManager();
  15477.         $categories $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')
  15478.             ->findBy([], ['displayOrder' => 'ASC''code' => 'ASC']);
  15479.         return $this->render('@Inventory/pages/list/list_epc_categories.html.twig', [
  15480.             'page_title'  => 'EPC Category Catalog',
  15481.             'categories'  => $categories,
  15482.         ]);
  15483.     }
  15484.     public function EpcCategoryEditAction(Request $request$id 0)
  15485.     {
  15486.         $em $this->getDoctrine()->getManager();
  15487.         $ex_id = (int)($request->request->get('ex_id'$id));
  15488.         $cat   null;
  15489.         if ($ex_id 0) {
  15490.             $cat $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')->find($ex_id);
  15491.         }
  15492.         if ($request->isMethod('POST')) {
  15493.             $entity $cat ?? new \ApplicationBundle\Entity\EpcCategory();
  15494.             $entity->setCode(strtoupper(trim($request->request->get('code'''))));
  15495.             $entity->setName(trim($request->request->get('name''')));
  15496.             $entity->setDescription(trim($request->request->get('description''')));
  15497.             $entity->setDisplayOrder((int)$request->request->get('display_order'99));
  15498.             $entity->setActive($request->request->get('active') ? 0);
  15499.             if (!$cat) {
  15500.                 $entity->setCreatedAt(new \DateTime());
  15501.                 $entity->setCreatedLoginId((int)$request->getSession()->get(UserConstants::USER_LOGIN_ID0));
  15502.             }
  15503.             $em->persist($entity);
  15504.             $em->flush();
  15505.             $this->addFlash('success''EPC Category saved.');
  15506.             return $this->redirectToRoute('epc_category_list');
  15507.         }
  15508.         return $this->render('@Inventory/pages/input_forms/edit_epc_category.html.twig', [
  15509.             'page_title' => $ex_id 'Edit EPC Category' 'New EPC Category',
  15510.             'ex_id'      => $ex_id,
  15511.             'cat'        => $cat,
  15512.         ]);
  15513.     }
  15514.     public function EpcCategoryGetAllAction(Request $request)
  15515.     {
  15516.         $em $this->getDoctrine()->getManager();
  15517.         $cats $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')
  15518.             ->findBy(['active' => 1], ['displayOrder' => 'ASC']);
  15519.         $data = [];
  15520.         foreach ($cats as $c) {
  15521.             $data[] = ['code' => $c->getCode(), 'name' => $c->getName()];
  15522.         }
  15523.         return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => true'categories' => $data]);
  15524.     }
  15525.     // ─────────────────────────────────────────────────────────
  15526.     // S2.1 — Article Translation endpoints
  15527.     // ─────────────────────────────────────────────────────────
  15528.     public function SuggestProductsFromCentralAction(Request $request)
  15529.     {
  15530.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15531.         if ($systemType === '_CENTRAL_') {
  15532.             return new JsonResponse(['success' => false'message' => 'Not applicable on central'], 403);
  15533.         }
  15534.         $em        $this->getDoctrine()->getManager();
  15535.         $companyId $this->getLoggedUserCompanyId($request);
  15536.         $query     trim($request->request->get('query'''));
  15537.         $igName    trim($request->request->get('igName'''));
  15538.         $modelNo   trim($request->request->get('modelNo'''));
  15539.         if (strlen($query) < && !$modelNo) {
  15540.             return new JsonResponse(['success' => true'results' => []]);
  15541.         }
  15542.         $results Inventory::SearchProductsOnCentral($query$igName$modelNo10);
  15543.         // filter out products already local for this company
  15544.         $filtered = [];
  15545.         foreach ($results as $row) {
  15546.             $globalId = (int)($row['globalId'] ?? 0);
  15547.             if ($globalId 0) {
  15548.                 $local $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  15549.                 if ($local) continue;
  15550.             }
  15551.             $filtered[] = $row;
  15552.         }
  15553.         return new JsonResponse(['success' => true'results' => $filtered]);
  15554.     }
  15555.     public function ImportProductFromCentralAction(Request $request)
  15556.     {
  15557.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15558.         if ($systemType === '_CENTRAL_') {
  15559.             return new JsonResponse(['success' => false'message' => 'Not applicable on central'], 403);
  15560.         }
  15561.         $em        $this->getDoctrine()->getManager();
  15562.         $companyId $this->getLoggedUserCompanyId($request);
  15563.         $globalId  = (int)$request->request->get('globalId'0);
  15564.         if ($globalId <= 0) {
  15565.             return new JsonResponse(['success' => false'message' => 'globalId is required'], 400);
  15566.         }
  15567.         // check idempotency
  15568.         $existing $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  15569.         if ($existing) {
  15570.             return new JsonResponse(['success' => true'productId' => $existing->getId(), 'message' => 'already_exists']);
  15571.         }
  15572.         // fetch the full row from central by globalId
  15573.         $centralUrl = \ApplicationBundle\Constants\GeneralConstant::HONEYBEE_CENTRAL_SERVER;
  15574.         $curl curl_init();
  15575.         curl_setopt_array($curl, [
  15576.             CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  15577.             CURLOPT_URL => $centralUrl '/api/search_global_products',
  15578.             CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 12,
  15579.             CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  15580.             CURLOPT_POSTFIELDS => http_build_query(['globalId' => $globalId]),
  15581.         ]);
  15582.         $response  curl_exec($curl);
  15583.         $curlError curl_error($curl);
  15584.         curl_close($curl);
  15585.         if ($curlError || !$response) {
  15586.             return new JsonResponse(['success' => false'message' => 'Central server unreachable'], 503);
  15587.         }
  15588.         $data json_decode($responsetrue);
  15589.         if (!is_array($data) || empty($data['success']) || empty($data['results'])) {
  15590.             return new JsonResponse(['success' => false'message' => 'Product not found on central'], 404);
  15591.         }
  15592.         try {
  15593.             $productId Inventory::MaterializeProductFromCentral($em$companyId$data['results'][0]);
  15594.         } catch (\Throwable $e) {
  15595.             return new JsonResponse(['success' => false'message' => $e->getMessage()], 500);
  15596.         }
  15597.         return new JsonResponse(['success' => true'productId' => $productId'message' => 'imported']);
  15598.     }
  15599.     public function ArticleTranslationSaveAction(Request $request)
  15600.     {
  15601.         $em        $this->getDoctrine()->getManager();
  15602.         $articleId = (int)$request->request->get('article_id'0);
  15603.         $data      $request->request->get('translations', []);
  15604.         $loginId   = (int)$request->getSession()->get(UserConstants::USER_LOGIN_ID0);
  15605.         if ($articleId === || !is_array($data)) {
  15606.             return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => false'message' => 'Invalid input']);
  15607.         }
  15608.         Inventory::saveArticleTranslations($em$articleId$data$loginId);
  15609.         return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => true]);
  15610.     }
  15611.     public function ArticleTranslationGetAction(Request $request$articleId 0)
  15612.     {
  15613.         $em $this->getDoctrine()->getManager();
  15614.         $translations Inventory::getArticleTranslations($em, (int)$articleId);
  15615.         return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => true'translations' => $translations]);
  15616.     }
  15617. }