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

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. use ApplicationBundle\Entity\BrandCompany;
  48. use ApplicationBundle\Entity\InvProducts;
  49. class InventoryController extends GenericController implements SessionCheckInterface
  50. {
  51.     private function getProductDependencyRows($em$parentProductId)
  52.     {
  53.         $rows = array();
  54.         $dependencies $em->getRepository('ApplicationBundle\\Entity\\InvProductDependencies')->findBy(
  55.             array(
  56.                 'parentProductId' => $parentProductId,
  57.             ),
  58.             array(
  59.                 'id' => 'ASC',
  60.             )
  61.         );
  62.         foreach ($dependencies as $dependency) {
  63.             $childProduct $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($dependency->getChildProductId());
  64.             $rows[] = array(
  65.                 'id' => $dependency->getId(),
  66.                 'parentProductId' => $dependency->getParentProductId(),
  67.                 'childProductId' => $dependency->getChildProductId(),
  68.                 'childProductName' => $childProduct $childProduct->getName() : '',
  69.                 'qty' => $dependency->getQty(),
  70.                 'repeatationThreshold' => $dependency->getRepeatationThreshold(),
  71.                 'repeatQty' => $dependency->getRepeatQty(),
  72.                 'required' => $dependency->getRequired() ? 0,
  73.                 'fdm' => $dependency->getFdm(),
  74.             );
  75.         }
  76.         return $rows;
  77.     }
  78.     private function saveProductDependencies($em$parentProductId$dependencies)
  79.     {
  80.         $parentProductId = (int) $parentProductId;
  81.         if ($parentProductId <= 0) {
  82.             return;
  83.         }
  84.         if (!is_array($dependencies)) {
  85.             $dependencies = array();
  86.         }
  87.         $connection $em->getConnection();
  88.         $connection->beginTransaction();
  89.         try {
  90.             $em->createQuery(
  91.                 'DELETE FROM ApplicationBundle\\Entity\\InvProductDependencies d WHERE d.parentProductId = :parentProductId'
  92.             )->setParameter('parentProductId'$parentProductId)->execute();
  93.             foreach ($dependencies as $dependencyRow) {
  94.                 if (!is_array($dependencyRow)) {
  95.                     continue;
  96.                 }
  97.                 $childProductId = (int) (
  98.                     $dependencyRow['child_product_id']
  99.                     ?? $dependencyRow['childProductId']
  100.                     ?? $dependencyRow['child_product']
  101.                     ?? $dependencyRow['childProduct']
  102.                     ?? 0
  103.                 );
  104.                 if ($childProductId <= || $childProductId === $parentProductId) {
  105.                     continue;
  106.                 }
  107.                 $qty = isset($dependencyRow['qty']) ? (float) $dependencyRow['qty'] : 0;
  108.                 if ($qty <= 0) {
  109.                     continue;
  110.                 }
  111.                 $repeatationThreshold = isset($dependencyRow['repeatation_threshold'])
  112.                     ? (int) $dependencyRow['repeatation_threshold']
  113.                     : (isset($dependencyRow['repeatationThreshold']) ? (int) $dependencyRow['repeatationThreshold'] : 1);
  114.                 if ($repeatationThreshold <= 0) {
  115.                     $repeatationThreshold 1;
  116.                 }
  117.                 $repeatQtyRaw $dependencyRow['repeat_qty'] ?? $dependencyRow['repeatQty'] ?? null;
  118.                 $repeatQty = ($repeatQtyRaw === '' || $repeatQtyRaw === null) ? null : (float) $repeatQtyRaw;
  119.                 $required $dependencyRow['required'] ?? 1;
  120.                 $required = ($required === '0' || $required === || $required === false || $required === 'false') ? 1;
  121.                 $fdm trim((string) ($dependencyRow['fdm'] ?? ''));
  122.                 if ($fdm === '') {
  123.                     $fdm null;
  124.                 }
  125.                 $dependency = new \ApplicationBundle\Entity\InvProductDependencies();
  126.                 $dependency->setParentProductId($parentProductId);
  127.                 $dependency->setChildProductId($childProductId);
  128.                 $dependency->setQty($qty);
  129.                 $dependency->setRepeatationThreshold($repeatationThreshold);
  130.                 $dependency->setRepeatQty($repeatQty);
  131.                 $dependency->setRequired($required);
  132.                 $dependency->setFdm($fdm);
  133.                 $em->persist($dependency);
  134.             }
  135.             $em->flush();
  136.             $connection->commit();
  137.         } catch (\Exception $e) {
  138.             if ($connection->isTransactionActive()) {
  139.                 $connection->rollBack();
  140.             }
  141.             throw $e;
  142.         }
  143.     }
  144.     private function normalizeSqlIntList($values): array
  145.     {
  146.         $normalized = array();
  147.         foreach ((array) $values as $value) {
  148.             if ($value === '' || $value === null) {
  149.                 continue;
  150.             }
  151.             if (is_numeric($value)) {
  152.                 $normalized[] = (int) $value;
  153.             }
  154.         }
  155.         return $normalized;
  156.     }
  157.     private function buildNamedInClause(array $valuesstring $paramPrefix, array &$params): string
  158.     {
  159.         $placeholders = array();
  160.         foreach ($values as $index => $value) {
  161.             $paramName $paramPrefix $index;
  162.             $placeholders[] = ':' $paramName;
  163.             $params[$paramName] = $value;
  164.         }
  165.         return implode(', '$placeholders);
  166.     }
  167.     private function buildTokenizedLikeSearchFragment(array $fields, array $queryGroupsstring $outerOperatorstring $paramPrefix): array
  168.     {
  169.         $fragment ' ';
  170.         $params = array();
  171.         $paramIndex 0;
  172.         foreach ($fields as $field) {
  173.             if (empty($queryGroups)) {
  174.                 continue;
  175.             }
  176.             $fragment .= ' ' $outerOperator ' ( ';
  177.             foreach ($queryGroups as $queryGroup) {
  178.                 $terms preg_split('/\s+/'trim((string) $queryGroup));
  179.                 $terms array_values(array_filter($terms, static function ($term) {
  180.                     return $term !== '';
  181.                 }));
  182.                 if (empty($terms)) {
  183.                     continue;
  184.                 }
  185.                 $fragment .= '( ';
  186.                 $andNeeded 0;
  187.                 foreach ($terms as $term) {
  188.                     if ($andNeeded === 1) {
  189.                         $fragment .= ' and ';
  190.                     }
  191.                     $paramName $paramPrefix $paramIndex++;
  192.                     $fragment .= ' ' $field ' like :' $paramName ' ';
  193.                     $params[$paramName] = '%' $term '%';
  194.                     $andNeeded 1;
  195.                 }
  196.                 $fragment .= ') or ';
  197.             }
  198.             $fragment .= ' 1=0 ) ';
  199.         }
  200.         return array($fragment$params);
  201.     }
  202.     private function buildFlatLikeSearchFragment(array $fields, array $valuesstring $outerOperatorstring $paramPrefix): array
  203.     {
  204.         $fragment ' ';
  205.         $params = array();
  206.         $paramIndex 0;
  207.         foreach ($fields as $field) {
  208.             $sanitizedValues array_values(array_filter(array_map('trim', (array) $values), static function ($value) {
  209.                 return $value !== '';
  210.             }));
  211.             if (empty($sanitizedValues)) {
  212.                 continue;
  213.             }
  214.             $fragment .= ' ' $outerOperator ' ( 1=0 ';
  215.             foreach ($sanitizedValues as $value) {
  216.                 $paramName $paramPrefix $paramIndex++;
  217.                 $fragment .= ' or ' $field ' like :' $paramName ' ';
  218.                 $params[$paramName] = '%' $value '%';
  219.             }
  220.             $fragment .= ' ) ';
  221.         }
  222.         return array($fragment$params);
  223.     }
  224.     private function buildConjunctiveLikeFragment(string $column, array $valuesstring $paramPrefix): array
  225.     {
  226.         $fragment '';
  227.         $params = array();
  228.         if (!empty($values)) {
  229.             $fragment .= ' and ( ';
  230.             foreach (array_values($values) as $index => $value) {
  231.                 $paramName $paramPrefix $index;
  232.                 $fragment .= ' ' $column ' like :' $paramName ' and';
  233.                 $params[$paramName] = '%' $value '%';
  234.             }
  235.             $fragment .= ' 1=1 ) ';
  236.         }
  237.         return array($fragment$params);
  238.     }
  239.     public function GetInitialDataForProductSelectVendorAppAction(Request $request)
  240.     {
  241.         $em $this->getDoctrine()->getManager();
  242.         $em_goc $this->getDoctrine()->getManager('company_group');
  243.         $session $request->getSession();
  244.         $companyId $this->getLoggedUserCompanyId($request);
  245.         $userRestrictions = [];
  246.         $selectiveDocumentsFlag 0;
  247.         $allowedLoginIds = [];
  248. //        $salesPersonList = Client::SalesPersonList($this->getDoctrine()->getManager());
  249. //
  250. //        $clientList = SalesOrderM::GetClientList($em, [], $companyId);
  251.         $userType $session->get(UserConstants::USER_TYPE);
  252.         $userId $session->get(UserConstants::USER_ID);
  253.         $productListArray = [];
  254.         $subCategoryListArray = [];
  255.         $categoryListArray = [];
  256.         $igListArray = [];
  257.         $unitListArray = [];
  258.         $skipProductList $request->request->has('skipProductList') ? $request->request->get('skipProductList') : 0;
  259.         $productList = ($skipProductList == 1) ? [] : Inventory::ProductList($em$companyId);
  260.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  261.         $categoryList Inventory::ProductCategoryList($em$companyId);
  262.         $igList Inventory::ItemGroupList($em$companyId);
  263.         $unitList Inventory::UnitTypeList($em);
  264.         $brandList Inventory::GetBrandList($em$companyId);
  265.         $defaultSuffix 'lemon-o';
  266.         $pidsByCategory = [];
  267.         $pidsBySubCategory = [];
  268.         $pidsByIg = [];
  269.         $pidsByBrand = [];
  270.         foreach ($igList as $key => $product) {
  271.             if ($product['classSuffix'] == '') {
  272.                 $product['classSuffix'] = $defaultSuffix;
  273.                 $igList[$key]['classSuffix'] = $defaultSuffix;
  274.             }
  275.             $igListArray[] = $product;
  276.         }
  277.         foreach ($categoryList as $product) {
  278.             if ($product['classSuffix'] == '' && isset($igList[$product['igId']]))
  279.                 $product['classSuffix'] = $igList[$product['igId']]['classSuffix'];
  280.             $categoryListArray[] = $product;
  281.         }
  282.         foreach ($subCategoryList as $product) {
  283.             if ($product['classSuffix'] == '' && isset($igList[$product['igId']]))
  284.                 $product['classSuffix'] = $igList[$product['igId']]['classSuffix'];
  285.             $subCategoryListArray[] = $product;
  286.         }
  287.         foreach ($unitList as $product) {
  288.             $unitListArray[] = $product;
  289.         }
  290.         $brandListArray = [];
  291.         foreach ($brandList as $product) {
  292.             $brandListArray[] = $product;
  293.         }
  294.         foreach ($productList as $key => $product) {
  295. //            $productListArray[] = $product;
  296.             $product['igName'] = $igList[$product['igId']]['name'];
  297.             $product['categoryName'] = $categoryList[$product['categoryId']]['name'];
  298.             $product['subCategoryName'] = $subCategoryList[$product['subCategoryId']]['name'];
  299.             $product['brandName'] = $brandList[$product['brandCompany']]['name'];
  300.             $pidsByCategory[$product['categoryId']][] = $key;
  301.             $pidsBySubCategory[$product['subCategoryId']][] = $key;
  302.             $pidsIg[$product['igId']][] = $key;
  303.             $pidsByBrand[$product['brandCompany']][] = $key;
  304. //            $pidsBySubCategory=[];
  305. //            $pidsByIg=[];
  306.             $productListArray[] = $product;
  307.             $productList[$key] = $product;
  308.         }
  309.         $data = [
  310.             ''
  311.         ];
  312. //        if ($request->request->has('returnJson') || $request->query->has('returnJson'))
  313.         {
  314.             return new JsonResponse(
  315.                 array(
  316.                     'page_title' => ' ',
  317.                     'data' => $data,
  318.                     'productList' => $productList,
  319.                     'subCategoryList' => $subCategoryList,
  320.                     'categoryList' => $categoryList,
  321.                     'igList' => $igList,
  322.                     'unitList' => $unitList,
  323.                     'brandList' => $brandList,
  324.                     'productListArray' => $productListArray,
  325.                     'subCategoryListArray' => $subCategoryListArray,
  326.                     'categoryListArray' => $categoryListArray,
  327.                     'igListArray' => $igListArray,
  328.                     'unitListArray' => $unitListArray,
  329.                     'brandListArray' => $brandListArray,
  330.                     'pidsByCategory' => $pidsByCategory,
  331.                     'pidsBySubCategory' => $pidsBySubCategory,
  332.                     'pidsByBrand' => $pidsByBrand,
  333.                     'pidsByIg' => $pidsByIg,
  334.                     'success' => true
  335.                 )
  336.             );
  337.         }
  338.     }
  339.     public function GetRefreshedItemAction(Request $request$type 0)
  340.     {
  341.         $em $this->getDoctrine()->getManager();
  342.         $companyId $this->getLoggedUserCompanyId($request);
  343.         $productListArray = [];
  344.         $subCategoryListArray = [];
  345.         $categoryListArray = [];
  346.         $igListArray = [];
  347.         $unitListArray = [];
  348.         $skipProductList $request->request->has('skipProductList') ? $request->request->get('skipProductList') : 0;
  349.         $productList = ($skipProductList == 1) ? [] : Inventory::ProductList($em$companyId$type);
  350.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  351.         $categoryList Inventory::ProductCategoryList($em$companyId);
  352.         $igList Inventory::ItemGroupList($em$companyId);
  353.         $unitList Inventory::UnitTypeList($em);
  354.         $brandList Inventory::GetBrandList($em$companyId);
  355.         foreach ($productList as $product) {
  356.             $productListArray[] = $product;
  357.         }
  358.         foreach ($categoryList as $product) {
  359.             $categoryListArray[] = $product;
  360.         }
  361.         foreach ($subCategoryList as $product) {
  362.             $subCategoryListArray[] = $product;
  363.         }
  364.         foreach ($igList as $product) {
  365.             $igListArray[] = $product;
  366.         }
  367.         foreach ($unitList as $product) {
  368.             $unitListArray[] = $product;
  369.         }
  370.         $brandListArray = [];
  371.         foreach ($brandList as $product) {
  372.             $brandListArray[] = $product;
  373.         }
  374.         $qry $em->getRepository("ApplicationBundle\\Entity\\AccService")->findBy(array(
  375.             "status" => GeneralConstant::ACTIVE,
  376.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  377. //            'type'=>1//trade items
  378.         ));
  379.         $sl = [];
  380.         $sl_array = [];
  381.         foreach ($qry as $product) {
  382.             $sl[$product->getServiceId()] = array(
  383.                 'text' => $product->getServiceName(),
  384.                 'value' => $product->getServiceId(),
  385.                 'name' => $product->getServiceName(),
  386.                 'id' => $product->getServiceId(),
  387.             );
  388.             $sl_array[] = array(
  389.                 'text' => $product->getServiceName(),
  390.                 'value' => $product->getServiceId(),
  391.                 'name' => $product->getServiceName(),
  392.                 'id' => $product->getServiceId(),
  393.             );
  394.         }
  395.         $hl Accounts::HeadList($em);
  396.         $hl_array Accounts::getParentLedgerHeads($em"""", [], 1$this->getLoggedUserCompanyId($request));
  397.         return new JsonResponse(
  398.             array(
  399. //                'page_title'=>'BOM',
  400. //                'clients'=>SalesOrderM::GetClientList($em),
  401. //                'clients_by_ac_head'=>SalesOrderM::GetClientListByAcHead($em),
  402.                 'productList' => $productList,
  403.                 'subCategoryList' => $subCategoryList,
  404.                 'categoryList' => $categoryList,
  405.                 'igList' => $igList,
  406.                 'unitList' => $unitList,
  407.                 'brandList' => $brandList,
  408.                 'productListArray' => $productListArray,
  409.                 'subCategoryListArray' => $subCategoryListArray,
  410.                 'categoryListArray' => $categoryListArray,
  411.                 'igListArray' => $igListArray,
  412.                 'unitListArray' => $unitListArray,
  413.                 'brandListArray' => $brandListArray,
  414.                 "success" => true,
  415.                 'users' => Users::getUserListById($em),
  416.                 'stages' => ProjectConstant::$projectStages,
  417.                 'sl' => $sl,
  418.                 'hl' => $hl,
  419.                 'hl_array' => $hl_array,
  420.                 'sl_array' => $sl_array,
  421. //                'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
  422.             )
  423.         );
  424.     }
  425.     public function GetProductListForMisAction(Request $request)
  426.     {
  427.         $em $this->getDoctrine()->getManager();
  428.         $productIds $request->query->get('productId');
  429.         $fdmList = [];
  430.         $find_array = array('id' => $productIds);
  431.         if ($request->query->get('fdmList')) {
  432.             $find_array = array();
  433.             $fdmList $productIds $request->query->get('fdmList');
  434.         }
  435. //            $find_array=array('id' =>  $productIds);
  436.         $products $this->getDoctrine()
  437.             ->getRepository('ApplicationBundle\\Entity\\InvProducts')
  438.             ->findBy(
  439.                 $find_array
  440.             );
  441.         $productList = [];
  442.         $productListForShow = [];
  443.         foreach ($products as $entry) {
  444.             $productList[$entry->getId()] = array(
  445.                 'id' => $entry->getId(),
  446.                 'name' => $entry->getName(),
  447.                 'fdm' => $entry->getProductFdm(),
  448.             );
  449.         }
  450.         $products_in_stock $this->getDoctrine()
  451.             ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  452.             ->findBy(
  453.                 $find_array
  454.             );
  455.         $warehouseList Inventory::WarehouseList($em);
  456.         if (!empty($fdmList)) {
  457.             foreach ($products_in_stock as $dt) {
  458. //            if()
  459.                 $matched_a_product 0;
  460.                 foreach ($fdmList as $fdm) {
  461.                     $matchFdm Inventory::MatchFdm($fdm$productList[$dt->getProductId()]['fdm']);
  462.                     if ($matchFdm['hasMatched'] == 1) {
  463.                         if ($matchFdm['isIdentical'] == || $matchFdm['FirstBelongsToSecond'] == 1) {
  464.                             $matched_a_product 1;
  465.                             if (isset($productListForShow[$dt->getProductId()])) {
  466.                             } else {
  467.                                 $productListForShow[$dt->getProductId()] = array(
  468.                                     'id' => $productList[$dt->getProductId()]['id'],
  469.                                     'name' => $productList[$dt->getProductId()]['name'],
  470.                                     'fdm' => $productList[$dt->getProductId()]['fdm'],
  471.                                 );
  472.                             }
  473.                             if (isset($productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  474.                                 $productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  475.                             else {
  476.                                 $productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  477.                             }
  478.                             break;
  479.                         }
  480.                     }
  481.                 }
  482.                 if ($matched_a_product == 0) {
  483.                     continue;
  484.                 }
  485.                 if (isset($productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  486.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  487.                 else
  488.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  489.             }
  490.         } else {
  491.             foreach ($products_in_stock as $dt) {
  492. //            if()
  493.                 if (isset($productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  494.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  495.                 else
  496.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  497.             }
  498.             $productListForShow $productList;
  499.         }
  500.         $engine $this->container->get('twig');
  501. //        $SD=Supplier::GetSupplierDetailsForMis($em,$supplier_id);
  502.         if ($productList) {
  503.             $Content $engine->render('@Inventory/pages/report/selected_item_stock.html.twig', array("productList" => $productListForShow'warehouseList' => $warehouseList));
  504.             return new JsonResponse(array("success" => true"content" => $Content'productListForShow' => $productListForShow));
  505.         }
  506.         return new JsonResponse(array("success" => false));
  507.     }
  508.     public function CreateProductAction(Request $request$id 0)
  509.     {
  510.         $ex_id 0;
  511.         $prod_det = [];
  512.         $product_duplicate 0;
  513.         $createdProduct null;
  514.         $createdService null;
  515.         $group_type 1;//item
  516.         $em $this->getDoctrine()->getManager();
  517.         $companyId $this->getLoggedUserCompanyId($request);
  518.         $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  519.         $route $request->get('_route');
  520.         if ($route == 'create_service')
  521.             $group_type 2;//service
  522.         $quickCreateMode = (int)$request->request->get('quick_create_mode'0);
  523.         $productFormDefaults $this->getProductFormDefaults($em$companyId$loginId);
  524.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  525.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  526. //                $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  527. //        file_put_contents($path, json_encode(array(
  528. //            'sessionDataString'=>$request->request->get('sessionDataString'),
  529. //            'sessionData'=>json_decode($request->request->get('sessionDataString')),
  530. ////            'invData'=>$data_searched,
  531. //
  532. //        )));//overwrite
  533.         if ($request->isMethod('POST')) {
  534.             if ($id == 0)
  535.                 $id $request->request->has('ex_id') ? $request->request->get('ex_id') : 0;
  536.             if ($id == 0) {
  537.                 if ($group_type == 2)
  538.                     $ext_pr $this->getDoctrine()
  539.                         ->getRepository('ApplicationBundle\\Entity\\AccService')
  540.                         ->findOneBy(
  541.                             array(
  542.                                 'serviceName' => $request->request->get('name'),
  543.                             )
  544.                         );
  545.                 else
  546.                     $ext_pr $this->getDoctrine()
  547.                         ->getRepository('ApplicationBundle\\Entity\\InvProducts')
  548.                         ->findOneBy(
  549.                             array(
  550.                                 'name' => $request->request->get('name'),
  551.                             )
  552.                         );
  553.                 if ($ext_pr)
  554.                     $product_duplicate 1;
  555.             }
  556.             if ($product_duplicate == 1) {
  557.                 $this->addFlash(
  558.                     'error',
  559.                     'Duplicate Entry Found'
  560.                 );
  561.             } else {
  562.                 $image_list = [];
  563.                 $defaultImage "";
  564.                 $defaultImageUploadedFile null;
  565.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  566. //
  567. //                if ($request->files->has('product_default_image')) {
  568. //
  569. //
  570. ////                    foreach ($request->files->get('product_default_image') as $uploadedFile)
  571. //                    $defaultImageUploadedFile = $request->files->get('product_default_image');
  572. //                    {
  573. //
  574. //                        $path = "";
  575. //
  576. //                        if ($defaultImageUploadedFile != null) {
  577. //
  578. //                            $fileName = 'p' . md5(uniqid()) . '.' . $defaultImageUploadedFile->guessExtension();
  579. //                            $path = $fileName;
  580. //
  581. //                            if (!file_exists($upl_dir)) {
  582. //                                mkdir($upl_dir, 0777, true);
  583. //                            }
  584. ////                            $file = $uploadedFile->move($upl_dir, $path);
  585. //
  586. //                        }
  587. //                        $file_list[] = $path;
  588. //                        $defaultImage = $path;
  589. //                    }
  590. //
  591. //
  592. //                }
  593. //                if ($request->files->has('product_images')) {
  594. //
  595. //
  596. //                    foreach ($request->files->get('product_default_image') as $ind=>$uploadedFile)
  597. //                    {
  598. //
  599. //                        $path = "";
  600. //
  601. //                        if ($uploadedFile != null) {
  602. //
  603. //                            $fileName = 'p_'.$ind . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
  604. //                            $path = $fileName;
  605. //
  606. //                            if (!file_exists($upl_dir)) {
  607. //                                mkdir($upl_dir, 0777, true);
  608. //                            }
  609. ////                            $file = $uploadedFile->move($upl_dir, $path);
  610. //
  611. //                        }
  612. //                        $image_list[] = $path;
  613. //                        if($defaultImage=='' && $ind==0) {
  614. //                            $defaultImage = $path;
  615. //                            $uploadedFile = $path;
  616. //                        }
  617. //
  618. //                    }
  619. //
  620. //
  621. //                }
  622.                 if ($group_type == 2) {
  623.                     $ig $this->getDoctrine()
  624.                         ->getRepository('ApplicationBundle\\Entity\\InvItemGroup')
  625.                         ->findOneBy(
  626.                             array(
  627.                                 'id' => $request->request->get('itemgroupId')
  628.                             )
  629.                         );
  630.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Service/';
  631.                     $defaultPurchaseActionTagId $request->request->get('defaultPurchaseActionTagId''');
  632.                     $ledgerHitAs $request->request->get('ledgerHitAs''');
  633.                     $defaultExpenseId $request->request->get('defaultExpenseId''');
  634.                     $createdService Inventory::CreateNewService(
  635.                         $this->getDoctrine()->getManager(),
  636.                         $request->request->get('ex_id'),
  637.                         $request->request->get('name'),
  638.                         $companyId,
  639.                         $request->request->get('typeId'),
  640.                         $request->request->get('categoryId'),
  641.                         $request->request->get('brandCompany'),
  642.                         $request->request->get('subCategoryId'),
  643.                         $request->request->get('itemgroupId'),
  644.                         $request->request->get('unitTypeId'),
  645.                         $request->request->get('note'),
  646.                         $request->request->get('alias'''),
  647.                         $request->files->get('dataSheets', []),
  648.                         $request->files->get('service_default_image'null),
  649.                         $upl_dir,
  650.                         $request->files->get('service_images', []),
  651.                         [
  652.                             $request->request->get('categorization_1'''),
  653.                             $request->request->get('categorization_2'''),
  654.                             $request->request->get('categorization_3'''),
  655.                             $request->request->get('categorization_4'''),
  656.                             $request->request->get('categorization_5'''),
  657.                             $request->request->get('categorization_6'''),
  658.                             $request->request->get('categorization_7'''),
  659.                             $request->request->get('categorization_8'''),
  660.                             $request->request->get('categorization_9'''),
  661.                             $request->request->get('categorization_10'''),
  662.                         ],
  663.                         $request->request->get('purchasePrice'0),
  664.                         $request->request->get('salesPrice'0),
  665.                         $request->request->get('productFdm'''),
  666.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  667.                         ($ledgerHitAs != '') ? $ledgerHitAs $ig->getLedgerHitAs(),
  668.                         ($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId $ig->getDefaultPurchaseActionTagId(),
  669.                         ($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId $ig->getDefaultExpenseId(),
  670.                         $request->request->get('taxConfigIds', []),
  671.                         $request->request->get('defaultTaxConfigId'0),
  672.                         $request->request->get('purchaseTaxConfigIds', []),
  673.                         $request->request->get('defaultPurchaseTaxConfigId'0),
  674.                         $request->request->get('product_type''simple_product')
  675.                     );
  676.                     $this->saveProductFormDefaults($em$companyId$loginId$createdService$request);
  677.                     $this->addFlash(
  678.                         'success',
  679.                         'Service Have Been Added/Updated'
  680.                     );
  681.                 } else {
  682.                     $ig $this->getDoctrine()
  683.                         ->getRepository('ApplicationBundle\\Entity\\InvItemGroup')
  684.                         ->findOneBy(
  685.                             array(
  686.                                 'id' => $request->request->get('itemgroupId')
  687.                             )
  688.                         );
  689.                     $defaultPurchaseActionTagId $request->request->get('defaultPurchaseActionTagId''');
  690.                     $ledgerHitAs $request->request->get('ledgerHitAs''');
  691.                     $defaultExpenseId $request->request->get('defaultExpenseId''');
  692.                     $specData = [];
  693.                     $specData = [];
  694.                     foreach ($request->request->get('spec', []) as $specIndex => $specId) {
  695.                         $specData[] = array(
  696.                             'id' => $request->request->get('spec', [])[$specIndex],
  697.                             'value' => $request->request->get('spec_value', [])[$specIndex],
  698.                         );
  699.                     }
  700.                     $crateData = [];
  701.                     $crateData = [];
  702.                     foreach ($request->request->get('product_crate', []) as $crateIndex => $crateId) {
  703.                         $crateData[] = array(
  704.                             'id' => $crateId,
  705.                             'qty' => $request->request->get('product_qty', []),
  706.                         );
  707.                     }
  708.                     $sizesData = [];
  709.                     foreach ($request->request->get('product_crate', []) as $crateIndex => $crateId) {
  710.                         $sizesData[] = array(
  711.                             'size' => $request->request->get('product_size', []),
  712.                             'dimension' => $request->request->get('product_dimension', []),
  713.                             'dimensionUnitType' => $request->request->get('product_dimension_unit_type', []),
  714.                             'weight' => $request->request->get('product_weight', []),
  715.                             'weightUnitType' => $request->request->get('product_weight_unit_type', []),
  716.                         );
  717.                     }
  718.                     $createdProduct Inventory::CreateNewProduct(
  719.                         $this->getDoctrine()->getManager(),
  720.                         $request->request->get('ex_id'0),
  721.                         $request->request->get('name'''),
  722.                         $request->request->get('model_no'''),
  723.                         $this->getLoggedUserCompanyId($request),
  724.                         $request->request->get('typeId'1),
  725.                         $request->request->get('categoryId'null),
  726.                         $request->request->get('hasSerial'null),
  727.                         $ig->getDraccountsHeadId(),
  728.                         $ig->getCraccountsHeadId(),
  729.                         ($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId $ig->getDefaultPurchaseActionTagId(),
  730.                         $ig->getVatAsExpenseFlag(),
  731.                         $request->request->get('brandCompany'null),
  732.                         $request->request->get('subCategoryId'null),
  733.                         $request->request->get('yearlyDepreciation'0),
  734.                         $request->request->get('purchaseWarrantyMonths'0),
  735.                         $request->request->get('salesWarrantyMonths'0),
  736.                         $request->request->get('startingBalanceUnit'0),
  737.                         $request->request->get('reorderLevel'0),
  738.                         $request->request->get('note'''),
  739.                         $request->request->get('alias'''),
  740.                         $request->request->get('itemgroupId'null),
  741.                         $request->request->get('unitTypeId'null),
  742.                         $request->request->get('hsCode'''),
  743.                         $request->request->get('skuCode'''),
  744.                         $request->files->get('dataSheets', []),
  745.                         $request->request->get('partId'''),
  746.                         $request->request->get('productCode'''),
  747.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  748.                         $request->request->get('purchasePrice'0),
  749.                         $request->request->get('salesPrice'0),
  750.                         $request->files->get('product_default_image'null),
  751.                         $upl_dir,
  752.                         $request->files->get('product_images', []),
  753.                         $request->request->get('expiryDays'0),
  754.                         $request->request->get('dimension'''),
  755.                         $request->request->get('dimensionUnitTypeId'0),
  756.                         $request->request->get('productFdm'''),
  757.                         $request->request->get('weight'''),
  758.                         $request->request->get('weightUnitTypeId'0),
  759.                         $request->request->get('specification'null),
  760.                         $request->request->get('ingredient'null),
  761.                         $request->request->get('nutrition'null),
  762.                         $request->request->get('segregatePriceByColorsFlag'null),
  763.                         $request->request->get('segregatePriceBySizesFlag'null),
  764.                         [
  765.                             $request->request->get('categorization_1'''),
  766.                             $request->request->get('categorization_2'''),
  767.                             $request->request->get('categorization_3'''),
  768.                             $request->request->get('categorization_4'''),
  769.                             $request->request->get('categorization_5'''),
  770.                             $request->request->get('categorization_6'''),
  771.                             $request->request->get('categorization_7'''),
  772.                             $request->request->get('categorization_8'''),
  773.                             $request->request->get('categorization_9'''),
  774.                             $request->request->get('categorization_10'''),
  775.                         ],
  776.                         $request->request->get('weightVarianceValue'0),
  777.                         $request->request->get('weightVarianceType'0),
  778.                         $request->request->get('singleWeight'''),
  779.                         $request->request->get('singleWeightUnitTypeId'0),
  780.                         $request->request->get('singleWeightVarianceValue'0),
  781.                         $request->request->get('singleWeightVarianceType'0),
  782.                         $request->request->get('cartonWeightVarianceValue'0),
  783.                         $request->request->get('cartonWeightVarianceType'0),
  784.                         $request->request->get('cartonCapacityCount'0),
  785.                         $request->request->get('tac'''),
  786.                         $request->request->get('sellable'0),
  787.                         $request->request->get('abstract'0),
  788.                         $request->request->get('tags'''),
  789.                         $request->request->get('markerFlags'''),
  790.                         $request->request->get('defaultColorId'0),
  791.                         $request->request->get('product_color', []),
  792.                         $request->request->get('product_size', []),
  793.                         ($ledgerHitAs != '') ? $ledgerHitAs $ig->getLedgerHitAs(),
  794.                         ($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId $ig->getDefaultExpenseId(),
  795.                         $crateData,
  796.                         $sizesData,
  797.                         $specData,
  798.                         $request->request->get('taxConfigIds', []),
  799.                         $request->request->get('defaultTaxConfigId'0),
  800.                         $request->request->get('purchaseTaxConfigIds', []),
  801.                         $request->request->get('defaultPurchaseTaxConfigId'0),
  802.                         $request->request->get('product_type''simple_product')
  803.                     );
  804.                     if ($group_type != 2) {
  805.                         $savedProductId $createdProduct $createdProduct->getId() : (int) $request->request->get('ex_id'0);
  806.                         // S2.2 â€” persist epc_category_code
  807.                         $epcCode trim($request->request->get('epc_category_code'''));
  808.                         if ($savedProductId 0) {
  809.                             $productToTag $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($savedProductId);
  810.                             if ($productToTag) {
  811.                                 $productToTag->setEpcCategoryCode($epcCode !== '' $epcCode null);
  812.                                 // S3.3 â€” persist dispositionMethod
  813.                                 $dispMethod $request->request->get('dispositionMethod''demand_driven');
  814.                                 $allowedDisp = ['demand_driven''make_to_order''min_max''none'];
  815.                                 $productToTag->setDispositionMethod(in_array($dispMethod$allowedDisp) ? $dispMethod 'demand_driven');
  816.                                 $em->flush();
  817.                             }
  818.                         }
  819.                         $this->saveProductDependencies(
  820.                             $this->getDoctrine()->getManager(),
  821.                             $savedProductId,
  822.                             $request->request->get('dependencies', array())
  823.                         );
  824.                     }
  825.                     $this->saveProductFormDefaults($em$companyId$loginId$group_type == $createdService $createdProduct$request);
  826.                     $this->addFlash(
  827.                         'success',
  828.                         'Product Have Been Added/Updated'
  829.                     );
  830.                     // push new/updated product to central catalog
  831.                     if ($createdProduct) {
  832.                         $syncSystemType $this->container->hasParameter('system_type')
  833.                             ? $this->container->getParameter('system_type')
  834.                             : '_ERP_';
  835.                         Inventory::SyncProductToGlobal($em$createdProduct$ig $ig->getName() : ''$syncSystemType);
  836.                     }
  837.                 }
  838.             }
  839.             if ($request->request->has('returnJson')) {
  840.                 return new JsonResponse(array(
  841.                     'success' => true
  842.                 ));
  843.             }
  844.             if ($quickCreateMode === 1) {
  845.                 if ($group_type == 2) {
  846.                     $savedServiceId $createdService $createdService->getServiceId() : (int)$request->request->get('ex_id'0);
  847.                     return $this->redirectToRoute("create_service", array('id' => $savedServiceId));
  848.                 }
  849.                 $savedProductId $createdProduct $createdProduct->getId() : (int)$request->request->get('ex_id'0);
  850.                 return $this->redirectToRoute("create_product", array('id' => $savedProductId));
  851.             }
  852.             if ($group_type == 2)
  853.                 return $this->redirectToRoute("create_service");
  854.             else
  855.                 return $this->redirectToRoute("create_product");
  856.         }
  857.         if ($id != 0) {
  858.             $ex_id $id;
  859.             if ($group_type == 2)
  860.                 $prod_det $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccService')->findOneBy(array(
  861.                     'serviceId' => $id//for now for stock of goods
  862. //                    'opening_locked'=>0
  863.                 ));
  864.             else
  865.                 $prod_det $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(array(
  866.                     'id' => $id//for now for stock of goods
  867. //                    'opening_locked'=>0
  868.                 ));
  869.         }
  870. //        dump($prod_det);
  871.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  872.             'name' => 'warehouse_action_1'//for now for stock of goods
  873.         ));
  874.         return $this->render('@Inventory/pages/input_forms/create_product.html.twig',
  875.             array(
  876.                 'page_title' => $group_type == 'Service Entry' 'Product Entry',
  877.                 'group_type' => $group_type,
  878.                 'inv_head' => $inv_head $inv_head->getData() : '',
  879. //                'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  880.                 'services' => Inventory::ServiceList($this->getDoctrine()->getManager()),
  881.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  882.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  883.                 'itemgroup' => Inventory::ItemGroupList($em$companyId$group_type),
  884.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  885.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  886.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager(), 1),
  887.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  888.                 'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  889.                 'productDependencies' => $ex_id != $this->getProductDependencyRows($this->getDoctrine()->getManager(), $ex_id) : array(),
  890.                 'ex_id' => $ex_id,
  891.                 'warehouse_action_list' => $warehouse_action_list,
  892.                 'warehouse_action_list_array' => $warehouse_action_list_array,
  893.                 'markerFlags' => InventoryConstant::$SPECIAL_MARKER_ARRAY,
  894.                 'productFormDefaults' => $productFormDefaults,
  895. //                'isUpdate' => true,
  896.                 'ex_prod_det' => $prod_det,
  897.                 'epcCategories' => $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')
  898.                     ->findBy(['active' => 1], ['displayOrder' => 'ASC']),
  899.                 // dev-admin-only: enables the "Load from Central" product picker
  900.                 'dev_admin' => (int) $request->getSession()->get('devAdminMode'0) === 1,
  901.             )
  902.         );
  903.     }
  904.     public function ProductListAction(Request $request)
  905.     {
  906.         $em $this->getDoctrine()->getManager();
  907.         $companyId $this->getLoggedUserCompanyId($request);
  908.         $listData Inventory::GetProductListForProductListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  909.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  910.             if ($request->query->has('dataTableQry')) {
  911.                 return new JsonResponse(
  912.                     $listData
  913.                 );
  914.             }
  915.         }
  916.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  917.             'name' => 'warehouse_action_1'//for now for stock of goods
  918.         ));
  919.         return $this->render('@Inventory/pages/list/product_list.html.twig',
  920.             array(
  921.                 'page_title' => 'Product List',
  922.                 'inv_head' => $inv_head $inv_head->getData() : '',
  923. //                'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  924.                 'products' => [],
  925.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  926.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  927.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  928.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  929.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  930. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  931.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  932.                 'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  933.             )
  934.         );
  935.     }
  936.     public function SalesVsDeliveryListAction(Request $request)
  937.     {
  938.         $em $this->getDoctrine()->getManager();
  939.         $session $request->getSession();
  940.         $userType $session->get(UserConstants::USER_TYPE);
  941.         $userId $session->get(UserConstants::USER_ID);
  942.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  943.             'approved' => GeneralConstant::APPROVED,
  944. //            'stage' => GeneralConstant::STAGE_PENDING
  945.         );
  946.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  947.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  948.         }
  949. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  950. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  951. //            $selectiveDocumentsFlag=1; //by default will show only selective
  952. //            if(isset($userRestrictions['canSeeAllSo'])) {
  953. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  954. //                    $selectiveDocumentsFlag = 0;
  955. //                }
  956. //            }
  957. //
  958. //            if($selectiveDocumentsFlag==1)
  959. //            {
  960. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  961. //            }
  962. //        }
  963.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  964.             'name' => 'warehouse_action_1'//for now for stock of goods
  965.         ));
  966.         if ($request->query->has('queryDate')) {
  967.             $date = new \DateTime($request->query->get('queryDate'));
  968.         } else {
  969.             $today = new \DateTime();
  970.             $todayStr $today->format('Y-m-d');
  971.             $date = new \DateTime($todayStr);
  972.         }
  973.         $orderQryArray['salesOrderDate'] = $date;
  974.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findBy($orderQryArray);
  975.         $so_ids = [];
  976.         $so_data = [];
  977.         $so_item_ids = [];
  978.         $so_item_data = [];
  979.         foreach ($salesOrders as $salesOrder) {
  980.             if ($salesOrder->getSalesOrderDate() > $date)
  981.                 continue;
  982.             $so_ids[] = $salesOrder->getSalesOrderId();
  983.             $so_data[$salesOrder->getSalesOrderId()] = array(
  984.                 "id" => $salesOrder->getSalesOrderId(),
  985.                 "documentHash" => $salesOrder->getDocumentHash(),
  986.                 "clientId" => $salesOrder->getClientId(),
  987.             );
  988.         }
  989.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findBy(array(
  990.             'salesOrderId' => $so_ids,
  991.         ));
  992.         foreach ($salesOrderItems as $salesOrderItem) {
  993.             $so_item_ids[] = $salesOrderItem->getId();
  994.             $so_item_data[$salesOrderItem->getId()] = array(
  995.                 "id" => $salesOrderItem->getId(),
  996.                 "productId" => $salesOrderItem->getProductId(),
  997.                 "productName" => $salesOrderItem->getProductNameFdm(),
  998.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  999.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  1000.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  1001. //                "documentHash"=>$salesOrder->getDocumentHash(),
  1002.                 "qty" => $salesOrderItem->getQty(),
  1003.                 "transitQty" => $salesOrderItem->getTransitQty(),
  1004.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  1005.             );
  1006.         }
  1007.         return $this->render('@Inventory/pages/views/sales_vs_delivery_status.html.twig',
  1008.             array(
  1009.                 'page_title' => 'Order Vs. Disperse',
  1010.                 'inv_head' => $inv_head $inv_head->getData() : '',
  1011.                 'so_data' => $so_data,
  1012.                 'queryDate' => $date,
  1013.                 'so_item_data' => $so_item_data,
  1014.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  1015.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  1016.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  1017.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  1018.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  1019.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  1020.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  1021. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  1022.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  1023.             )
  1024.         );
  1025.     }
  1026.     public function DeliveryPendingOrderListAction(Request $request)
  1027.     {
  1028.         $em $this->getDoctrine()->getManager();
  1029.         $session $request->getSession();
  1030.         $userType $session->get(UserConstants::USER_TYPE);
  1031.         $userId $session->get(UserConstants::USER_ID);
  1032.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  1033.             'approved' => GeneralConstant::APPROVED,
  1034.             'stage' => GeneralConstant::STAGE_PENDING
  1035.         );
  1036.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  1037.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  1038.         }
  1039. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  1040. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  1041. //            $selectiveDocumentsFlag=1; //by default will show only selective
  1042. //            if(isset($userRestrictions['canSeeAllSo'])) {
  1043. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  1044. //                    $selectiveDocumentsFlag = 0;
  1045. //                }
  1046. //            }
  1047. //
  1048. //            if($selectiveDocumentsFlag==1)
  1049. //            {
  1050. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  1051. //            }
  1052. //        }
  1053.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1054.             'name' => 'warehouse_action_1'//for now for stock of goods
  1055.         ));
  1056.         if ($request->query->has('queryDate')) {
  1057.             $date = new \DateTime($request->query->get('queryDate'));
  1058.         } else {
  1059.             $today = new \DateTime();
  1060.             $todayStr $today->format('Y-m-d');
  1061.             $date = new \DateTime($todayStr);
  1062.         }
  1063. //        $orderQryArray['salesOrderDate'] = $date;
  1064.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findBy($orderQryArray);
  1065.         $so_ids = [];
  1066.         $so_data = [];
  1067.         $so_item_ids = [];
  1068.         $so_item_data = [];
  1069.         foreach ($salesOrders as $salesOrder) {
  1070.             if ($salesOrder->getSalesOrderDate() > $date)
  1071.                 continue;
  1072.             $so_ids[] = $salesOrder->getSalesOrderId();
  1073.             $so_data[$salesOrder->getSalesOrderId()] = array(
  1074.                 "id" => $salesOrder->getSalesOrderId(),
  1075.                 "documentHash" => $salesOrder->getDocumentHash(),
  1076.                 "clientId" => $salesOrder->getClientId(),
  1077.             );
  1078.         }
  1079.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findBy(array(
  1080.             'salesOrderId' => $so_ids,
  1081.         ));
  1082.         foreach ($salesOrderItems as $salesOrderItem) {
  1083.             $so_item_ids[] = $salesOrderItem->getId();
  1084.             $so_item_data[$salesOrderItem->getId()] = array(
  1085.                 "id" => $salesOrderItem->getId(),
  1086.                 "productId" => $salesOrderItem->getProductId(),
  1087.                 "productName" => $salesOrderItem->getProductNameFdm(),
  1088.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  1089.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  1090.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  1091. //                "documentHash"=>$salesOrder->getDocumentHash(),
  1092.                 "qty" => $salesOrderItem->getQty(),
  1093.                 "transitQty" => $salesOrderItem->getTransitQty(),
  1094.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  1095.             );
  1096.         }
  1097.         return $this->render('@Inventory/pages/views/delivery_pending_order_list.html.twig',
  1098.             array(
  1099.                 'page_title' => 'Pending Delivery',
  1100.                 'inv_head' => $inv_head $inv_head->getData() : '',
  1101.                 'so_data' => $so_data,
  1102.                 'queryDate' => $date,
  1103.                 'so_item_data' => $so_item_data,
  1104.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  1105.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  1106.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  1107.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  1108.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  1109.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  1110.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  1111. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  1112.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  1113.             )
  1114.         );
  1115.     }
  1116.     public function AddSpecTypeAction(Request $request$id 0)
  1117.     {
  1118.         $ex_id 0;
  1119.         $det = [];
  1120.         $em $this->getDoctrine()->getManager();
  1121.         $companyId $this->getLoggedUserCompanyId($request);
  1122.         if ($request->isMethod('POST')) {
  1123. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  1124. //            $request->request->get('ex_id');
  1125. //
  1126. //
  1127. //            $this->addFlash(
  1128. //                'success',
  1129. //                'Spec Type Added'
  1130. //            );
  1131.             Inventory::CreateSpecType(
  1132.                 $this->getDoctrine()->getManager(),
  1133.                 $request->request->get('ex_id'),
  1134.                 $request->request,
  1135.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  1136.             );
  1137.         }
  1138.         if ($id != 0) {
  1139.             $ex_id $id;
  1140.             $det $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SpecType')->findOneBy(array(
  1141.                 'id' => $id
  1142.             ));
  1143.         }
  1144.         $specTypeDetails $em->getRepository(SpecType::class)->findAll();
  1145.         return $this->render('@Inventory/pages/input_forms/addSpecType.html.twig',
  1146.             array(
  1147.                 'page_title' => 'Add Spec Type',
  1148.                 'ex_id' => $ex_id,
  1149.                 'ex_det' => $det,
  1150.                 'specTypeDetails' => $specTypeDetails,
  1151.             )
  1152.         );
  1153.     }
  1154.     public function ItemGroupAction(Request $request$id 0)
  1155.     {
  1156.         $ex_id 0;
  1157.         $det = [];
  1158.         $em $this->getDoctrine()->getManager();
  1159.         $companyId $this->getLoggedUserCompanyId($request);
  1160.         $group_type 1;//item
  1161.         $route $request->get('_route');
  1162.         if ($route == 'service_group')
  1163.             $group_type 2;//service
  1164.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');
  1165.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');
  1166.         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ItemGroup/';
  1167.         if ($request->isMethod('POST')) {
  1168.             Inventory::CreateItemGroup(
  1169.                 $this->getDoctrine()->getManager(),
  1170.                 $request->request->get('ex_id'),
  1171.                 $this->getLoggedUserCompanyId($request),
  1172.                 $request->request,
  1173.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  1174.                 $request->files->get('dataSheets', []),
  1175.                 $request->files->get('item_group_icon'),
  1176.                 $request->files->get('item_group_banner_image'),
  1177.                 $request->files->get('item_group_default_image'),
  1178.                 $upl_dir,
  1179.                 $request->files->get('item_group_images', []));
  1180.         }
  1181.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1182.             'name' => 'warehouse_action_1',
  1183.         ));
  1184.         if ($group_type == 1) {
  1185.             if ($id != 0) {
  1186.                 $ex_id $id;
  1187.                 $det $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(array(
  1188.                     'id' => $id//for now for stock of goods
  1189. //                    'opening_locked'=>0
  1190.                 ));
  1191.             }
  1192.         } else {
  1193.             if ($id != 0) {
  1194.                 $ex_id $id;
  1195.                 $det $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccService')->findOneBy(array(
  1196.                     'serviceId' => $id
  1197.                 ));
  1198.             }
  1199.         }
  1200. //        dump($det);
  1201.         return $this->render('@Inventory/pages/input_forms/item_group.html.twig',
  1202.             array(
  1203.                 'page_title' => $group_type == "Item Group" "Service Group",
  1204.                 'inv_head' => $inv_head $inv_head->getData() : '',
  1205.                 'group_type' => $group_type,
  1206.                 'igList' => Inventory::ItemGroupList($em$companyId$group_type),
  1207.                 'warehouse_action_list' => $warehouse_action_list,
  1208. //                'data'=>Inventory::ItemGroupFormRelatedData($this->getDoctrine()->getManager()),
  1209.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  1210.                 'spec_type_list' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  1211.                 'ex_id' => $ex_id,
  1212.                 'ex_det' => $det,
  1213.                 'upl_dir' => $upl_dir,
  1214.             )
  1215.         );
  1216.     }
  1217.     public function addStartingOpeningInOutAction(Request $request$refreshed_opening 0)
  1218.     {
  1219.         //be very careful!!
  1220.         $em $this->getDoctrine()->getManager();
  1221. //        $last_refresh_date="";
  1222.         //steps
  1223.         //1. set all inventory to their opening position
  1224.         $assign_list = array();
  1225.         $data = array();
  1226.         if ($refreshed_opening == 0) {
  1227.             $new_cc $em
  1228.                 ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  1229.                 ->findOneBy(
  1230.                     array(
  1231.                         'name' => 'accounting_year_start',
  1232.                     )
  1233.                 );
  1234.             $date_start = new \DateTime($new_cc->getData());
  1235.             $date_start_str $date_start->format('Y-m-d');
  1236.             $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  1237. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  1238.             $stmt $em->getConnection()->fetchAllAssociative($closingQuery);
  1239.             $iniClosing $stmt;
  1240. //                $stmt = $em->getConnection()->fetchAllAssociative($transQuery);
  1241. //                
  1242. //                $iniTrans = $stmt;
  1243.             $singleClosing_byProductId = array();
  1244.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1245.             foreach ($iniClosing as $item) {
  1246.                 if (!isset($singleClosing_byProductId[$item['product_id']])) {
  1247.                     $singleClosing_byProductId[$item['product_id']] = array(
  1248.                         'date' => $item['date'],
  1249.                         'qtyAdd' => $item['qty_addition'],
  1250.                         'qtySub' => '0',
  1251.                         'valueAdd' => $item['addition'],
  1252.                         'valueSub' => '0',
  1253.                         'fromWarehouse' => 0,
  1254.                         'toWarehouse' => $item['warehouse_id'],
  1255.                         'fromWarehouseSub' => 0,
  1256.                         'toWarehouseSub' => $item['action_tag_id'],
  1257.                         'price' => ($item['addition'] / $item['qty_addition'])
  1258.                     );
  1259.                 }
  1260.             }
  1261.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1262. //                foreach ($iniTrans as $item) {
  1263. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  1264. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  1265. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  1266. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  1267. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  1268. //                    }
  1269. //                }
  1270.             foreach ($singleClosing_byProductId as $key => $item) {
  1271.                 if (!isset($data[$key])) {
  1272.                     $data[$key][] = $item;
  1273.                 }
  1274.             }
  1275.             //now that we go the data we can empty the closing table
  1276. //                $get_kids_sql ='UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  1277. //    truncate `inv_closing_balance`;
  1278. //    truncate `inventory_storage`;
  1279. //    truncate `inv_item_transaction`;';
  1280. //                $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1281. //                
  1282. //                
  1283. //                $stmt;
  1284.             $total_inv_value_in 0;
  1285.             foreach ($data as $key => $item) {
  1286.                 if (!empty($item)) {
  1287.                     foreach ($item as $entry) {
  1288.                         $transDate = new \DateTime($entry['date']);
  1289.                         $new = new InvItemInOut();
  1290.                         $new->setProductId($key);
  1291.                         $new->setWarehouseId($entry['toWarehouse']);
  1292.                         $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  1293.                         $new->setActionTagId($entry['toWarehouseSub']);
  1294.                         $new->setTransactionDate($transDate);
  1295.                         $new->setQty($entry['qtyAdd']);
  1296.                         $new->setPrice($entry['price']);
  1297.                         $new->setAmount($entry['qtyAdd'] * $entry['price']);
  1298.                         $new->setEntity(0);// opening =0
  1299.                         $new->setEntityId(0);// opening =0
  1300.                         $new->setDebitCreditHeadId(0);// opening =0
  1301.                         $new->setVoucherIds(null);// opening =0
  1302.                         $em->persist($new);
  1303.                         $em->flush();
  1304.                         $total_inv_value_in += $entry['qtyAdd'] * $entry['price'];
  1305.                     }
  1306.                 }
  1307.             }
  1308.             $refreshed_opening 1;
  1309. //                $terminate=1;
  1310. //                $last_refresh_date=$last_refresh_date_obj->format('Y-m-d');
  1311.             return new JsonResponse(array(
  1312.                 "success" => true,
  1313.             ));
  1314.             //now call the function which will add the 1st ever entry or opening entry
  1315.         }
  1316.         //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  1317.         return new JsonResponse(array(
  1318.             "success" => false,
  1319.         ));
  1320.     }
  1321.     public function RefreshInventoryAction(Request $request$refreshed_opening 0)
  1322.     {
  1323.         //be very careful!!
  1324.         // GATE (2026-07-26). A full day-by-day stock replay on live data was
  1325.         // reachable by ANY logged-in user (class declares only SessionCheckInterface).
  1326.         // Super-users only, same rule as /rebuild-rectify and /tenant-reset.
  1327.         $denial = \ApplicationBundle\Modules\Accounts\Support\RebuildAccessGuard::previewDenial($request->getSession());
  1328.         if ($denial !== '') {
  1329.             return new JsonResponse(array('success' => false'error' => $denial), 403);
  1330.         }
  1331.         $em $this->getDoctrine()->getManager();
  1332.         $refreshed_opening 0;
  1333.         $last_refresh_date "";
  1334.         $last_refresh_date_obj "";
  1335.         $terminate 0;
  1336.         $companyId $this->getLoggedUserCompanyId($request);
  1337.         $modifyAccTransaction $request->request->has('modify_acc_trans_flag') ? $request->request->get('modify_acc_trans_flag') : 0;
  1338.         $modifyProductionPrice $request->request->has('modify_production_price') ? $request->request->get('modify_production_price') : 0;
  1339. //        $last_refresh_date="";
  1340.         if ($request->isMethod('POST')) {
  1341.             //steps
  1342.             //1. set all inventory to their opening position
  1343.             $assign_list = array();
  1344.             $data = array();
  1345.             if ($request->request->has('inventory_refreshed'))
  1346.                 $refreshed_opening $request->request->get('inventory_refreshed');
  1347.             if ($request->request->has('last_refresh_date'))
  1348.                 $last_refresh_date $request->request->get('last_refresh_date');
  1349.             if ($refreshed_opening == 0) {
  1350. //                System::log_it($this->container->getParameter('kernel.root_dir'), "",
  1351. //                    'inventory_refresh_debug', 0); //last er 1 is append
  1352.                 $new_cc $em
  1353.                     ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  1354.                     ->findOneBy(
  1355.                         array(
  1356.                             'name' => 'accounting_year_start',
  1357.                         )
  1358.                     );
  1359.                 $date_start = new \DateTime($new_cc->getData());
  1360.                 $date_start_str $date_start->format('Y-m-d');
  1361.                 $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  1362. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  1363.                 $stmt $em->getConnection()->fetchAllAssociative($closingQuery);
  1364.                 $iniClosing $stmt;
  1365. //                $stmt = $em->getConnection()->fetchAllAssociative($transQuery);
  1366. //                
  1367. //                $iniTrans = $stmt;
  1368.                 $singleClosing_byProductId = array();
  1369.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1370.                 foreach ($iniClosing as $item) {
  1371.                     if (!isset($singleClosing_byProductId[$item['product_id']])) {
  1372.                         $singleClosing_byProductId[$item['product_id']] = array(
  1373.                             'date' => $item['date'],
  1374.                             'qtyAdd' => $item['qty_addition'],
  1375.                             'qtySub' => '0',
  1376.                             'valueAdd' => $item['addition'],
  1377.                             'valueSub' => '0',
  1378.                             'fromWarehouse' => 0,
  1379.                             'toWarehouse' => $item['warehouse_id'],
  1380.                             'fromWarehouseSub' => 0,
  1381.                             'toWarehouseSub' => $item['action_tag_id'],
  1382.                             'price' => $item['qty_addition'] != ? ($item['addition'] / $item['qty_addition']) : $item['addition']
  1383.                         );
  1384.                     }
  1385.                 }
  1386.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1387. //                foreach ($iniTrans as $item) {
  1388. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  1389. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  1390. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  1391. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  1392. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  1393. //                    }
  1394. //                }
  1395.                 foreach ($singleClosing_byProductId as $key => $item) {
  1396.                     if (!isset($data[$key])) {
  1397.                         $data[$key][] = $item;
  1398.                     }
  1399.                 }
  1400.                 //new one
  1401.                 //chekc if ultra opening stock received note exists if not create it
  1402.                 $mo $em
  1403.                     ->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')
  1404.                     ->findOneBy(
  1405.                         array(
  1406.                             'documentHash' => '_MASTER_OPENING_',
  1407.                             'typeHash' => 'SR',
  1408.                             'prefixHash' => 4,
  1409.                             'assocHash' => '_MASTER_OPENING_',
  1410.                             'numberHash' => 1,
  1411.                         )
  1412.                     );
  1413.                 if (!$mo) {
  1414.                     //doensot exist to add :)
  1415. //                    $products = $post_data->get('products');
  1416. //                    $qty = $post_data->get('qty');
  1417. //                    $note = $post_data->get('note');
  1418.                     $new = new StockReceivedNote();
  1419.                     $new->setStockReceivedNoteDate(new \DateTime($date_start_str));
  1420.                     $new->setCompanyId($companyId);
  1421.                     $new->setDocumentHash('_MASTER_OPENING_');
  1422.                     $new->setTypeHash('SR');
  1423.                     $new->setPrefixHash(4);
  1424.                     $new->setAssocHash('_MASTER_OPENING_');
  1425.                     $new->setNumberHash(1);
  1426.                     $new->setCreditHeadId(0);
  1427.                     $new->setStockTransferId(0);
  1428.                     $new->setSalesOrderId(0);
  1429.                     $new->setType(4);
  1430.                     $new->setStatus(GeneralConstant::ACTIVE);
  1431.                     $new->setWarehouseId(0);
  1432.                     $new->setNote('');
  1433.                     $new->setAutoCreated(1);
  1434.                     $new->setApproved(GeneralConstant::APPROVED);
  1435. //        $new->setIndentTagged(0);
  1436.                     $new->setStage(GeneralConstant::STAGE_COMPLETE);
  1437.                     $new->setCreatedLoginId(0);
  1438.                     $new->setEditedLoginId(0);
  1439.                     $em->persist($new);
  1440.                     $em->flush();
  1441.                     $SRID $new->getStockReceivedNoteId();
  1442.                     $last_refresh_date_obj $new->getStockReceivedNoteDate();
  1443.                     //now add items to details
  1444.                     foreach ($data as $key => $item) {
  1445.                         if (!empty($item)) {
  1446.                             foreach ($item as $entry) {
  1447.                                 $transDate = new \DateTime($entry['date']);
  1448.                                 if ($last_refresh_date_obj == '') {
  1449.                                     $last_refresh_date_obj $transDate;
  1450.                                 } else if ($transDate $last_refresh_date_obj) {
  1451.                                     $last_refresh_date_obj $transDate;
  1452.                                 }
  1453.                                 $new = new StockReceivedNoteItem();
  1454.                                 $new->setStockReceivedNoteId($SRID);
  1455.                                 $new->setStockTransferItemId(0);
  1456.                                 $salesCodeRange = [];
  1457.                                 $salesCodeRangeStr '';
  1458.                                 $new->setSalesCodeRange("[" $salesCodeRangeStr "]");
  1459.                                 $new->setQty($entry['qtyAdd']);
  1460.                                 $new->setPrice($entry['price']);
  1461.                                 $new->setBalance($entry['qtyAdd']);
  1462.                                 $new->setProductId($key);
  1463.                                 $new->setWarrantyMon(0);
  1464.                                 $new->setWarehouseId($entry['toWarehouse']);
  1465.                                 $new->setWarehouseActionId($entry['toWarehouseSub']);
  1466.                                 $em->persist($new);
  1467.                                 $em->flush();
  1468.                             }
  1469.                         }
  1470.                     }
  1471. //                    for ($i = 0; $i < count($products); $i++) {
  1472. //
  1473. //
  1474. //                        $srItem = self::CreateNewStockReceivedNoteItem($em, $post_data, $i, $new->getStockReceivedNoteId(), $LoginID);
  1475. //                    }
  1476.                 }
  1477.                 if ($mo)
  1478.                     $last_refresh_date_obj $mo->getStockReceivedNoteDate();
  1479.                 $last_refresh_date_obj->modify('-1 day');///new so that it willstart form this day on next call
  1480.                 //new ends
  1481.                 //now that we go the data we can empty the closing table
  1482.                 // Run each statement on its OWN executeStatement call. Passing all five as a
  1483.                 // single ";"-joined string only executed the FIRST statement (the inv_products
  1484.                 // reset) â€” the three TRUNCATEs silently never ran. That left the old ledger
  1485.                 // (inv_item_transaction / inv_closing_balance / inventory_storage) in place, so
  1486.                 // every refresh REBUILT on top of stale rows and duplicated postings (one SRCV
  1487.                 // showing 2–3×; pre-refresh rows survived a "full" refresh). Separate calls
  1488.                 // guarantee the wipe actually happens before the day-by-day rebuild.
  1489.                 $conn $em->getConnection();
  1490.                 $conn->executeStatement("UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1");
  1491.                 $conn->executeStatement("UPDATE `purchase_order` SET expense_amount=0, expense_pending_balance_amount=0, grn_tag_pending_expense_invoice_ids='[]' WHERE 1");
  1492.                 $conn->executeStatement("TRUNCATE `inv_closing_balance`");
  1493.                 $conn->executeStatement("TRUNCATE `inventory_storage`");
  1494.                 $conn->executeStatement("TRUNCATE `inv_item_transaction`");
  1495. //                $stmt;
  1496. //                foreach ($data as $key => $item) {
  1497. //                    if (!empty($item)) {
  1498. //                        foreach ($item as $entry) {
  1499. //                            $transDate = new \DateTime($entry['date']);
  1500. //                            Inventory::addItemToInventoryCompact($em,
  1501. //                                $key,
  1502. //                                $entry['fromWarehouse'],
  1503. //                                $entry['toWarehouse'],
  1504. //                                $entry['fromWarehouseSub'],
  1505. //                                $entry['toWarehouseSub'],
  1506. //                                $transDate,
  1507. //                                $entry['qtyAdd'],
  1508. //                                $entry['qtySub'],
  1509. //                                $entry['valueAdd'],
  1510. //                                $entry['valueSub'],
  1511. //                                $entry['price'],
  1512. //                                $this->getLoggedUserCompanyId($request));
  1513. //                            if ($last_refresh_date_obj == '') {
  1514. //                                $last_refresh_date_obj = $transDate;
  1515. //                            } else if ($transDate < $last_refresh_date_obj) {
  1516. //                                $last_refresh_date_obj = $transDate;
  1517. //                            }
  1518. //                        }
  1519. //                    }
  1520. //                }
  1521.                 $refreshed_opening 1;
  1522. //                $terminate=1;
  1523.                 if ($last_refresh_date_obj == "") {
  1524.                     $last_refresh_date $date_start_str;
  1525.                 } else {
  1526.                     $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1527.                 }
  1528.                 return new JsonResponse(array(
  1529.                     "success" => true,
  1530.                     "last_refresh_date" => $last_refresh_date,
  1531.                     "inventory_refreshed" => $refreshed_opening
  1532.                 ));
  1533.                 //now call the function which will add the 1st ever entry or opening entry
  1534.             }
  1535.             //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  1536.             if ($last_refresh_date != '')
  1537.                 $last_refresh_date_obj = new \DateTime($last_refresh_date);
  1538.             else {
  1539.                 $new_cc $em
  1540.                     ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  1541.                     ->findOneBy(
  1542.                         array(
  1543.                             'name' => 'accounting_year_start',
  1544.                         )
  1545.                     );
  1546.                 $last_refresh_date_obj = new \DateTime($new_cc->getData());
  1547.                 $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1548.             }
  1549.             $last_refresh_date_obj->modify('+1 day');
  1550.             $today = new \DateTime();
  1551.             if ($last_refresh_date_obj $today) {
  1552.                 $terminate 1;
  1553.             }
  1554.             $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1555.             // â”€â”€ Idempotency guard for the day's replay â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  1556.             // This pass REBUILDS every inventory-moving document dated $last_refresh_date
  1557.             // (GRN, StockReceivedNote, StockTransfer, DeliveryReceipt, ConsumptionNote,
  1558.             // ProductionEntry â€” all queried below). The one-shot TRUNCATE that was meant to
  1559.             // clear the ledger only runs on the inventory_refreshed==0 opening pass, which is
  1560.             // skipped whenever the loop resumes with inventory_refreshed==1 â€” so re-running or
  1561.             // resuming the refresh kept APPENDING a second/third copy of each posting (a single
  1562.             // SRCV showing 2×, 3×, 8×). Delete this date's postings first so the rebuild below
  1563.             // REPLACES them instead of stacking. Safe because the blocks below re-post every
  1564.             // document of that date; nothing on the date is left unaccounted.
  1565.             $__dayStart $last_refresh_date_obj->format('Y-m-d') . ' 00:00:00';
  1566.             $__nextDay = (clone $last_refresh_date_obj)->modify('+1 day')->format('Y-m-d') . ' 00:00:00';
  1567.             $em->getConnection()->executeStatement(
  1568.                 "DELETE FROM inv_item_transaction WHERE transaction_date >= '" $__dayStart "' AND transaction_date < '" $__nextDay "'"
  1569.             );
  1570.             //ok now we got the date so get grn item on this date
  1571.             //GRN
  1572.             $query "SELECT grn_item.*, grn.grn_date, grn.document_hash from  grn_item
  1573.               join grn on grn.grn_id=grn_item.grn_id
  1574.             where grn.grn_date ='" $last_refresh_date " 00:00:00' and grn.approved=1";
  1575.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1576.             $queryData $stmt;
  1577.             $grn_ids = [];
  1578.             foreach ($queryData as $item) {
  1579.                 $data[$item['product_id']][] = array(
  1580.                     'date' => $last_refresh_date,
  1581.                     'entity' => array_flip(GeneralConstant::$Entity_list)['Grn'],
  1582.                     'entityId' => $item['grn_id'],
  1583.                     'colorId' => $item['color_id'],
  1584.                     'sizeId' => $item['size_id'],
  1585.                     'entityDocHash' => $item['document_hash'],
  1586.                     'qtyAdd' => $item['qty'],
  1587.                     'qtySub' => 0,
  1588.                     'valueAdd' => ($item['qty'] * $item['price_with_expense']),
  1589.                     'valueSub' => 0,
  1590.                     'price' => $item['price_with_expense'],
  1591.                     'fromWarehouse' => 0,
  1592.                     'toWarehouse' => $item['warehouse_id'],
  1593.                     'fromWarehouseSub' => 0,
  1594. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1595.                     'toWarehouseSub' => $item['warehouse_action_id']
  1596.                 );
  1597.                 if (!in_array($item['grn_id'], $grn_ids))
  1598.                     $grn_ids[] = $item['grn_id'];
  1599.             }
  1600.             //now add grns
  1601.             foreach ($data as $key => $item) {
  1602.                 if (!empty($item)) {
  1603.                     foreach ($item as $entry) {
  1604.                         $transDate = new \DateTime($entry['date']);
  1605.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1606.                             $key,
  1607.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1608.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1609.                             $entry['fromWarehouse'],
  1610.                             $entry['toWarehouse'],
  1611.                             $entry['fromWarehouseSub'],
  1612.                             $entry['toWarehouseSub'],
  1613.                             $transDate,
  1614.                             $entry['qtyAdd'],
  1615.                             $entry['qtySub'],
  1616.                             $entry['valueAdd'],
  1617.                             $entry['valueSub'],
  1618.                             $entry['price'],
  1619.                             $this->getLoggedUserCompanyId($request),
  1620.                             0,
  1621.                             $entry['entity'],
  1622.                             $entry['entityId'],
  1623.                             $entry['entityDocHash'],
  1624.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_SUPPLER
  1625.                         );
  1626.                         if ($last_refresh_date_obj == '') {
  1627.                             $last_refresh_date_obj $transDate;
  1628.                         } else if ($transDate $last_refresh_date_obj) {
  1629.                             $last_refresh_date_obj $transDate;
  1630.                         }
  1631.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1632.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1633.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1634.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1635.                             "",
  1636.                             'inventory_refresh_debug'1); //last er 1 is append
  1637.                     }
  1638.                 }
  1639.             }
  1640.             ///adding grn vouhcer mod here too incase it wasnot in the distributed IG for heads
  1641. //            $grn=$em->getRepository('ApplicationBundle\\Entity\\Grn')->findBy(array(
  1642. //                'grnId'=>$grn_ids,
  1643. //                'modifyVoucherFlag'=>1 //have to add this flag
  1644. //            ));
  1645.             foreach ($grn_ids as $grn_id) {
  1646.                 if ($modifyAccTransaction == 1)
  1647.                     Inventory::ModifyGrnTransactions($em$grn_id1);
  1648.                 else
  1649.                     Inventory::ModifyGrnTransactions($em$grn_id);
  1650.             }
  1651.             //adding voucher ends
  1652.             $inv_head_list_by_wa = [];
  1653.             $inv_head_list = [];
  1654.             $cogs_head 0;
  1655.             $cogs_head 0;
  1656.             $internal_proj 0;
  1657. //            if ($project) {
  1658. //                if ($project->getProjectType() == 2) {
  1659. //                    $cogs_head = $project->getInternalProjectAssetHeadId();
  1660. //                    $internal_proj = 1;
  1661. //                } else {
  1662. //                    $cogs_head_qry = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1663. //                        'name' => 'cogs'
  1664. //                    ));
  1665. //                    $cogs_head = $cogs_head_qry->getData();
  1666. //                }
  1667. //            } else {
  1668.             $cogs_head_qry $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1669.                 'name' => 'cogs'
  1670.             ));
  1671.             $cogs_head $cogs_head_qry->getData();
  1672. //            }
  1673.             $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');
  1674.             foreach ($warehouse_action_list as $wa) {
  1675.                 $inv_head_data $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1676.                         'name' => 'warehouse_action_' $wa['id'])
  1677.                 );
  1678.                 if ($inv_head_data) {
  1679.                     $inv_head_list_by_wa[$wa['id']] = $inv_head_data->getData();
  1680.                     $inv_head_list[] = $inv_head_data->getData();
  1681.                 }
  1682.             }
  1683.             $data = [];
  1684.             //____________STOCK_RECEIVED___________________
  1685.             $docEntity "StockReceivedNote";
  1686.             $docEntityIdField "stockReceivedNoteId";
  1687.             $accTransactionDataByDocId = [];
  1688.             $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
  1689.               join stock_received_note on stock_received_note.stock_received_note_id=stock_received_note_item.stock_received_note_id
  1690.             where stock_received_note.stock_received_note_date ='" $last_refresh_date " 00:00:00' and stock_received_note.approved=1";
  1691.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1692.             $queryData $stmt;
  1693.             $grn_ids = [];
  1694.             foreach ($queryData as $item) {
  1695.                 $data[$item['product_id']][] = array(
  1696.                     'date' => $last_refresh_date,
  1697.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  1698.                     'entityId' => $item['stock_received_note_id'],
  1699.                     'colorId' => $item['color_id'],
  1700.                     'sizeId' => $item['size_id'],
  1701.                     'type' => $item['type'],
  1702.                     'entityDocHash' => $item['document_hash'],
  1703.                     'qtyAdd' => $item['qty'],
  1704.                     'qtySub' => 0,
  1705.                     'valueAdd' => ($item['qty'] * $item['price']),
  1706.                     'valueSub' => 0,
  1707.                     'price' => $item['price'],
  1708.                     'fromWarehouse' => 0,
  1709.                     'toWarehouse' => $item['warehouse_id'],
  1710.                     'fromWarehouseSub' => 0,
  1711. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1712.                     'toWarehouseSub' => $item['warehouse_action_id']
  1713.                 );
  1714. //                if (!in_array($item['grn_id'], $grn_ids))
  1715. //                    $grn_ids[] = $item['grn_id'];
  1716.             }
  1717.             foreach ($data as $key => $item) {
  1718.                 if (!empty($item)) {
  1719.                     foreach ($item as $entry) {
  1720.                         $transDate = new \DateTime($entry['date']);
  1721.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1722.                             $key,
  1723.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1724.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1725.                             $entry['fromWarehouse'],
  1726.                             $entry['toWarehouse'],
  1727.                             $entry['fromWarehouseSub'],
  1728.                             $entry['toWarehouseSub'],
  1729.                             $transDate,
  1730.                             $entry['qtyAdd'],
  1731.                             $entry['qtySub'],
  1732.                             $entry['valueAdd'],
  1733.                             $entry['valueSub'],
  1734.                             $entry['price'],
  1735.                             $this->getLoggedUserCompanyId($request),
  1736.                             0,
  1737.                             $entry['entity'],
  1738.                             $entry['entityId'],
  1739.                             $entry['entityDocHash'],
  1740.                             $entry['type'] == ?
  1741.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_OPENING :
  1742.                                 ($entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_STOCK_IN :
  1743.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT)
  1744.                         );
  1745.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1746.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1747.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1748.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1749.                             "",
  1750.                             'inventory_refresh_debug'1); //last er 1 is append
  1751.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1752.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1753.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  1754.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  1755.                         else
  1756.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  1757.                         if ($last_refresh_date_obj == '') {
  1758.                             $last_refresh_date_obj $transDate;
  1759.                         } else if ($transDate $last_refresh_date_obj) {
  1760.                             $last_refresh_date_obj $transDate;
  1761.                         }
  1762.                     }
  1763.                 }
  1764.             }
  1765.             if ($modifyAccTransaction == 1) {
  1766.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1767.                     $docHere $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  1768.                         $docEntityIdField => $docId,
  1769.                     ));;
  1770.                     if ($docHere) {
  1771.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1772.                         if ($curr_v_ids == null)
  1773.                             $curr_v_ids = [];
  1774.                         $skipVids = [];
  1775.                         $toChangeVid 0;
  1776.                         $voucher null;
  1777.                         foreach ($curr_v_ids as $vid) {
  1778.                             if (in_array($vid$skipVids))
  1779.                                 continue;
  1780.                             $skipVids[] = $vid//to prevent duplicate query
  1781.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  1782.                                 'transactionId' => $vid,
  1783.                             ));;
  1784.                             if ($voucher) {
  1785.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1786.                                     $toChangeVid $vid;
  1787.                                 } else {
  1788.                                     continue;
  1789.                                 }
  1790.                             }
  1791.                         }
  1792.                         if ($toChangeVid == 0) {
  1793.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1794.                                 $em,
  1795.                                 $docHere->getStockReceivedNoteDate()->format('Y-m-d'),
  1796.                                 0,
  1797.                                 AccountsConstant::VOUCHER_JOURNAL,
  1798.                                 'Journal For Stock Received Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  1799.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1800.                                 'JV',
  1801.                                 'GN',
  1802.                                 0,
  1803.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1804.                                 0,
  1805.                                 $docHere->getCreatedLoginId(),
  1806.                                 $docHere->getCompanyId(),
  1807.                                 '',
  1808.                                 0,
  1809.                                 1
  1810.                             );
  1811.                             $em->flush();
  1812.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  1813.                                 'transactionId' => $toChangeVid,
  1814.                             ));;
  1815.                         }
  1816.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  1817.                         $tot_inv_amount 0;
  1818.                         foreach ($transData as $k => $v) {
  1819.                             $tot_inv_amount += ($v);
  1820.                             Accounts::CreateNewTransactionDetails($em,
  1821.                                 '',
  1822.                                 $toChangeVid,
  1823.                                 Generic::CurrToInt($v),
  1824.                                 $k,
  1825.                                 'Inventory Inward For - ' $docHere->getDocumentHash(),
  1826.                                 AccountsConstant::DEBIT,
  1827.                                 0,
  1828.                                 [],
  1829.                                 [],
  1830.                                 $docHere->getCreatedLoginId()
  1831.                             );
  1832.                         }
  1833.                         $stockReceivedType $docHere->getType();
  1834.                         $to_balance_head 0;
  1835.                         if (in_array($stockReceivedType, [23]))
  1836.                             $to_balance_head $docHere->getCreditHeadId();
  1837.                         else {
  1838.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1839.                                     'name' => 'inv_on_transit_head')
  1840.                             );
  1841.                             if ($inv_transit_head)
  1842.                                 $to_balance_head $inv_transit_head->getData();
  1843.                         }
  1844.                         Accounts::CreateNewTransactionDetails($em,
  1845.                             '',
  1846.                             $toChangeVid,
  1847.                             Generic::CurrToInt($tot_inv_amount),
  1848.                             $to_balance_head,
  1849.                             in_array($stockReceivedType, [23]) ? 'Balancing of Stock in Items for -' $docHere->getDocumentHash() : 'In Transit Items for -' $docHere->getDocumentHash(),
  1850.                             AccountsConstant::CREDIT,
  1851.                             0,
  1852.                             [],
  1853.                             [],
  1854.                             $docHere->getCreatedLoginId()
  1855.                         );
  1856.                         if ($voucher)
  1857.                             $voucher->setTransactionAmount($tot_inv_amount);
  1858.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1859.                         if ($curr_v_ids != null)
  1860.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1861.                         else
  1862.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1863.                         $em->flush();
  1864. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  1865.                     }
  1866.                 }
  1867.             }
  1868.             $data = [];
  1869.             $query "SELECT purchase_invoice.* from  purchase_invoice
  1870. where purchase_invoice.purchase_invoice_date ='" $last_refresh_date " 00:00:00' and purchase_invoice.approved=1
  1871.             ";
  1872.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1873.             $queryData $stmt;
  1874.             foreach ($queryData as $pi) {
  1875.                 $transDate = new \DateTime($pi['purchase_invoice_date']);
  1876.                 if ($last_refresh_date_obj == '') {
  1877.                     $last_refresh_date_obj $transDate;
  1878.                 } else if ($transDate $last_refresh_date_obj) {
  1879.                     $last_refresh_date_obj $transDate;
  1880.                 }
  1881.                 Accounts::CalibrateProductPriceWithPi($em$pi['purchase_invoice_id'], 1);
  1882.             }
  1883.             $data = [];
  1884.             $query "SELECT expense_invoice.* from  expense_invoice
  1885. where expense_invoice.expense_invoice_date ='" $last_refresh_date " 00:00:00' and expense_invoice.approved=1 and
  1886.             expense_invoice_type_id=1";
  1887.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1888.             $queryData $stmt;
  1889.             foreach ($queryData as $ei) {
  1890.                 $transDate = new \DateTime($ei['expense_invoice_date']);
  1891.                 if ($last_refresh_date_obj == '') {
  1892.                     $last_refresh_date_obj $transDate;
  1893.                 } else if ($transDate $last_refresh_date_obj) {
  1894.                     $last_refresh_date_obj $transDate;
  1895.                 }
  1896.                 $grn_ids json_decode($ei['grn_id_list'], true);
  1897.                 if ($grn_ids == null)
  1898.                     $grn_ids = [];
  1899. //                if (!empty($grn_ids)) {
  1900. //
  1901. //
  1902. //                        if ($ei->getExpenseInvocationStrategyOnGrn() != 2) {
  1903. //                            $grn = $em->getRepository('ApplicationBundle\\Entity\\Grn')->findBy(array(
  1904. //                                'purchaseOrderId' => $ei->getPurchaseOrderId()
  1905. //                            ));
  1906. //
  1907. //                        }
  1908. //                        else
  1909. //                        {
  1910. //                            $po = $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(array(
  1911. //                                'purchaseOrderId' => $ei['purchase_order_id']
  1912. //                            ));
  1913. //
  1914. //                            if ($po) {
  1915. //                                $po->setExpenseAmount($po->getExpenseAmount() + $ei['invoice_amount']);
  1916. //                            }
  1917. //                            continue; //grn expense will be there anyway
  1918. //                        }
  1919. //
  1920. //
  1921. //
  1922. //                }
  1923.                 Accounts::CalibrateProductPriceWithExpense($em$ei['expense_invoice_id']);
  1924. //                $po = $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(array(
  1925. //                    'purchaseOrderId' => $ei['purchase_order_id']
  1926. //                ));
  1927. //
  1928. //
  1929. //                //first get the total valuation
  1930. //                if ($po) {
  1931. //                    $total_product_value = 0;
  1932. //                    $total_pending_expense = 0;
  1933. //                    $po_item_data = $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(array(
  1934. ////                'productId' => $item->getProductId(),
  1935. //                        'purchaseOrderId' => $ei['purchase_order_id']
  1936. //                    ));
  1937. //
  1938. //
  1939. //                    foreach ($po_item_data as $it) {
  1940. ////                    $product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(array(
  1941. ////                        'id' => $item->getProductId()
  1942. ////                    ));
  1943. //
  1944. //                        $poqty = $it->getReceived();
  1945. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);
  1946. //                        $total_product_value += (1 * $po_price);
  1947. //
  1948. //
  1949. //                    }
  1950. //
  1951. //
  1952. //                    //now we know the total grn price value. lets get the fraction increase
  1953. //                    $total_pending_expense = $ei['invoice_amount'];
  1954. //                    if ($total_product_value != 0)
  1955. //                        $fraction_increase = ($total_pending_expense) / ($total_product_value);
  1956. //                    else
  1957. //                        $fraction_increase = 0;
  1958. //
  1959. //                    foreach ($po_item_data as $it) {
  1960. //                        $item = $it;
  1961. //                        $product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(array(
  1962. //                            'id' => $it->getProductId()
  1963. //                        ));
  1964. //                        if (!$product)
  1965. //                            continue;
  1966. //
  1967. ////                    $items_in_inventory=$em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(array(
  1968. ////                        'productId'=>$item->getProductId()
  1969. ////                    ));
  1970. //
  1971. //                        $poqty = $it->getReceived();
  1972. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);;
  1973. //
  1974. //                        $existing_qty = $product->getQty();;
  1975. //
  1976. //
  1977. //                        $increased_po_price = ($po_price * $fraction_increase);
  1978. //
  1979. //                        //now lets see homuch is the total price
  1980. //                        $new_purchase_price = $product->getPurchasePrice();
  1981. //
  1982. //                        if ($increased_po_price != 0) {
  1983. //                            $last_grn_item = $em->getRepository('ApplicationBundle\\Entity\\GrnItem')->findOneBy(array(
  1984. //                                'purchaseOrderItemId' => $item->getId()
  1985. //                            ));
  1986. //                            if ($last_grn_item) {
  1987. //
  1988. //                                $data[$last_grn_item->getProductId()][] = array(
  1989. //                                    'date' => $last_refresh_date,
  1990. //
  1991. //                                    'entity' => array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  1992. //                                    'entityId' => $ei['expense_invoice_id'],
  1993. //                                    'colorId' => $last_grn_item->getColorId(),
  1994. //                                    'sizeId' => $last_grn_item->getSizeId(),
  1995. //                                    'entityDocHash' => $ei['document_hash'],
  1996. //                                    'qtyAdd' => 0,
  1997. //                                    'qtySub' => 0,
  1998. //                                    'valueAdd' => $increased_po_price,
  1999. ////                                    'valueAdd' => $increased_po_price>=0?$increased_po_price:0,
  2000. ////                    'valueSub' => ($item['qty'] * $item['price']),
  2001. ////                                    'valueSub' => $increased_po_price<0?((-1)*$increased_po_price):0,
  2002. //                                    'valueSub' => 0,
  2003. //                                    'price' => '_UNSET_',
  2004. //                                    'fromWarehouse' => 0,
  2005. //                                    'toWarehouse' => $last_grn_item->getWarehouseId(),
  2006. //                                    'fromWarehouseSub' => 0,
  2007. ////                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  2008. //                                    'toWarehouseSub' => $last_grn_item->getWarehouseActionId()
  2009. //                                );
  2010. //
  2011. ////                                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);
  2012. ////
  2013. ////                                $total_item_price = $increased_po_price + ($product->getPurchasePrice() * ($existing_qty));
  2014. ////                                if ($existing_qty != 0)
  2015. ////                                    $new_purchase_price = $total_item_price / $existing_qty;
  2016. //
  2017. //
  2018. //                                $total_pending_expense -= $increased_po_price;
  2019. //                            }
  2020. //                        }
  2021. //                    }
  2022. //
  2023. //
  2024. //
  2025. //
  2026. //
  2027. //
  2028. //                } else {
  2029. //                    continue;
  2030. //                }
  2031.             }
  2032.             $data = [];
  2033.             //____________STOCK_TRANSFER___________________
  2034.             $docEntity "StockTransfer";
  2035.             $docEntityIdField "stockTransferId";
  2036.             $accTransactionDataByDocId = [];
  2037.             $query "SELECT stock_transfer_item.*,  stock_transfer.stock_transfer_date, stock_transfer.document_hash, stock_transfer.transfer_action_type from  stock_transfer_item
  2038.               join stock_transfer on stock_transfer.stock_transfer_id=stock_transfer_item.stock_transfer_id
  2039.             where stock_transfer.stock_transfer_date ='" $last_refresh_date " 00:00:00' and stock_transfer.approved=1";
  2040.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2041.             $queryData $stmt;
  2042.             $grn_ids = [];
  2043.             foreach ($queryData as $item) {
  2044.                 $data[$item['product_id']][] = array(
  2045.                     'date' => $last_refresh_date,
  2046.                     'transfer_action_type' => $item['transfer_action_type'],
  2047.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  2048.                     'entityId' => $item['stock_transfer_id'],
  2049.                     'colorId' => $item['color_id'],
  2050.                     'sizeId' => $item['size_id'],
  2051.                     'entityDocHash' => $item['document_hash'],
  2052.                     'qtyAdd' => $item['transfer_action_type'] == $item['qty'] : 0,
  2053.                     'qtySub' => $item['qty'],
  2054.                     'valueAdd' => 0,
  2055. //                    'valueSub' => ($item['qty'] * $item['price']),
  2056.                     'valueSub' => '_AUTO_',
  2057.                     'price' => $item['price'],
  2058.                     'fromWarehouse' => $item['warehouse_id'],
  2059.                     'toWarehouse' => $item['transfer_action_type'] == $item['to_warehouse_id'] : 0,
  2060.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  2061. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  2062.                     'toWarehouseSub' => $item['transfer_action_type'] == $item['to_warehouse_action_id'] : 0
  2063.                 );
  2064. //                if (!in_array($item['grn_id'], $grn_ids))
  2065. //                    $grn_ids[] = $item['grn_id'];
  2066.             }
  2067.             //now add grns
  2068.             foreach ($data as $key => $item) {
  2069.                 if (!empty($item)) {
  2070.                     foreach ($item as $entry) {
  2071.                         $transDate = new \DateTime($entry['date']);
  2072.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2073.                             $key,
  2074.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2075.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2076.                             $entry['fromWarehouse'],
  2077.                             $entry['toWarehouse'],
  2078.                             $entry['fromWarehouseSub'],
  2079.                             $entry['toWarehouseSub'],
  2080.                             $transDate,
  2081.                             $entry['qtyAdd'],
  2082.                             $entry['qtySub'],
  2083.                             $entry['valueAdd'],
  2084.                             $entry['valueSub'],
  2085.                             $entry['price'],
  2086.                             $this->getLoggedUserCompanyId($request),
  2087.                             0,
  2088.                             $entry['entity'],
  2089.                             $entry['entityId'],
  2090.                             $entry['entityDocHash'],
  2091.                             $entry['transfer_action_type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_INTER_WAREHOUSE GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT
  2092.                         );
  2093.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2094.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2095.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2096.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2097.                             "",
  2098.                             'inventory_refresh_debug'1); //last er 1 is append
  2099.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2100.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  2101.                         if ($entry['transfer_action_type'] == 4) {
  2102.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2103.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2104.                             else
  2105.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2106.                         }
  2107.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2108.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2109.                         else
  2110.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2111.                         if ($last_refresh_date_obj == '') {
  2112.                             $last_refresh_date_obj $transDate;
  2113.                         } else if ($transDate $last_refresh_date_obj) {
  2114.                             $last_refresh_date_obj $transDate;
  2115.                         }
  2116.                     }
  2117.                 }
  2118.             }
  2119.             if ($modifyAccTransaction == 1) {
  2120.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2121.                     $docHere $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  2122.                         $docEntityIdField => $docId,
  2123.                     ));;
  2124.                     if ($docHere) {
  2125.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2126.                         if ($curr_v_ids == null)
  2127.                             $curr_v_ids = [];
  2128.                         $skipVids = [];
  2129.                         $toChangeVid 0;
  2130.                         $voucher null;
  2131.                         foreach ($curr_v_ids as $vid) {
  2132.                             if (in_array($vid$skipVids))
  2133.                                 continue;
  2134.                             $skipVids[] = $vid//to prevent duplicate query
  2135.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2136.                                 'transactionId' => $vid,
  2137.                             ));;
  2138.                             if ($voucher) {
  2139.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2140.                                     $toChangeVid $vid;
  2141.                                 } else {
  2142.                                     continue;
  2143.                                 }
  2144.                             }
  2145.                         }
  2146.                         if ($toChangeVid == 0) {
  2147.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2148.                                 $em,
  2149.                                 $docHere->getStockTransferDate()->format('Y-m-d'),
  2150.                                 0,
  2151.                                 AccountsConstant::VOUCHER_JOURNAL,
  2152.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  2153.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2154.                                 'JV',
  2155.                                 'GN',
  2156.                                 0,
  2157.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2158.                                 0,
  2159.                                 $docHere->getCreatedLoginId(),
  2160.                                 $docHere->getCompanyId(),
  2161.                                 '',
  2162.                                 0,
  2163.                                 1
  2164.                             );
  2165.                             $em->flush();
  2166.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2167.                                 'transactionId' => $toChangeVid,
  2168.                             ));;
  2169.                         }
  2170.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  2171.                         $tot_inv_amount 0;
  2172.                         foreach ($transData as $k => $v) {
  2173.                             $tot_inv_amount += ($v);
  2174.                             Accounts::CreateNewTransactionDetails($em,
  2175.                                 '',
  2176.                                 $toChangeVid,
  2177.                                 Generic::CurrToInt($v),
  2178.                                 $k,
  2179.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2180.                                 $v >= AccountsConstant::DEBIT AccountsConstant::CREDIT,
  2181.                                 0,
  2182.                                 [],
  2183.                                 [],
  2184.                                 $docHere->getCreatedLoginId()
  2185.                             );
  2186.                         }
  2187. //                        $stockReceivedType = $docHere->getType();
  2188.                         $to_balance_head 0;
  2189.                         if ($docHere->getTransferActionType() == 4) {
  2190.                         } else {
  2191.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  2192.                                     'name' => 'inv_on_transit_head')
  2193.                             );
  2194.                             if ($inv_transit_head)
  2195.                                 $to_balance_head $inv_transit_head->getData();
  2196.                         }
  2197.                         if ($to_balance_head != 0) {
  2198.                             Accounts::CreateNewTransactionDetails($em,
  2199.                                 '',
  2200.                                 $toChangeVid,
  2201.                                 Generic::CurrToInt($tot_inv_amount),
  2202.                                 $to_balance_head,
  2203.                                 'In Transit Items for -' $docHere->getDocumentHash(),
  2204.                                 $tot_inv_amount >= AccountsConstant::CREDIT AccountsConstant::DEBIT,
  2205.                                 0,
  2206.                                 [],
  2207.                                 [],
  2208.                                 $docHere->getCreatedLoginId()
  2209.                             );
  2210.                         }
  2211.                         if ($voucher)
  2212.                             $voucher->setTransactionAmount($tot_inv_amount);
  2213.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2214.                         if ($curr_v_ids != null)
  2215.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2216.                         else
  2217.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2218.                         $em->flush();
  2219. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2220.                     }
  2221.                 }
  2222.             }
  2223.             $data = [];
  2224.             //____________IRR___________________
  2225.             $docEntity "ItemReceivedAndReplacement";
  2226.             $docEntityIdField "itemReceivedAndReplacementId";
  2227.             $accTransactionDataByDocId = [];
  2228.             $query "SELECT irr_item.*,  item_received_replacement.irr_date, item_received_replacement.document_hash from  irr_item
  2229.               join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  2230.             where item_received_replacement.irr_date ='" $last_refresh_date " 00:00:00' and item_received_replacement.approved=1";
  2231.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2232.             $queryData $stmt;
  2233.             $irr_add_data = [];
  2234.             $irr_replace_data = [];
  2235.             $irr_dispose_data = [];
  2236.             foreach ($queryData as $item) {
  2237.                 $irr_add_data[$item['received_product_id']][] = array(
  2238.                     'date' => $last_refresh_date,
  2239.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  2240.                     'entityId' => $item['irr_id'],
  2241.                     'colorId' => $item['received_product_color_id'],
  2242.                     'sizeId' => $item['received_product_color_id'],
  2243.                     'entityDocHash' => $item['document_hash'],
  2244.                     'qtyAdd' => $item['received_qty'],
  2245.                     'qtySub' => 0,
  2246.                     'valueAdd' => ($item['received_qty'] * $item['received_unit_purchase_price']),
  2247.                     'valueSub' => 0,
  2248.                     'price' => $item['received_unit_purchase_price'],
  2249.                     'fromWarehouse' => 0,
  2250.                     'toWarehouse' => $item['received_warehouse_id'],
  2251.                     'fromWarehouseSub' => 0,
  2252.                     'toWarehouseSub' => $item['received_warehouse_action_id']
  2253.                 );
  2254.                 $irr_replace_data[$item['replaced_product_id']][] = array(
  2255.                     'date' => $last_refresh_date,
  2256.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  2257.                     'entityId' => $item['irr_id'],
  2258.                     'colorId' => $item['replaced_product_color_id'],
  2259.                     'sizeId' => $item['replaced_product_color_id'],
  2260.                     'entityDocHash' => $item['document_hash'],
  2261.                     'qtyAdd' => 0,
  2262.                     'qtySub' => $item['replaced_qty'],
  2263.                     'valueAdd' => 0,
  2264.                     'valueSub' => ($item['replaced_qty'] * $item['replaced_unit_purchase_price']),
  2265.                     'price' => $item['replaced_unit_purchase_price'],
  2266.                     'fromWarehouse' => $item['replaced_warehouse_id'],
  2267.                     'toWarehouse' => 0,
  2268.                     'fromWarehouseSub' => $item['replaced_warehouse_action_id'],
  2269.                     'toWarehouseSub' => 0
  2270.                 );
  2271.                 $irr_dispose_data[$item['received_product_id']][] = array(
  2272.                     'date' => $last_refresh_date,
  2273.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  2274.                     'entityId' => $item['irr_id'],
  2275.                     'colorId' => $item['received_product_color_id'],
  2276.                     'sizeId' => $item['received_product_size_id'],
  2277.                     'entityDocHash' => $item['document_hash'],
  2278.                     'qtyAdd' => 0,
  2279.                     'qtySub' => $item['dispose_qty'],
  2280.                     'valueAdd' => 0,
  2281.                     'valueSub' => ($item['dispose_qty'] * $item['received_unit_purchase_price']),
  2282.                     'price' => $item['received_unit_purchase_price'],
  2283.                     'fromWarehouse' => $item['received_warehouse_id'],
  2284.                     'toWarehouse' => 0,
  2285.                     'fromWarehouseSub' => $item['received_warehouse_id'],
  2286.                     'toWarehouseSub' => 0
  2287.                 );
  2288.             }
  2289.             //now add irrs
  2290.             foreach ($irr_add_data as $key => $item) {
  2291.                 if (!empty($item)) {
  2292.                     foreach ($item as $entry) {
  2293.                         $transDate = new \DateTime($entry['date']);
  2294.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2295.                             $key,
  2296.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2297.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2298.                             $entry['fromWarehouse'],
  2299.                             $entry['toWarehouse'],
  2300.                             $entry['fromWarehouseSub'],
  2301.                             $entry['toWarehouseSub'],
  2302.                             $transDate,
  2303.                             $entry['qtyAdd'],
  2304.                             $entry['qtySub'],
  2305.                             $entry['valueAdd'],
  2306.                             $entry['valueSub'],
  2307.                             $entry['price'],
  2308.                             $this->getLoggedUserCompanyId($request),
  2309.                             0,
  2310.                             $entry['entity'],
  2311.                             $entry['entityId'],
  2312.                             $entry['entityDocHash'],
  2313.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2314.                         );
  2315.                         if ($modifiedData)
  2316.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2317.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2318.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2319.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2320.                                 "",
  2321.                                 'inventory_refresh_debug'1); //last er 1 is append
  2322.                         if ($last_refresh_date_obj == '') {
  2323.                             $last_refresh_date_obj $transDate;
  2324.                         } else if ($transDate $last_refresh_date_obj) {
  2325.                             $last_refresh_date_obj $transDate;
  2326.                         }
  2327.                     }
  2328.                 }
  2329.             }
  2330.             foreach ($irr_replace_data as $key => $item) {
  2331.                 if (!empty($item)) {
  2332.                     foreach ($item as $entry) {
  2333.                         $transDate = new \DateTime($entry['date']);
  2334.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2335.                             $key,
  2336.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2337.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2338.                             $entry['fromWarehouse'],
  2339.                             $entry['toWarehouse'],
  2340.                             $entry['fromWarehouseSub'],
  2341.                             $entry['toWarehouseSub'],
  2342.                             $transDate,
  2343.                             $entry['qtyAdd'],
  2344.                             $entry['qtySub'],
  2345.                             $entry['valueAdd'],
  2346.                             $entry['valueSub'],
  2347.                             $entry['price'],
  2348.                             $this->getLoggedUserCompanyId($request),
  2349.                             0,
  2350.                             $entry['entity'],
  2351.                             $entry['entityId'],
  2352.                             $entry['entityDocHash']);
  2353.                         if ($modifiedData)
  2354.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2355.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2356.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2357.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2358.                                 "",
  2359.                                 'inventory_refresh_debug'1); //last er 1 is append
  2360.                         if ($last_refresh_date_obj == '') {
  2361.                             $last_refresh_date_obj $transDate;
  2362.                         } else if ($transDate $last_refresh_date_obj) {
  2363.                             $last_refresh_date_obj $transDate;
  2364.                         }
  2365.                     }
  2366.                 }
  2367.             }
  2368.             foreach ($irr_dispose_data as $key => $item) {
  2369.                 if (!empty($item)) {
  2370.                     foreach ($item as $entry) {
  2371.                         $transDate = new \DateTime($entry['date']);
  2372.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2373.                             $key,
  2374.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2375.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2376.                             $entry['fromWarehouse'],
  2377.                             $entry['toWarehouse'],
  2378.                             $entry['fromWarehouseSub'],
  2379.                             $entry['toWarehouseSub'],
  2380.                             $transDate,
  2381.                             $entry['qtyAdd'],
  2382.                             $entry['qtySub'],
  2383.                             $entry['valueAdd'],
  2384.                             $entry['valueSub'],
  2385.                             $entry['price'],
  2386.                             $this->getLoggedUserCompanyId($request),
  2387.                             0,
  2388.                             $entry['entity'],
  2389.                             $entry['entityId'],
  2390.                             $entry['entityDocHash'],
  2391.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2392.                         );
  2393.                         if ($modifiedData)
  2394.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2395.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2396.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2397.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2398.                                 "",
  2399.                                 'inventory_refresh_debug'1); //last er 1 is append
  2400.                         if ($last_refresh_date_obj == '') {
  2401.                             $last_refresh_date_obj $transDate;
  2402.                         } else if ($transDate $last_refresh_date_obj) {
  2403.                             $last_refresh_date_obj $transDate;
  2404.                         }
  2405.                     }
  2406.                 }
  2407.             }
  2408.             $data = [];
  2409.             //____________DELIVERY_RECEIPT___________________
  2410.             $docEntity "DeliveryReceipt";
  2411.             $docEntityIdField "deliveryReceiptId";
  2412.             $accTransactionDataByDocId = [];
  2413.             $query "SELECT delivery_receipt_item.*, delivery_receipt.delivery_receipt_date, delivery_receipt.document_hash, delivery_receipt.skip_inventory_hit from  delivery_receipt_item
  2414.               join delivery_receipt on delivery_receipt.delivery_receipt_id=delivery_receipt_item.delivery_receipt_id
  2415.             where delivery_receipt.delivery_receipt_date ='" $last_refresh_date " 00:00:00' and delivery_receipt.approved=1";
  2416.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2417.             $queryData $stmt;
  2418.             foreach ($queryData as $item) {
  2419.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  2420.                     ->findOneBy(
  2421.                         array(
  2422.                             'id' => $item['product_id']
  2423.                         )
  2424.                     );
  2425.                 $curr_purchase_price $product->getPurchasePrice();
  2426.                 if ($item['skip_inventory_hit'] != 1) {
  2427.                     $data[$item['product_id']][] = array(
  2428.                         'date' => $last_refresh_date,
  2429.                         'entity' => array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  2430.                         'entityId' => $item['delivery_receipt_id'],
  2431.                         'colorId' => $item['color_id'],
  2432.                         'sizeId' => $item['size_id'],
  2433.                         'entityDocHash' => $item['document_hash'],
  2434.                         'qtyAdd' => 0,
  2435.                         'qtySub' => ($item['qty'] * $item['unit_multiplier']),
  2436.                         'valueAdd' => 0,
  2437.                         'valueSub' => '_AUTO_',
  2438.                         'price' => $curr_purchase_price,
  2439.                         'fromWarehouse' => $item['warehouse_id'],
  2440.                         'toWarehouse' => 0,
  2441.                         'fromWarehouseSub' => $item['warehouse_action_id'] != null $item['warehouse_action_id'] : GeneralConstant::WAREHOUSE_ACTION_GOODS,
  2442.                         'toWarehouseSub' => 0
  2443.                     );
  2444.                 }
  2445.                 $get_kids_sql "UPDATE `delivery_receipt_item` SET current_purchase_price='" $curr_purchase_price "' WHERE id=" $item['id'] . ";";
  2446.                 $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2447.             }
  2448.             foreach ($data as $key => $item) {
  2449.                 if (!empty($item)) {
  2450.                     foreach ($item as $entry) {
  2451.                         $transDate = new \DateTime($entry['date']);
  2452.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2453.                             $key,
  2454.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2455.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2456.                             $entry['fromWarehouse'],
  2457.                             $entry['toWarehouse'],
  2458.                             $entry['fromWarehouseSub'],
  2459.                             $entry['toWarehouseSub'],
  2460.                             $transDate,
  2461.                             $entry['qtyAdd'],
  2462.                             $entry['qtySub'],
  2463.                             $entry['valueAdd'],
  2464.                             $entry['valueSub'],
  2465.                             $entry['price'],
  2466.                             $this->getLoggedUserCompanyId($request),
  2467.                             0,
  2468.                             $entry['entity'],
  2469.                             $entry['entityId'],
  2470.                             $entry['entityDocHash'],
  2471.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2472.                         );
  2473.                         if ($modifiedData)
  2474.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2475.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2476.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2477.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2478.                                 "",
  2479.                                 'inventory_refresh_debug'1); //last er 1 is append
  2480.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2481.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  2482.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2483.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2484.                         else
  2485.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2486.                         if ($last_refresh_date_obj == '') {
  2487.                             $last_refresh_date_obj $transDate;
  2488.                         } else if ($transDate $last_refresh_date_obj) {
  2489.                             $last_refresh_date_obj $transDate;
  2490.                         }
  2491.                     }
  2492.                 }
  2493.             }
  2494.             if ($modifyAccTransaction == 1) {
  2495.                 //for now we are suuming there is only receipt without confirmation needed
  2496.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2497.                     $docHereDr $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  2498.                         $docEntityIdField => $docId,
  2499.                     ));;
  2500.                     $so $em->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findOneBy(
  2501.                         array(
  2502.                             'salesOrderId' => $docHereDr->getSalesOrderId()
  2503.                         )
  2504.                     );
  2505.                     $query $em->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
  2506.                         ->createQueryBuilder('p');
  2507.                     $query->where('p.salesOrderId = :soID')
  2508.                         ->setParameter('soID'$docHereDr->getSalesOrderId());
  2509.                     $query->andWhere("p.deliveryReceiptIds LIKE '%" $docId "%' ");
  2510.                     $query->setMaxResults(1);
  2511.                     $results $query->getQuery()->getResult();
  2512.                     $docHere null;
  2513.                     if (!empty($results))
  2514.                         $docHere $results[0];
  2515.                     if ($docHere) {
  2516.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2517.                         if ($curr_v_ids == null)
  2518.                             $curr_v_ids = [];
  2519.                         $skipVids = [];
  2520.                         $toChangeVid 0;
  2521.                         $voucher null;
  2522.                         foreach ($curr_v_ids as $vid) {
  2523.                             if (in_array($vid$skipVids))
  2524.                                 continue;
  2525.                             $skipVids[] = $vid//to prevent duplicate query
  2526.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2527.                                 'transactionId' => $vid,
  2528.                             ));;
  2529.                             if ($voucher) {
  2530.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2531.                                     $toChangeVid $vid;
  2532.                                 } else {
  2533.                                     continue;
  2534.                                 }
  2535.                                 if (strpos($voucher->getDescription(), 'Inventory') !== false) {
  2536. //                                    echo "Word Found!";
  2537.                                     $toChangeVid $vid;
  2538.                                 } else {
  2539.                                     continue;
  2540.                                 }
  2541.                             }
  2542.                         }
  2543.                         if ($toChangeVid == 0) {
  2544.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2545.                                 $em,
  2546.                                 $docHere->getSalesInvoiceDate()->format('Y-m-d'),
  2547.                                 0,
  2548.                                 AccountsConstant::VOUCHER_JOURNAL,
  2549.                                 'Journal For Inventory balance for Sales Invoice ' $docHere->getDocumentHash(),
  2550.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2551.                                 'JV',
  2552.                                 'GN',
  2553.                                 0,
  2554.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2555.                                 0,
  2556.                                 $docHere->getCreatedLoginId(),
  2557.                                 $docHere->getCompanyId(),
  2558.                                 '',
  2559.                                 0,
  2560.                                 1,
  2561.                                 0''$so->getBranchId(),
  2562.                                 AccountsConstant::INVOICE_REVENUE_JOURNAL,
  2563.                                 array_flip(GeneralConstant::$Entity_list)['SalesInvoice'], $docHere->getSalesInvoiceId(), $docHere->getDocumentHash()
  2564.                             );
  2565.                             $em->flush();
  2566.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2567.                                 'transactionId' => $toChangeVid,
  2568.                             ));;
  2569.                         }
  2570. //                        DeleteDocument::AccTransactions($em, $toChangeVid, 0);
  2571.                         //now remove cogs or inventory related transactions
  2572.                         $voucherDetails $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(array(
  2573.                             'transactionId' => $toChangeVid,
  2574.                         ));;
  2575.                         foreach ($voucherDetails as $vdtls) {
  2576.                             if (in_array($vdtls->getAccountsHeadId(), $inv_head_list)) {
  2577.                                 $em->remove($vdtls);
  2578.                                 $em->flush();
  2579.                             }
  2580.                             if ($cogs_head == $vdtls->getAccountsHeadId()) {
  2581.                                 $em->remove($vdtls);
  2582.                                 $em->flush();
  2583.                             }
  2584.                         }
  2585.                         $tot_inv_amount 0;
  2586.                         foreach ($transData as $k => $v) {
  2587.                             $tot_inv_amount += ($v);
  2588.                             Accounts::CreateNewTransactionDetails($em,
  2589.                                 '',
  2590.                                 $toChangeVid,
  2591.                                 Generic::CurrToInt($v),
  2592.                                 $k,
  2593.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2594.                                 AccountsConstant::DEBIT,
  2595.                                 0,
  2596.                                 [],
  2597.                                 [],
  2598.                                 $docHere->getCreatedLoginId()
  2599.                             );
  2600.                         }
  2601. //                        $stockReceivedType = $docHere->getType();
  2602.                         $to_balance_head 0;
  2603. //                        if ($docHere->getTransferActionType() == 4)
  2604.                         if (1) {
  2605.                         } else {
  2606.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  2607.                                     'name' => 'inv_on_transit_head')
  2608.                             );
  2609.                             if ($inv_transit_head)
  2610.                                 $to_balance_head $inv_transit_head->getData();
  2611.                         }
  2612.                         if ($to_balance_head != 0) {
  2613.                             Accounts::CreateNewTransactionDetails($em,
  2614.                                 '',
  2615.                                 $toChangeVid,
  2616.                                 Generic::CurrToInt($tot_inv_amount),
  2617.                                 $to_balance_head,
  2618.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  2619.                                 AccountsConstant::CREDIT,
  2620.                                 0,
  2621.                                 [],
  2622.                                 [],
  2623.                                 $docHere->getCreatedLoginId()
  2624.                             );
  2625.                         }
  2626.                         if ($voucher)
  2627.                             $voucher->setTransactionAmount($tot_inv_amount);
  2628.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2629.                         if ($curr_v_ids != null)
  2630.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2631.                         else
  2632.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2633.                         $em->flush();
  2634. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2635.                     }
  2636.                 }
  2637.             }
  2638.             $data = [];
  2639.             //____________STOCK_CONSUMPTION___________________
  2640.             $docEntity "StockConsumptionNote";
  2641.             $docEntityIdField "stockConsumptionNoteId";
  2642.             $accTransactionDataByDocId = [];
  2643.             $query "SELECT stock_consumption_note_item.*,  stock_consumption_note.stock_consumption_note_date, stock_consumption_note.document_hash, stock_consumption_note.data
  2644.               from  stock_consumption_note_item
  2645.               join stock_consumption_note on stock_consumption_note.stock_consumption_note_id=stock_consumption_note_item.stock_consumption_note_id
  2646.             where stock_consumption_note.stock_consumption_note_date ='" $last_refresh_date " 00:00:00' and stock_consumption_note.approved=1";
  2647.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2648.             $queryData $stmt;
  2649.             $consumption_data = [];
  2650.             $produced_data = [];
  2651.             $checked_stcm_ids = [];
  2652.             foreach ($queryData as $item) {
  2653. //                $product=$em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  2654. //                    ->findOneBy(
  2655. //                        array(
  2656. //                            'id'=>$item['product_id']
  2657. //                        )
  2658. //                    );
  2659. //
  2660. //                $curr_purchase_price=$product->getPurchasePrice();
  2661.                 if (!in_array($item['stock_consumption_note_id'], $checked_stcm_ids)) {
  2662.                     $conversion_data json_decode($item['data'], true);
  2663.                     if ($conversion_data == null)
  2664.                         $conversion_data = [];
  2665.                     if (isset($conversion_data['conversionData'])) {
  2666.                         if (isset($conversion_data['conversionData']['converted_products'])) {
  2667.                             $curr_spec_data $conversion_data['conversionData'];
  2668.                             foreach ($curr_spec_data['converted_products'] as $pika_key => $val) {
  2669.                                 $consumption_data[$val][] = array(
  2670.                                     'date' => $last_refresh_date,
  2671.                                     'type' => 2,
  2672.                                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2673.                                     'entityId' => $item['stock_consumption_note_id'],
  2674.                                     'colorId' => isset($curr_spec_data['converted_product_colors'][$pika_key]) ? ($curr_spec_data['converted_product_colors'][$pika_key]) : 0,
  2675.                                     'sizeId' => isset($curr_spec_data['converted_product_sizes'][$pika_key]) ? ($curr_spec_data['converted_product_sizes'][$pika_key]) : 0,
  2676.                                     'entityDocHash' => $item['document_hash'],
  2677.                                     'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_units'][$pika_key]) : 0,
  2678.                                     'qtySub' => 0,
  2679.                                     '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,
  2680.                                     'valueSub' => 0,
  2681.                                     'price' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_unit_price'][$pika_key]) : 0,
  2682.                                     'fromWarehouse' => 0,
  2683.                                     'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key]) ? ($curr_spec_data['converted_warehouseId'][$pika_key]) : 0,
  2684.                                     'fromWarehouseSub' => 0,
  2685.                                     'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key]) ? ($curr_spec_data['converted_warehouseActionId'][$pika_key]) : 0
  2686.                                 );
  2687.                             }
  2688.                         }
  2689.                     }
  2690. //                    if(isset($conversion_data['expenseCost'] ))
  2691. //                    if(isset($conversion_data['expenseCost']['expense_heads'] ))
  2692. //                    {
  2693. //                        $curr_spec_data=$conversion_data['expenseCost'];
  2694. //                        foreach($curr_spec_data['expense_heads'] as $pika_key=>$val)
  2695. //                        {
  2696. //
  2697. //                            $consumption_data[$val][] = array(
  2698. //                                'date' => $last_refresh_date,
  2699. //                                'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2700. //                                'entityId' => $item['stock_consumption_note_id'],
  2701. //                                'entityDocHash' => $item['document_hash'],
  2702. //                                'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_units'][$pika_key]):0,
  2703. //                                'qtySub' => 0,
  2704. //                                '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,
  2705. //                                'valueSub' => 0,
  2706. //                                'price' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_unit_price'][$pika_key]):0,
  2707. //                                'fromWarehouse' => 0,
  2708. //                                'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key])?(1*$curr_spec_data['converted_warehouseId'][$pika_key]):0,
  2709. //                                'fromWarehouseSub' => 0,
  2710. //                                'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key])?(1*$curr_spec_data['converted_warehouseActionId'][$pika_key]):0
  2711. //                            );
  2712. //                        }
  2713. //                    }
  2714.                     $checked_stcm_ids[] = $item['stock_consumption_note_id'];
  2715.                 }
  2716.                 $consumption_data[$item['product_id']][] = array(
  2717.                     'date' => $last_refresh_date,
  2718.                     'type' => 1,
  2719.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2720.                     'entityId' => $item['stock_consumption_note_id'],
  2721.                     'colorId' => $item['color_id'],
  2722.                     'sizeId' => $item['size_id'],
  2723.                     'entityDocHash' => $item['document_hash'],
  2724.                     'qtyAdd' => 0,
  2725.                     'qtySub' => ($item['qty'] * 1),
  2726.                     'valueAdd' => 0,
  2727.                     'valueSub' => (($item['qty']) * ($item['price'])),
  2728.                     'price' => $item['price'],
  2729.                     'fromWarehouse' => $item['warehouse_id'],
  2730.                     'toWarehouse' => 0,
  2731.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  2732.                     'toWarehouseSub' => 0
  2733.                 );
  2734. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2735. //                $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  2736. //                
  2737.             }
  2738.             foreach ($consumption_data as $key => $item) {
  2739.                 if (!empty($item)) {
  2740.                     foreach ($item as $entry) {
  2741.                         $transDate = new \DateTime($entry['date']);
  2742.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2743.                             $key,
  2744.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2745.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2746.                             $entry['fromWarehouse'],
  2747.                             $entry['toWarehouse'],
  2748.                             $entry['fromWarehouseSub'],
  2749.                             $entry['toWarehouseSub'],
  2750.                             $transDate,
  2751.                             $entry['qtyAdd'],
  2752.                             $entry['qtySub'],
  2753.                             $entry['valueAdd'],
  2754.                             $entry['valueSub'],
  2755.                             $entry['price'],
  2756.                             $this->getLoggedUserCompanyId($request),
  2757.                             0,
  2758.                             $entry['entity'],
  2759.                             $entry['entityId'],
  2760.                             $entry['entityDocHash'],
  2761.                             $entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION
  2762.                         );
  2763.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2764.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2765.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2766.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2767.                             "",
  2768.                             'inventory_refresh_debug'1); //last er 1 is append
  2769.                         if ($last_refresh_date_obj == '') {
  2770.                             $last_refresh_date_obj $transDate;
  2771.                         } else if ($transDate $last_refresh_date_obj) {
  2772.                             $last_refresh_date_obj $transDate;
  2773.                         }
  2774.                     }
  2775.                 }
  2776.             }
  2777.             $data = [];
  2778.             //____________PRODUCTION___________________
  2779.             $docEntity "Production";
  2780.             $docEntityIdField "productionId";
  2781.             $accTransactionDataByDocId = [];
  2782.             $consumedAmountByProductionId = [];
  2783.             $query "SELECT * from production_process_settings
  2784.             where approved=1 order by production_process_settings_id asc  ";
  2785.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2786.             $processList $stmt;
  2787. //            $processList=[];
  2788.             foreach ($processList as $process) {
  2789.                 $query "SELECT production_entry_item.*,  production.production_date, production.document_hash
  2790.               from  production_entry_item
  2791.               join production on production_entry_item.production_id=production.production_id
  2792.             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  ";
  2793.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  2794.                 $queryData $stmt;
  2795.                 $produced_data = [];
  2796.                 $rejected_data = [];
  2797.                 $consumed_data = [];
  2798.                 foreach ($queryData as $item) {
  2799. //                $product=$em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  2800. //                    ->findOneBy(
  2801. //                        array(
  2802. //                            'id'=>$item['product_id']
  2803. //                        )
  2804. //                    );
  2805. //
  2806. //                $curr_purchase_price=$product->getPurchasePrice();
  2807.                     if ($item['price'] == '')
  2808.                         $item['price'] = 0;
  2809.                     if ($item['price'] < 0)
  2810.                         $item['price'] = 0;
  2811.                     $item['production_nature_id'];
  2812.                     $consumed_data[$item['product_id']][] = array(
  2813.                         'date' => $last_refresh_date,
  2814.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2815.                         'entityId' => $item['production_id'],
  2816.                         'colorId' => $item['color_id'],
  2817.                         'sizeId' => $item['size_id'],
  2818.                         'entityDocHash' => $item['document_hash'],
  2819.                         'qtyAdd' => 0,
  2820.                         'qtySub' => ($item['additional_consumed_qty'] * 1) + ($item['consumed_qty']),
  2821.                         'valueAdd' => 0,
  2822.                         'valueSub' => '_AUTO_',
  2823.                         'price' => $item['price'],
  2824.                         'fromWarehouse' => $item['warehouse_id'],
  2825.                         'toWarehouse' => 0,
  2826.                         'fromWarehouseSub' => $item['consumed_item_action_tag_id'],
  2827.                         'toWarehouseSub' => 0,
  2828.                         'production_nature_id' => $item['production_nature_id'],
  2829.                     );
  2830.                     $produced_data[$item['product_id']][] = array(
  2831.                         'date' => $last_refresh_date,
  2832.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2833.                         'entityId' => $item['production_id'],
  2834.                         'colorId' => $item['color_id'],
  2835.                         'sizeId' => $item['size_id'],
  2836.                         'entityDocHash' => $item['document_hash'],
  2837.                         'qtyAdd' => ($item['accepted_qty'] * 1),
  2838.                         'qtySub' => 0,
  2839.                         'valueAdd' => (($item['accepted_qty'] * 1) * ($item['price'])),
  2840.                         'valueSub' => 0,
  2841.                         'price' => $item['price'],
  2842.                         'fromWarehouse' => 0,
  2843.                         'toWarehouse' => $item['warehouse_id'],
  2844.                         'fromWarehouseSub' => 0,
  2845.                         'toWarehouseSub' => $item['produced_item_action_tag_id'],
  2846.                         'production_nature_id' => $item['production_nature_id'],
  2847.                     );
  2848.                     $rejected_data[$item['product_id']][] = array(
  2849.                         'date' => $last_refresh_date,
  2850.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2851.                         'entityId' => $item['production_id'],
  2852.                         'colorId' => $item['color_id'],
  2853.                         'sizeId' => $item['size_id'],
  2854.                         'entityDocHash' => $item['document_hash'],
  2855.                         'qtyAdd' => ($item['rejected_qty'] * 1),
  2856.                         'qtySub' => 0,
  2857.                         'valueAdd' => (($item['rejected_qty'] * 1) * ($item['price'])),
  2858.                         'valueSub' => 0,
  2859.                         'price' => $item['price'],
  2860.                         'fromWarehouse' => 0,
  2861.                         'toWarehouse' => $item['warehouse_id'],
  2862.                         'fromWarehouseSub' => 0,
  2863.                         'toWarehouseSub' => $item['rejected_item_action_tag_id'],
  2864.                         'production_nature_id' => $item['production_nature_id'],
  2865.                     );
  2866. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2867. //                $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  2868. //                
  2869.                 }
  2870.                 foreach ($consumed_data as $key => $item) {
  2871.                     if (!empty($item)) {
  2872.                         foreach ($item as $entry) {
  2873.                             $transDate = new \DateTime($entry['date']);
  2874.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2875.                                 $key,
  2876.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2877.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2878.                                 $entry['fromWarehouse'],
  2879.                                 $entry['toWarehouse'],
  2880.                                 $entry['fromWarehouseSub'],
  2881.                                 $entry['toWarehouseSub'],
  2882.                                 $transDate,
  2883.                                 $entry['qtyAdd'],
  2884.                                 $entry['qtySub'],
  2885.                                 $entry['valueAdd'],
  2886.                                 $entry['valueSub'],
  2887.                                 $entry['price'],
  2888.                                 $this->getLoggedUserCompanyId($request),
  2889.                                 0,
  2890.                                 $entry['entity'],
  2891.                                 $entry['entityId'],
  2892.                                 $entry['entityDocHash'],
  2893.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION);
  2894.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2895.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2896.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2897.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2898.                                 "",
  2899.                                 'inventory_refresh_debug'1); //last er 1 is append
  2900.                             if (!isset($consumedAmountByProductionId[$entry['entityId']]))
  2901.                                 $consumedAmountByProductionId[$entry['entityId']] = ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2902.                             else
  2903.                                 $consumedAmountByProductionId[$entry['entityId']] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2904.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2905.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  2906.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2907.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2908.                             else
  2909.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2910.                             if ($last_refresh_date_obj == '') {
  2911.                                 $last_refresh_date_obj $transDate;
  2912.                             } else if ($transDate $last_refresh_date_obj) {
  2913.                                 $last_refresh_date_obj $transDate;
  2914.                             }
  2915.                         }
  2916.                     }
  2917.                 }
  2918.                 foreach ($produced_data as $key => $item) {
  2919.                     if (!empty($item)) {
  2920.                         foreach ($item as $entry) {
  2921.                             $transDate = new \DateTime($entry['date']);
  2922.                             $productionNature $entry['production_nature_id'];
  2923.                             if (in_array($productionNature, [12])) {
  2924.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2925.                                     $key,
  2926.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2927.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2928.                                     $entry['fromWarehouse'],
  2929.                                     $entry['toWarehouse'],
  2930.                                     $entry['fromWarehouseSub'],
  2931.                                     $entry['toWarehouseSub'],
  2932.                                     $transDate,
  2933.                                     $entry['qtyAdd'],
  2934.                                     $entry['qtySub'],
  2935. //                                $entry['valueAdd'],
  2936.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2937.                                     $entry['valueSub'],
  2938.                                     $entry['price'],
  2939.                                     $this->getLoggedUserCompanyId($request),
  2940.                                     0,
  2941.                                     $entry['entity'],
  2942.                                     $entry['entityId'],
  2943.                                     $entry['entityDocHash'],
  2944.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2945.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2946.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2947.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2948.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2949.                                     "",
  2950.                                     'inventory_refresh_debug'1); //last er 1 is append
  2951.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2952.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2953.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2954.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2955.                                 else
  2956.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2957. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2958. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2959. //                            else
  2960. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2961.                             } else {
  2962.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2963.                                     $key,
  2964.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2965.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2966.                                     $entry['fromWarehouse'],
  2967.                                     $entry['toWarehouse'],
  2968.                                     $entry['fromWarehouseSub'],
  2969.                                     $entry['toWarehouseSub'],
  2970.                                     $transDate,
  2971.                                     0,
  2972.                                     0,
  2973. //                                $entry['valueAdd'],
  2974.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2975.                                     0,
  2976.                                     $entry['price'],
  2977.                                     $this->getLoggedUserCompanyId($request),
  2978.                                     0,
  2979.                                     $entry['entity'],
  2980.                                     $entry['entityId'],
  2981.                                     $entry['entityDocHash'],
  2982.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2983.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2984.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2985.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2986.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2987.                                     "",
  2988.                                     'inventory_refresh_debug'1); //last er 1 is append
  2989.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2990.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2991.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2992.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2993.                                 else
  2994.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2995. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2996. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2997. //                            else
  2998. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2999.                             }
  3000.                             if ($last_refresh_date_obj == '') {
  3001.                                 $last_refresh_date_obj $transDate;
  3002.                             } else if ($transDate $last_refresh_date_obj) {
  3003.                                 $last_refresh_date_obj $transDate;
  3004.                             }
  3005.                         }
  3006.                     }
  3007.                 }
  3008.                 foreach ($rejected_data as $key => $item) {
  3009.                     if (!empty($item)) {
  3010.                         foreach ($item as $entry) {
  3011.                             $transDate = new \DateTime($entry['date']);
  3012.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  3013.                                 $key,
  3014.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  3015.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  3016.                                 $entry['fromWarehouse'],
  3017.                                 $entry['toWarehouse'],
  3018.                                 $entry['fromWarehouseSub'],
  3019.                                 $entry['toWarehouseSub'],
  3020.                                 $transDate,
  3021.                                 $entry['qtyAdd'],
  3022.                                 $entry['qtySub'],
  3023.                                 $entry['valueAdd'],
  3024.                                 $entry['valueSub'],
  3025.                                 $entry['price'],
  3026.                                 $this->getLoggedUserCompanyId($request),
  3027.                                 0,
  3028.                                 $entry['entity'],
  3029.                                 $entry['entityId'],
  3030.                                 $entry['entityDocHash'],
  3031.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  3032.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  3033.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  3034.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  3035.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  3036.                                 "",
  3037.                                 'inventory_refresh_debug'1); //last er 1 is append
  3038.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  3039.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  3040.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  3041.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = (-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  3042.                             else
  3043.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ((-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  3044.                             if ($last_refresh_date_obj == '') {
  3045.                                 $last_refresh_date_obj $transDate;
  3046.                             } else if ($transDate $last_refresh_date_obj) {
  3047.                                 $last_refresh_date_obj $transDate;
  3048.                             }
  3049.                         }
  3050.                     }
  3051.                 }
  3052.             }
  3053.             if ($modifyAccTransaction == 1) {
  3054.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  3055.                     $docHere $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  3056.                         $docEntityIdField => $docId,
  3057.                     ));;
  3058.                     if ($docHere) {
  3059.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  3060.                         if ($curr_v_ids == null)
  3061.                             $curr_v_ids = [];
  3062.                         $skipVids = [];
  3063.                         $toChangeVid 0;
  3064.                         $voucher null;
  3065.                         foreach ($curr_v_ids as $vid) {
  3066.                             if (in_array($vid$skipVids))
  3067.                                 continue;
  3068.                             $skipVids[] = $vid//to prevent duplicate query
  3069.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  3070.                                 'transactionId' => $vid,
  3071.                             ));;
  3072.                             if ($voucher) {
  3073.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  3074.                                     $toChangeVid $vid;
  3075.                                 } else {
  3076.                                     continue;
  3077.                                 }
  3078.                             }
  3079.                         }
  3080.                         if ($toChangeVid == 0) {
  3081.                             $toChangeVid Accounts::CreateNewTransaction(0,
  3082.                                 $em,
  3083.                                 $docHere->getProductionDate()->format('Y-m-d'),
  3084.                                 0,
  3085.                                 AccountsConstant::VOUCHER_JOURNAL,
  3086.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  3087.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  3088.                                 'JV',
  3089.                                 'GN',
  3090.                                 0,
  3091.                                 Accounts::GetVNoHash($em'jv''gn'0),
  3092.                                 0,
  3093.                                 $docHere->getCreatedLoginId(),
  3094.                                 $docHere->getCompanyId(),
  3095.                                 '',
  3096.                                 0,
  3097.                                 1
  3098.                             );
  3099.                             $em->flush();
  3100.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  3101.                                 'transactionId' => $toChangeVid,
  3102.                             ));;
  3103.                         }
  3104.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  3105.                         $tot_inv_amount 0;
  3106.                         foreach ($transData as $k => $v) {
  3107.                             $tot_inv_amount += ($v);
  3108.                             Accounts::CreateNewTransactionDetails($em,
  3109.                                 '',
  3110.                                 $toChangeVid,
  3111.                                 Generic::CurrToInt($v),
  3112.                                 $k,
  3113.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  3114.                                 AccountsConstant::DEBIT,
  3115.                                 0,
  3116.                                 [],
  3117.                                 [],
  3118.                                 $docHere->getCreatedLoginId()
  3119.                             );
  3120.                         }
  3121. //                        $stockReceivedType = $docHere->getType();
  3122.                         $to_balance_head 0;
  3123. //                        if ($docHere->getTransferActionType() == 4)
  3124.                         if (1) {
  3125.                         } else {
  3126.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  3127.                                     'name' => 'inv_on_transit_head')
  3128.                             );
  3129.                             if ($inv_transit_head)
  3130.                                 $to_balance_head $inv_transit_head->getData();
  3131.                         }
  3132.                         if ($to_balance_head != 0) {
  3133.                             Accounts::CreateNewTransactionDetails($em,
  3134.                                 '',
  3135.                                 $toChangeVid,
  3136.                                 Generic::CurrToInt($tot_inv_amount),
  3137.                                 $to_balance_head,
  3138.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  3139.                                 AccountsConstant::CREDIT,
  3140.                                 0,
  3141.                                 [],
  3142.                                 [],
  3143.                                 $docHere->getCreatedLoginId()
  3144.                             );
  3145.                         }
  3146.                         if ($voucher)
  3147.                             $voucher->setTransactionAmount($tot_inv_amount);
  3148.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  3149.                         if ($curr_v_ids != null)
  3150.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  3151.                         else
  3152.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  3153.                         $em->flush();
  3154. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  3155.                     }
  3156.                 }
  3157.             }
  3158.             if ($terminate == 0) {
  3159.                 return new JsonResponse(array(
  3160.                     "success" => true,
  3161.                     "last_refresh_date" => $last_refresh_date,
  3162.                     "inventory_refreshed" => $refreshed_opening
  3163.                 ));
  3164.             } else {
  3165.                 return new JsonResponse(array(
  3166.                     "success" => false,
  3167.                     "last_refresh_date" => $last_refresh_date,
  3168.                     "inventory_refreshed" => $refreshed_opening
  3169.                 ));
  3170.             }
  3171.         }
  3172.         return new JsonResponse(array(
  3173.             "success" => false,
  3174.             "last_refresh_date" => $last_refresh_date,
  3175.             "inventory_refreshed" => $refreshed_opening
  3176.         ));
  3177.         //2 .now make an array with necessary data based on challan and grn for now willl need consumption later
  3178.         //broken into transactions not closing
  3179.         //structure---> $data['productId']=array(
  3180.         //'date'=>'2017-09-02 00:00:00'
  3181.         //'qtyAdd'=>'2'
  3182.         //'qtySub'=>'0'
  3183.         //'valueAdd'=>'2000'
  3184.         //'valueSub'=>'0'
  3185.         //'fromWarehouse'=>'0'
  3186.         //'toWarehouse'=>'0'
  3187.         //'fromWarehouseSub'=>'0'
  3188.         //'toWarehouseSub'=>'0'
  3189.         //)
  3190.         //
  3191.     }
  3192.     public function OpeningItemAction(Request $request)
  3193.     {
  3194.         $em $this->getDoctrine()->getManager();
  3195.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  3196.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  3197.         if ($request->isMethod('POST')) {
  3198.             $pp trim($request->request->get('purchasePrice'));
  3199. //replace comma with space
  3200.             $pp str_replace(","""$pp);
  3201.             if ($request->request->get('productId') != '') {
  3202.                 foreach ($request->request->get('warehouseId') as $key => $value) {
  3203.                     $data = array(
  3204.                         'productId' => $request->request->get('productId'),
  3205.                         'warehouseId' => $request->request->get('warehouseId')[$key],
  3206.                         'warehouseActionId' => $request->request->get('warehouseActionId')[$key],
  3207.                         'purchasePrice' => $pp,
  3208.                         'date' => new \DateTime($request->request->get('date')),
  3209.                         'qty' => $request->request->get('qty')[$key],
  3210.                     );
  3211.                     $transDate = new \DateTime($request->request->get('date'));
  3212.                     $new = new InvItemInOut();
  3213.                     $new->setProductId($request->request->get('productId'));
  3214.                     $new->setWarehouseId($request->request->get('warehouseId')[$key]);
  3215.                     $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  3216.                     $new->setActionTagId($request->request->get('warehouseActionId')[$key]);
  3217.                     $new->setTransactionDate($transDate);
  3218.                     $new->setQty($request->request->get('qty')[$key]);
  3219.                     $new->setPrice($pp);
  3220.                     $new->setAmount($request->request->get('qty')[$key] * $pp);
  3221.                     $new->setEntity(0);// opening =0
  3222.                     $new->setEntityId(0);// opening =0
  3223.                     $new->setDebitCreditHeadId(0);// opening =0
  3224.                     $new->setVoucherIds(null);// opening =0
  3225.                     $em->persist($new);
  3226.                     $em->flush();
  3227. //                    $total_inv_value_in_by_id += $request->request->get('qty')[$key] * $pp;
  3228.                     Inventory::AddOpeningInventoryStock($em$data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3229.                 }
  3230.             }
  3231.         }
  3232.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  3233.             'name' => 'warehouse_action_1'//for now for stock of goods
  3234.         ));
  3235.         return $this->render('@Inventory/pages/input_forms/opening_item_assign.html.twig',
  3236.             array(
  3237.                 'page_title' => "Opening Items",
  3238.                 'inv_head' => $inv_head $inv_head->getData() : '',
  3239.                 'products' => $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\InvProducts')->findBy(array(
  3240.                     'status' => GeneralConstant::ACTIVE//for now for stock of goods
  3241. //                    'opening_locked'=>0
  3242.                 )),
  3243.                 'warehouseList' => Inventory::WarehouseList($em),
  3244.                 'warehouseActionList' => $warehouse_action_list
  3245.             )
  3246.         );
  3247.     }
  3248.     public function CreateProductCategoryAction(Request $request)
  3249.     {
  3250.         if ($request->isMethod('POST')) {
  3251.             $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));
  3252.             if ($cat_data['id'] != '')
  3253.                 return new JsonResponse(array("success" => true'cat_data' => $cat_data));
  3254.         }
  3255.         return new JsonResponse(array("success" => false,));
  3256. //        return $this->redirectToRoute("create_product");
  3257.     }
  3258.     public function CreateProductSubCategoryAction(Request $request)
  3259.     {
  3260.         if ($request->isMethod('POST')) {
  3261.             $spec_data Inventory::CreateSubCategory($this->getDoctrine()->getManager(),
  3262.                 $this->getLoggedUserCompanyId($request), $request->request->get('spec_name'),
  3263.                 $request->request->get('level'0),
  3264.                 $request->request->get('parentId'0),
  3265.                 $request->request->get('itemgroupId'),
  3266.                 $request->request->get('categoryId'),
  3267.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3268.             if ($spec_data['id'] != '')
  3269.                 return new JsonResponse(array("success" => true'spec_data' => $spec_data'level' => $request->request->get('level'0)));
  3270.         }
  3271.         return new JsonResponse(array("success" => false,));
  3272. //        return $this->redirectToRoute("create_product");
  3273.     }
  3274.     public function CreateProductSpecAction(Request $request)
  3275.     {
  3276.         $em $this->getDoctrine()->getManager();
  3277.         if ($request->isMethod('POST')) {
  3278.             //1st add to cnetral server
  3279.             $spec_data=[
  3280.                 'id' => 0,
  3281.                 'global_id' => 0,
  3282.                 'name' => $request->request->get('name'''),
  3283.                 'unit_text' => $request->request->get('unitText'''),
  3284.                 'unique_hash' => $request->request->get('uniqueHash'''),
  3285.                 'markers' => $request->request->get('markers'''),
  3286.                 'tags' => $request->request->get('tags'''),
  3287.             ];
  3288.             $specType $em->getRepository('ApplicationBundle\\Entity\\SpecType')->findOneBy(array(
  3289.                 'uniqueHash' => $request->request->get('uniqueHash'''),
  3290.             ));
  3291.             if ($specType) {
  3292.                 $spec_data['id'] = $specType->getId();
  3293.                 $spec_data['global_id'] = $specType->getGlobalId();
  3294.             }
  3295.             if(!$spec_data['global_id']) {
  3296.                 $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/api/create_product_spec_public';
  3297.                 $curl curl_init();
  3298.                 curl_setopt_array($curl, [
  3299.                     CURLOPT_RETURNTRANSFER => true,
  3300.                     CURLOPT_POST => true,
  3301.                     CURLOPT_URL => $urlToCall,
  3302.                     CURLOPT_CONNECTTIMEOUT => 10,
  3303.                     CURLOPT_SSL_VERIFYPEER => false,
  3304.                     CURLOPT_SSL_VERIFYHOST => false,
  3305.                     CURLOPT_HTTPHEADER => [],
  3306.                     CURLOPT_POSTFIELDS => http_build_query([
  3307.                         'name' => $request->request->get('name'''),
  3308.                         'unitText' => $request->request->get('unitText'''),
  3309.                         'uniqueHash' => $request->request->get('uniqueHash'''),
  3310.                         'markers' => $request->request->get('markers'''),
  3311.                         'tags' => $request->request->get('tags'''),
  3312.                     ])
  3313.                 ]);
  3314.                 $retData curl_exec($curl);
  3315.                 $errData curl_error($curl);
  3316.                 curl_close($curl);
  3317.                 if ($errData) {
  3318.                     return new JsonResponse(['success' => false]);
  3319.                 }
  3320.                 $retData json_decode($retDatatrue);
  3321.                 $spec_data $retData['spec_data'];
  3322.             }
  3323.             $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  3324.             $spec_data Inventory::CreateProductSpecification($em,
  3325.                 $systemType,
  3326.                 $spec_data['name'],
  3327.                 $spec_data['unit_text'],
  3328.                 $spec_data['unique_hash'],
  3329.                 $spec_data['markers'],
  3330.                 $spec_data['tags'],
  3331.                 $spec_data['global_id'],
  3332.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3333.             );
  3334.             if ($spec_data['id'] != '')
  3335.                 return new JsonResponse(array("success" => true'spec_data' => $spec_data));
  3336.         }
  3337.         return new JsonResponse(array("success" => false,));
  3338. //        return $this->redirectToRoute("create_product");
  3339.     }
  3340.     public function CreateProductBrandAction(Request $request)
  3341.     {
  3342.         if ($request->isMethod('POST')) {
  3343.             $data Inventory::CreateBrand($this->getDoctrine()->getManager(),
  3344.                 $this->getLoggedUserCompanyId($request), $request->request->get('brand_name'),
  3345.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3346.             if ($data['id'] != '')
  3347.                 return new JsonResponse(array("success" => true'data' => $data));
  3348.         }
  3349.         return new JsonResponse(array("success" => false,));
  3350. //        return $this->redirectToRoute("create_product");
  3351.     }
  3352.     public function CreateIssueNoteAction(Request $request)
  3353.     {
  3354.         return $this->render('@Inventory/pages/input_forms/issue_note.html.twig',
  3355.             array(
  3356.                 'page_title' => 'Issue Note'
  3357.             )
  3358.         );
  3359.     }
  3360.     public function ProcessDraftDeliveryReceiptAction(Request $request$id 0)
  3361.     {
  3362.         $em $this->getDoctrine()->getManager();
  3363.         $companyId $this->getLoggedUserCompanyId($request);
  3364.         $extId $id;
  3365.         $receiptId $id;
  3366.         $allowed 0;
  3367.         if ($request->isMethod('POST')) {
  3368.             $receiptId $request->request->get('deliveryReceiptId');
  3369.             $QD $this->getDoctrine()
  3370.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3371.                 ->findOneBy(
  3372.                     array(
  3373.                         'deliveryReceiptId' => $receiptId
  3374.                     ),
  3375.                     array()
  3376.                 );
  3377.             $soId $QD->getSalesOrderId();
  3378.             $drData = [];
  3379.             $dr_item_data $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')->findBy(
  3380.                 array(
  3381.                     'deliveryReceiptId' => $receiptId,
  3382.                 )
  3383.             );
  3384.             foreach ($dr_item_data as $dr_item) {
  3385.                 $drData[] = array(
  3386.                     'soItemId' => $dr_item->getSalesorderItemId(),
  3387.                     'qty' => $dr_item->getQty()
  3388.                 );
  3389.             }
  3390. //            $drData=[
  3391. //                ['soItemId'=>9,'qty'=>9],
  3392. //                ['soItemId'=>9,'qty'=>9],
  3393. //                ['soItemId'=>9,'qty'=>9],
  3394. //            ];
  3395.             $toGetSoItemsId = [];
  3396.             $toGetDoItemsId = [];
  3397.             $drDataBySoItemId = [];
  3398.             $drDataByDoItemId = [];
  3399.             $so $em->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findOneBy(array(
  3400.                 'salesOrderId' => $soId   //$id is soId
  3401.             ));
  3402.             if ($so->getDeliveryOrderSkipFlag() == 1) {
  3403.                 foreach ($drData as $pp) {
  3404.                     $toGetSoItemsId[] = $pp['soItemId'];
  3405.                     $drDataBySoItemId[$pp['soItemId']] = $pp;
  3406.                 }
  3407.             } else {
  3408.                 foreach ($drData as $pp) {
  3409.                     $toGetDoItemsId[] = $pp['soItemId'];
  3410.                     $drDataByDoItemId[$pp['soItemId']] = $pp;
  3411.                 }
  3412.                 $do_item_data $em->getRepository('ApplicationBundle\\Entity\\DeliveryOrderItem')->findBy(
  3413.                     array(
  3414.                         'salesorderId' => $id,
  3415.                         'id' => $toGetDoItemsId
  3416.                     )
  3417.                 );
  3418.                 foreach ($do_item_data as $dd) {
  3419.                     $toGetSoItemsId[] = $dd->getSalesorderItemId();
  3420.                     $drDataBySoItemId[$dd->getSalesorderItemId()] = $drDataByDoItemId[$dd->getId()];
  3421.                 }
  3422. //                $do_item_data = $em->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findOneBy(
  3423. //                    array(
  3424. ////                'salesOrderId'=>$post_data->get('soId', null),
  3425. //                        'id' => $post_data->get('do_details_id')[$key]
  3426. //                    )
  3427. //                );
  3428.             }
  3429.             $so_item_data $em->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findBy(
  3430.                 array(
  3431.                     'salesOrderId' => $soId,
  3432.                     'id' => $toGetSoItemsId
  3433.                 )
  3434.             );
  3435.             $prev_so_amount $so->getSoAmount();
  3436.             $total_discounted_amount 0;
  3437.             $total_product_amount 0;
  3438.             $total_discount 0;
  3439.             $total_special_discount $so->getSpecialDiscountAmount();
  3440.             $total_special_discount_rate $so->getSpecialDiscountRate();
  3441.             foreach ($so_item_data as $item) {
  3442.                 $qty $drDataBySoItemId[$item->getId()]['qty'];
  3443.                 $price $item->getPrice();
  3444.                 $amount $qty $price;
  3445.                 $discountAmount $amount * ($item->getDiscountRate() / 100);
  3446.                 $discountedAmount $amount $discountAmount;
  3447.                 $total_discounted_amount += $discountedAmount;
  3448.                 $total_discount += $discountAmount;
  3449.                 $total_product_amount += $amount;
  3450.             }
  3451.             $aitRate $so->getAitRate();
  3452.             $vatRate $so->getVatRate();
  3453.             if ($aitRate == '' || $aitRate == null$aitRate 0;
  3454.             if ($vatRate == '' || $vatRate == null$vatRate 0;
  3455. //        $so->setVatRate($post->get('vat_rate', null));
  3456.             $vatAmount $total_discounted_amount * ($vatRate 100);
  3457.             $aitAmount $total_discounted_amount * ($aitRate 100);
  3458.             $total_sales_amount $total_discounted_amount $vatAmount $aitAmount $total_special_discount;
  3459.             //now get client
  3460.             $client $em->getRepository('ApplicationBundle\\Entity\\AccClients')->findOneBy(array(
  3461.                 'clientId' => $so->getClientId(),
  3462.             ));
  3463.             if ($client->getCreditLimitEnabled() != 1) {
  3464.                 $allowed 1;
  3465.             } else {
  3466.                 $creditLimit $client->getCreditLimit();
  3467.                 $due $client->getClientDue();
  3468.                 if ($creditLimit >= ($due $total_sales_amount))
  3469.                     $allowed 1;
  3470.             }
  3471.             //now package data
  3472.             if ($allowed == 0) {
  3473.                 return new JsonResponse(array(
  3474.                     'success' => false,
  3475. //                        'documentHash' => $order->getDocumentHash(),
  3476.                     'documentId' => $receiptId,
  3477.                     'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3478.                     'viewUrl' => '',
  3479.                 ));
  3480.             }
  3481.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  3482.             $dochash $request->request->get('docHash'); //change
  3483.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3484.             $approveRole 1;  //created
  3485.             $approveHash $request->request->get('approvalHash');
  3486.             $receiptId $request->request->get('deliveryReceiptId');
  3487.             $sig DocValidation::isSignatureOk($em$loginId$approveHash);
  3488. //            $this->addFlash(
  3489. //                'success',
  3490. //                'New Transaction Added.'
  3491. //            );
  3492.             $success $sig == false true;
  3493.             if ($success == true) {
  3494.                 $QD $this->getDoctrine()
  3495.                     ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3496.                     ->findOneBy(
  3497.                         array(
  3498.                             'deliveryReceiptId' => $receiptId
  3499.                         ),
  3500.                         array()
  3501.                     );
  3502.                 $draftFlag $QD->getDraftFlag();
  3503.                 if ($draftFlag == 1) {
  3504.                     //now add Approval info
  3505.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3506.                     $approveRole 1;  //created
  3507.                     System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3508.                         $receiptId,
  3509.                         $loginId,
  3510.                         $approveRole,
  3511.                         $request->request->get('approvalHash'));
  3512.                     $options = array(
  3513.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3514.                         'notification_server' => $this->container->getParameter('notification_server'),
  3515.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3516.                         'url' => $this->generateUrl(
  3517.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  3518.                             ['entity_view_route_path_name']
  3519.                         )
  3520.                     );
  3521.                     System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3522.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3523.                         $receiptId,
  3524.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3525.                     );
  3526.                     $QD->setDraftFlag(0);
  3527.                     $em->flush();
  3528.                 }
  3529.                 $url $this->generateUrl(
  3530.                     'view_delivery_receipt'
  3531.                 );
  3532.                 if ($request->request->has('returnJson')) {
  3533. //                    $dr = $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findBy(
  3534. //                        array(
  3535. //                            'salesOrderId' => $orderId, ///material
  3536. //
  3537. //                        )
  3538. //                    );
  3539.                     return new JsonResponse(array(
  3540.                         'success' => true,
  3541. //                        'documentHash' => $order->getDocumentHash(),
  3542.                         'documentId' => $receiptId,
  3543.                         'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3544.                         'viewUrl' => $url "/" $receiptId,
  3545.                     ));
  3546.                 } else {
  3547.                     $this->addFlash(
  3548.                         'success',
  3549.                         'Action Successful'
  3550.                     );
  3551.                     return $this->redirect($url "/" $receiptId);
  3552.                 }
  3553.             }
  3554.         }
  3555.         return new JsonResponse(array(
  3556.             'success' => false,
  3557. //                        'documentHash' => $order->getDocumentHash(),
  3558.             'documentId' => $receiptId,
  3559.             'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3560.             'viewUrl' => '',
  3561.         ));
  3562.     }
  3563.     public function CreateServiceChallanAction(Request $request)
  3564.     {
  3565.         $em $this->getDoctrine()->getManager();
  3566.         if ($request->isMethod('POST')) {
  3567.             $entity_id array_flip(GeneralConstant::$Entity_list)['ServiceChallan']; //change
  3568.             $dochash $request->request->get('docHash'); //change
  3569.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3570.             $approveRole $request->request->get('approvalRole');
  3571.             $approveHash $request->request->get('approvalHash');
  3572.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  3573.                 $loginId$approveRole$approveHash)
  3574.             ) {
  3575.                 $this->addFlash(
  3576.                     'error',
  3577.                     'Sorry Could not insert Data.'
  3578.                 );
  3579.             } else {
  3580.                 $receiptId SalesOrderM::CreateNewServiceChallan($this->getDoctrine()->getManager(), $request->request,
  3581.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  3582.                     $this->getLoggedUserCompanyId($request));
  3583.                 //now add Approval info
  3584.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3585. //                $approveRole = 1;  //created
  3586.                 $options = array(
  3587.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3588.                     'notification_server' => $this->container->getParameter('notification_server'),
  3589.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3590.                     'url' => $this->generateUrl(
  3591.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ServiceChallan']]
  3592.                         ['entity_view_route_path_name']
  3593.                     )
  3594.                 );
  3595.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3596.                     array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3597.                     $receiptId,
  3598.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3599.                 );
  3600.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3601.                     $receiptId,
  3602.                     $loginId,
  3603.                     $approveRole,
  3604.                     $request->request->get('approvalHash'));
  3605.                 $this->addFlash(
  3606.                     'success',
  3607.                     'New Service Challan Created'
  3608.                 );
  3609.                 $url $this->generateUrl(
  3610.                     'view_service_challan'
  3611.                 );
  3612.                 return $this->redirect($url "/" $receiptId);
  3613.             }
  3614.         }
  3615.         return $this->render('@Inventory/pages/input_forms/create_service_challan.html.twig',
  3616.             array(
  3617.                 'page_title' => 'New Service Challan',
  3618.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  3619.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  3620.                 'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  3621.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  3622.                 'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
  3623.                 'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
  3624.                 'deliveryOrders' => SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
  3625.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
  3626.                 'serviceList' => Inventory::ServiceList($em$this->getLoggedUserCompanyId($request))
  3627.             )
  3628.         );
  3629.     }
  3630.     public function GetItemListForDrAction(Request $request)
  3631.     {
  3632.         $em $this->getDoctrine()->getManager();
  3633.         $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3634.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3635.         if ($request->isMethod('POST')) {
  3636.             $em $this->getDoctrine();
  3637.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3638.             );
  3639.             $Content = [];
  3640.             $Transport_data = [];
  3641.             $Lul_data = [];
  3642.             if ($request->request->get('doId') != '')
  3643.                 $find_array['deliveryOrderId'] = $request->request->get('doId');
  3644. //            if($request->request->get('warehouseId')!='')
  3645. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3646.             $QD $this->getDoctrine()
  3647.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryOrderItem')
  3648.                 ->findBy(
  3649.                     $find_array,
  3650.                     array()
  3651.                 );
  3652. //            if($request->request->get('wareHouseId')!='')
  3653.             $DO $this->getDoctrine()
  3654.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryOrder')
  3655.                 ->findOneBy(
  3656.                     $find_array,
  3657.                     array()
  3658.                 );
  3659.             $sendData = array(
  3660. //                'salesType'=>$SO->getSalesType(),
  3661. //                'packageData'=>[],
  3662.                 'productList' => [],
  3663. //                'productListByPackage'=>[],
  3664.             );
  3665.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3666.             $pckg_item_cross_match_data = [];
  3667.             $unitList Inventory::UnitTypeList($em);
  3668.             $colorList Inventory::GetColorList($em);
  3669.             foreach ($QD as $product) {
  3670. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  3671.                 if (($product->getBalance()) <= 0)
  3672.                     continue;
  3673.                 $fdm $product->getProductFdm();
  3674.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3675.                 $find_query = array();
  3676.                 $soItem $this->getDoctrine()
  3677.                     ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  3678.                     ->findOneBy(
  3679.                         array(
  3680.                             'id' => $product->getSalesorderItemId()
  3681.                         )
  3682.                     );
  3683.                 if (!$soItem)
  3684.                     continue;
  3685. //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3686. //                $soBalance = $soItem->getBalance();
  3687.                 $soBalance $soItem->getQty();
  3688. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3689. //                $doBalance = $product->getBalance();
  3690.                 $doBalance $product->getQty();
  3691.                 //now check if any so ir do item id there that is at
  3692.                 //least pending
  3693.                 $approvalPendingDrs $this->getDoctrine()
  3694.                     ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3695.                     ->findBy(
  3696.                         array(
  3697.                             'deliveryOrderId' => $DO->getDeliveryOrderId(),
  3698.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3699.                         )
  3700.                     );
  3701.                 foreach ($approvalPendingDrs as $appPendDr) {
  3702.                     $appPendDrItem $this->getDoctrine()
  3703.                         ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3704.                         ->findOneBy(
  3705.                             array(
  3706.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3707.                                 'salesorderItemId' => $product->getSalesorderItemId()
  3708.                             )
  3709.                         );
  3710.                     if ($appPendDrItem) {
  3711.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3712.                             $soBalance $soBalance $appPendDrItem->getQty();
  3713.                             $doBalance $doBalance $appPendDrItem->getQty();
  3714.                         }
  3715.                     }
  3716.                 }
  3717.                 $colorId $product->getColorId();
  3718.                 $size $product->getSizeId();
  3719. //                $find_query['colorId']=
  3720.                 if ($productData['productId'] != 0) {
  3721.                     $find_query['productId'] = $productData['productId'];
  3722.                     if ($colorId == '' || $colorId == || $colorId == null)
  3723.                         $colorId $productData['defaultColorId'] ?? 0;
  3724.                     if ($size == '' || $size == || $size == null)
  3725.                         $size $productData['defaultSize'] ?? 0;
  3726.                     $find_query['productId'] = $productData['productId'];
  3727.                 } else {
  3728.                     if ($productData['igId'] != 0) {
  3729.                         $find_query['igId'] = $productData['igId'];
  3730.                     }
  3731.                     if ($productData['categoryId'] != 0) {
  3732.                         $find_query['categoryId'] = $productData['categoryId'];
  3733.                     }
  3734.                     if ($productData['subCategoryId'] != 0) {
  3735.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3736.                     }
  3737.                     if ($productData['brandId'] != 0) {
  3738.                         $find_query['brandId'] = $productData['brandId'];
  3739.                     }
  3740.                 }
  3741.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3742.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3743.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3744. //                    $find_query['color'] = $colorId;
  3745.                 } else
  3746.                     $find_query['color'] = $colorId;
  3747.                 if ($size == '' || $size == || $size == null) {
  3748. //                    $find_query['size'] = $size;
  3749.                 } else
  3750.                     $find_query['size'] = 0;
  3751.                 $inventory_by_warehouse_list $this->getDoctrine()
  3752.                     ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  3753.                     ->findBy(
  3754.                         $find_query,
  3755.                         array()
  3756.                     );
  3757.                 $new_pid $productData['productId'];
  3758.                 $p_data = array(
  3759.                     'details_id' => $product->getId(),
  3760. //                        'productId'=>$new_pid,
  3761.                     'productIdList' => [],
  3762.                     'multList' => [],
  3763.                     'drItemIds' => [],
  3764.                     'drItemQty' => [],
  3765.                     'drItemCodeIds' => [],
  3766.                     'drItemCartonIds' => [],
  3767.                     'drItemReturnableFlag' => [],
  3768.                     'drItemReturnDueDate' => [],
  3769.                     'drItemReturnNote' => [],
  3770.                     'drItemReturnStatus' => [],
  3771.                     'colorIds' => [],
  3772.                     'colorNames' => [],
  3773.                     'sizeIds' => [],
  3774.                     'productNameList' => [],
  3775.                     'availableInventoryList' => [],
  3776.                     'warehouseActionId' => [],
  3777.                     'warehouseActionName' => [],
  3778.                     'availableBarcodes' => [],
  3779.                     'availableBarcodesStr' => [],
  3780. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3781. //                        'available_inventory'=>0,
  3782. //                        'package_id'=>$product->getPackageId(),
  3783.                     'qty' => $product->getQty(),
  3784.                     'delivered' => $product->getDelivered(),
  3785. //                    'deliverable' => $product->getDeliverable() - $product->getTransitQty(),
  3786.                     'deliverable' => min($soBalance$doBalance),
  3787. //                    'balance' => $product->getBalance(),
  3788.                     'balance' => min($soBalance$doBalance),
  3789.                     'productNameFdm' => $product->getProductNameFdm(),
  3790.                     'productFdm' => $product->getProductFdm(),
  3791. //                        'delivered'=>$product->getDelivered(),
  3792.                 );
  3793.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  3794.                     if ($inventory_by_warehouse->getQty() <= 0)
  3795.                         continue;
  3796.                     $unitType $product->getUnitTypeId();
  3797.                     $mult_unit 1;
  3798.                     if ($drId != 0) {
  3799.                         $drItem $this->getDoctrine()
  3800.                             ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3801.                             ->findOneBy(
  3802.                                 array(
  3803.                                     'deliveryReceiptId' => $drId,
  3804.                                     'productId' => $inventory_by_warehouse->getProductId(),
  3805.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  3806.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  3807.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  3808.                                 )
  3809.                             );
  3810.                         if ($drItem) {
  3811.                             $returnableMeta SalesOrderM::GetDeliveryReceiptItemReturnableMetaFromOtherdata($drItem->getOtherdata());
  3812.                             $p_data['drItemIds'][] = $drItem->getId();
  3813.                             $p_data['drItemQty'][] = $drItem->getQty();
  3814.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  3815.                             if ($codes == null)
  3816.                                 $codes = [];
  3817.                             $p_data['drItemCodeIds'][] = $codes;
  3818.                             $codes json_decode($drItem->getCartonIds(), true);
  3819.                             if ($codes == null)
  3820.                                 $codes = [];
  3821.                             $p_data['drItemCartonIds'][] = $codes;
  3822.                             $p_data['drItemReturnableFlag'][] = $returnableMeta['temporary_returnable_flag'];
  3823.                             $p_data['drItemReturnDueDate'][] = $returnableMeta['temporary_return_due_date'];
  3824.                             $p_data['drItemReturnNote'][] = $returnableMeta['temporary_return_note'];
  3825.                             $p_data['drItemReturnStatus'][] = $returnableMeta['temporary_return_status'];
  3826.                         } else {
  3827.                             $p_data['drItemIds'][] = 0;
  3828.                             $p_data['drItemQty'][] = 0;
  3829.                             $p_data['drItemCodeIds'][] = 0;
  3830.                             $p_data['drItemCartonIds'][] = 0;
  3831.                             $p_data['drItemReturnableFlag'][] = 0;
  3832.                             $p_data['drItemReturnDueDate'][] = '';
  3833.                             $p_data['drItemReturnNote'][] = '';
  3834.                             $p_data['drItemReturnStatus'][] = '';
  3835.                         }
  3836.                     } else {
  3837.                         $p_data['drItemIds'][] = 0;
  3838.                         $p_data['drItemQty'][] = 0;
  3839.                         $p_data['drItemCodeIds'][] = 0;
  3840.                         $p_data['drItemCartonIds'][] = 0;
  3841.                         $p_data['drItemReturnableFlag'][] = 0;
  3842.                         $p_data['drItemReturnDueDate'][] = '';
  3843.                         $p_data['drItemReturnNote'][] = '';
  3844.                         $p_data['drItemReturnStatus'][] = '';
  3845.                     }
  3846.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  3847.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  3848.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  3849.                         }
  3850.                     };
  3851.                     if ($mult_unit == 0)
  3852.                         $mult_unit 1;
  3853.                     $inv_product_id $inventory_by_warehouse->getProductId();
  3854.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  3855.                     $p_data['multList'][] = $mult_unit;
  3856.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  3857.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  3858.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  3859.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  3860.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  3861. //                        $p_data['availableInventoryList'][]=$inventory_by_warehouse?(($inventory_by_warehouse->getQty())*$mult_unit):0;
  3862.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  3863.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  3864.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  3865.                 }
  3866.                 $sendData['productList'][] = $p_data;
  3867.             }
  3868.             //now package data
  3869.             if ($sendData) {
  3870.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3871.             }
  3872.             return new JsonResponse(array("success" => false));
  3873.         }
  3874.         return new JsonResponse(array("success" => false));
  3875.     }
  3876.     public function GetItemListForDrBySoAction(Request $request)
  3877.     {
  3878.         $em $this->getDoctrine()->getManager();
  3879.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3880.         if ($request->isMethod('POST')) {
  3881.             $em $this->getDoctrine();
  3882.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3883. //                'type'=>1//product only
  3884.             );
  3885.             $find_item_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3886.                 'type' => 1//product only
  3887.             );
  3888.             $Content = [];
  3889.             $Transport_data = [];
  3890.             $Lul_data = [];
  3891.             $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3892.             if ($request->request->get('soId') != '') {
  3893.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3894.                 $find_item_array['salesOrderId'] = $request->request->get('soId');
  3895.             }
  3896. //            if($request->request->get('warehouseId')!='')
  3897. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3898.             $QD $this->getDoctrine()
  3899.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  3900.                 ->findBy(
  3901.                     $find_item_array,
  3902.                     array()
  3903.                 );
  3904. //            if($request->request->get('wareHouseId')!='')
  3905.             $DO $this->getDoctrine()
  3906.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  3907.                 ->findOneBy(
  3908.                     $find_array,
  3909.                     array()
  3910.                 );
  3911.             $sendData = array(
  3912. //                'salesType'=>$SO->getSalesType(),
  3913. //                'packageData'=>[],
  3914.                 'productList' => [],
  3915. //                'productListByPackage'=>[],
  3916.             );
  3917.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3918.             $pckg_item_cross_match_data = [];
  3919.             $unitList Inventory::UnitTypeList($em);
  3920.             $colorList Inventory::GetColorList($em);
  3921.             foreach ($QD as $product) {
  3922.                 if (($product->getBalance() - $product->getTransitQty()) <= 0)
  3923.                     continue;
  3924.                 //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3925. //                $soBalance = $soItem->getBalance();
  3926.                 $soBalance $product->getQty();
  3927. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3928. //                $doBalance = $product->getBalance();
  3929. //                $doBalance = 0;
  3930.                 //now check if any so ir do item id there that is at
  3931.                 //least pending
  3932.                 $approvalPendingDrs $this->getDoctrine()
  3933.                     ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3934.                     ->findBy(
  3935.                         array(
  3936.                             'salesOrderId' => $DO->getSalesOrderId(),
  3937.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3938.                         )
  3939.                     );
  3940.                 foreach ($approvalPendingDrs as $appPendDr) {
  3941.                     $appPendDrItem $this->getDoctrine()
  3942.                         ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3943.                         ->findOneBy(
  3944.                             array(
  3945.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3946. //                                'salesorderItemId' => $product->getId(),
  3947.                                 'salesorderItemId' => $product->getId()
  3948.                             )
  3949.                         );
  3950.                     if ($appPendDrItem) {
  3951.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3952.                             $soBalance $soBalance $appPendDrItem->getQty();
  3953.                         }
  3954. //                        $doBalance=$doBalance-$appPendDrItem->getQty();
  3955.                     }
  3956.                 }
  3957.                 $fdm $product->getProductFdm();
  3958.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3959.                 $find_query = array();
  3960.                 $colorId $product->getColorId();
  3961.                 $size $product->getSizeId();
  3962. //                $find_query['colorId']=
  3963.                 if ($productData['productId'] != 0) {
  3964.                     $find_query['productId'] = $productData['productId'];
  3965.                     if ($colorId == '' || $colorId == || $colorId == null)
  3966.                         $colorId $productData['defaultColorId'] ?? 0;
  3967.                     if ($size == '' || $size == || $size == null)
  3968.                         $size $productData['defaultSize'] ?? 0;
  3969.                 } else {
  3970.                     if ($productData['igId'] != 0) {
  3971.                         $find_query['igId'] = $productData['igId'];
  3972.                     }
  3973.                     if ($productData['categoryId'] != 0) {
  3974.                         $find_query['categoryId'] = $productData['categoryId'];
  3975.                     }
  3976.                     if ($productData['subCategoryId'] != 0) {
  3977.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3978.                     }
  3979.                     if ($productData['brandId'] != 0) {
  3980.                         $find_query['brandId'] = $productData['brandId'];
  3981.                     }
  3982.                 }
  3983.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3984.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3985.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3986. //                    $find_query['color'] = $colorId;
  3987.                 } else
  3988.                     $find_query['color'] = $colorId;
  3989.                 if ($size == '' || $size == || $size == null) {
  3990. //                    $find_query['size'] = $size;
  3991.                 } else
  3992.                     $find_query['size'] = 0;
  3993.                 $inventory_by_warehouse_list $this->getDoctrine()
  3994.                     ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  3995.                     ->findBy(
  3996.                         $find_query,
  3997.                         array()
  3998.                     );
  3999.                 $new_pid $productData['productId'];
  4000.                 $unitType $product->getUnitTypeId();
  4001.                 $p_data = array(
  4002.                     'details_id' => $product->getId(),
  4003.                     'unitType' => $unitType,
  4004.                     'productIdList' => [],
  4005.                     'multList' => [],
  4006.                     'drItemIds' => [],
  4007.                     'drItemQty' => [],
  4008.                     'drItemCodeIds' => [],
  4009.                     'drItemCartonIds' => [],
  4010.                     'drItemReturnableFlag' => [],
  4011.                     'drItemReturnDueDate' => [],
  4012.                     'drItemReturnNote' => [],
  4013.                     'drItemReturnStatus' => [],
  4014.                     'colorIds' => [],
  4015.                     'colorNames' => [],
  4016.                     'sizeIds' => [],
  4017.                     'productNameList' => [],
  4018.                     'availableInventoryList' => [],
  4019.                     'warehouseActionId' => [],
  4020.                     'warehouseActionName' => [],
  4021.                     'availableBarcodes' => [],
  4022.                     'availableBarcodesStr' => [],
  4023. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  4024. //                        'available_inventory'=>0,
  4025. //                        'package_id'=>$product->getPackageId(),
  4026.                     'qty' => $product->getQty(),
  4027.                     'delivered' => $product->getDelivered(),
  4028. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  4029. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  4030.                     'deliverable' => $soBalance,
  4031. //                    'deliverable' => $product->getBalance(),
  4032.                     'balance' => $soBalance,
  4033. //                    'balance' => $product->getBalance(),
  4034.                     'productNameFdm' => $product->getProductNameFdm(),
  4035.                     'productFdm' => $product->getProductFdm(),
  4036. //                        'delivered'=>$product->getDelivered(),
  4037.                 );
  4038.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  4039.                     if ($inventory_by_warehouse->getQty() <= 0)
  4040.                         continue;
  4041.                     $mult_unit 1;
  4042.                     if ($drId != 0) {
  4043.                         $drItem $this->getDoctrine()
  4044.                             ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  4045.                             ->findOneBy(
  4046.                                 array(
  4047.                                     'deliveryReceiptId' => $drId,
  4048.                                     'productId' => $inventory_by_warehouse->getProductId(),
  4049.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  4050.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  4051.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  4052.                                 )
  4053.                             );
  4054.                         if ($drItem) {
  4055.                             $returnableMeta SalesOrderM::GetDeliveryReceiptItemReturnableMetaFromOtherdata($drItem->getOtherdata());
  4056.                             $p_data['drItemIds'][] = $drItem->getId();
  4057.                             $p_data['drItemQty'][] = $drItem->getQty();
  4058.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  4059.                             if ($codes == null)
  4060.                                 $codes = [];
  4061.                             $p_data['drItemCodeIds'][] = $codes;
  4062.                             $codes json_decode($drItem->getCartonIds(), true);
  4063.                             if ($codes == null)
  4064.                                 $codes = [];
  4065.                             $p_data['drItemCartonIds'][] = $codes;
  4066.                             $p_data['drItemReturnableFlag'][] = $returnableMeta['temporary_returnable_flag'];
  4067.                             $p_data['drItemReturnDueDate'][] = $returnableMeta['temporary_return_due_date'];
  4068.                             $p_data['drItemReturnNote'][] = $returnableMeta['temporary_return_note'];
  4069.                             $p_data['drItemReturnStatus'][] = $returnableMeta['temporary_return_status'];
  4070.                         } else {
  4071.                             $p_data['drItemIds'][] = 0;
  4072.                             $p_data['drItemQty'][] = 0;
  4073.                             $p_data['drItemCodeIds'][] = 0;
  4074.                             $p_data['drItemCartonIds'][] = 0;
  4075.                             $p_data['drItemReturnableFlag'][] = 0;
  4076.                             $p_data['drItemReturnDueDate'][] = '';
  4077.                             $p_data['drItemReturnNote'][] = '';
  4078.                             $p_data['drItemReturnStatus'][] = '';
  4079.                         }
  4080.                     } else {
  4081.                         $p_data['drItemIds'][] = 0;
  4082.                         $p_data['drItemQty'][] = 0;
  4083.                         $p_data['drItemCodeIds'][] = 0;
  4084.                         $p_data['drItemCartonIds'][] = 0;
  4085.                         $p_data['drItemReturnableFlag'][] = 0;
  4086.                         $p_data['drItemReturnDueDate'][] = '';
  4087.                         $p_data['drItemReturnNote'][] = '';
  4088.                         $p_data['drItemReturnStatus'][] = '';
  4089.                     }
  4090.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  4091.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  4092.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  4093.                         }
  4094.                     };
  4095.                     if ($mult_unit == 0)
  4096.                         $mult_unit 1;
  4097.                     $inv_product_id $inventory_by_warehouse->getProductId();
  4098.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  4099.                     $p_data['multList'][] = $mult_unit;
  4100.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  4101.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  4102.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  4103.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  4104.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  4105.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  4106.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  4107.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  4108.                 }
  4109.                 $sendData['productList'][] = $p_data;
  4110.             }
  4111.             //now package data
  4112.             if ($sendData) {
  4113.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4114.             }
  4115.             return new JsonResponse(array("success" => false));
  4116.         }
  4117.         return new JsonResponse(array("success" => false));
  4118.     }
  4119.     public function GetExtraTemporaryReturnableItemsForDrAction(Request $request)
  4120.     {
  4121.         $em $this->getDoctrine()->getManager();
  4122.         $companyId $this->getLoggedUserCompanyId($request);
  4123.         $warehouseActionList Inventory::warehouse_action_list($em$companyId'');
  4124.         $unitList Inventory::UnitTypeList($em);
  4125.         $colorList Inventory::GetColorList($em);
  4126.         if (!$request->isMethod('POST')) {
  4127.             return new JsonResponse(array("success" => false));
  4128.         }
  4129.         $productId $request->request->get('productId'0);
  4130.         $warehouseId $request->request->get('warehouseId'0);
  4131.         $drId $request->request->get('drId'0);
  4132.         if (($productId) == || ($warehouseId) == 0) {
  4133.             return new JsonResponse(array("success" => false));
  4134.         }
  4135.         $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($productId);
  4136.         if (!$product) {
  4137.             return new JsonResponse(array("success" => false));
  4138.         }
  4139.         $productList Inventory::ProductList($em$companyId);
  4140.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(array(
  4141.             'CompanyId' => $companyId,
  4142.             'warehouseId' => $warehouseId,
  4143.             'productId' => $productId,
  4144.         ));
  4145.         $sendData = array(
  4146.             'productList' => [],
  4147.         );
  4148.         foreach ($slotList as $slot) {
  4149.             if ($slot->getQty() <= 0) {
  4150.                 continue;
  4151.             }
  4152.             $multUnit 1;
  4153.             if ($product->getUnitTypeId() != $slot->getUnitTypeId()) {
  4154.                 if (isset($unitList[$slot->getUnitTypeId()]['conversion'][$product->getUnitTypeId()])) {
  4155.                     $multUnit $unitList[$slot->getUnitTypeId()]['conversion'][$product->getUnitTypeId()];
  4156.                 }
  4157.             }
  4158.             if ($multUnit == 0) {
  4159.                 $multUnit 1;
  4160.             }
  4161.             $drItem null;
  4162.             if (($drId) != 0) {
  4163.                 $drItem $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')->findOneBy(array(
  4164.                     'deliveryReceiptId' => $drId,
  4165.                     'salesorderItemId' => [0null''],
  4166.                     'productId' => $slot->getProductId(),
  4167.                     'warehouseActionId' => $slot->getActionTagId(),
  4168.                     'colorId' => $slot->getColor() == ? [0null''] : $slot->getColor(),
  4169.                     'sizeId' => $slot->getSize() == ? [0null''] : $slot->getSize(),
  4170.                 ));
  4171.             }
  4172.             $returnableMeta SalesOrderM::GetDeliveryReceiptItemReturnableMetaFromOtherdata($drItem $drItem->getOtherdata() : []);
  4173.             $availableQty = (($slot->getQty()) / $multUnit);
  4174.             if ($drItem && $availableQty < ($drItem->getQty())) {
  4175.                 $availableQty $drItem->getQty();
  4176.             }
  4177.             $sendData['productList'][] = array(
  4178.                 'details_id' => 0,
  4179.                 'productIdList' => array($slot->getProductId()),
  4180.                 'multList' => array($multUnit),
  4181.                 'drItemIds' => array($drItem $drItem->getId() : 0),
  4182.                 'drItemQty' => array($drItem ? ($drItem->getQty()) : 0),
  4183.                 'drItemCodeIds' => array($drItem ? (json_decode($drItem->getProductByCodeIds(), true) ?: []) : []),
  4184.                 'drItemCartonIds' => array($drItem ? (json_decode($drItem->getCartonIds(), true) ?: []) : []),
  4185.                 'drItemReturnableFlag' => array($drItem $returnableMeta['temporary_returnable_flag'] : 1),
  4186.                 'drItemReturnDueDate' => array($drItem $returnableMeta['temporary_return_due_date'] : ''),
  4187.                 'drItemReturnNote' => array($drItem $returnableMeta['temporary_return_note'] : ''),
  4188.                 'drItemReturnStatus' => array($drItem $returnableMeta['temporary_return_status'] : 'pending'),
  4189.                 'colorIds' => array($slot->getColor() ? $slot->getColor() : 0),
  4190.                 'colorNames' => array($slot->getColor() && isset($colorList[$slot->getColor()]) ? $colorList[$slot->getColor()]['name'] : ''),
  4191.                 'sizeIds' => array($slot->getSize() ? $slot->getSize() : 0),
  4192.                 'productNameList' => array(isset($productList[$slot->getProductId()]) ? $productList[$slot->getProductId()]['name'] : $product->getName()),
  4193.                 'availableInventoryList' => array($availableQty),
  4194.                 'warehouseActionId' => array($slot->getActionTagId()),
  4195.                 'warehouseActionName' => array(isset($warehouseActionList[$slot->getActionTagId()]) ? $warehouseActionList[$slot->getActionTagId()] : ''),
  4196.                 'availableBarcodes' => array([]),
  4197.                 'availableBarcodesStr' => array(''),
  4198.                 'serialEnabled' => array(isset($productList[$slot->getProductId()]) ? $productList[$slot->getProductId()]['has_serial'] : 0),
  4199.                 'qty' => $availableQty,
  4200.                 'delivered' => 0,
  4201.                 'deliverable' => $availableQty,
  4202.                 'balance' => $availableQty,
  4203.                 'productNameFdm' => 'Temporary returnable item',
  4204.                 'productFdm' => $product->getProductFdm(),
  4205.                 'extraTempItemFlag' => 1,
  4206.             );
  4207.         }
  4208.         return new JsonResponse(array("success" => true"content" => $sendData));
  4209.     }
  4210.     public function GetItemListForStockReqBySoAction(Request $request)
  4211.     {
  4212.         $em $this->getDoctrine()->getManager();
  4213.         if ($request->isMethod('POST')) {
  4214.             $em $this->getDoctrine();
  4215.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  4216.             );
  4217.             $Content = [];
  4218.             $Transport_data = [];
  4219.             $Lul_data = [];
  4220.             // NOTE: do NOT pre-filter by serviceId. In the filter-based sales model every sales-order
  4221.             // line carries a serviceId (>0, referencing AccService) with an empty product_fdm, so the
  4222.             // old `serviceId => [0, null]` filter excluded 100% of the items and the Stock Requisition
  4223.             // item list always came back empty. We fetch all lines of the SO and resolve their names below.
  4224.             $sendData = array(
  4225. //                'salesType'=>$SO->getSalesType(),
  4226. //                'packageData'=>[],
  4227.                 'productList' => [],
  4228. //                'productListByPackage'=>[],
  4229.             );
  4230.             if ($request->request->get('soId') != '') {
  4231.                 $find_array['salesOrderId'] = $request->request->get('soId');
  4232. //            if($request->request->get('warehouseId')!='')
  4233. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4234.                 $QD $this->getDoctrine()
  4235.                     ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  4236.                     ->findBy(
  4237.                         $find_array,
  4238.                         array()
  4239.                     );
  4240. //            if($request->request->get('wareHouseId')!='')
  4241. //            $DO = $this->getDoctrine()
  4242. //                ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  4243. //                ->findOneBy(
  4244. //                    $find_array,
  4245. //                    array()
  4246. //                );
  4247.                 $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4248.                 $pckg_item_cross_match_data = [];
  4249.                 $unitList Inventory::UnitTypeList($em);
  4250.                 // Service/filter lines have no productNameFdm yet â€” resolve their name from AccService.
  4251.                 $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  4252.                 foreach ($QD as $product) {
  4253. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  4254. //                    continue;
  4255.                     $fdm $product->getProductFdm();
  4256.                     $serviceId = (int) $product->getServiceId();
  4257.                     $unitType $product->getUnitTypeId();
  4258.                     // Display name: product lines carry a productNameFdm; filter/service-based lines
  4259.                     // (no FDM finalised yet) are named from the AccService they reference.
  4260.                     $nameFdm $product->getProductNameFdm();
  4261.                     if (($nameFdm === null || $nameFdm === '') && $serviceId && isset($serviceList[$serviceId])) {
  4262.                         $nameFdm $serviceList[$serviceId]['name'];
  4263.                         if (!$unitType && isset($serviceList[$serviceId]['unit_type'])) {
  4264.                             $unitType $serviceList[$serviceId]['unit_type'];
  4265.                         }
  4266.                     }
  4267.                     $p_data = array(
  4268.                         'details_id' => $product->getId(),
  4269.                         'serviceId' => $serviceId,
  4270.                         'unitType' => $unitType,
  4271.                         'productIdList' => [],
  4272.                         'multList' => [],
  4273.                         'productNameList' => [],
  4274.                         'availableInventoryList' => [],
  4275.                         'warehouseActionId' => [],
  4276.                         'warehouseActionName' => [],
  4277.                         'availableBarcodes' => [],
  4278.                         'availableBarcodesStr' => [],
  4279. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  4280. //                        'available_inventory'=>0,
  4281. //                        'package_id'=>$product->getPackageId(),
  4282.                         'qty' => $product->getQty(),
  4283.                         'delivered' => $product->getDelivered(),
  4284. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  4285. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  4286.                         'deliverable' => $product->getBalance(),
  4287.                         'balance' => $product->getBalance(),
  4288.                         'productNameFdm' => $nameFdm,
  4289.                         'productFdm' => $product->getProductFdm(),
  4290. //                        'delivered'=>$product->getDelivered(),
  4291.                     );
  4292.                     $sendData['productList'][] = $p_data;
  4293.                 }
  4294.             }
  4295.             //now package data
  4296.             if ($sendData) {
  4297.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4298.             }
  4299.             return new JsonResponse(array("success" => false));
  4300.         }
  4301.         return new JsonResponse(array("success" => false));
  4302.     }
  4303.     public function GetProductPriceAjaxAction(Request $request)
  4304.     {
  4305.         $em $this->getDoctrine()->getManager();
  4306.         $priceData = [];
  4307.         $defaultData = [
  4308.             => [    //currId
  4309.                 => 0       ///customerID=> value
  4310.             ]
  4311.         ];
  4312.         $priceData = [
  4313.             => $defaultData
  4314.         ];
  4315.         if ($request->isMethod('POST')) {
  4316.             $em $this->getDoctrine();
  4317.             $find_query = array();
  4318.             $pid $request->request->get('productId'0);
  4319.             $find_query['productId'] = $pid;
  4320.             $priceData = [
  4321. //                $pid =>$defaultData
  4322.             ];
  4323.             $priceDataQry $em
  4324.                 ->getRepository('ApplicationBundle\\Entity\\ProductMrp')
  4325.                 ->findBy(
  4326.                     $find_query,
  4327.                     array(
  4328.                         'productMrpId' => 'desc'
  4329.                     )
  4330.                 );
  4331.             if (!empty($priceDataQry)) {
  4332.                 foreach ($priceDataQry as $priceDataQ) {
  4333.                     $currId $priceDataQ->getCurrency();
  4334.                     if ($currId == null$currId 0;
  4335.                     if (!isset($priceData[$pid][$currId]))
  4336.                         $priceData[$pid][$currId] = $defaultData;
  4337.                     $priceByCustomerType json_decode($priceDataQ->getPriceByCustomerTypes(), true);
  4338.                     if ($priceByCustomerType == null$priceByCustomerType = [];
  4339.                     foreach ($priceByCustomerType as $ct => $pbct) {
  4340.                         if (!isset($priceData[$pid][$currId][$ct]))
  4341.                             $priceData[$pid][$currId][$ct] = $pbct;
  4342.                     }
  4343.                 }
  4344.             }
  4345.         }
  4346.         //now package data
  4347.         $retData = array(
  4348.             'success' => true,
  4349.             'data' => $priceData
  4350.         );
  4351.         return new JsonResponse($retData);
  4352.     }
  4353.     public function GetBarcodesListForStAction(Request $request)
  4354.     {
  4355.         $em $this->getDoctrine()->getManager();
  4356.         $sendData = [];
  4357.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  4358.         if ($request->isMethod('POST')) {
  4359.             $em $this->getDoctrine();
  4360.             $find_query = array();
  4361.             $find_query['warehouseId'] = $request->request->get('warehouseId');
  4362.             $find_query['actionTagId'] = $request->request->get('warehouseActionId');
  4363.             $find_query['productId'] = $request->request->get('productId');
  4364.             $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  4365.             $inventory_by_warehouse_list $this->getDoctrine()
  4366.                 ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  4367.                 ->findBy(
  4368.                     $find_query,
  4369.                     array()
  4370.                 );
  4371.             $new_pid $request->request->get('productId');
  4372.             $p_data = array();
  4373.             //now get bacodes if available
  4374. //                    $query = "SELECT product_by_code_id, GROUP_CONCAT(DISTINCT sales_code SEPARATOR ',') sales_code_list_str
  4375. //FROM product_by_code
  4376. //where company_id=" . $this->getLoggedUserCompanyId($request).
  4377. //                        " and product_id=".$inv_product_id.
  4378. //                        " and warehouse_id=".$inventory_by_warehouse->getWarehouseId().
  4379. //                        " and warehouse_action_id=".$inventory_by_warehouse->getActionTagId();
  4380. //                        " GROUP BY product_by_code_id" ;
  4381.             $query "SELECT product_by_code_id, sales_code
  4382. FROM product_by_code
  4383. where company_id = :companyId
  4384.   and product_id = :productId
  4385.   and warehouse_id = :warehouseId
  4386.   and warehouse_action_id = :warehouseActionId";
  4387.             $stmt $em->getConnection()->fetchAllAssociative($query, array(
  4388.                 'companyId' => (int) $this->getLoggedUserCompanyId($request),
  4389.                 'productId' => (int) $request->request->get('productId'),
  4390.                 'warehouseId' => (int) $request->request->get('warehouseId'),
  4391.                 'warehouseActionId' => (int) $request->request->get('warehouseActionId'),
  4392.             ));
  4393.             $results $stmt;
  4394.             $sales_code_list_str '';
  4395.             foreach ($results as $pika => $result) {
  4396.                 if ($pika != 0)
  4397.                     $sales_code_list_str .= ',';
  4398.                 $sales_code_list_str .= str_pad($result['sales_code'], 13'0'STR_PAD_LEFT);
  4399.             }
  4400.             if ($results) {
  4401.                 $p_data['availableBarcodes'] = $sales_code_list_str != '' || $sales_code_list_str != null
  4402.                     explode(','$sales_code_list_str) : [];
  4403.                 $p_data['availableBarcodesStr'] = $sales_code_list_str != '' || $sales_code_list_str != null
  4404.                     $sales_code_list_str "";
  4405. //
  4406.             } else {
  4407.                 $p_data['availableBarcodes'] = [];
  4408.                 $p_data['availableBarcodesStr'] = "";
  4409. //
  4410.             }
  4411.             $sendData $p_data;
  4412.         }
  4413.         //now package data
  4414.         if (!empty($sendData['availableBarcodes'])) {
  4415.             return new JsonResponse(array("success" => true"content" => $sendData));
  4416.         }
  4417.         return new JsonResponse(array("success" => false));
  4418.     }
  4419.     public function GetItemListForSalesReturnAction(Request $request)
  4420.     {
  4421.         if ($request->isMethod('POST')) {
  4422.             $em $this->getDoctrine();
  4423.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  4424.             );
  4425.             $Content = [];
  4426.             $Transport_data = [];
  4427.             $Lul_data = [];
  4428.             if ($request->request->get('drId') != '')
  4429.                 $find_array['deliveryReceiptId'] = $request->request->get('drId');
  4430. //            if($request->request->get('warehouseId')!='')
  4431. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4432.             $QD $this->getDoctrine()
  4433.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  4434.                 ->findBy(
  4435.                     $find_array,
  4436.                     array()
  4437.                 );
  4438. //            if($request->request->get('wareHouseId')!='')
  4439.             $DR $this->getDoctrine()
  4440.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  4441.                 ->findOneBy(
  4442.                     $find_array,
  4443.                     array()
  4444.                 );
  4445.             $sendData = array(
  4446.                 'productList' => [],
  4447.             );
  4448.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4449.             $pckg_item_cross_match_data = [];
  4450.             $unitList Inventory::UnitTypeList($em);
  4451.             foreach ($QD as $product) {
  4452.                 if (($product->getQty()) <= 0)
  4453.                     continue;
  4454.                 $new_pid $product->getProductId();
  4455.                 $sales_code_range = [];
  4456.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  4457.                     $sales_code_range json_decode($product->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  4458.                 } else {
  4459.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  4460.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getSalesCodeRange());
  4461.                     $sales_code_range json_decode($json_without_bigintstrue);
  4462.                 }
  4463.                 $p_data = array(
  4464.                     'details_id' => $product->getId(),
  4465.                     'dr_id' => $product->getDeliveryReceiptId(),
  4466.                     'productId' => $new_pid,
  4467.                     'product_name' => isset($productList[$new_pid]) ? $productList[$new_pid]['name'] : '',
  4468.                     'qty' => $product->getQty(),
  4469.                     'delivered' => $product->getDelivered(),
  4470.                     'unitTypeId' => $product->getUnitTypeId(),
  4471.                     'deliverable' => $product->getDeliverable(),
  4472.                     'balance' => $product->getBalance(),
  4473.                     'salesCodeRangeStr' => $product->getSalesCodeRange(),
  4474.                     'salesCodeRange' => $sales_code_range,
  4475.                     'sales_codes' => $sales_code_range,
  4476.                     'sales_price' => $product->getPrice(),
  4477.                     'purchase_price' => $product->getCurrentPurchasePrice()
  4478. //                        'delivered'=>$product->getDelivered(),
  4479.                 );
  4480.                 $sendData['productList'][] = $p_data;
  4481.             }
  4482.             //now package data
  4483.             if ($sendData) {
  4484.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4485.             }
  4486.             return new JsonResponse(array("success" => false));
  4487.         }
  4488.         return new JsonResponse(array("success" => false));
  4489.     }
  4490.     public function GetItemListForIrrAction(Request $request)
  4491.     {
  4492.         if ($request->isMethod('POST')) {
  4493.             $em $this->getDoctrine();
  4494.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  4495.             );
  4496.             $Content = [];
  4497.             $Transport_data = [];
  4498.             $Lul_data = [];
  4499.             if ($request->request->get('srId') != '')
  4500.                 $find_array['salesReturnId'] = $request->request->get('srId');
  4501. //            if($request->request->get('warehouseId')!='')
  4502. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4503.             $QD $this->getDoctrine()
  4504.                 ->getRepository('ApplicationBundle\\Entity\\SalesReturnItem')
  4505.                 ->findBy(
  4506.                     $find_array,
  4507.                     array()
  4508.                 );
  4509. //            if($request->request->get('wareHouseId')!='')
  4510.             $sendData = array(
  4511.                 'productList' => [],
  4512.             );
  4513.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4514.             $pckg_item_cross_match_data = [];
  4515.             $unitList Inventory::UnitTypeList($em);
  4516.             foreach ($QD as $product) {
  4517.                 if (($product->getReceivedBalance()) <= && ($product->getReplacedBalance()) <= 0)
  4518.                     continue;
  4519.                 $DR_ITEM null;
  4520.                 $DR_TAGGED_CODES = [];
  4521.                 $DR_TAGGED_CODES_FOR_SELECTIZE = [];
  4522.                 $RESTRICT_RECEIVED_CODES_FLAG 0;
  4523.                 $sales_code_range = [];
  4524.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  4525.                     $sales_code_range json_decode($product->getReceivedCodeRange(), true512JSON_BIGINT_AS_STRING);
  4526.                 } else {
  4527.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  4528.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getReceivedCodeRange());
  4529.                     $sales_code_range json_decode($json_without_bigintstrue);
  4530.                 }
  4531.                 $DR_TAGGED_CODES $sales_code_range;
  4532.                 if (!empty($DR_TAGGED_CODES)) {
  4533.                     $RESTRICT_RECEIVED_CODES_FLAG 1;
  4534.                     foreach ($DR_TAGGED_CODES as $DTC) {
  4535.                         $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  4536.                             'value' => $DTC
  4537.                         );
  4538.                     }
  4539.                 }
  4540. //                if ($product->getTaggedDetailsId() != 0 && $product->getTaggedDetailsId() != null) {
  4541. //
  4542. //                    $DR_ITEM = $this->getDoctrine()
  4543. //                        ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  4544. //                        ->findOneBy(
  4545. //                            array(
  4546. //                                'id' => $product->getTaggedDetailsId()
  4547. //                            ),
  4548. //                            array()
  4549. //                        );
  4550. //                    if ($DR_ITEM) {
  4551. //                        if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  4552. //
  4553. //                            $DR_TAGGED_CODES = json_decode($DR_ITEM->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  4554. //                        } else {
  4555. //
  4556. //                            $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  4557. //                            $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $DR_ITEM->getSalesCodeRange());
  4558. //                            $DR_TAGGED_CODES = json_decode($json_without_bigints, true);
  4559. //                        }
  4560. //
  4561. //                        if ($DR_TAGGED_CODES == null)
  4562. //                            $DR_TAGGED_CODES = [];
  4563. //                        if (!empty($DR_TAGGED_CODES)) {
  4564. //                            $RESTRICT_RECEIVED_CODES_FLAG = 1;
  4565. //                            foreach ($DR_TAGGED_CODES as $DTC) {
  4566. //                                $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  4567. //                                    'value' => $DTC
  4568. //                                );
  4569. //                            }
  4570. //                        }
  4571. //                    }
  4572. //                }
  4573.                 $p_data = array(
  4574.                     'details_id' => $product->getId(),
  4575.                     'receivedDrTaggedCodes' => $DR_TAGGED_CODES,
  4576.                     'receivedDrTaggedCodesStr' => implode(','$DR_TAGGED_CODES),
  4577.                     'receivedDrTaggedCodesForSel' => $DR_TAGGED_CODES_FOR_SELECTIZE,
  4578.                     'receivedRestrictCodesFlag' => $RESTRICT_RECEIVED_CODES_FLAG,
  4579.                     'receivedProductId' => $product->getReceivedProductId(),
  4580.                     'receivedBalance' => $product->getReceivedBalance(),
  4581.                     'receivedUnitSalesPrice' => $product->getReceivedUnitSalesPrice(),
  4582.                     'receivedUnitPurchasePrice' => $product->getReceivedUnitPurchasePrice(),
  4583.                     'receivedProductName' => isset($productList[$product->getReceivedProductId()]) ? $productList[$product->getReceivedProductId()]['name'] : '',
  4584.                     'replacedProductId' => $product->getReplacedProductId(),
  4585.                     'replacedBalance' => $product->getReplacedBalance(),
  4586.                     'replacedUnitSalesPrice' => $product->getReplacedUnitSalesPrice(),
  4587.                     'replacedUnitPurchasePrice' => $product->getReplacedUnitPurchasePrice(),
  4588.                     'replacedProductName' => isset($productList[$product->getReplacedProductId()]) ? $productList[$product->getReplacedProductId()]['name'] : '',
  4589.                     'disposeBalance' => $product->getDisposeBalance(),
  4590.                     'unusedBalance' => $product->getUnusedBalance(),
  4591.                     'disposeTag' => $product->getDisposeTag(),
  4592.                     'unitTypeId' => $product->getUnitTypeId(),
  4593. //                        'delivered'=>$product->getDelivered(),
  4594.                 );
  4595.                 $sendData['productList'][] = $p_data;
  4596.             }
  4597.             //now package data
  4598.             if ($sendData) {
  4599.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4600.             }
  4601.             return new JsonResponse(array("success" => false));
  4602.         }
  4603.         return new JsonResponse(array("success" => false));
  4604.     }
  4605.     public function LabelFormatAction(Request $request$id 0)
  4606.     {
  4607.         $data = array(
  4608.             'formatId' => '',
  4609.             'formatCode' => '',
  4610.             'name' => '',
  4611.             'labelType' => 0,
  4612.             'width' => 60,
  4613.             'pageWidth' => 6,
  4614.             'height' => 39,
  4615.             'pageHeight' => 2,
  4616.             'formatData' => '',
  4617.         );
  4618.         if ($request->isMethod('POST')) {
  4619.             $post $request->request;
  4620.             $exists_already 0;
  4621.             if ($request->request->get('formatId') != '') {
  4622.                 $query_here $this->getDoctrine()
  4623.                     ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  4624.                     ->findOneBy(
  4625.                         array(
  4626.                             'formatId' => $request->request->get('formatId')
  4627.                         )
  4628.                     );
  4629.                 if (!empty($query_here)) {
  4630.                     $exists_already 1;
  4631.                     $new $query_here;
  4632.                 } else
  4633.                     $new = new LabelFormat();
  4634.             } else
  4635.                 $new = new LabelFormat();
  4636.             $new->setName($request->request->get('name'));
  4637.             $new->setLabelType($request->request->get('labelType'));
  4638.             $new->setWidth($request->request->get('width'));
  4639.             $new->setHeight($request->request->get('height'));
  4640.             $new->setFormatCode($request->request->get('formatCode'));
  4641.             $new->setActive(GeneralConstant::ACTIVE);
  4642.             $new->setPageHeight($request->request->get('pageHeight'));
  4643.             $new->setPageWidth($request->request->get('pageWidth'));
  4644.             $new->setFormatData($request->request->get('formatData'));
  4645.             if ($exists_already == 0)
  4646.                 $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4647.             $new->setEditLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4648.             $new->setCompanyId($request->getSession()->get(UserConstants::USER_COMPANY_ID));
  4649.             $em $this->getDoctrine()->getManager();
  4650.             $em->persist($new);
  4651.             $em->flush();
  4652.         }
  4653.         if ($id != 0) {
  4654.             $query_here $this->getDoctrine()
  4655.                 ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  4656.                 ->findOneBy(
  4657.                     array(
  4658.                         'formatId' => $id
  4659.                     )
  4660.                 );
  4661.             if ($query_here)
  4662.                 $data $query_here;
  4663.         } else if ($request->query->has('formatId')) {
  4664.             $query_here $this->getDoctrine()
  4665.                 ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  4666.                 ->findOneBy(
  4667.                     array(
  4668.                         'formatId' => $request->query->get('formatId')
  4669.                     )
  4670.                 );
  4671.             if ($query_here)
  4672.                 $data $query_here;
  4673.         }
  4674.         return $this->render(
  4675.             '@Inventory/pages/input_forms/label_format.html.twig',
  4676.             array(
  4677.                 'page_title' => 'Label Format',
  4678.                 'data' => $data,
  4679.                 'labelTypeList' => LabelConstant::$label_type_list,
  4680.                 'labelFieldsList' => LabelConstant::$label_fields_list,
  4681.                 'formatList' => $this->getDoctrine()
  4682.                     ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  4683.                     ->findBy(
  4684.                         array( //                            'formatId' => $request->query->get('formatId')
  4685.                         )
  4686.                     )
  4687.                 //                'incomeLedgerHeads'=>Accounts::getChildLedgerHeads($this->getDoctrine()->getManager(),AccountsConstant::INCOME)
  4688.             )
  4689.         );
  4690.     }
  4691.     public function GetServiceListForScAction(Request $request)
  4692.     {
  4693.         if ($request->isMethod('POST')) {
  4694.             $em $this->getDoctrine();
  4695.             $find_array = array(
  4696.                 'type' => 2//service
  4697.             );
  4698.             $Content = [];
  4699.             $Transport_data = [];
  4700.             $Lul_data = [];
  4701.             if ($request->request->get('soId') != '')
  4702.                 $find_array['salesOrderId'] = $request->request->get('soId');
  4703. //            if($request->request->get('warehouseId')!='')
  4704. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4705.             $QD $this->getDoctrine()
  4706.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  4707.                 ->findBy(
  4708.                     $find_array,
  4709.                     array()
  4710.                 );
  4711. //            if($request->request->get('wareHouseId')!='')
  4712.             $SO $this->getDoctrine()
  4713.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  4714.                 ->findOneBy(
  4715.                     array(
  4716.                         'salesOrderId' => $request->request->get('soId')
  4717.                     ),
  4718.                     array()
  4719.                 );
  4720.             $sendData = array(
  4721. //                'salesType'=>$SO->getSalesType(),
  4722. //                'packageData'=>[],
  4723.                 'productList' => [],
  4724. //                'productListByPackage'=>[],
  4725.             );
  4726.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager(), $SO->getCompanyId());
  4727.             $pckg_item_cross_match_data = [];
  4728.             foreach ($QD as $product) {
  4729.                 $p_data = array(
  4730.                     'details_id' => $product->getId(),
  4731.                     'service_id' => $product->getServiceId(),
  4732.                     'service_name' => $serviceList[$product->getServiceId()]['name'],
  4733.                     'available_inventory' => $product->getBalance(),
  4734. //                        'package_id'=>$product->getPackageId(),
  4735.                     'qty' => $product->getQty(),
  4736.                     'delivered' => $product->getDelivered(),
  4737. //                    'deliverable'=>$product->getDeliverable(),
  4738.                     'balance' => $product->getBalance(),
  4739. //                        'delivered'=>$product->getDelivered(),
  4740.                 );
  4741.                 $sendData['serviceList'][] = $p_data;
  4742.             }
  4743.             //now package data
  4744.             if ($sendData) {
  4745.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4746.             }
  4747.             return new JsonResponse(array("success" => false));
  4748.         }
  4749.         return new JsonResponse(array("success" => false));
  4750.     }
  4751.     public function CreateReceivedNoteAction(Request $request)
  4752.     {
  4753.         if ($request->isMethod('POST')) {
  4754.             $em $this->getDoctrine()->getManager();
  4755.             $entity_id array_flip(GeneralConstant::$Entity_list)['Grn']; //change
  4756.             $dochash $request->request->get('docHash'); //change
  4757.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4758.             $approveRole 1;  //created
  4759.             $approveHash $request->request->get('approvalHash');
  4760.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4761.                 $loginId$approveRole$approveHash)
  4762.             ) {
  4763.                 $this->addFlash(
  4764.                     'error',
  4765.                     'Sorry Couldnot insert Data.'
  4766.                 );
  4767.             } else {
  4768.                 $data $request->request;
  4769.                 // A GRN is always received against a Purchase Order â€” CreateGrn reads line prices,
  4770.                 // the supplier head and expense tags from it. An empty/stale poId leaves $po null
  4771.                 // and used to 500 deep inside CreateGrn. Reject it here with a clear message.
  4772.                 $poCheck $data->get('poId')
  4773.                     ? $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')
  4774.                         ->findOneBy(array('purchaseOrderId' => $data->get('poId')))
  4775.                     : null;
  4776.                 if (!$poCheck) {
  4777.                     $this->addFlash('error''Select a valid Purchase Order before saving the GRN.');
  4778.                     return $this->redirect($request->getUri());
  4779.                 }
  4780.                 try {
  4781.                     $grnId Inventory::CreateGrn($this->getDoctrine()->getManager(), $data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4782.                 } catch (\Throwable $e) {
  4783.                     // Convert any residual failure into a graceful message rather than a raw error page.
  4784.                     $this->addFlash('error''Could not save the GRN: ' $e->getMessage());
  4785.                     return $this->redirect($request->getUri());
  4786.                 }
  4787.                 //now add Approval info
  4788.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4789.                 $approveRole 1;  //created
  4790.                 $options = array(
  4791.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4792.                     'notification_server' => $this->container->getParameter('notification_server'),
  4793.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4794.                     'url' => $this->generateUrl(
  4795.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['Grn']]
  4796.                         ['entity_view_route_path_name']
  4797.                     )
  4798.                 );
  4799.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4800.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  4801.                     $grnId,
  4802.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4803.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['Grn'], $grnId,
  4804.                     $loginId,
  4805.                     $approveRole,
  4806.                     $request->request->get('approvalHash'));
  4807.                 $this->addFlash(
  4808.                     'success',
  4809.                     'New GRN Added.'
  4810.                 );
  4811.                 $url $this->generateUrl(
  4812.                     'view_grn'
  4813.                 );
  4814.                 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),
  4815.                     "Good Received Note : " $dochash " Has Been Created And is Under Processing",
  4816.                     'pos',
  4817.                     System::getPositionIdsByDepartment($em, [GeneralConstant::SALES_DEPARTMENTGeneralConstant::PURCHASE_DEPARTMENTGeneralConstant::ACCOUNTS_DEPARTMENTGeneralConstant::INVENTORY_DEPARTMENT]),
  4818.                     'success',
  4819.                     $url "/" $grnId,
  4820.                     "GRN"
  4821.                 );
  4822.                 return $this->redirect($url "/" $grnId);
  4823.             }
  4824.         }
  4825.         return $this->render('@Inventory/pages/input_forms/received_note.html.twig',
  4826.             array(
  4827.                 'page_title' => 'GRN',
  4828.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  4829.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  4830.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  4831.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  4832.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  4833.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  4834.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  4835.                 'material_inward' => $this->getDoctrine()
  4836.                     ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  4837.                     ->findBy(
  4838.                         array(
  4839.                             'stage' => GeneralConstant::STAGE_PENDING_TAG
  4840.                         )
  4841.                     )
  4842. //                'po'=>Inventory::getPurchaseOrderList
  4843.             )
  4844.         );
  4845.     }
  4846.     public function GetQcListForGrnAction(Request $request)
  4847.     {
  4848.         if ($request->isMethod('POST')) {
  4849.             $find_array = array(
  4850.                 'stage' => GeneralConstant::STAGE_PENDING_TAG
  4851.             );
  4852.             $Content = [];
  4853.             $ContentByProductId = [];
  4854.             $Transport_data = [];
  4855.             $Lul_data = [];
  4856.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4857.             if ($request->request->get('poId') != '')
  4858.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4859.             if ($request->request->get('warehouseId') != '')
  4860.                 $find_array['warehouseId'] = $request->request->get('warehouseId');
  4861.             $QD $this->getDoctrine()
  4862.                 ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  4863.                 ->findBy(
  4864.                     $find_array,
  4865.                     array(
  4866.                         'inwardDate' => 'ASC',
  4867.                         'qcDate' => 'ASC'
  4868.                     )
  4869.                 );
  4870.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4871.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4872.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4873.             $lotNumArray = [];
  4874.             foreach ($QD as $entry) {
  4875. //                $inwardDate=strtotime($entry->getInwardDate());
  4876. //                $qcDate=strtotime($entry->getQcDate());
  4877.                 $inwardDate = ($entry->getInwardDate() instanceof \DateTime) ? $entry->getInwardDate()->format('m/d/Y') : '';
  4878.                 $qcDate = ($entry->getQcDate() instanceof \DateTime) ? $entry->getQcDate()->format('m/d/Y') : '';
  4879.                 if (!in_array($entry->getLotNumber(), $lotNumArray))
  4880.                     $lotNumArray[] = $entry->getLotNumber();
  4881.                 if (isset($ContentByProductId[$entry->getPurchaseOrderItemId()])) {
  4882.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['inwardDateList'][] = $inwardDate;
  4883.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcDateList'][] = $inwardDate;
  4884.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcIdList'][] = $entry->getQcId();
  4885.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['appQtyList'][] = $entry->getApprovedQty();
  4886.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['totQty'] += ($entry->getApprovedQty());
  4887.                 } else {
  4888.                     $ContentByProductId[$entry->getPurchaseOrderItemId()] = array(
  4889.                         'productName' => $productList[$entry->getProductId()]['name'],
  4890.                         'productUnitName' => $unitList[$productList[$entry->getProductId()]['unit_type']]['name'],
  4891.                         'qcHash' => $entry->getDocumentHash(),
  4892.                         'warehouseName' => $warehouse[$entry->getWarehouseId()]['name'],
  4893.                         'inwardDate' => $inwardDate,
  4894.                         'inwardDateList' => [$inwardDate],
  4895.                         'qcDateList' => [$qcDate],
  4896.                         'qcIdList' => [$entry->getQcId()],
  4897.                         'qcDate' => $qcDate,
  4898.                         'poQty' => $entry->getPoQty(),
  4899.                         'poPrevbalance' => $entry->getPoBalance(),
  4900.                         'appQty' => $entry->getApprovedQty(),
  4901.                         'appQtyList' => [$entry->getApprovedQty()],
  4902.                         'totQty' => $entry->getApprovedQty(),
  4903.                         'poBalance' => $entry->getPoBalance() - $entry->getApprovedQty(),
  4904.                         'qcId' => $entry->getQcId(),
  4905.                         'productId' => $entry->getProductId()
  4906.                     );
  4907.                 }
  4908.                 $Expense_Cost[$entry->getQcId()] = json_decode($entry->getExpenseCost());
  4909.                 $Expense_Id[$entry->getQcId()] = json_decode($entry->getExpenseId());
  4910.             }
  4911.             foreach ($ContentByProductId as $c) {
  4912.                 $Content[] = $c;
  4913.             }
  4914.             if ($QD) {
  4915.                 return new JsonResponse(array("success" => true"content" => $Content"lotNumber" => implode(', '$lotNumArray), 'Expense_Cost' => $Expense_Cost'Expense_Id' => $Expense_Id));
  4916.             }
  4917.             return new JsonResponse(array("success" => false));
  4918.         }
  4919.         return new JsonResponse(array("success" => false));
  4920.     }
  4921.     public function GetSrListForIrAction(Request $request)
  4922.     {
  4923.         if ($request->isMethod('POST')) {
  4924.             $find_array = array();
  4925.             $Content = [];
  4926.             if ($request->request->get('srId') != '')
  4927.                 $find_array['stockRequisitionId'] = $request->request->get('srId');
  4928.             $find_array['forceSkipTag'] = [0null];
  4929.             $QD $this->getDoctrine()
  4930.                 ->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')
  4931.                 ->findBy(
  4932.                     $find_array
  4933.                 );
  4934.             $itemList Inventory::ItemGroupList($this->getDoctrine()->getManager());
  4935.             $catgoryList Inventory::ProductCategoryList($this->getDoctrine()->getManager());
  4936.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4937.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4938.             $fdmData = array();
  4939.             $em $this->getDoctrine()->getManager();
  4940.             $matchType 'MAXIMUM';
  4941.             if ($request->request->has('matchType') != '') {
  4942.                 $matchType $request->request->get('matchType');
  4943.             }
  4944.             if ($matchType == 'MINIMUM') {
  4945.                 foreach ($QD as $entry) {
  4946.                     if ($entry->getTagPendingAmount() <= 0)
  4947.                         continue;
  4948.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4949.                     $combined_id $entry->getProductFdm();
  4950.                     if (isset($fdmData[$combined_id])) {
  4951.                         $fdmData[$combined_id]['unit'] += $entry->getTagPendingAmount();
  4952.                         $fdmData[$combined_id]['specific_unit'][] = $entry->getTagPendingAmount();
  4953.                         $fdmData[$combined_id]['detailsIds'][] = $entry->getId();
  4954.                         $fdmData[$combined_id]['docIds'][] = $entry->getStockRequisitionId();
  4955.                     } else {
  4956.                         $fdmData[$combined_id] = array(
  4957.                             'id' => 0,
  4958.                             'alias' => $entry->getNote(),
  4959.                             'unit' => $entry->getTagPendingAmount(),
  4960.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4961.                             'warranty' => 0,
  4962.                             'unitTypeId' => 0,
  4963.                             'unit_price' => 0,
  4964.                             'fdm' => $combined_id,
  4965.                             'extDetailsId' => 0,
  4966.                             'product_name' => $productData['productName'],
  4967.                             'total_price' => 0,
  4968.                             'detailsIds' => [$entry->getId()],
  4969.                             'docIds' => [$entry->getStockRequisitionId()],
  4970.                         );
  4971.                     }
  4972.                 }
  4973.             }
  4974.             if ($matchType == 'MAXIMUM') {
  4975.                 foreach ($QD as $entry) {
  4976.                     if ($entry->getTagPendingAmount() <= 0)
  4977.                         continue;
  4978.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4979.                     $combined_id $entry->getProductFdm();
  4980.                     $assigned 0;
  4981.                     foreach ($fdmData as $key_ind => $rel_val) {
  4982.                         $matchFdm Inventory::MatchFdm($key_ind$combined_id);
  4983.                         if ($matchFdm['hasMatched'] == 1) {
  4984.                             if ($matchFdm['isIdentical'] == 1) {
  4985.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4986.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4987.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4988.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4989.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4990.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4991.                                 $assigned 1;
  4992.                             } elseif ($matchFdm['SecondBelongsToFirst'] == 1) {
  4993.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4994.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4995.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4996.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4997.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4998.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4999.                                 $assigned 1;
  5000.                             } elseif ($matchFdm['FirstBelongsToSecond'] == 1) {
  5001.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  5002.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  5003.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  5004.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  5005.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  5006.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  5007.                                 $fdmData[$combined_id] = $fdmData[$key_ind];
  5008.                                 unset($fdmData[$key_ind]);
  5009.                                 $assigned 1;
  5010.                             }
  5011.                         } else {
  5012.                         }
  5013.                         if ($assigned == 1)
  5014.                             break;
  5015.                     }
  5016.                     if ($assigned == 0) {
  5017.                         $fdmData[$combined_id] = array(
  5018.                             'id' => 0,
  5019.                             'alias' => $entry->getNote(),
  5020.                             'unit' => $entry->getTagPendingAmount(),
  5021.                             'specific_unit' => [$entry->getTagPendingAmount()],
  5022.                             'specific_unit_type_id' => [$entry->getUnitTypeId()],
  5023.                             'warranty' => 0,
  5024.                             'unitTypeId' => $productData['unitTypeId'],
  5025. //                            'unitTypeId' => $productData['unitTypeId'],
  5026.                             'unit_price' => 0,
  5027.                             'fdm' => $combined_id,
  5028.                             'extDetailsId' => 0,
  5029.                             'product_name' => htmlspecialchars($productData['productName']),
  5030.                             'total_price' => 0,
  5031.                             'detailsIds' => [$entry->getId()],
  5032.                             'docIds' => [$entry->getStockRequisitionId()],
  5033.                         );
  5034.                     }
  5035.                     if (isset($fdmData[$combined_id])) {
  5036.                     } else {
  5037.                     }
  5038.                 }
  5039.             }
  5040.             $QD $this->getDoctrine()
  5041.                 ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  5042.                 ->findBy(
  5043.                     array('stockRequisitionId' => $request->request->get('srId'))
  5044.                 );
  5045.             $contentNote "";
  5046.             foreach ($QD as $r) {
  5047.                 $contentNote .= $r->getNote();
  5048.                 $contentNote .= " , ";
  5049.             }
  5050.             foreach ($fdmData as $dt) {
  5051.                 $Content[] = $dt;
  5052.             }
  5053.             if ($Content) {
  5054.                 return new JsonResponse(array("success" => true"content" => $Content"contentNote" => $contentNote));
  5055.             }
  5056.             return new JsonResponse(array("success" => false));
  5057.         }
  5058.         return new JsonResponse(array("success" => false));
  5059.     }
  5060.     public function GetGrnListForEiAction(Request $request)
  5061.     {
  5062.         if ($request->isMethod('POST')) {
  5063.             $find_array = array(
  5064.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  5065.                 'approved' => GeneralConstant::APPROVED,
  5066.                 'invoiceTagged' => 1
  5067.             );
  5068.             $Content = [];
  5069.             $Content_obj = [];
  5070.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  5071.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  5072.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  5073.             if ($request->request->get('poId') != '')
  5074.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  5075.             if ($request->request->get('grnId') != '')
  5076.                 $find_array['grnId'] = $request->request->get('grnId');
  5077.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5078.             $QD_GRN $this->getDoctrine()
  5079.                 ->getRepository('ApplicationBundle\\Entity\\Grn')
  5080.                 ->findBy(
  5081.                     $find_array,
  5082.                     array(
  5083.                         'grnDate' => 'ASC'
  5084.                     )
  5085.                 );
  5086.             $poId 0;
  5087. //
  5088. //            $expense_id=$QD_GRN->getExpenseId()!=''?json_decode($QD_GRN->getExpenseId()):[];
  5089. //                $expense_list=$QD_GRN->getExpenseCost()!=''?json_decode($QD_GRN->getExpenseCost()):[];
  5090. //                $expense_tagged=$QD_GRN->getExpenseTagged()!=''?json_decode($QD_GRN->getExpenseTagged()):[];
  5091.             $partyId $request->request->get('partyId');
  5092.             $bill_details = [];
  5093.             $bill_details_data = [];
  5094.             $bill_details_for_grn = [];
  5095.             $exp_list InventoryConstant::$Expense_list_details;
  5096.             $supp_list Inventory::ProductSupplierList($this->getDoctrine()->getManager());
  5097.             $head_qry $this->getDoctrine()
  5098.                 ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  5099.                 ->findAll();
  5100.             $head_list = [];
  5101.             $head_list_by_advance = [];
  5102.             foreach ($head_qry as $data) {
  5103.                 $head_list[$data->getAccountsHeadId()] = array(
  5104.                     'id' => $data->getAccountsHeadId(),
  5105.                     'name' => $data->getName(),
  5106.                     'advanceTagged' => $data->getAdvanceTagged(),
  5107.                     'advanceOf' => $data->getAdvanceOf(),
  5108.                     'balance' => $data->getCurrentBalance()
  5109.                 );
  5110.                 if ($data->getAdvanceOf() != null && $data->getAdvanceOf() != && $data->getAdvanceOf() != '')
  5111.                     $head_list_by_advance[$data->getAdvanceOf()] = array(
  5112.                         'id' => $data->getAccountsHeadId(),
  5113.                         'name' => $data->getName(),
  5114.                         'advanceTagged' => $data->getAdvanceTagged(),
  5115.                         'advanceOf' => $data->getAdvanceOf(),
  5116.                         'balance' => $data->getCurrentBalance()
  5117.                     );
  5118.             }
  5119.             $exp_def_head = [];
  5120.             foreach ($exp_list as $key => $item) {
  5121.                 $def_settings $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  5122.                     'name' => $item['name'] . '_onsite_head'
  5123.                 ));
  5124.                 if ($def_settings)
  5125.                     $exp_def_head[$item['id']] = $def_settings->getData();
  5126.                 else
  5127.                     $exp_def_head[$item['id']] = '';
  5128.             }
  5129.             $bill_details_by_party = [];
  5130. //            System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($QD_GRN),'debug_data');
  5131. //            System::log_it($this->container->getParameter('kernel.root_dir'),$partyId,'debug_data');
  5132. //            System::log_it($this->container->getParameter('kernel.root_dir'),"\nexp list here".json_encode($exp_list),'debug_data');
  5133. //
  5134.             foreach ($QD_GRN as $key => $value) {
  5135.                 $expense_id $value->getExpenseId() != '' json_decode($value->getExpenseId(), true) : [];
  5136.                 $expense_list $value->getExpenseCost() != '' json_decode($value->getExpenseCost(), true) : [];
  5137.                 $expense_tagged $value->getExpenseTagged() != '' json_decode($value->getExpenseTagged(), true) : [];
  5138. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_id),'debug_data');
  5139. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_list),'debug_data');
  5140.                 foreach ($exp_list as $chabi => $entry) {
  5141. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nChabi ".$chabi,'debug_data');
  5142. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nkeys are ".array_keys($expense_id),'debug_data');
  5143.                     if (array_key_exists($chabi$expense_id)) {
  5144. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nFOUND KEY!! ",'debug_data');
  5145.                         if ($partyId == ''//all
  5146.                         {
  5147.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  5148.                                 $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  5149.                                 $advance_balance 0;
  5150.                                 if ($partyHeadId != 0) {
  5151.                                     $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  5152.                                     $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  5153.                                     $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  5154.                                 }
  5155.                                 $bill_details_by_party[$my_val][] = array(
  5156.                                     'partyId' => $my_val,
  5157.                                     'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  5158.                                     'partyHeadId' => $partyHeadId,
  5159.                                     'expTypeId' => $chabi,
  5160.                                     'expTypeName' => $exp_list[$chabi]['name'],
  5161.                                     'expTypeAlias' => $exp_list[$chabi]['alias'],
  5162.                                     'expAmount' => $expense_list[$chabi][$index],
  5163.                                     'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  5164.                                     'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  5165.                                     'AdvanceBalance' => $advance_balance,
  5166.                                     'grnId' => $value->getGrnId(),
  5167.                                     'grnName' => $value->getDocumentHash(),
  5168.                                 );
  5169.                             }
  5170.                         } else {
  5171.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  5172.                                 if (in_array($my_val$partyId)) {
  5173.                                     $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  5174.                                     $advance_balance 0;
  5175.                                     if ($partyHeadId != 0) {
  5176.                                         $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  5177.                                         $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  5178.                                         $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  5179.                                     }
  5180.                                     $bill_details_by_party[$my_val][] = array(
  5181.                                         'partyId' => $my_val,
  5182.                                         'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  5183.                                         'partyHeadId' => $partyHeadId,
  5184.                                         'expTypeId' => $chabi,
  5185.                                         'expTypeName' => $exp_list[$chabi]['name'],
  5186.                                         'expTypeAlias' => $exp_list[$chabi]['alias'],
  5187.                                         'expAmount' => $expense_list[$chabi][$index],
  5188.                                         'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  5189.                                         'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  5190.                                         'AdvanceBalance' => $advance_balance,
  5191.                                         'grnId' => $value->getGrnId(),
  5192.                                         'grnName' => $value->getDocumentHash(),
  5193.                                     );
  5194.                                 }
  5195.                             }
  5196.                         }
  5197.                     }
  5198.                 }
  5199.             }
  5200. //            $Content_obj=
  5201. //
  5202. //            foreach($Content_obj as $item)
  5203. //            {
  5204. //                $Content[]=$item;
  5205. //
  5206. //            }
  5207.             $list_of_keys array_keys($bill_details_by_party);
  5208.             if ($bill_details_by_party) {
  5209.                 return new JsonResponse(array("success" => true"content" => $bill_details_by_party'index' => $list_of_keys'h_l_b_a' => $head_list_by_advance));
  5210.             }
  5211.             return new JsonResponse(array("success" => false));
  5212.         }
  5213.         return new JsonResponse(array("success" => false));
  5214.     }
  5215.     public function GetServiceListForPiAction(Request $request)
  5216.     {
  5217.         if ($request->isMethod('POST')) {
  5218. //            $find_array=array(
  5219. //                'stage' =>  GeneralConstant::STAGE_PENDING_TAG,
  5220. //                'approved'=>GeneralConstant::APPROVED
  5221. //            );
  5222.             $Content = [];
  5223.             $Content_obj = [];
  5224.             $ContentService = [];
  5225.             $Content_service_obj = [];
  5226. //            $warehouse=Inventory::WarehouseList($this->getDoctrine()->getManager());
  5227. //            $poList=Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  5228. //            $productList=Inventory::ProductList($this->getDoctrine()->getManager());
  5229.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  5230.             if ($request->request->get('poId') != '')
  5231.                 $poId $request->request->get('poId');
  5232.             if ($request->request->get('grnId') != '')
  5233.                 $find_array['grnId'] = $request->request->get('grnId');
  5234.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5235.             //adding service data temporarily
  5236.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(
  5237.                 array('purchaseOrderId' => $poId));
  5238.             $multiply_type $po->getCurrencyMultiply();
  5239.             $multiply_rate $po->getCurrencyMultiplyRate();
  5240.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  5241.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  5242.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5243.                 array('purchaseOrderId' => $poId));
  5244.             foreach ($po_items as $item) {
  5245. //                $po_item_list[$item->getProductId()]=$item;
  5246.                 //temporary service add
  5247.                 if ($item->getType() == 2)
  5248.                     $Content_service_obj[$item->getId()] = array(
  5249.                         'serviceId' => $item->getServiceId(),
  5250.                         'poItemId' => $item->getId(),
  5251.                         'colorId' => 0,
  5252.                         'sizeId' => 0,
  5253.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  5254.                         'qty' => $item->getQty(),
  5255.                         'balance' => $item->getBalance(),
  5256.                         'unit_name' => '',
  5257.                         'unit_price' => $item->getPrice() * $multiplier,
  5258.                         'grn_id' => 0,
  5259.                     );
  5260.                 //temprary service add end
  5261.             }
  5262.             //temporary service data adding done
  5263.             $po_data = [];
  5264.             $po_data = array(
  5265.                 'docHash' => $po->getDocumentHash(),
  5266.                 'docDate' => $po->getPurchaseOrderDate(),
  5267.                 'supplierId' => $po->getSupplierId(),
  5268.                 'supplierName' => $po->getSupplierId(),
  5269.                 'vatRate' => $po->getVatRate(),
  5270.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  5271.                 'aitRate' => $po->getAitRate(),
  5272.                 'aitAmount' => $po->getAitAmount(),
  5273.                 'tdsRate' => $po->getTdsRate(),
  5274.                 'tdsAmount' => $po->getTdsAmount(),
  5275.                 'vdsRate' => $po->getVdsRate(),
  5276.                 'vdsAmount' => $po->getVdsAmount(),
  5277.                 'discountRate' => $po->getDiscountRate(),
  5278.                 'discountAmount' => $po->getVatAmount(),
  5279.             );
  5280.             foreach ($Content_obj as $item) {
  5281.                 $Content[] = $item;
  5282.             }
  5283.             foreach ($Content_service_obj as $item) {
  5284.                 $ContentService[] = $item;
  5285.             }
  5286.             if ($Content || $ContentService) {
  5287.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  5288.             }
  5289.             return new JsonResponse(array("success" => false));
  5290.         }
  5291.         return new JsonResponse(array("success" => false));
  5292.     }
  5293.     public function GetGrnListForPiAction(Request $request)
  5294.     {
  5295.         if ($request->isMethod('POST')) {
  5296.             $find_array = array(
  5297.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  5298.                 'approved' => GeneralConstant::APPROVED
  5299.             );
  5300.             $Content = [];
  5301.             $Content_obj = [];
  5302.             $ContentService = [];
  5303.             $Content_service_obj = [];
  5304.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  5305.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  5306.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  5307.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  5308.             if ($request->request->get('poId') != '')
  5309.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  5310.             if ($request->request->get('grnId') != '')
  5311.                 $find_array['grnId'] = $request->request->get('grnId');
  5312.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5313.             $QD_GRN $this->getDoctrine()
  5314.                 ->getRepository('ApplicationBundle\\Entity\\Grn')
  5315.                 ->findBy(
  5316.                     $find_array,
  5317.                     array(
  5318.                         'grnDate' => 'ASC'
  5319.                     )
  5320.                 );
  5321.             $poId 0;
  5322.             foreach ($QD_GRN as $value) {
  5323.                 $grn_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\GrnItem')->findBy(
  5324.                     array('grnId' => $value->getGrnId()));
  5325.                 $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5326.                     array('purchaseOrderId' => $value->getPurchaseOrderId()));
  5327.                 $poId $value->getPurchaseOrderId();
  5328.                 $po_item_list = [];
  5329.                 foreach ($po_items as $item) {
  5330.                     $po_item_list[$item->getProductId()] = $item;
  5331.                 }
  5332.                 foreach ($grn_items as $entry) {
  5333.                     //adding transaction
  5334. //                    System::log_it($this->container->getParameter('kernel.root_dir'),$entry->getProductId(),'debug_data');
  5335.                     $Content_obj[$entry->getId()] = array(
  5336.                         'productId' => $entry->getProductId(),
  5337.                         'poItemId' => $entry->getPurchaseOrderItemId(),
  5338.                         'productName' => $productList[$entry->getProductId()]['name'],
  5339.                         'colorId' => $entry->getColorId(),
  5340.                         'sizeId' => $entry->getSizeId(),
  5341.                         'qty' => isset($Content_obj[$entry->getId()]) ? $Content_obj[$entry->getId()]['qty'] + $entry->getQty() : $entry->getQty(),
  5342.                         'unit_name' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  5343. //                            'unit_price'=>$po_item_list[$entry->getProductId()]->getPrice(),
  5344.                         'unit_price' => $entry->getPrice(),
  5345.                         'grn_id' => $entry->getId(),
  5346.                     );
  5347.                 }
  5348. //            for
  5349.             }
  5350.             //adding service data temporarily
  5351.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(
  5352.                 array('purchaseOrderId' => $poId));
  5353.             $multiply_type $po->getCurrencyMultiply();
  5354.             $multiply_rate $po->getCurrencyMultiplyRate();
  5355.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  5356.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  5357.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5358.                 array('purchaseOrderId' => $poId));
  5359.             foreach ($po_items as $item) {
  5360. //                $po_item_list[$item->getProductId()]=$item;
  5361.                 //temporary service add
  5362.                 if ($item->getType() == 2)
  5363.                     $Content_service_obj[$item->getId()] = array(
  5364.                         'serviceId' => $item->getServiceId(),
  5365.                         'poItemId' => $item->getId(),
  5366.                         'colorId' => 0,
  5367.                         'sizeId' => 0,
  5368.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  5369.                         'qty' => $item->getQty(),
  5370.                         'balance' => $item->getBalance(),
  5371.                         'unit_name' => '',
  5372.                         'unit_price' => $item->getPrice() * $multiplier,
  5373.                         'grn_id' => 0,
  5374.                     );
  5375.                 //temprary service add end
  5376.             }
  5377.             //temporary service data adding done
  5378.             $po_data = [];
  5379.             $vatAmount $po->getVatAmount();
  5380.             $priceAfterDiscount $po->getSupplierPayableAmount() - $po->getVatAmount();
  5381.             $vatRate = ($vatAmount $priceAfterDiscount) * 100;
  5382.             $po_data = array(
  5383.                 'docHash' => $po->getDocumentHash(),
  5384.                 'docDate' => $po->getPurchaseOrderDate(),
  5385.                 'supplierId' => $po->getSupplierId(),
  5386.                 'supplierName' => $po->getSupplierId(),
  5387.                 'vatRate' => $vatRate,
  5388.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  5389.                 'aitRate' => $po->getAitRate(),
  5390.                 'aitAmount' => $po->getAitAmount(),
  5391.                 'tdsRate' => $po->getTdsRate(),
  5392.                 'tdsAmount' => $po->getTdsAmount(),
  5393.                 'vdsRate' => $po->getVdsRate(),
  5394.                 'vdsAmount' => $po->getVdsAmount(),
  5395.                 'discountRate' => $po->getDiscountRate(),
  5396. //                'discountAmount' => $po->getVatAmount(),
  5397.                 'vatAmount' => $vatAmount,
  5398.                 'discountAmount' => $po->getDiscountAmount(),
  5399.                 'supplierPayableAmount' => $po->getSupplierPayableAmount(),
  5400.                 'priceAfterDiscount' => $priceAfterDiscount
  5401.             );
  5402.             foreach ($Content_obj as $item) {
  5403.                 $Content[] = $item;
  5404.             }
  5405.             foreach ($Content_service_obj as $item) {
  5406.                 $ContentService[] = $item;
  5407.             }
  5408.             if ($Content) {
  5409.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  5410.             }
  5411.             return new JsonResponse(array("success" => false));
  5412.         }
  5413.         return new JsonResponse(array("success" => false));
  5414.     }
  5415.     public function GetPoDetailsForPiAction(Request $request$poId)
  5416.     {
  5417.     }
  5418.     public function GetPoDetailsAction(Request $request$poId)
  5419.     {
  5420.         if ($request->isMethod('POST')) {
  5421.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findBy(
  5422.                 array('purchaseOrderId' => $poId));
  5423.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5424.                 array('purchaseOrderId' => $poId));
  5425.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  5426.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5427.             $spec_type Inventory::SpecTypeList($this->getDoctrine()->getManager());
  5428.             $Content = [];
  5429.             $po_items_list = [];
  5430.             foreach ($po_items as $entry) {
  5431.                 $po_items_list[] = array(
  5432.                     'productId' => $entry->getProductId(),
  5433.                     'productName' => $productList[$entry->getProductId()]['name'],
  5434.                     'price' => $entry->getPrice(),
  5435.                     'unit' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  5436.                     'spec' => $spec_type[$productList[$entry->getProductId()]['spec_type']]['name'],
  5437.                     'received' => $entry->getReceived(),
  5438.                     'qty' => $entry->getQty(),
  5439.                     'balance' => $entry->getBalance()
  5440.                 );
  5441.             }
  5442.             $po_data = [];
  5443.             $po_data = array(
  5444.                 'docHash' => $po->getDocumentHash(),
  5445.                 'docDate' => $po->getPurchaseOrderDate(),
  5446.                 'supplierId' => $po->getSupplierId(),
  5447.                 'supplierName' => $po->getSupplierId(),
  5448.             );
  5449.             if ($po_data) {
  5450.                 return new JsonResponse(array("success" => true"content" => $po_data));
  5451.             }
  5452.             return new JsonResponse(array("success" => false));
  5453.         }
  5454.         return new JsonResponse(array("success" => false));
  5455.     }
  5456.     public function CreateSalesReplacementAction(Request $request)
  5457.     {
  5458.         $em $this->getDoctrine()->getManager();
  5459.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5460.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5461.         if ($request->isMethod('POST')) {
  5462.             $em $this->getDoctrine()->getManager();
  5463.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesReplacement']; //change
  5464.             $dochash $request->request->get('voucherNumber'); //change
  5465.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5466.             $approveRole $request->request->get('approvalRole');
  5467.             $approveHash $request->request->get('approvalHash');
  5468.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5469.                 $loginId$approveRole$approveHash)
  5470.             ) {
  5471.                 $this->addFlash(
  5472.                     'error',
  5473.                     'Sorry Couldnot insert Data.'
  5474.                 );
  5475.             } else {
  5476.                 if ($request->request->has('check_allowed'))
  5477.                     $check_allowed 1;
  5478.                 $StID Inventory::CreateNewSalesReplacement(
  5479.                     $this->getDoctrine()->getManager(),
  5480.                     $request->request,
  5481.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5482.                     $this->getLoggedUserCompanyId($request)
  5483.                 );
  5484.                 //now add Approval info
  5485.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5486.                 $approveRole 1;  //created
  5487.                 $options = array(
  5488.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5489.                     'notification_server' => $this->container->getParameter('notification_server'),
  5490.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5491.                     'url' => $this->generateUrl(
  5492.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesReplacement']]
  5493.                         ['entity_view_route_path_name']
  5494.                     )
  5495.                 );
  5496.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5497.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5498.                     $StID,
  5499.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5500.                 );
  5501.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesReplacement'], $StID,
  5502.                     $loginId,
  5503.                     $approveRole,
  5504.                     $request->request->get('approvalHash'));
  5505.                 $this->addFlash(
  5506.                     'success',
  5507.                     'Stock Transfer Added.'
  5508.                 );
  5509.                 $url $this->generateUrl(
  5510.                     'view_st'
  5511.                 );
  5512.                 return $this->redirect($url "/" $StID);
  5513.             }
  5514.         }
  5515.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  5516.             array(
  5517.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5518.             )
  5519.         );
  5520.         $INVLIST = [];
  5521.         foreach ($slotList as $slot) {
  5522.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5523.         }
  5524.         return $this->render('@Inventory/pages/input_forms/sales_replacement.html.twig',
  5525.             array(
  5526.                 'page_title' => 'Sales Replacement Note',
  5527.                 'warehouseList' => Inventory::WarehouseList($em),
  5528.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5529.                 'warehouseActionList' => $warehouse_action_list,
  5530.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5531.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5532.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5533.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5534.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5535.                 'prefix_list' => array(
  5536.                     [
  5537.                         'id' => 1,
  5538.                         'value' => 'GN',
  5539.                         'text' => 'GN'
  5540.                     ]
  5541.                 ),
  5542.                 'assoc_list' => array(
  5543.                     [
  5544.                         'id' => 1,
  5545.                         'value' => 1,
  5546.                         'text' => 'GN'
  5547.                     ]
  5548.                 ),
  5549.                 'INVLIST' => $INVLIST
  5550.             )
  5551.         );
  5552.     }
  5553.     public function SalesReplacementListAction(Request $request)
  5554.     {
  5555.         $q $this->getDoctrine()
  5556.             ->getRepository('ApplicationBundle\\Entity\\SalesReplacement')
  5557.             ->findBy(
  5558.                 array(
  5559.                     'status' => GeneralConstant::ACTIVE,
  5560.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5561. //                    'approved' =>  GeneralConstant::APPROVED,
  5562.                 )
  5563.             );
  5564.         $stage_list = array(
  5565.             => 'Pending',
  5566.             => 'Pending',
  5567.             => 'Complete',
  5568.             => 'Partial',
  5569.         );
  5570.         $data = [];
  5571.         foreach ($q as $entry) {
  5572.             $data[] = array(
  5573.                 'doc_date' => $entry->getSalesReplacementDate(),
  5574.                 'id' => $entry->getSalesReplacementId(),
  5575.                 'doc_hash' => $entry->getDocumentHash(),
  5576.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5577.                 'stage' => GeneralConstant::stageLabel($stage_list$entry->getStage())
  5578.             );
  5579.         }
  5580.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5581.             array(
  5582.                 'page_title' => 'Stock Transfer List',
  5583.                 'data' => $data
  5584.             )
  5585.         );
  5586.     }
  5587.     public function ViewSalesReplacementAction(Request $request$id)
  5588.     {
  5589.         $em $this->getDoctrine()->getManager();
  5590.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5591.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  5592.             array(
  5593.                 'page_title' => 'Stock Transfer',
  5594.                 'data' => $dt,
  5595.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5596.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5597.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5598.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5599.                     $id,
  5600.                     $dt['created_by'],
  5601.                     $dt['edited_by'])
  5602.             )
  5603.         );
  5604.     }
  5605.     public function PrintSalesReplacementAction(Request $request$id)
  5606.     {
  5607.         $em $this->getDoctrine()->getManager();
  5608.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5609.         $company_data Company::getCompanyData($em1);
  5610.         $document_mark = array(
  5611.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5612.             'copy' => ''
  5613.         );
  5614.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5615.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5616.                 array(
  5617.                     //full array here
  5618.                     'pdf' => true,
  5619.                     'page_title' => 'Stock Transfer',
  5620.                     'export' => 'pdf,print',
  5621.                     'data' => $dt,
  5622.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5623.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5624.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5625.                         array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5626.                         $id,
  5627.                         $dt['created_by'],
  5628.                         $dt['edited_by']),
  5629.                     'document_mark_image' => $document_mark['original'],
  5630.                     'company_name' => $company_data->getName(),
  5631.                     'company_data' => $company_data,
  5632.                     'company_address' => $company_data->getAddress(),
  5633.                     'company_image' => $company_data->getImage(),
  5634.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5635.                     'red' => 0
  5636.                 )
  5637.             );
  5638.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5639. //                'orientation' => 'landscape',
  5640. //                'enable-javascript' => true,
  5641. //                'javascript-delay' => 1000,
  5642.                 'no-stop-slow-scripts' => false,
  5643.                 'no-background' => false,
  5644.                 'lowquality' => false,
  5645.                 'encoding' => 'utf-8',
  5646. //            'images' => true,
  5647. //            'cookie' => array(),
  5648.                 'dpi' => 300,
  5649.                 'image-dpi' => 300,
  5650. //                'enable-external-links' => true,
  5651. //                'enable-internal-links' => true
  5652.             ));
  5653.             return new Response(
  5654.                 $pdf_response,
  5655.                 200,
  5656.                 array(
  5657.                     'Content-Type' => 'application/pdf',
  5658.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5659.                 )
  5660.             );
  5661.         }
  5662.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5663.             array(
  5664.                 'page_title' => 'Stock Transfer',
  5665.                 'export' => 'pdf,print',
  5666.                 'data' => $dt,
  5667.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5668.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5669.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5670.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5671.                     $id,
  5672.                     $dt['created_by'],
  5673.                     $dt['edited_by']),
  5674.                 'document_mark_image' => $document_mark['original'],
  5675.                 'company_name' => $company_data->getName(),
  5676.                 'company_data' => $company_data,
  5677.                 'company_address' => $company_data->getAddress(),
  5678.                 'company_image' => $company_data->getImage(),
  5679.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5680.                 'red' => 0
  5681.             )
  5682.         );
  5683.     }
  5684.     public function CreateStockTransferAction(Request $request)
  5685.     {
  5686.         $em $this->getDoctrine()->getManager();
  5687.         $companyId $this->getLoggedUserCompanyId($request);
  5688.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5689.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5690.         if ($request->isMethod('POST')) {
  5691.             $em $this->getDoctrine()->getManager();
  5692.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  5693.             $dochash $request->request->get('docHash'); //change
  5694.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5695.             $approveRole $request->request->get('approvalRole');
  5696.             $approveHash $request->request->get('approvalHash');
  5697.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5698.                 $loginId$approveRole$approveHash)
  5699.             ) {
  5700.                 $this->addFlash(
  5701.                     'error',
  5702.                     'Sorry Couldnot insert Data.'
  5703.                 );
  5704.             } else {
  5705.                 if ($request->request->has('check_allowed'))
  5706.                     $check_allowed 1;
  5707.                 $StID Inventory::CreateNewStockTransfer(
  5708.                     $this->getDoctrine()->getManager(),
  5709.                     $request->request,
  5710.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5711.                     $this->getLoggedUserCompanyId($request)
  5712.                 );
  5713.                 //now add Approval info
  5714.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5715.                 $approveRole 1;  //created
  5716.                 $options = array(
  5717.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5718.                     'notification_server' => $this->container->getParameter('notification_server'),
  5719.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5720.                     'url' => $this->generateUrl(
  5721.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  5722.                         ['entity_view_route_path_name']
  5723.                     )
  5724.                 );
  5725.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5726.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5727.                     $StID,
  5728.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  5729.                 );
  5730.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  5731.                     $loginId,
  5732.                     $approveRole,
  5733.                     $request->request->get('approvalHash'));
  5734.                 $this->addFlash(
  5735.                     'success',
  5736.                     'Stock Transfer Added.'
  5737.                 );
  5738.                 $url $this->generateUrl(
  5739.                     'view_st'
  5740.                 );
  5741.                 return $this->redirect($url "/" $StID);
  5742.             }
  5743.         }
  5744. //        $slotList = $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  5745. //            array(
  5746. //                'CompanyId' => $this->getLoggedUserCompanyId($request),
  5747. //
  5748. //            )
  5749. //        );
  5750.         $INVLIST = [];
  5751. //        foreach ($slotList as $slot) {
  5752. //            $INVLIST[$slot->getWarehouseId() . '_' . $slot->getActionTagId() . '_' . $slot->getproductId()] = $slot->getQty();
  5753. //        }
  5754.         return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  5755.             array(
  5756.                 'page_title' => 'Stock Transfer Note',
  5757.                 'warehouseList' => Inventory::WarehouseList($em),
  5758.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5759.                 'colorList' => Inventory::GetColorList($em),
  5760.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  5761.                 'srList' => [],
  5762.                 'warehouseActionList' => $warehouse_action_list,
  5763.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5764.                 'item_list' => Inventory::ItemGroupList($em),
  5765.                 'item_list_array' => Inventory::ItemGroupListArray($em),
  5766.                 'category_list_array' => Inventory::ProductCategoryListArray($em),
  5767.                 'product_list_array' => Inventory::ProductListDetailedArray($em),
  5768. //                'product_list_array' => [],
  5769.                 'product_list' => Inventory::ProductList($em$companyId),
  5770. //                'product_list' => [],
  5771.                 'prefix_list' => array(
  5772.                     [
  5773.                         'id' => 1,
  5774.                         'value' => 'GN',
  5775.                         'text' => 'GN'
  5776.                     ]
  5777.                 ),
  5778.                 'assoc_list' => array(
  5779.                     [
  5780.                         'id' => 1,
  5781.                         'value' => 1,
  5782.                         'text' => 'GN'
  5783.                     ]
  5784.                 ),
  5785.                 'INVLIST' => $INVLIST
  5786.             )
  5787.         );
  5788.     }
  5789.     public function GetSrItemForTransferAction(Request $request)
  5790.     {
  5791.         $em $this->getDoctrine()->getManager();
  5792.         $search_query = [];
  5793.         $res_data_by_so_item_id = [];
  5794.         $Content = [];
  5795.         $productionProcessSettings = array(
  5796.             'id' => 0
  5797.         );
  5798.         if ($request->query->has('srId'))
  5799.             $search_query['stockRequisitionId'] = $request->query->get('srId');
  5800.         $DT $this->getDoctrine()
  5801.             ->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')
  5802.             ->findBy(
  5803.                 $search_query
  5804.             );
  5805.         $Content = array(
  5806.             'requisitioned_product_item_id' => [],
  5807.             'requisitioned_products' => [],
  5808.             'requisitioned_product_fdm' => [],
  5809.             'requisitioned_product_name' => [],
  5810.             'requisitioned_product_units' => [],
  5811.             'requisitioned_product_unit_type' => [],
  5812.             'requisitioned_product_balance' => [],
  5813.         );
  5814.         foreach ($DT as $dt) {
  5815. //            $data=json_decode($DT->getData(),true);
  5816.             $Content['requisitioned_products'][] = $dt->getProductId();
  5817.             $Content['requisitioned_product_item_id'][] = $dt->getId();
  5818.             $Content['requisitioned_product_fdm'][] = $dt->getProductFdm();
  5819.             $Content['requisitioned_product_name'][] = $dt->getProductNameFdm();
  5820.             $Content['requisitioned_product_units'][] = $dt->getQty();
  5821.             $Content['requisitioned_product_balance'][] = $dt->getAlottmentPendingAmount();
  5822.         }
  5823.         $INVLIST = [];
  5824.         if (!empty($Content)) {
  5825.             return new JsonResponse(array("success" => true"content" => $Content"INVLIST" => $INVLIST));
  5826.         } else {
  5827.             return new JsonResponse(array("success" => false"content" => $Content"INVLIST" => $INVLIST));
  5828.         }
  5829.     }
  5830.     public function StockTransferListAction(Request $request)
  5831.     {
  5832.         $q $this->getDoctrine()
  5833.             ->getRepository('ApplicationBundle\\Entity\\StockTransfer')
  5834.             ->findBy(
  5835.                 array(
  5836.                     'status' => GeneralConstant::ACTIVE,
  5837.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5838. //                    'approved' =>  GeneralConstant::APPROVED,
  5839.                 )
  5840.             );
  5841.         $stage_list = array(
  5842.             => 'Pending',
  5843.             => 'Pending',
  5844.             => 'Complete',
  5845.             => 'Partial',
  5846.         );
  5847.         $data = [];
  5848.         foreach ($q as $entry) {
  5849.             $data[] = array(
  5850.                 'doc_date' => $entry->getStockTransferDate(),
  5851.                 'id' => $entry->getStockTransferId(),
  5852.                 'doc_hash' => $entry->getDocumentHash(),
  5853.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5854.                 'stage' => GeneralConstant::stageLabel($stage_list$entry->getStage())
  5855.             );
  5856.         }
  5857.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5858.             array(
  5859.                 'page_title' => 'Stock Transfer List',
  5860.                 'data' => $data
  5861.             )
  5862.         );
  5863.     }
  5864.     public function ViewStockTransferAction(Request $request$id)
  5865.     {
  5866.         $em $this->getDoctrine()->getManager();
  5867.         $dt Inventory::GetStockTransferDetails($em$id);
  5868.         return $this->render(
  5869.             '@Inventory/pages/views/view_stock_transfer.html.twig',
  5870.             array(
  5871.                 'page_title' => 'Stock Transfer',
  5872.                 'data' => $dt,
  5873.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5874.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5875.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5876.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5877.                     $id,
  5878.                     $dt['created_by'],
  5879.                     $dt['edited_by'])
  5880.             )
  5881.         );
  5882.     }
  5883.     public function PrintStockTransferAction(Request $request$id)
  5884.     {
  5885.         $em $this->getDoctrine()->getManager();
  5886.         $dt Inventory::GetStockTransferDetails($em$id);
  5887.         $company_data Company::getCompanyData($em1);
  5888.         $document_mark = array(
  5889.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5890.             'copy' => ''
  5891.         );
  5892.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5893.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5894.                 array(
  5895.                     //full array here
  5896.                     'pdf' => true,
  5897.                     'page_title' => 'Stock Transfer',
  5898.                     'export' => 'pdf,print',
  5899.                     'data' => $dt,
  5900.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5901.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5902.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5903.                         array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5904.                         $id,
  5905.                         $dt['created_by'],
  5906.                         $dt['edited_by']),
  5907.                     'document_mark_image' => $document_mark['original'],
  5908.                     'company_name' => $company_data->getName(),
  5909.                     'company_data' => $company_data,
  5910.                     'company_address' => $company_data->getAddress(),
  5911.                     'company_image' => $company_data->getImage(),
  5912.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5913.                     'red' => 0
  5914.                 )
  5915.             );
  5916.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5917. //                'orientation' => 'landscape',
  5918. //                'enable-javascript' => true,
  5919. //                'javascript-delay' => 1000,
  5920.                 'no-stop-slow-scripts' => false,
  5921.                 'no-background' => false,
  5922.                 'lowquality' => false,
  5923.                 'encoding' => 'utf-8',
  5924. //            'images' => true,
  5925. //            'cookie' => array(),
  5926.                 'dpi' => 300,
  5927.                 'image-dpi' => 300,
  5928. //                'enable-external-links' => true,
  5929. //                'enable-internal-links' => true
  5930.             ));
  5931.             return new Response(
  5932.                 $pdf_response,
  5933.                 200,
  5934.                 array(
  5935.                     'Content-Type' => 'application/pdf',
  5936.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5937.                 )
  5938.             );
  5939.         }
  5940.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5941.             array(
  5942.                 'page_title' => 'Stock Transfer',
  5943.                 'export' => 'pdf,print',
  5944.                 'data' => $dt,
  5945.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5946.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5947.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5948.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5949.                     $id,
  5950.                     $dt['created_by'],
  5951.                     $dt['edited_by']),
  5952.                 'document_mark_image' => $document_mark['original'],
  5953.                 'company_name' => $company_data->getName(),
  5954.                 'company_data' => $company_data,
  5955.                 'company_address' => $company_data->getAddress(),
  5956.                 'company_image' => $company_data->getImage(),
  5957.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5958.                 'red' => 0
  5959.             )
  5960.         );
  5961.     }
  5962.     public function CreateStockConsumptionNoteAction(Request $request)
  5963.     {
  5964.         $em $this->getDoctrine()->getManager();
  5965.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5966.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5967.         if ($request->isMethod('POST')) {
  5968.             $em $this->getDoctrine()->getManager();
  5969.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']; //change
  5970.             $dochash $request->request->get('voucherNumber'); //change
  5971.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5972.             $approveRole $request->request->get('approvalRole');
  5973.             $approveHash $request->request->get('approvalHash');
  5974.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5975.                 $loginId$approveRole$approveHash)
  5976.             ) {
  5977.                 $this->addFlash(
  5978.                     'error',
  5979.                     'Sorry Could not insert Data.'
  5980.                 );
  5981.             } else {
  5982.                 if ($request->request->has('check_allowed'))
  5983.                     $check_allowed 1;
  5984.                 $StID Inventory::CreateNewStockConsumptionNote(
  5985.                     $this->getDoctrine()->getManager(),
  5986.                     $request->request,
  5987.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5988.                     $this->getLoggedUserCompanyId($request)
  5989.                 );
  5990.                 //now add Approval info
  5991.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5992.                 $approveRole 1;  //created
  5993.                 $options = array(
  5994.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5995.                     'notification_server' => $this->container->getParameter('notification_server'),
  5996.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5997.                     'url' => $this->generateUrl(
  5998.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']]
  5999.                         ['entity_view_route_path_name']
  6000.                     )
  6001.                 );
  6002.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6003.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6004.                     $StID,
  6005.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6006.                 );
  6007.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'], $StID,
  6008.                     $loginId,
  6009.                     $approveRole,
  6010.                     $request->request->get('approvalHash'));
  6011.                 $this->addFlash(
  6012.                     'success',
  6013.                     'Stock Consumption Added.'
  6014.                 );
  6015.                 $url $this->generateUrl(
  6016.                     'view_stock_consumption_note'
  6017.                 );
  6018.                 return $this->redirect($url "/" $StID);
  6019.             }
  6020.         }
  6021.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  6022.             array(
  6023.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6024.             )
  6025.         );
  6026.         $INVLIST = [];
  6027.         foreach ($slotList as $slot) {
  6028.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  6029.         }
  6030.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  6031.             array(
  6032.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6033.             )
  6034.         );
  6035.         $consumptionTypeList = [];
  6036.         $consumptionTypeListArray = [];
  6037.         foreach ($consumptionTypeQry as $entry) {
  6038.             $p = array(
  6039.                 'name' => $entry->getName(),
  6040.                 'id' => $entry->getConsumptionTypeId(),
  6041.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  6042.                 'cost_center_id' => $entry->getCostCenterId(),
  6043.             );
  6044.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  6045.             $consumptionTypeListArray[] = $p;
  6046.         }
  6047.         //add bill list
  6048.         $service_purchase_bill_query $this->getDoctrine()
  6049.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  6050.             ->findBy(
  6051.                 array(
  6052.                     'typeHash' => 'SPB',
  6053.                     'approved' => GeneralConstant::APPROVED
  6054.                 )
  6055.             );
  6056.         $service_purchase_bill_list = [];
  6057.         $service_purchase_bill_list_array = [];
  6058.         $bill = array(
  6059.             'id' => 0,
  6060.             'type' => 'SPB',
  6061.             'name' => 'New Expense',
  6062.             'text' => 'New Expense',
  6063.             'amount' => 0,
  6064.         );
  6065.         $service_purchase_bill_list[0] = $bill;
  6066.         $service_purchase_bill_list_array[] = $bill;
  6067.         foreach ($service_purchase_bill_query as $d) {
  6068.             $bill = array(
  6069.                 'id' => $d->getPurchaseInvoiceId(),
  6070.                 'type' => 'SPB',
  6071.                 'name' => $d->getDocumentHash(),
  6072.                 'text' => $d->getDocumentHash(),
  6073.                 'amount' => $d->getInvoiceAmount(),
  6074.             );
  6075.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  6076.             $service_purchase_bill_list_array[] = $bill;
  6077.         }
  6078.         return $this->render('@Inventory/pages/input_forms/stock_consumption_note.html.twig',
  6079.             array(
  6080.                 'page_title' => 'Stock Consumption Note',
  6081.                 'warehouseList' => Inventory::WarehouseList($em),
  6082.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  6083.                 'consumptionTypeList' => $consumptionTypeList,
  6084.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  6085.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  6086.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6087.                 'warehouseActionList' => $warehouse_action_list,
  6088.                 'warehouseActionListArray' => $warehouse_action_list_array,
  6089.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6090.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6091.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6092.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6093.                 'product_list' => Inventory::ProductListDetailed($this->getDoctrine()->getManager()),
  6094.                 'prefix_list' => array(
  6095.                     [
  6096.                         'id' => 1,
  6097.                         'value' => 'GN',
  6098.                         'text' => 'GN'
  6099.                     ]
  6100.                 ),
  6101.                 'assoc_list' => array(
  6102.                     [
  6103.                         'id' => 1,
  6104.                         'value' => 1,
  6105.                         'text' => 'GN'
  6106.                     ]
  6107.                 ),
  6108.                 'INVLIST' => $INVLIST,
  6109.                 'project_list_array' => ProjectM::GetProjectList($em)
  6110.             )
  6111.         );
  6112.     }
  6113.     public function StockConsumptionNoteListAction(Request $request)
  6114.     {
  6115.         $q $this->getDoctrine()
  6116.             ->getRepository('ApplicationBundle\\Entity\\StockConsumptionNote')
  6117.             ->findBy(
  6118.                 array(
  6119.                     'status' => GeneralConstant::ACTIVE,
  6120.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  6121. //                    'approved' =>  GeneralConstant::APPROVED,
  6122.                 )
  6123.             );
  6124.         $stage_list = array(
  6125.             => 'Pending',
  6126.             => 'Pending',
  6127.             => 'Complete',
  6128.             => 'Partial',
  6129.         );
  6130.         $data = [];
  6131.         foreach ($q as $entry) {
  6132.             $data[] = array(
  6133.                 'doc_date' => $entry->getStockConsumptionNoteDate(),
  6134.                 'id' => $entry->getStockConsumptionNoteId(),
  6135.                 'doc_hash' => $entry->getDocumentHash(),
  6136.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  6137.                 'stage' => GeneralConstant::stageLabel($stage_list$entry->getStage())
  6138.             );
  6139.         }
  6140.         return $this->render('@Inventory/pages/views/stock_consumption_note_list.html.twig',
  6141.             array(
  6142.                 'page_title' => 'Stock Consumption Note List',
  6143.                 'data' => $data
  6144.             )
  6145.         );
  6146.     }
  6147.     public function ViewStockConsumptionNoteAction(Request $request$id)
  6148.     {
  6149.         $em $this->getDoctrine()->getManager();
  6150.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  6151.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  6152.             array(
  6153.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6154.             )
  6155.         );
  6156.         $consumptionTypeList = [];
  6157.         $consumptionTypeListArray = [];
  6158.         foreach ($consumptionTypeQry as $entry) {
  6159.             $p = array(
  6160.                 'name' => $entry->getName(),
  6161.                 'id' => $entry->getConsumptionTypeId(),
  6162.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  6163.                 'cost_center_id' => $entry->getCostCenterId(),
  6164.             );
  6165.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  6166.             $consumptionTypeListArray[] = $p;
  6167.         }
  6168.         //add bill list
  6169.         $service_purchase_bill_query $this->getDoctrine()
  6170.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  6171.             ->findBy(
  6172.                 array(
  6173.                     'typeHash' => 'SPB',
  6174.                     'approved' => GeneralConstant::APPROVED
  6175.                 )
  6176.             );
  6177.         $service_purchase_bill_list = [];
  6178.         $service_purchase_bill_list_array = [];
  6179.         $bill = array(
  6180.             'id' => 0,
  6181.             'type' => 'SPB',
  6182.             'name' => 'New Expense',
  6183.             'text' => 'New Expense',
  6184.             'amount' => 0,
  6185.         );
  6186.         $service_purchase_bill_list[0] = $bill;
  6187.         $service_purchase_bill_list_array[] = $bill;
  6188.         foreach ($service_purchase_bill_query as $d) {
  6189.             $bill = array(
  6190.                 'id' => $d->getPurchaseInvoiceId(),
  6191.                 'type' => 'SPB',
  6192.                 'name' => $d->getDocumentHash(),
  6193.                 'text' => $d->getDocumentHash(),
  6194.                 'amount' => $d->getInvoiceAmount(),
  6195.             );
  6196.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  6197.             $service_purchase_bill_list_array[] = $bill;
  6198.         }
  6199.         return $this->render(
  6200.             '@Inventory/pages/views/view_stock_consumption_note.html.twig',
  6201.             array(
  6202.                 'page_title' => 'Stock Transfer',
  6203.                 'data' => $dt,
  6204.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  6205.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6206.                 'consumptionTypeList' => $consumptionTypeList,
  6207.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  6208.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6209.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6210.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6211.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6212.                     $id,
  6213.                     $dt['created_by'],
  6214.                     $dt['edited_by'])
  6215.             )
  6216.         );
  6217.     }
  6218.     public function PrintStockConsumptionNoteAction(Request $request$id)
  6219.     {
  6220.         $em $this->getDoctrine()->getManager();
  6221.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  6222.         $company_data Company::getCompanyData($em1);
  6223.         $document_mark = array(
  6224.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6225.             'copy' => ''
  6226.         );
  6227.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  6228.             array(
  6229.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6230.             )
  6231.         );
  6232.         $consumptionTypeList = [];
  6233.         $consumptionTypeListArray = [];
  6234.         foreach ($consumptionTypeQry as $entry) {
  6235.             $p = array(
  6236.                 'name' => $entry->getName(),
  6237.                 'id' => $entry->getConsumptionTypeId(),
  6238.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  6239.                 'cost_center_id' => $entry->getCostCenterId(),
  6240.             );
  6241.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  6242.             $consumptionTypeListArray[] = $p;
  6243.         }
  6244.         //add bill list
  6245.         $service_purchase_bill_query $this->getDoctrine()
  6246.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  6247.             ->findBy(
  6248.                 array(
  6249.                     'typeHash' => 'SPB',
  6250.                     'approved' => GeneralConstant::APPROVED
  6251.                 )
  6252.             );
  6253.         $service_purchase_bill_list = [];
  6254.         $service_purchase_bill_list_array = [];
  6255.         $bill = array(
  6256.             'id' => 0,
  6257.             'type' => 'SPB',
  6258.             'name' => 'New Expense',
  6259.             'text' => 'New Expense',
  6260.             'amount' => 0,
  6261.         );
  6262.         $service_purchase_bill_list[0] = $bill;
  6263.         $service_purchase_bill_list_array[] = $bill;
  6264.         foreach ($service_purchase_bill_query as $d) {
  6265.             $bill = array(
  6266.                 'id' => $d->getPurchaseInvoiceId(),
  6267.                 'type' => 'SPB',
  6268.                 'name' => $d->getDocumentHash(),
  6269.                 'text' => $d->getDocumentHash(),
  6270.                 'amount' => $d->getInvoiceAmount(),
  6271.             );
  6272.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  6273.             $service_purchase_bill_list_array[] = $bill;
  6274.         }
  6275.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6276.             $html $this->renderView('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  6277.                 array(
  6278.                     //full array here
  6279.                     'pdf' => true,
  6280.                     'page_title' => 'Stock Consumption',
  6281.                     'export' => 'pdf,print',
  6282.                     'data' => $dt,
  6283.                     'service_purchase_bill_list' => $service_purchase_bill_list,
  6284.                     'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6285.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6286.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6287.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6288.                         array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6289.                         $id,
  6290.                         $dt['created_by'],
  6291.                         $dt['edited_by']),
  6292.                     'document_mark_image' => $document_mark['original'],
  6293.                     'consumptionTypeList' => $consumptionTypeList,
  6294.                     'consumptionTypeListArray' => $consumptionTypeListArray,
  6295.                     'company_name' => $company_data->getName(),
  6296.                     'company_data' => $company_data,
  6297.                     'company_address' => $company_data->getAddress(),
  6298.                     'company_image' => $company_data->getImage(),
  6299.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6300.                     'red' => 0
  6301.                 )
  6302.             );
  6303.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6304. //                'orientation' => 'landscape',
  6305. //                'enable-javascript' => true,
  6306. //                'javascript-delay' => 1000,
  6307.                 'no-stop-slow-scripts' => false,
  6308.                 'no-background' => false,
  6309.                 'lowquality' => false,
  6310.                 'encoding' => 'utf-8',
  6311. //            'images' => true,
  6312. //            'cookie' => array(),
  6313.                 'dpi' => 300,
  6314.                 'image-dpi' => 300,
  6315. //                'enable-external-links' => true,
  6316. //                'enable-internal-links' => true
  6317.             ));
  6318.             return new Response(
  6319.                 $pdf_response,
  6320.                 200,
  6321.                 array(
  6322.                     'Content-Type' => 'application/pdf',
  6323.                     'Content-Disposition' => 'attachment; filename="stock_consumption_note_' $id '.pdf"'
  6324.                 )
  6325.             );
  6326.         }
  6327.         return $this->render('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  6328.             array(
  6329.                 'page_title' => 'Stock Consumption',
  6330.                 'export' => 'pdf,print',
  6331.                 'data' => $dt,
  6332.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  6333.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6334.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6335.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6336.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6337.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6338.                     $id,
  6339.                     $dt['created_by'],
  6340.                     $dt['edited_by']),
  6341.                 'document_mark_image' => $document_mark['original'],
  6342.                 'consumptionTypeList' => $consumptionTypeList,
  6343.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  6344.                 'company_name' => $company_data->getName(),
  6345.                 'company_data' => $company_data,
  6346.                 'company_address' => $company_data->getAddress(),
  6347.                 'company_image' => $company_data->getImage(),
  6348.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6349.                 'red' => 0
  6350.             )
  6351.         );
  6352.     }
  6353.     public function CreateStockReceivedNoteAction(Request $request$id 0)
  6354.     {
  6355.         $em $this->getDoctrine()->getManager();
  6356.         $companyId $this->getLoggedUserCompanyId($request);
  6357.         $extDocData = [];
  6358.         $userId $request->getSession()->get(UserConstants::USER_ID);
  6359.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  6360.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  6361. //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  6362.         $userBranchIdList $request->getSession()->get('branchIdList');
  6363.         if ($userBranchIdList == null$userBranchIdList = [];
  6364.         $userBranchId $request->getSession()->get('branchId');
  6365.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  6366.             $em $this->getDoctrine()->getManager();
  6367.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //change
  6368.             $dochash $request->request->get('docHash'); //change
  6369.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6370.             $approveRole $request->request->get('approvalRole');
  6371.             $approveHash $request->request->get('approvalHash');
  6372.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6373.                 $loginId$approveRole$approveHash$id)
  6374.             ) {
  6375.                 if ($request->request->has('returnJson')) {
  6376.                     return new JsonResponse(array(
  6377.                         'success' => false,
  6378.                         'documentHash' => 0,
  6379.                         'documentId' => 0,
  6380.                         'billIds' => [],
  6381.                         'drIds' => [],
  6382.                         'pmntTransIds' => [],
  6383.                         'viewUrl' => '',
  6384.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  6385.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  6386.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  6387.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  6388.                     ));
  6389.                 } else
  6390.                     $this->addFlash(
  6391.                         'error',
  6392.                         'Sorry Could not insert Data.'
  6393.                     );
  6394.             } else {
  6395.                 if ($request->request->has('check_allowed'))
  6396.                     $check_allowed 1;
  6397.                 try {
  6398.                     $StID Inventory::CreateNewStockReceivedNote(
  6399.                         $this->getDoctrine()->getManager(),
  6400.                         $request->request,
  6401.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6402.                         $this->getLoggedUserCompanyId($request),
  6403.                         0,
  6404.                         (int) $id   // edit id from the route â†’ update in place instead of duplicating
  6405.                     );
  6406.                 } catch (\InvalidArgumentException $e) {
  6407.                     if ($request->request->has('returnJson')) {
  6408.                         return new JsonResponse(array(
  6409.                             'success' => false,
  6410.                             'message' => $e->getMessage(),
  6411.                         ));
  6412.                     }
  6413.                     $this->addFlash('error'$e->getMessage());
  6414.                     return $this->redirect($request->getUri());
  6415.                 } catch (\Exception $e) {
  6416.                     if ($request->request->has('returnJson')) {
  6417.                         return new JsonResponse(array(
  6418.                             'success' => false,
  6419.                             'message' => 'Sorry Could not insert Data.',
  6420.                         ));
  6421.                     }
  6422.                     $this->addFlash('error''Sorry Could not insert Data.');
  6423.                     return $this->redirect($request->getUri());
  6424.                 }
  6425.                 //now add Approval info
  6426.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6427.                 $approveRole 1;  //created
  6428.                 $options = array(
  6429.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6430.                     'notification_server' => $this->container->getParameter('notification_server'),
  6431.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6432.                     'url' => $this->generateUrl(
  6433.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  6434.                         ['entity_view_route_path_name']
  6435.                     )
  6436.                 );
  6437.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6438.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6439.                     $StID,
  6440.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6441.                 );
  6442.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  6443.                     $loginId,
  6444.                     $approveRole,
  6445.                     $request->request->get('approvalHash'));
  6446.                 $url $this->generateUrl(
  6447.                     'view_srcv'
  6448.                 );
  6449.                 if ($request->request->has('returnJson')) {
  6450.                     return new JsonResponse(array(
  6451.                         'success' => true,
  6452.                         'documentHash' => $dochash,
  6453.                         'documentId' => $StID,
  6454.                         'viewUrl' => $url "/" $StID,
  6455.                     ));
  6456.                 } else {
  6457.                     $this->addFlash(
  6458.                         'success',
  6459.                         'Stock Received Note Added.'
  6460.                     );
  6461.                     return $this->redirect($url "/" $StID);
  6462.                 }
  6463.             }
  6464.         }
  6465.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  6466.             array(
  6467.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6468.             )
  6469.         );
  6470.         $extDocItems = [];
  6471.         if ($id == 0) {
  6472.         } else {
  6473.             $extDoc $em->getRepository('ApplicationBundle\Entity\StockReceivedNote')->findOneBy(
  6474.                 array(
  6475.                     'stockReceivedNoteId' => $id,
  6476.                 )
  6477.             );
  6478.             //now if its not editable, redirect to view
  6479.             if ($extDoc) {
  6480.                 if ($extDoc->getEditFlag() != 1) {
  6481.                     $url $this->generateUrl(
  6482.                         'view_srcv'
  6483.                     );
  6484.                     return $this->redirect($url "/" $id);
  6485.                 } else {
  6486.                     $extDocData $extDoc;
  6487.                     $extDocDataDetails $em->getRepository('ApplicationBundle\Entity\StockReceivedNoteItem')->findBy(
  6488.                         array(
  6489.                             'stockReceivedNoteId' => $id,
  6490.                         )
  6491.                     );
  6492.                     foreach ($extDocDataDetails as $itemEntry) {
  6493.                         $product $em->getRepository('ApplicationBundle\Entity\InvProducts')->findOneBy(
  6494.                             array('id' => $itemEntry->getProductId())
  6495.                         );
  6496.                         $extDocItems[] = array(
  6497.                             'productId' => $itemEntry->getProductId(),
  6498.                             'productName' => $product $product->getName() : '',
  6499.                             'warehouseId' => $itemEntry->getWarehouseId(),
  6500.                             'warehouseActionId' => $itemEntry->getWarehouseActionId(),
  6501.                             'qty' => $itemEntry->getQty(),
  6502.                             'price' => $itemEntry->getPrice(),
  6503.                             'warrantyMon' => $itemEntry->getWarrantyMon(),
  6504.                             'batchNo' => $itemEntry->getBatchNo(),
  6505.                             'mfgDate' => $itemEntry->getMfgDate() ? $itemEntry->getMfgDate()->format('Y-m-d') : '',
  6506.                             'expiryDate' => $itemEntry->getExpiryDate() ? $itemEntry->getExpiryDate()->format('Y-m-d') : '',
  6507.                         );
  6508.                     }
  6509.                 }
  6510.             } else {
  6511.             }
  6512.         }
  6513.         $INVLIST = [];
  6514.         foreach ($slotList as $slot) {
  6515.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  6516.         }
  6517.         $dataArray = array(
  6518.             'page_title' => 'Stock Received Note',
  6519. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  6520.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  6521.             'users' => Users::getUserListById($em),
  6522.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  6523.             'warehouseList' => Inventory::WarehouseList($em),
  6524.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  6525.             'warehouseActionList' => $warehouse_action_list,
  6526.             'warehouseActionListArray' => $warehouse_action_list_array,
  6527.             'extDocItems' => $extDocItems,
  6528.             'extDocData' => $extDocData,
  6529.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  6530.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6531.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6532.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6533. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6534. //            'product_list' => Inventory::ProductList($em, $companyId),
  6535.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  6536.             'prefix_list' => array(
  6537.                 [
  6538.                     'id' => 1,
  6539.                     'value' => 'GN',
  6540.                     'text' => 'GN'
  6541.                 ]
  6542.             ),
  6543.             'assoc_list' => array(
  6544.                 [
  6545.                     'id' => 1,
  6546.                     'value' => 1,
  6547.                     'text' => 'GN'
  6548.                 ]
  6549.             ),
  6550.             'INVLIST' => $INVLIST,
  6551.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  6552.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  6553.             'userBranchIdList' => $userBranchIdList,
  6554.             'userBranchId' => $userBranchId,
  6555. //            'headList' => Accounts::HeadList($em),
  6556.         );
  6557.         //json
  6558.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  6559.         {
  6560.             $dataArray['success'] = true;
  6561.             return new JsonResponse(
  6562.                 $dataArray
  6563.             );
  6564.         }
  6565.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  6566.             $dataArray
  6567.         );
  6568.     }
  6569.     public function GetItemListForStockReceivedAction(Request $request)
  6570.     {
  6571.         if ($request->isMethod('POST')) {
  6572.             $em $this->getDoctrine();
  6573.             $receiveType 1;//transfer
  6574.             if ($request->request->has('receiveType'))
  6575.                 $receiveType $request->request->get('receiveType');
  6576.             $QD = [];
  6577.             if ($receiveType == 1)
  6578.                 $QD $this->getDoctrine()
  6579.                     ->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  6580.                     ->findBy(
  6581.                         array(
  6582. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  6583.                             'stockTransferId' => $request->request->get('stId')
  6584.                         ),
  6585.                         array()
  6586.                     );
  6587.             if ($receiveType == 2)
  6588.                 $QD $this->getDoctrine()
  6589.                     ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  6590.                     ->findBy(
  6591.                         array(
  6592. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  6593.                             'salesOrderId' => $request->request->get('soId')
  6594.                         ),
  6595.                         array()
  6596.                     );
  6597. //            if($request->request->get('wareHouseId')!='')
  6598. //
  6599. //            $DO=$this->getDoctrine()
  6600. //                ->getRepository('ApplicationBundle\\Entity\\DeliveryOrder')
  6601. //                ->findOneBy(
  6602. //                    $find_array,
  6603. //                    array(
  6604. //
  6605. //                    )
  6606. //                );
  6607.             $sendData = array(
  6608. //                'salesType'=>$SO->getSalesType(),
  6609. //                'packageData'=>[],
  6610.                 'productList' => [],
  6611. //                'productListByPackage'=>[],
  6612.             );
  6613.             $productList Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request));
  6614.             $pckg_item_cross_match_data = [];
  6615.             foreach ($QD as $product) {
  6616. //                $b_code=json_decode($product->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  6617.                 $b_code = [];
  6618.                 $newProductId $product->getProductId();
  6619.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  6620.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6621.                     if ($to_analyze_codes_str != null)
  6622.                         $b_code json_decode($to_analyze_codes_strtrue512JSON_BIGINT_AS_STRING);
  6623.                     else
  6624.                         $b_code = [];
  6625.                 } else {
  6626.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6627.                     if ($to_analyze_codes_str != null) {
  6628.                         $max_int_length strlen((string)PHP_INT_MAX) - 1;
  6629.                         $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$to_analyze_codes_str);
  6630.                         $b_code json_decode($json_without_bigintstrue);
  6631.                     } else {
  6632.                         $b_code = [];
  6633.                     }
  6634.                 }
  6635.                 $b_code_data = [];
  6636.                 foreach ($b_code as $d) {
  6637.                     $b_code_data[] = array(
  6638.                         'id' => $d,
  6639.                         'name' => str_pad($d13'0'STR_PAD_LEFT),
  6640.                     );
  6641.                 }
  6642.                 $p_data = array(
  6643.                     'details_id' => $product->getId(),
  6644.                     'productId' => $product->getProductId(),
  6645.                     'product_name' => isset($productList[$product->getProductId()]) ? $productList[$product->getProductId()]['name'] : 'Unknown Product',
  6646.                     'product_barcodes' => $b_code_data,
  6647. //                    'available_inventory'=>$inventory_by_warehouse?$inventory_by_warehouse->getQty():0,
  6648. //                        'package_id'=>$product->getPackageId(),
  6649.                     'qty' => $receiveType == $product->getQty() : $product->getToBeReceived(),
  6650.                     'unit_price' => $receiveType == $product->getPrice() : $productList[$product->getProductId()]['purchase_price'],
  6651.                     'balance' => $receiveType == $product->getBalance() : ($product->getToBeReceived() - $product->getReceived()),
  6652. //                        'delivered'=>$product->getDelivered(),
  6653.                 );
  6654.                 $sendData['productList'][] = $p_data;
  6655.             }
  6656.             //now package data
  6657.             if ($sendData) {
  6658.                 return new JsonResponse(array("success" => true"content" => $sendData));
  6659.             }
  6660.             return new JsonResponse(array("success" => false));
  6661.         }
  6662.         return new JsonResponse(array("success" => false));
  6663.     }
  6664.     public function StockReceivedNoteListAction(Request $request)
  6665.     {
  6666.         $q $this->getDoctrine()
  6667.             ->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')
  6668.             ->findBy(
  6669.                 array(
  6670.                     'status' => GeneralConstant::ACTIVE,
  6671.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  6672. //                    'approved' =>  GeneralConstant::APPROVED,
  6673.                 )
  6674.             );
  6675.         $stage_list = array(
  6676.             => 'Pending',
  6677.             => 'Pending',
  6678.             => 'Complete',
  6679.             => 'Partial',
  6680.         );
  6681.         $data = [];
  6682.         foreach ($q as $entry) {
  6683.             $data[] = array(
  6684.                 'doc_date' => $entry->getStockReceivedNoteDate(),
  6685.                 'id' => $entry->getStockReceivedNoteId(),
  6686.                 'doc_hash' => $entry->getDocumentHash(),
  6687.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  6688.                 'stage' => GeneralConstant::stageLabel($stage_list$entry->getStage())
  6689.             );
  6690.         }
  6691.         return $this->render('@Inventory/pages/views/stock_received_note_list.html.twig',
  6692.             array(
  6693.                 'page_title' => 'Stock Received List',
  6694.                 'data' => $data
  6695.             )
  6696.         );
  6697.     }
  6698.     public function ViewStockReceivedNoteAction(Request $request$id)
  6699.     {
  6700.         $em $this->getDoctrine()->getManager();
  6701.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6702.         return $this->render(
  6703.             '@Inventory/pages/views/view_stock_received_note.html.twig',
  6704.             array(
  6705.                 'page_title' => 'Stock Received Note',
  6706.                 'data' => $dt,
  6707.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  6708.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6709.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6710.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6711.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6712.                     $id,
  6713.                     $dt['created_by'],
  6714.                     $dt['edited_by'])
  6715.             )
  6716.         );
  6717.     }
  6718.     public function PrintStockReceivedNoteAction(Request $request$id)
  6719.     {
  6720.         $em $this->getDoctrine()->getManager();
  6721.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6722.         $company_data Company::getCompanyData($em1);
  6723.         $document_mark = array(
  6724.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6725.             'copy' => ''
  6726.         );
  6727.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6728.             $html $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
  6729.                 array(
  6730.                     //full array here
  6731.                     'pdf' => true,
  6732.                     'page_title' => 'Stock Received Note',
  6733.                     'export' => 'pdf,print',
  6734.                     'data' => $dt,
  6735.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6736.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6737.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6738.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6739.                         $id,
  6740.                         $dt['created_by'],
  6741.                         $dt['edited_by']),
  6742.                     'document_mark_image' => $document_mark['original'],
  6743.                     'company_name' => $company_data->getName(),
  6744.                     'company_data' => $company_data,
  6745.                     'company_address' => $company_data->getAddress(),
  6746.                     'company_image' => $company_data->getImage(),
  6747.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6748.                     'red' => 0
  6749.                 )
  6750.             );
  6751.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6752. //                'orientation' => 'landscape',
  6753. //                'enable-javascript' => true,
  6754. //                'javascript-delay' => 1000,
  6755.                 'no-stop-slow-scripts' => false,
  6756.                 'no-background' => false,
  6757.                 'lowquality' => false,
  6758.                 'encoding' => 'utf-8',
  6759. //            'images' => true,
  6760. //            'cookie' => array(),
  6761.                 'dpi' => 300,
  6762.                 'image-dpi' => 300,
  6763. //                'enable-external-links' => true,
  6764. //                'enable-internal-links' => true
  6765.             ));
  6766.             return new Response(
  6767.                 $pdf_response,
  6768.                 200,
  6769.                 array(
  6770.                     'Content-Type' => 'application/pdf',
  6771.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  6772.                 )
  6773.             );
  6774.         }
  6775.         return $this->render('@Inventory/pages/print/print_stock_received_note.html.twig',
  6776.             array(
  6777.                 'page_title' => 'Stock Received Note',
  6778.                 'export' => 'pdf,print',
  6779.                 'data' => $dt,
  6780.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6781.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6782.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6783.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6784.                     $id,
  6785.                     $dt['created_by'],
  6786.                     $dt['edited_by']),
  6787.                 'document_mark_image' => $document_mark['original'],
  6788.                 'company_name' => $company_data->getName(),
  6789.                 'company_data' => $company_data,
  6790.                 'company_address' => $company_data->getAddress(),
  6791.                 'company_image' => $company_data->getImage(),
  6792.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6793.                 'red' => 0
  6794.             )
  6795.         );
  6796.     }
  6797.     public function CreateStoreRequisitionSlipAction(Request $request$id 0)
  6798.     {
  6799.         $em $this->getDoctrine()->getManager();
  6800. //        $id;
  6801.         if ($request->isMethod('POST')) {
  6802.             $em $this->getDoctrine()->getManager();
  6803.             $entity_id array_flip(GeneralConstant::$Entity_list)['StoreRequisition']; //change
  6804.             $dochash $request->request->get('voucherNumber'); //change
  6805.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6806.             $approveRole $request->request->get('approvalRole');
  6807.             $approveHash $request->request->get('approvalHash');
  6808.             $validation Inventory::ValidateStoreRequisitionSlip($request->request);
  6809.             if (!$validation['success']) {
  6810.                 $this->addFlash(
  6811.                     'error',
  6812.                     $validation['error']
  6813.                 );
  6814.             } else if (!DocValidation::isInsertable($em$entity_id$dochash,
  6815.                 $loginId$approveRole$approveHash$id)
  6816.             ) {
  6817.                 $this->addFlash(
  6818.                     'error',
  6819.                     'Sorry, could not insert Data.'
  6820.                 );
  6821.             } else {
  6822.                 if ($request->request->has('check_allowed'))
  6823.                     $check_allowed 1;
  6824.                 $IrID Inventory::CreateNewStoreRequisition($id,
  6825.                     $this->getDoctrine()->getManager(),
  6826.                     $request->request,
  6827.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6828.                     $this->getLoggedUserCompanyId($request)
  6829.                 );
  6830.                 //now add Approval info
  6831.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6832.                 $approveRole $request->request->get('approvalRole');
  6833.                 $options = array(
  6834.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6835.                     'notification_server' => $this->container->getParameter('notification_server'),
  6836.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6837.                     'url' => $this->generateUrl(
  6838.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StoreRequisition']]
  6839.                         ['entity_view_route_path_name']
  6840.                     )
  6841.                 );
  6842.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6843.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  6844.                     $IrID,
  6845.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6846.                 );
  6847.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StoreRequisition'], $IrID,
  6848.                     $loginId,
  6849.                     $approveRole,
  6850.                     $request->request->get('approvalHash'));
  6851.                 $this->addFlash(
  6852.                     'success',
  6853.                     'New Indent Added.'
  6854.                 );
  6855.                 $url $this->generateUrl(
  6856.                     'view_ir'
  6857.                 );
  6858.                 return $this->redirect($url "/" $IrID);
  6859.             }
  6860.         }
  6861.         $extDocData = [];
  6862.         $extDocDetailsData = [];
  6863.         if ($id == 0) {
  6864.         } else {
  6865.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StoreRequisition')->findOneBy(
  6866.                 array(
  6867.                     'storeRequisitionId' => $id///material
  6868.                 )
  6869.             );
  6870.             //now if its not editable, redirect to view
  6871.             if ($extDoc) {
  6872.                 if ($extDoc->getEditFlag() != 1) {
  6873.                     $url $this->generateUrl(
  6874.                         'view_ir'
  6875.                     );
  6876.                     return $this->redirect($url "/" $id);
  6877.                 } else {
  6878.                     $extDocData $extDoc;
  6879.                     $extDocDetailsData $em->getRepository('ApplicationBundle\\Entity\\StoreRequisitionItem')->findBy(
  6880.                         array(
  6881.                             'storeRequisitionId' => $id///material
  6882.                         )
  6883.                     );;
  6884.                 }
  6885.             } else {
  6886.             }
  6887.         }
  6888.         $companyId $this->getLoggedUserCompanyId($request);
  6889.         $productListArray = [];
  6890.         $subCategoryListArray = [];
  6891.         $categoryListArray = [];
  6892.         $igListArray = [];
  6893.         $unitListArray = [];
  6894.         $brandListArray = [];
  6895.         $productList Inventory::ProductList($em$companyId);
  6896.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6897.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6898.         $igList Inventory::ItemGroupList($em$companyId);
  6899.         $unitList Inventory::UnitTypeList($em);
  6900.         $brandList Inventory::GetBrandList($em$companyId);
  6901.         foreach ($productList as $product$productListArray[] = $product;
  6902.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6903.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6904.         foreach ($igList as $product$igListArray[] = $product;
  6905.         foreach ($unitList as $product$unitListArray[] = $product;
  6906.         foreach ($brandList as $product$brandListArray[] = $product;
  6907.         $sr_list = [];
  6908.         $QD $this->getDoctrine()
  6909.             ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  6910.             ->findBy(
  6911.                 array(
  6912.                     'indentTagged' => 0,
  6913.                     'approved' => 1
  6914.                 )
  6915.             );
  6916.         foreach ($QD as $dt) {
  6917.             $sr_list[$dt->getStockRequisitionId()] = array(
  6918.                 'id' => $dt->getStockRequisitionId(),
  6919.                 'name' => $dt->getDocumentHash(),
  6920.                 'text' => $dt->getDocumentHash(),
  6921.             );
  6922.         }
  6923.         return $this->render('@Inventory/pages/input_forms/store_requisition.html.twig',
  6924.             array(
  6925.                 'page_title' => 'Indent Requisition Slip',
  6926.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6927.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6928.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6929.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6930.                 'sr_list' => $sr_list,
  6931.                 'productList' => $productList,
  6932.                 'subCategoryList' => $subCategoryList,
  6933.                 'categoryList' => $categoryList,
  6934.                 'igList' => $igList,
  6935.                 'extId' => $id,
  6936.                 'extDocDetailsData' => $extDocDetailsData,
  6937.                 'extDocData' => $extDocData,
  6938.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6939.                 'unitList' => $unitList,
  6940.                 'brandList' => $brandList,
  6941.                 'brandListArray' => $brandListArray,
  6942.                 'productListArray' => $productListArray,
  6943.                 'subCategoryListArray' => $subCategoryListArray,
  6944.                 'categoryListArray' => $categoryListArray,
  6945.                 'igListArray' => $igListArray,
  6946.                 'unitListArray' => $unitListArray,
  6947.                 'prefix_list' => array(
  6948.                     [
  6949.                         'id' => 1,
  6950.                         'value' => 'GN',
  6951.                         'text' => 'General'
  6952.                     ],
  6953.                     [
  6954.                         'id' => 1,
  6955.                         'value' => 'SD',
  6956.                         'text' => 'For Sales Demand'
  6957.                     ]
  6958.                 ),
  6959.                 'assoc_list' => array(
  6960.                     [
  6961.                         'id' => 1,
  6962.                         'value' => 1,
  6963.                         'text' => 'GN'
  6964.                     ]
  6965.                 )
  6966.             )
  6967.         );
  6968.     }
  6969.     public function CreateStockRequisitionSlipAction(Request $request$id 0)
  6970.     {
  6971.         $em $this->getDoctrine()->getManager();
  6972.         if ($request->isMethod('POST')) {
  6973.             $em $this->getDoctrine()->getManager();
  6974.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockRequisition']; //change
  6975.             $dochash $request->request->get('voucherNumber'); //change
  6976.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6977.             $approveRole $request->request->get('approvalRole');
  6978.             $approveHash $request->request->get('approvalHash');
  6979.             $validation Inventory::ValidateStockRequisitionSlip($request->request);
  6980.             if (!$validation['success']) {
  6981.                 $this->addFlash(
  6982.                     'error',
  6983.                     $validation['error']
  6984.                 );
  6985.             } else if (!DocValidation::isInsertable($em$entity_id$dochash,
  6986.                 $loginId$approveRole$approveHash$id)
  6987.             ) {
  6988.                 $this->addFlash(
  6989.                     'error',
  6990.                     'Sorry, could not insert Data.'
  6991.                 );
  6992.             } else {
  6993.                 if ($request->request->has('check_allowed'))
  6994.                     $check_allowed 1;
  6995.                 $SrID Inventory::CreateNewStockRequisition($id,
  6996.                     $this->getDoctrine()->getManager(),
  6997.                     $request->request,
  6998.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6999.                     $this->getLoggedUserCompanyId($request)
  7000.                 );
  7001.                 //now add Approval info
  7002.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7003.                 $approveRole $request->request->get('approvalRole');
  7004.                 $options = array(
  7005.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  7006.                     'notification_server' => $this->container->getParameter('notification_server'),
  7007.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  7008.                     'url' => $this->generateUrl(
  7009.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockRequisition']]
  7010.                         ['entity_view_route_path_name']
  7011.                     )
  7012.                 );
  7013.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  7014.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  7015.                     $SrID,
  7016.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  7017.                 );
  7018.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockRequisition'], $SrID,
  7019.                     $loginId,
  7020.                     $approveRole,
  7021.                     $request->request->get('approvalHash'));
  7022.                 $this->addFlash(
  7023.                     'success',
  7024.                     'New Requisition Added.'
  7025.                 );
  7026.                 $url $this->generateUrl(
  7027.                     'view_sr'
  7028.                 );
  7029. //                return $this->redirect($url . "/" . $SrID);
  7030.             }
  7031.         }
  7032.         $extDocData = [];
  7033.         $extDocDetailsData = [];
  7034.         if ($id == 0) {
  7035.         } else {
  7036.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StockRequisition')->findOneBy(
  7037.                 array(
  7038.                     'stockRequisitionId' => $id///material
  7039.                 )
  7040.             );
  7041.             //now if its not editable, redirect to view
  7042.             if ($extDoc) {
  7043.                 if ($extDoc->getEditFlag() != 1) {
  7044.                     $url $this->generateUrl(
  7045.                         'view_sr'
  7046.                     );
  7047.                     return $this->redirect($url "/" $id);
  7048.                 } else {
  7049.                     $extDocData $extDoc;
  7050.                     $extDocDetailsData $em->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')->findBy(
  7051.                         array(
  7052.                             'stockRequisitionId' => $id///material
  7053.                         )
  7054.                     );;
  7055.                 }
  7056.             } else {
  7057.             }
  7058.         }
  7059.         $companyId $this->getLoggedUserCompanyId($request);
  7060.         $productListArray = [];
  7061.         $subCategoryListArray = [];
  7062.         $categoryListArray = [];
  7063.         $igListArray = [];
  7064.         $unitListArray = [];
  7065.         $brandListArray = [];
  7066.         $productList Inventory::ProductList($em$companyId);
  7067.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  7068.         $categoryList Inventory::ProductCategoryList($em$companyId);
  7069.         $igList Inventory::ItemGroupList($em$companyId);
  7070.         $unitList Inventory::UnitTypeList($em);
  7071.         $brandList Inventory::GetBrandList($em$companyId);
  7072.         foreach ($productList as $product$productListArray[] = $product;
  7073.         foreach ($categoryList as $product$categoryListArray[] = $product;
  7074.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  7075.         foreach ($igList as $product$igListArray[] = $product;
  7076.         foreach ($unitList as $product$unitListArray[] = $product;
  7077.         foreach ($brandList as $product$brandListArray[] = $product;
  7078.         return $this->render('@Inventory/pages/input_forms/stock_requisition_slip.html.twig',
  7079.             array(
  7080.                 'page_title' => 'Stock Requisition Slip',
  7081.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7082.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  7083.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  7084.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  7085.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  7086.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  7087.                 'productList' => $productList,
  7088.                 'extId' => $id,
  7089.                 'extDocDetailsData' => $extDocDetailsData,
  7090.                 'extDocData' => $extDocData,
  7091.                 'subCategoryList' => $subCategoryList,
  7092.                 'categoryList' => $categoryList,
  7093.                 'igList' => $igList,
  7094.                 'unitList' => $unitList,
  7095.                 'brandList' => $brandList,
  7096.                 'brandListArray' => $brandListArray,
  7097.                 'productListArray' => $productListArray,
  7098.                 'subCategoryListArray' => $subCategoryListArray,
  7099.                 'categoryListArray' => $categoryListArray,
  7100.                 'igListArray' => $igListArray,
  7101.                 'unitListArray' => $unitListArray,
  7102.                 'productionBomList' => ProductionM::ProductionBomList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  7103.                 'productionScheduleList' => ProductionM::ProductionScheduleList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  7104.                 'prefix_list' => array(
  7105.                     [
  7106.                         'id' => 1,
  7107.                         'value' => 'GN',
  7108.                         'text' => 'General'
  7109.                     ],
  7110.                     [
  7111.                         'id' => 1,
  7112.                         'value' => 'SD',
  7113.                         'text' => 'For Sales Demand'
  7114.                     ]
  7115.                 ),
  7116.                 'projectList' => $em->getRepository('ApplicationBundle\\Entity\\Project')->findBy(
  7117.                     array(
  7118.                         'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  7119.                     ), array('projectDate' => 'desc')
  7120.                 ),
  7121.                 'salesOrderList' => SalesOrderM::SalesOrderListPendingDelivery($em),
  7122.                 'assoc_list' => array(
  7123.                     [
  7124.                         'id' => 1,
  7125.                         'value' => 'GN',
  7126.                         'text' => 'General'
  7127.                     ]
  7128.                 )
  7129.             )
  7130.         );
  7131.     }
  7132.     public function CreateStockReturnAction(Request $request)
  7133.     {
  7134.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  7135.             array(
  7136.                 'page_title' => 'Stock Return',
  7137. //                'dataList'=>$dta_list
  7138.             )
  7139.         );
  7140.     }
  7141.     public function MaterialInwardAction(Request $request)
  7142.     {
  7143.         $data = [];
  7144.         if ($request->isMethod('POST')) {
  7145.             $errors = [];
  7146.             $poId = (int)$request->request->get('poId');
  7147.             $warehouseId = (int)$request->request->get('warehouseId');
  7148.             $docHash trim((string)$request->request->get('docHash'));
  7149.             $products $request->request->get('products', []);
  7150.             $receivedQty $request->request->get('receivedQty', []);
  7151.             $purchaseOrderItemId $request->request->get('purchaseOrderItemId', []);
  7152.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  7153.             if ($poId <= 0) {
  7154.                 $errors[] = 'Please select a purchase order.';
  7155.             } elseif (!isset($poList[$poId])) {
  7156.                 $errors[] = 'Please select a valid purchase order.';
  7157.             }
  7158.             if ($warehouseId <= 0) {
  7159.                 $errors[] = 'Please select a warehouse.';
  7160.             }
  7161.             if (empty($products) || !is_array($products)) {
  7162.                 $errors[] = 'Please add at least one item.';
  7163.             }
  7164.             $hasPositiveQty false;
  7165.             foreach ((array)$receivedQty as $qty) {
  7166.                 if ($qty === '' || !is_numeric($qty)) {
  7167.                     $errors[] = 'Please enter a valid received quantity.';
  7168.                     break;
  7169.                 }
  7170.                 if ((float)$qty 0) {
  7171.                     $errors[] = 'Received quantity cannot be negative.';
  7172.                     break;
  7173.                 }
  7174.                 if ((float)$qty 0) {
  7175.                     $hasPositiveQty true;
  7176.                 }
  7177.             }
  7178.             if (!$hasPositiveQty) {
  7179.                 $errors[] = 'Please enter received quantity greater than zero for at least one item.';
  7180.             }
  7181.             if ($docHash === '' || stripos($docHash'undefined') !== false || stripos($docHash'document') !== false) {
  7182.                 $errors[] = 'Please generate a valid document number.';
  7183.             }
  7184.             if (empty($errors)) {
  7185.                 //first of all resolve the transport costs
  7186.                 $total_price_value 0;
  7187.                 $data_list $this->getDoctrine()
  7188.                     ->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')
  7189.                     ->findBy(
  7190.                         array(
  7191.                             'purchaseOrderId' => $poId,
  7192.                             'productId' => $products
  7193.                         )
  7194.                     );
  7195.                 $purchase_items = [];
  7196.                 foreach ($data_list as $key => $value) {
  7197.                     $purchase_items[$value->getProductId()] = $value;
  7198.                 }
  7199.                 foreach ($products as $key => $entry) {
  7200.                     if (!isset($purchase_items[$entry])) {
  7201.                         $errors[] = 'Selected product list does not match the chosen purchase order.';
  7202.                         break;
  7203.                     }
  7204.                     $total_price_value $total_price_value + ($receivedQty[$key]) * ($purchase_items[$entry]->getPrice());
  7205.                 }
  7206.                 if (empty($errors)) {
  7207.                     $po_data $poList[$poId];
  7208.                     $supplier_id $po_data['supplier_id'];
  7209.                     $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  7210.                     foreach ($products as $key => $entry) {
  7211.                         if ((float)$receivedQty[$key] > 0) {
  7212.                             Inventory::NewMaterialInward($this->getDoctrine()->getManager(),
  7213.                                 $request->request,
  7214.                                 $key,
  7215.                                 $poId,
  7216.                                 $purchaseOrderItemId,
  7217.                                 $supplier_id,
  7218.                                 $warehouseId,
  7219.                                 $request->request->get('lotNumber'),
  7220.                                 $request->request->get('type_hash'),
  7221.                                 $request->request->get('prefix_hash'),
  7222.                                 $request->request->get('assoc_hash'),
  7223.                                 $request->request->get('number_hash'),
  7224.                                 $docHash,
  7225.                                 $request->request->get('docDate'),
  7226.                                 $purchase_items[$entry],
  7227.                                 $total_price_value,
  7228.                                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7229.                         }
  7230.                     }
  7231.                     $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$warehouseId]['name'];
  7232. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  7233.                     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),
  7234.                         "A stack of material Has Arrived at The " $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  7235.                         'all',
  7236.                         "",
  7237.                         'information',
  7238.                         "",
  7239.                         "Inbound Material"
  7240.                     );
  7241.                 }
  7242.             }
  7243.             foreach ($errors as $error) {
  7244.                 $this->addFlash('error'$error);
  7245.             }
  7246. //                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);
  7247.         }
  7248.         return $this->render('@Inventory/pages/input_forms/material_inward.html.twig',
  7249.             array(
  7250.                 'page_title' => 'Material Inward',
  7251.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  7252.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  7253.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  7254.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  7255.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  7256.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  7257.                 "unitList" => Inventory::UnitTypeList($this->getDoctrine()->getManager())
  7258. //                'po'=>Inventory::getPurchaseOrderList
  7259.             )
  7260.         );
  7261.     }
  7262.     public function QualityControlAction(Request $request)
  7263.     {
  7264.         $checked_qc_list_flag 0;
  7265.         if ($request->query->has('checked_qc_list_flag'))
  7266.             $checked_qc_list_flag $request->query->has('checked_qc_list_flag');
  7267.         if ($request->isMethod('POST')) {
  7268.             $errors = [];
  7269.             $checkedRows $request->request->get('qc_checked', []);
  7270.             $approvedQty $request->request->get('approvedQty', []);
  7271.             if (empty($checkedRows)) {
  7272.                 $errors[] = 'Please select at least one QC item.';
  7273.             }
  7274.             $positiveQtyFound false;
  7275.             foreach ($approvedQty as $qcId => $qty) {
  7276.                 $qtyValue trim((string)$qty);
  7277.                 if ($qtyValue === '' || !is_numeric($qtyValue)) {
  7278.                     $errors[] = 'Approved quantity must be numeric.';
  7279.                     break;
  7280.                 }
  7281.                 if ((float)$qtyValue 0) {
  7282.                     $errors[] = 'Approved quantity cannot be negative.';
  7283.                     break;
  7284.                 }
  7285.                 if ((float)$qtyValue 0) {
  7286.                     $positiveQtyFound true;
  7287.                     if (!in_array($qcId$checkedRows)) {
  7288.                         $errors[] = 'Please check QC before submitting approved rows.';
  7289.                         break;
  7290.                     }
  7291.                 }
  7292.             }
  7293.             if (empty($errors) && !$positiveQtyFound) {
  7294.                 $errors[] = 'Please enter approved quantity greater than zero for at least one QC item.';
  7295.             }
  7296.             if (empty($errors)) {
  7297.                 foreach ($checkedRows as $key => $entry) {
  7298.                     $em $this->getDoctrine()->getManager();
  7299.                     $data $this->getDoctrine()
  7300.                         ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  7301.                         ->findOneBy(
  7302.                             array(
  7303.                                 'qcId' => $entry
  7304.                             )
  7305.                         );
  7306.                     if (!$data) {
  7307.                         $errors[] = 'Invalid QC row selected.';
  7308.                         break;
  7309.                     }
  7310.                     $data->setApprovedQty($approvedQty[$entry]);
  7311.                     $data->setRejectedQty($data->getInwardQty() - $approvedQty[$entry]);
  7312.                     $data->setQcDate(new \DateTime($request->request->get('qcDate')));
  7313.                     $data->setStage(GeneralConstant::STAGE_PENDING_TAG);
  7314.                     $em->flush();
  7315.                     //notification
  7316.                     $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$data->getPurchaseOrderId()];
  7317.                     $supplier_id $po_data['supplier_id'];
  7318.                     $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  7319.                     $product_name Inventory::ProductList($this->getDoctrine()->getManager())[$data->getProductId()]['name'];
  7320.                     $qty $approvedQty[$entry];
  7321.                     $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$data->getWarehouseId()]['name'];
  7322. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  7323.                     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),
  7324.                         $qty " among " $data->getInwardQty() . " units of " $product_name " has passed the Quality Control in " .
  7325.                         $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  7326.                         'all',
  7327.                         "",
  7328.                         'success',
  7329.                         "",
  7330.                         "Quality Control"
  7331.                     );
  7332.                 }
  7333.             }
  7334.             foreach ($errors as $error) {
  7335.                 $this->addFlash('error'$error);
  7336.             }
  7337.         }
  7338.         return $this->render('@Inventory/pages/input_forms/qc.html.twig',
  7339.             array(
  7340.                 'page_title' => 'Quality Control',
  7341.                 'checked_qc_list_flag' => $checked_qc_list_flag,
  7342.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  7343.                 'warehouse_indexed' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7344.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  7345.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  7346.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  7347.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  7348.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7349.                 'material_inward' => $this->getDoctrine()
  7350.                     ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  7351.                     ->findBy(
  7352.                         array(
  7353.                             'stage' => $checked_qc_list_flag == GeneralConstant::STAGE_PENDING GeneralConstant::STAGE_PENDING_TAG
  7354.                         )
  7355.                     )
  7356. //                'po'=>Inventory::getPurchaseOrderList
  7357.             )
  7358.         );
  7359.     }
  7360.     public function InventoryTransactionViewAction(Request $request)
  7361.     {
  7362.         $em $this->getDoctrine()->getManager();
  7363.         $qry_data = array(
  7364.             'warehouseId' => [0],
  7365.             'igId' => [0],
  7366.             'brandId' => [0],
  7367.             'categoryId' => [0],
  7368.             'actionTagId' => [0],
  7369.         );
  7370.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  7371.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  7372.         $data_searched = [];
  7373.         $em $this->getDoctrine()->getManager();
  7374.         $companyId $this->getLoggedUserCompanyId($request);
  7375.         $company_data Company::getCompanyData($em$companyId);
  7376.         $data = [];
  7377.         $print_title "Inventory Report";
  7378.         $document_mark = array(
  7379.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  7380.             'copy' => ''
  7381.         );
  7382.         if ($request->isMethod('POST'))
  7383.             $method 'POST';
  7384.         else
  7385.             $method 'GET';
  7386.         {
  7387.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  7388.                 $request->request$method,
  7389.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7390.                 $companyId);
  7391.             if ($request->query->has('returnJson') || $request->request->has('returnJson')) {
  7392.                 return new JsonResponse(
  7393.                     array(
  7394.                         'success' => true,
  7395. //                    'page_title' => 'Product Details',
  7396. //                    'company_data' => $company_data,
  7397.                         'page_title' => 'Inventory Transactions',
  7398.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7399.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7400.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7401.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7402.                         'data_products' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7403.                         'action_tag' => $warehouse_action_list,
  7404.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7405.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7406.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7407.                         'data_searched' => $data_searched
  7408.                     )
  7409.                 );
  7410.             } else if ($request->request->get('print_data_enabled') == 1) {
  7411.                 $print_sub_title "";
  7412.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  7413.                     array(
  7414.                         'page_title' => 'Inventory Report',
  7415.                         'page_header' => 'Report',
  7416.                         'print_title' => $print_title,
  7417.                         'document_type' => 'Journal voucher',
  7418.                         'document_mark_image' => $document_mark['original'],
  7419.                         'page_header_sub' => 'Add',
  7420.                         'item_data' => [],
  7421.                         'received' => 2,
  7422.                         'return' => 1,
  7423.                         'total_w_vat' => 1,
  7424.                         'total_vat' => 1,
  7425.                         'total_wo_vat' => 1,
  7426.                         'invoice_id' => 'abcd1234',
  7427.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  7428.                         'created_by' => 'created by',
  7429.                         'created_at' => '',
  7430.                         'red' => 0,
  7431.                         'company_name' => $company_data->getName(),
  7432.                         'company_data' => $company_data,
  7433.                         'company_address' => $company_data->getAddress(),
  7434.                         'company_image' => $company_data->getImage(),
  7435.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7436.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7437.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7438.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7439.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7440.                         'action_tag' => $warehouse_action_list,
  7441.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7442.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7443.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7444.                         'data_searched' => $data_searched
  7445.                     )
  7446.                 );
  7447.             }
  7448.         }
  7449.         return $this->render('@Inventory/pages/report/inventory_transaction_view.html.twig',
  7450.             array(
  7451.                 'page_title' => 'Inventory Transactions',
  7452.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7453.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7454.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7455.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7456.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7457.                 'action_tag' => $warehouse_action_list,
  7458.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7459.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7460.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7461.                 'data_searched' => $data_searched
  7462.             )
  7463.         );
  7464.     }
  7465.     public function StockConsumptionViewAction(Request $request)
  7466.     {
  7467.         $em $this->getDoctrine()->getManager();
  7468.         $start_date $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
  7469.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : new \DateTime();
  7470.         $qry_data = array(
  7471.             'warehouseId' => [0],
  7472.             'igId' => [0],
  7473.             'brandId' => [0],
  7474.             'categoryId' => [0],
  7475.             'actionTagId' => [0],
  7476.         );
  7477.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  7478.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  7479.         $data_searched = [];
  7480.         $em $this->getDoctrine()->getManager();
  7481.         $company_data Company::getCompanyData($em1);
  7482.         $data = [];
  7483.         $print_title "Inventory Report";
  7484.         $document_mark = array(
  7485.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  7486.             'copy' => ''
  7487.         );
  7488.         if ($request->isMethod('POST'))
  7489.             $method 'POST';
  7490.         else
  7491.             $method 'GET';
  7492.         $post_data $method == 'POST' $request->request $request->query;
  7493.         $data_searched Inventory::GetStockConsumptionData($this->getDoctrine()->getManager(),
  7494.             $post_data,
  7495.             $method,
  7496.             $start_date,
  7497.             $end_date,
  7498.             $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7499.         if ($post_data->get('print_data_enabled') == 1) {
  7500.             $print_sub_title "";
  7501.             if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  7502.                 $html $this->renderView('@Inventory/pages/print/print_stock_consumption.html.twig',
  7503.                     array(
  7504.                         'pdf' => 'true',
  7505.                         'page_title' => 'Inventory Report',
  7506.                         'page_header' => 'Report',
  7507.                         'print_title' => $print_title,
  7508.                         'document_type' => 'Journal voucher',
  7509.                         'document_mark_image' => $document_mark['original'],
  7510.                         'page_header_sub' => 'Add',
  7511.                         'item_data' => [],
  7512.                         'received' => 2,
  7513.                         'return' => 1,
  7514.                         'total_w_vat' => 1,
  7515.                         'total_vat' => 1,
  7516.                         'total_wo_vat' => 1,
  7517.                         'invoice_id' => 'abcd1234',
  7518.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  7519.                         'created_by' => 'created by',
  7520.                         'created_at' => '',
  7521.                         'red' => 0,
  7522.                         'start_date' => $start_date,
  7523.                         'end_date' => $end_date,
  7524.                         'openFilter' => empty($post_data->keys()) ? 0,
  7525.                         'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  7526.                         'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  7527.                         'company_name' => $company_data->getName(),
  7528.                         'company_data' => $company_data,
  7529.                         'company_address' => $company_data->getAddress(),
  7530.                         'company_image' => $company_data->getImage(),
  7531.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7532.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7533.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7534.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7535.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7536.                         'action_tag' => $warehouse_action_list,
  7537.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7538.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7539.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7540.                         'data_searched' => $data_searched,
  7541.                         'export' => 'all'
  7542.                     )
  7543.                 );
  7544.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  7545.                     'orientation' => count($data_searched['query_columns_filter']) > 'landscape' 'portrait',
  7546.                     'no-stop-slow-scripts' => true,
  7547.                     'no-background' => false,
  7548.                     'lowquality' => false,
  7549.                     'encoding' => 'utf-8',
  7550.                     'dpi' => 300,
  7551.                     'image-dpi' => 300,
  7552.                 ));
  7553.                 return new Response(
  7554.                     $pdf_response,
  7555.                     200,
  7556.                     array(
  7557.                         'Content-Type' => 'application/pdf',
  7558.                         'Content-Disposition' => 'attachment; filename="Stock_Consumption.pdf"'
  7559.                     )
  7560.                 );
  7561.             }
  7562.             return $this->render('@Inventory/pages/print/print_stock_consumption.html.twig',
  7563.                 array(
  7564.                     'page_title' => 'Inventory Report',
  7565.                     'page_header' => 'Report',
  7566.                     'print_title' => $print_title,
  7567.                     'document_type' => 'Journal voucher',
  7568.                     'document_mark_image' => $document_mark['original'],
  7569.                     'page_header_sub' => 'Add',
  7570.                     'item_data' => [],
  7571.                     'received' => 2,
  7572.                     'return' => 1,
  7573.                     'total_w_vat' => 1,
  7574.                     'total_vat' => 1,
  7575.                     'total_wo_vat' => 1,
  7576.                     'invoice_id' => 'abcd1234',
  7577.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  7578.                     'created_by' => 'created by',
  7579.                     'created_at' => '',
  7580.                     'red' => 0,
  7581.                     'start_date' => $start_date,
  7582.                     'end_date' => $end_date,
  7583.                     'openFilter' => empty($post_data->keys()) ? 0,
  7584.                     'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  7585.                     'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  7586.                     'company_name' => $company_data->getName(),
  7587.                     'company_data' => $company_data,
  7588.                     'company_address' => $company_data->getAddress(),
  7589.                     'company_image' => $company_data->getImage(),
  7590.                     'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7591.                     'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7592.                     'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7593.                     'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7594.                     'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7595.                     'action_tag' => $warehouse_action_list,
  7596.                     'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7597.                     'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7598.                     'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7599.                     'data_searched' => $data_searched,
  7600.                     'export' => 'all'
  7601.                 )
  7602.             );
  7603.         }
  7604. //        return new JsonResponse(Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()));
  7605.         return $this->render('@Inventory/pages/report/stock_consumption.html.twig',
  7606.             array(
  7607.                 'page_title' => 'Stock Consumption',
  7608.                 'start_date' => $start_date,
  7609.                 'end_date' => $end_date,
  7610.                 'openFilter' => empty($post_data->keys()) ? 0,
  7611.                 'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  7612.                 'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  7613.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7614.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7615.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7616.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7617.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7618.                 'action_tag' => $warehouse_action_list,
  7619.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7620.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7621.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7622.                 'data_searched' => $data_searched
  7623.             )
  7624.         );
  7625.     }
  7626.     public function ItemViewAction(Request $request)
  7627.     {
  7628.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  7629.             array(
  7630.                 'page_title' => 'Stock Return'
  7631.             )
  7632.         );
  7633.     }
  7634.     public function ProductViewAction(Request $request$id 0)
  7635.     {
  7636.         $em $this->getDoctrine()->getManager();
  7637.         $companyId $this->getLoggedUserCompanyId($request);
  7638.         $company_data Company::getCompanyData($em$companyId);
  7639.         $data = [];
  7640.         $specData = [];
  7641.         $specIds = [];
  7642.         $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  7643.             ->findOneBy(
  7644.                 array(
  7645.                     'id' => $id
  7646.                 )
  7647.             );
  7648.         if ($productData) {
  7649.             $tempSpecData json_decode($productData->getSpecData(), true);
  7650.             if ($tempSpecData == null) {
  7651.                 $tempSpecData = [];
  7652.             }
  7653.             foreach ($tempSpecData as $indSpecData) {
  7654. //                $specId = $indSpecData['id'];
  7655.                 $specData[] = [
  7656.                     'id' => $indSpecData['id'],
  7657.                     'value' => $indSpecData['value']
  7658.                 ];
  7659.                 $specIds[] = $indSpecData['id'];
  7660.             }
  7661.         }
  7662.         $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  7663.             ->findBy(
  7664.                 array(
  7665.                     'productId' => $id
  7666.                 )
  7667.             );
  7668.         $trans_history $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')
  7669.             ->findBy(
  7670.                 array(
  7671.                     'productId' => $id
  7672.                 ), array(
  7673.                     'transactionDate' => 'ASC',
  7674.                     'id' => 'ASC'
  7675.                 )
  7676.             );
  7677. //        $specId = array_keys($specData);
  7678.         $finSpecData = [];
  7679. //        if($productData){
  7680. //            $tempSpec = json_decode($productData->getSpecData(),true);
  7681. //
  7682. //            if($tempSpec == null){
  7683. //                $tempSpecName=[];
  7684. //            }
  7685. //            foreach ($tempSpec as $indSpec)
  7686. //            {
  7687. //                $specIds[]=$indSpec['id'];
  7688. //
  7689. //                $spec = $em->getRepository('ApplicationBundle\\Entity\\SpecType')
  7690. //                    ->findOneBy(
  7691. //                        array(
  7692. //                            'id' => $indSpec['id']
  7693. //                        )
  7694. //                    );
  7695. //
  7696. //                if($spec)
  7697. //                    $indSpec['name']=$spec->getName();
  7698. //                else
  7699. //                    $indSpec['name']='';
  7700. ////                $specId = $indSpecData['id'];
  7701. //
  7702. //                $finSpecData[]=$indSpec;
  7703. //
  7704. //            }
  7705. //        }
  7706.         $specList $em->getRepository('ApplicationBundle\\Entity\\SpecType')
  7707.             ->findBy(
  7708.                 array(
  7709.                     'id' => $specIds
  7710.                 )
  7711.             );
  7712.         $specListById = [];
  7713.         foreach ($specList as $specHere) {
  7714.             $specListById[$specHere->getId()] = $specHere->getName();
  7715.         }
  7716.         foreach ($specData as $specDatum) {
  7717.             $finSpecData[] = [
  7718.                 'id' => $specDatum['id'],
  7719.                 'name' => isset($specListById[$specDatum['id']]) ? $specListById[$specDatum['id']] : '',
  7720.                 'value' => $specDatum['value']
  7721.             ];
  7722.         }
  7723.         $productDataObj = array();
  7724.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  7725.             $getters array_filter(get_class_methods($productData), function ($method) {
  7726.                 return 'get' === substr($method03);
  7727.             });
  7728.             foreach ($getters as $getter) {
  7729.                 if ($getter == 'getGlobalId')
  7730.                     continue;
  7731. //                    if ($getter == 'getId')
  7732. //                        continue;
  7733.                 $Fieldname str_replace('get'''$getter);
  7734.                 $productDataObj[$Fieldname] = $productData->{$getter}(); // `foo!`
  7735.             }
  7736.             if ($request->request->has('genInfoOnly') && $request->request->get('genInfoOnly') == 1) {
  7737.                 $dataArray = array(
  7738.                     'success' => true,
  7739.                     'page_title' => 'Product Details',
  7740.                     'company_data' => $company_data,
  7741.                     'productData' => $productData,
  7742.                     'productDataObj' => $productDataObj,
  7743.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7744.                 );
  7745.             } else {
  7746.                 $dataArray = array(
  7747.                     'success' => true,
  7748.                     'page_title' => 'Product Details',
  7749.                     'company_data' => $company_data,
  7750.                     'productData' => $productData,
  7751.                     'productDataObj' => $productDataObj,
  7752.                     'currInvList' => $currInvList,
  7753.                     'finSpecData' => $finSpecData,
  7754.                     'specList' => $specList,
  7755.                     'trans_history' => $trans_history,
  7756.                     'entityList' => GeneralConstant::$Entity_list_details,
  7757. //                    'productList' => Inventory::ProductList($em, $companyId),
  7758.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7759.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7760.                     'igList' => Inventory::ItemGroupList($em$companyId),
  7761.                     'unitList' => Inventory::UnitTypeList($em),
  7762.                     'brandList' => Inventory::GetBrandList($em$companyId),
  7763.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7764.                     'warehouseList' => Inventory::WarehouseList($em),
  7765.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7766.                 );
  7767.             }
  7768.             return new JsonResponse(
  7769.                 $dataArray
  7770.             );
  7771.         }
  7772.         $dataArray = array(
  7773.             'page_title' => 'Product Details',
  7774.             'company_data' => $company_data,
  7775.             'productData' => $productData,
  7776.             'currInvList' => $currInvList,
  7777.             'specData' => $specData,
  7778. //            'specListById' => $specListById,
  7779.             'finSpecData' => $finSpecData,
  7780.             'trans_history' => $trans_history,
  7781.             'entityList' => GeneralConstant::$Entity_list_details,
  7782. //            'productList' => Inventory::ProductList($em, $companyId),
  7783.             'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7784.             'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7785.             'igList' => Inventory::ItemGroupList($em$companyId),
  7786.             'unitList' => Inventory::UnitTypeList($em),
  7787.             'brandList' => Inventory::GetBrandList($em$companyId),
  7788.             'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7789.             'warehouseList' => Inventory::WarehouseList($em),
  7790.         );
  7791.         return $this->render('@Inventory/pages/views/product_view.html.twig'$dataArray
  7792.         );
  7793.     }
  7794.     public function CheckForProductInWarehouseAction(Request $request$queryStr '')
  7795.     {
  7796.         $em $this->getDoctrine()->getManager();
  7797.         $companyId $this->getLoggedUserCompanyId($request);
  7798.         $data = [
  7799.             'availableQty' => 0,
  7800.             'productByCodesArray' => [],
  7801.             'indRowId' => 0
  7802.         ];
  7803.         $html '';
  7804.         $productByCodeData = [];
  7805.         if ($request->isMethod('POST')) {
  7806.             $warehouseId $request->request->get('warehouseId'0);
  7807.             $warehouseActionId $request->request->get('warehouseActionId'0);
  7808.             $productId $request->request->get('productId'0);
  7809.             $indRowId $request->request->get('indRowId'0);
  7810.             $data['indRowId'] = $indRowId;
  7811.             $inStorage $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  7812.                 ->findBy(
  7813.                     array(
  7814.                         'productId' => $productId,
  7815.                         'warehouseId' => $warehouseId,
  7816.                         'actionTagId' => $warehouseActionId,
  7817.                         'CompanyId' => $companyId,
  7818.                     )
  7819.                 );
  7820.             foreach ($inStorage as $strg) {
  7821.                 $data['availableQty'] += $strg->getQty();
  7822.             }
  7823.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  7824.                 ->findBy(
  7825.                     array(
  7826.                         'productId' => $productId,
  7827.                         'warehouseId' => $warehouseId,
  7828.                         'warehouseActionId' => $warehouseActionId,
  7829.                         'CompanyId' => $companyId,
  7830.                     )
  7831.                 );
  7832.             foreach ($productByCodeData as $pbc) {
  7833.                 $data['productByCodesArray'][] = array(
  7834.                     'id' => $pbc->getProductByCodeId(),
  7835.                     'productId' => $pbc->getProductId(),
  7836.                     'warehouseId' => $pbc->getWarehouseId(),
  7837.                     'warehouseActionId' => $pbc->getWarehouseActionId(),
  7838. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7839.                     'sales_code' => str_pad($pbc->getSalesCode(), 13'0'STR_PAD_LEFT),
  7840. //                'sales_code'=>$d['sales_code'],
  7841.                 );
  7842.             }
  7843.             return new JsonResponse(array(
  7844.                     'success' => true,
  7845.                     'data' => $data,
  7846.                 )
  7847.             );
  7848.         }
  7849.         return new JsonResponse(
  7850.             array(
  7851.                 'success' => false,
  7852.                 'data' => $data,
  7853.             )
  7854.         );
  7855.     }
  7856.     public function ProductByCodeListAjaxAction(Request $request$queryStr '')
  7857.     {
  7858.         $em $this->getDoctrine()->getManager();
  7859.         $companyId $this->getLoggedUserCompanyId($request);
  7860.         $company_data Company::getCompanyData($em$companyId);
  7861.         $data = [];
  7862.         $html '';
  7863.         $productByCodeData = [];
  7864.         if ($request->request->has('query') && $queryStr == '')
  7865.             $queryStr $request->request->get('queryStr');
  7866.         $likeQueryStr '%' $queryStr '%';
  7867.         $get_kids_sql "select product_by_code_id id, product_id, warehouse_id, warehouse_action_id,
  7868.                             sales_code ,
  7869.                             serial_no,
  7870.                             imei1,
  7871.                             imei2,
  7872.                             imei3,
  7873.                             imei4
  7874.                             from product_by_code
  7875.                             where ( CONVERT(sales_code,char)  like :queryStr
  7876.                                     or  CONVERT(serial_no,char)  like :queryStr
  7877.                                     or  CONVERT(imei1,char)  like :queryStr
  7878.                                     or  CONVERT(imei2,char)  like :queryStr
  7879.                                     or  CONVERT(imei3,char)  like :queryStr
  7880.                                     or  CONVERT(imei4,char)  like :queryStr
  7881.                                     ) ";
  7882.         $queryParams = array(
  7883.             'queryStr' => $likeQueryStr,
  7884.             'companyId' => (int) $companyId,
  7885.         );
  7886.         if ($request->query->has('warehouseId')) {
  7887.             $get_kids_sql .= " and warehouse_id = :warehouseId ";
  7888.             $queryParams['warehouseId'] = (int) $request->query->get('warehouseId');
  7889.         }
  7890.         if ($request->query->has('position')) {
  7891.             $get_kids_sql .= " and position = :position ";
  7892.             $queryParams['position'] = (int) $request->query->get('position');
  7893.         }
  7894.         if ($request->query->has('deliveryReceiptId')) {
  7895.             $get_kids_sql .= " and deliveryReceiptId = :deliveryReceiptId ";
  7896.             $queryParams['deliveryReceiptId'] = (int) $request->query->get('deliveryReceiptId');
  7897.         }
  7898.         if ($request->query->has('warehouseActionId')) {
  7899.             $get_kids_sql .= " and warehouse_action_id = :warehouseActionId ";
  7900.             $queryParams['warehouseActionId'] = (int) $request->query->get('warehouseActionId');
  7901.         }
  7902.         if ($request->query->has('productId')) {
  7903.             $get_kids_sql .= " and product_id = :productId ";
  7904.             $queryParams['productId'] = (int) $request->query->get('productId');
  7905.         }
  7906.         $get_kids_sql .= " and company_id = :companyId limit 25";
  7907.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$queryParams);
  7908.         $get_kids $stmt;
  7909.         if (!empty($get_kids)) {
  7910.             foreach ($get_kids as $d) {
  7911.                 $dt = array(
  7912.                     'id' => $d['id'],
  7913.                     'productId' => $d['product_id'],
  7914.                     'warehouseId' => $d['warehouse_id'],
  7915.                     'warehouseActionId' => $d['warehouse_action_id'],
  7916. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7917.                     'sales_code' => str_pad($d['sales_code'], 13'0'STR_PAD_LEFT),
  7918.                     'serial_no' => str_pad($d['serial_no'], 13'0'STR_PAD_LEFT),
  7919.                     'imei1' => str_pad($d['imei1'], 13'0'STR_PAD_LEFT),
  7920.                     'imei2' => str_pad($d['imei2'], 13'0'STR_PAD_LEFT),
  7921.                     'imei3' => str_pad($d['imei3'], 13'0'STR_PAD_LEFT),
  7922.                     'imei4' => str_pad($d['imei4'], 13'0'STR_PAD_LEFT),
  7923. //                'sales_code'=>$d['sales_code'],
  7924.                 );
  7925.                 $data[] = $dt;
  7926.             }
  7927.         }
  7928. //        if($request->query->has('returnJson'))
  7929.         {
  7930.             return new JsonResponse(
  7931.                 array(
  7932.                     'success' => true,
  7933. //                    'page_title' => 'Product Details',
  7934. //                    'company_data' => $company_data,
  7935.                     'data' => $data,
  7936. //                    'exId'=>$id,
  7937. //                'productByCodeData' => $productByCodeData,
  7938. //                'productData' => $productData,
  7939. //                'currInvList' => $currInvList,
  7940. //                'productList' => Inventory::ProductList($em, $companyId),
  7941. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  7942. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  7943. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  7944. //                'unitList' => Inventory::UnitTypeList($em),
  7945. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  7946. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  7947. //                'warehouseList' => Inventory::WarehouseList($em),
  7948.                 )
  7949.             );
  7950.         }
  7951.     }
  7952.     public function selectDataAjaxAction(Request $request$queryStr '',
  7953.                                                  $version 'latest',
  7954.                                                  $identifier '_default_',
  7955.                                                  $apiKey '_ignore_'
  7956.     )
  7957.     {
  7958.         $em $this->getDoctrine()->getManager();
  7959.         $em_goc $this->getDoctrine()->getManager('company_group');
  7960.         $companyId 0;
  7961.         $skipCurrentUserIdRestriction $request->get('skipCurrentUserIdRestriction'0);
  7962.         $dataOnly $request->get('dataOnly'0);
  7963.         $skipCurrentEmployeeIdRestriction $request->get('skipCurrentEmployeeIdRestriction'0);
  7964.         $skipCurrentUserLoginIdRestriction $request->get('skipCurrentUserLoginIdRestriction'0);
  7965.         $currentUserId $request->getSession()->get(UserConstants::USER_ID0);
  7966.         $currentEmployeeId $request->getSession()->get(UserConstants::USER_EMPLOYEE_ID0);
  7967.         $currentUserLoginIds = [];
  7968.         if ($request->request->get('entity_group'0)) {
  7969.             $companyId 0;
  7970.             $em $this->getDoctrine()->getManager('company_group');
  7971.         } else {
  7972.             if ($request->request->get('appId'0) != 0) {
  7973.                 $gocEnabled 0;
  7974.                 if ($this->container->hasParameter('entity_group_enabled'))
  7975.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7976.                 else
  7977.                     $gocEnabled 1;
  7978.                 if ($gocEnabled == 1) {
  7979.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7980.                         $this->getDoctrine()->getManager('company_group'),
  7981.                         $gocEnabled,
  7982.                         $request->request->get('appId'0)
  7983.                     );
  7984.                     if (!empty($dataToConnect)) {
  7985.                         $connector $this->container->get('application_connector');
  7986.                         $connector->resetConnection(
  7987.                             'default',
  7988.                             $dataToConnect['dbName'],
  7989.                             $dataToConnect['dbUser'],
  7990.                             $dataToConnect['dbPass'],
  7991.                             $dataToConnect['dbHost'],
  7992.                             $reset true
  7993.                         );
  7994.                         $em $this->getDoctrine()->getManager();
  7995.                     }
  7996.                 }
  7997.             } else if ($request->getSession()->get(UserConstants::USER_APP_ID) != && $request->getSession()->get(UserConstants::USER_APP_ID) != null) {
  7998.                 $gocEnabled 0;
  7999.                 if ($this->container->hasParameter('entity_group_enabled'))
  8000.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  8001.                 else
  8002.                     $gocEnabled 1;
  8003.                 if ($gocEnabled == 1) {
  8004.                     $dataToConnect System::changeDoctrineManagerByAppId(
  8005.                         $this->getDoctrine()->getManager('company_group'),
  8006.                         $gocEnabled,
  8007.                         $request->getSession()->get(UserConstants::USER_APP_ID)
  8008.                     );
  8009.                     if (!empty($dataToConnect)) {
  8010.                         $connector $this->container->get('application_connector');
  8011.                         $connector->resetConnection(
  8012.                             'default',
  8013.                             $dataToConnect['dbName'],
  8014.                             $dataToConnect['dbUser'],
  8015.                             $dataToConnect['dbPass'],
  8016.                             $dataToConnect['dbHost'],
  8017.                             $reset true
  8018.                         );
  8019.                         $em $this->getDoctrine()->getManager();
  8020.                     }
  8021.                 }
  8022.             }
  8023.             $companyId $this->getLoggedUserCompanyId($request);
  8024.         }
  8025.         $configData = [];
  8026.         $isSingleDataset 1;
  8027.         $dataSet $request->request->has('dataset') ? $request->request->get('dataset') : [];
  8028.         if (is_string($dataSet)) $dataSet json_decode($dataSettrue);
  8029.         $valuePairs $request->get('valuePairs', []);
  8030.         if (is_string($valuePairs)) $valuePairs json_decode($valuePairstrue);
  8031.         $allResult = [];
  8032.         $datasetFromConfig = [];
  8033.         if ($identifier != '_default_') {
  8034.             $config_file $this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' $identifier 'Config.json';
  8035.             if (!file_exists($config_file)) {
  8036.             } else {
  8037.                 $fileText file_get_contents($config_file);
  8038.                 //now replace any value pairs
  8039.                 foreach ($valuePairs as $kkeeyy => $vvaalluuee) {
  8040.                     if (is_array($vvaalluuee)) {
  8041.                         if (isset($vvaalluuee['value']) && isset($vvaalluuee['type'])) {
  8042.                             if ($vvaalluuee['type'] == 'array'$fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee['value']), $fileText);
  8043.                             if ($vvaalluuee['type'] == 'value'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  8044.                             if ($vvaalluuee['type'] == 'text'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  8045.                         } else {
  8046.                             $fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee), $fileText);
  8047.                         }
  8048.                     } else
  8049.                         $fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee$fileText);
  8050.                 }
  8051.                 $fileText str_ireplace('_query_'$request->get('query'$queryStr), $fileText);
  8052.                 $fileText str_ireplace('_itemLimit_'$request->get('itemLimit''_all_'), $fileText);
  8053.                 $fileText str_ireplace('_offset_'$request->get('offset', ($request->get('itemLimit'10)) * ($request->get('page'1) - 1)), $fileText);
  8054.                 if (!(strpos($fileText'_CURRENT_USER_LOGIN_IDS_') === false) && $skipCurrentUserLoginIdRestriction == 0) {
  8055.                     $userInfo = [];
  8056.                     if ($request->getSession()->get(UserConstants::USER_TYPE0) == UserConstants::USER_TYPE_APPLICANT) {
  8057.                         $userInfo $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityLoginLog')->findBy(
  8058.                             array('userId' => $currentUserId)
  8059.                         );
  8060.                     } else {
  8061.                         $userInfo $em->getRepository('ApplicationBundle\\Entity\\SysLoginLog')->findBy(
  8062.                             array('userId' => $currentUserId)
  8063.                         );
  8064.                     }
  8065.                     foreach ($userInfo as $uLogininfo) {
  8066.                         $currentUserLoginIds[] = $uLogininfo->getLoginId();
  8067.                     }
  8068.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_'json_encode($currentUserLoginIds), $fileText);
  8069.                 } else {
  8070.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_''_EMPTY_'$fileText);
  8071.                 }
  8072.                 if (!(strpos($fileText'_CURRENT_USER_ID_') === false) && $skipCurrentUserIdRestriction == 0) {
  8073.                     $fileText str_ireplace('_CURRENT_USER_ID_'$currentUserId$fileText);
  8074.                 } else {
  8075.                     $fileText str_ireplace('_CURRENT_USER_ID_''_EMPTY_'$fileText);
  8076.                 }
  8077.                 if (!(strpos($fileText'_CURRENT_USER_EMPLOYEE_ID_') === false) && $skipCurrentEmployeeIdRestriction == 0) {
  8078.                     if ((strpos($fileText'skipCurrentEmployeeIdRestriction') === false)) {
  8079.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_'$currentEmployeeId$fileText);
  8080.                     } else {
  8081.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  8082.                     }
  8083.                 } else {
  8084.                     $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  8085.                 }
  8086.                 if ($fileText)
  8087.                     $datasetFromConfig json_decode($fileTexttrue);
  8088.                 $skipCurrentUserIdRestriction = isset($datasetFromConfig['skipCurrentUserIdRestriction']) ? $datasetFromConfig['skipCurrentUserIdRestriction'] : $skipCurrentUserIdRestriction;
  8089.                 $skipCurrentEmployeeIdRestriction = isset($datasetFromConfig['skipCurrentEmployeeIdRestriction']) ? $datasetFromConfig['skipCurrentEmployeeIdRestriction'] : $skipCurrentEmployeeIdRestriction;
  8090.                 $skipCurrentUserLoginIdRestriction = isset($datasetFromConfig['skipCurrentUserLoginIdRestriction']) ? $datasetFromConfig['skipCurrentUserLoginIdRestriction'] : $skipCurrentUserLoginIdRestriction;
  8091.             }
  8092.         }
  8093.         if ($dataSet == null$dataSet = [];
  8094. //        return new JsonResponse(array(
  8095. //            'queryStr'=>$queryStr
  8096. //        ));
  8097.         if (!empty($datasetFromConfig)) {
  8098.             if (isset($datasetFromConfig['tableName'])) {
  8099.                 $isSingleDataset 1;
  8100.                 $dataSet[] = $datasetFromConfig;
  8101.             } else {
  8102.                 if (count($datasetFromConfig) == 1)
  8103.                     $isSingleDataset 1;
  8104.                 $dataSet $datasetFromConfig;
  8105.             }
  8106.         }
  8107.         if (empty($dataSet)) {
  8108.             $isSingleDataset 1;
  8109.             $singleDataSet = array(
  8110.                 "valueField" => $request->request->has('valueField') ? $request->request->get('valueField') : 'id',
  8111.                 "query" => $request->get('query'$queryStr),
  8112.                 "headMarkers" => $request->get('headMarkers'''),
  8113.                 "headMarkersStrictMatch" => $request->get('headMarkersStrictMatch'0),
  8114.                 "itemLimit" => $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25,
  8115.                 "selectorId" => $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_',
  8116.                 "textField" => $request->request->has('textField') ? $request->request->get('textField') : 'name',
  8117.                 "tableName" => $request->request->has('tableName') ? $request->request->get('tableName') : '',
  8118.                 "isMultiple" => $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0,
  8119.                 "orConditions" => $request->request->has('orConditions') ? $request->request->get('orConditions') : [],
  8120.                 "andConditions" => $request->request->has('andConditions') ? $request->request->get('andConditions') : [],
  8121.                 "andOrConditions" => $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [],
  8122.                 "mustConditions" => $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [],
  8123.                 "joinTableData" => $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [],
  8124.                 "selectFieldList" => $request->request->has('selectFieldList') ? $request->request->get('selectFieldList') : ['*'],
  8125.                 "renderTextFormat" => $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '',
  8126.                 "setDataForSingle" => $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0,
  8127.                 "dataId" => $request->request->has('dataId') ? $request->request->get('dataId') : 0,
  8128.                 "lastChildrenOnly" => $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0,
  8129.                 "parentOnly" => $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0,
  8130.                 "parentIdField" => $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id',
  8131.                 "skipDefaultCompanyId" => $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1,
  8132.                 "offset" => $request->request->has('offset') ? $request->request->get('offset') : 0,
  8133.                 "returnTotalMatchedEntriesFlag" => $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0,
  8134.                 "nextOffset" => 0,
  8135.                 "totalMatchedEntries" => 0,
  8136.                 "convertToObject" => $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [],
  8137.                 "convertDateToStringFieldList" => $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [],
  8138.                 "orderByConditions" => $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [],
  8139.                 "convertToUrl" => $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [],
  8140.                 "fullPathList" => $request->request->has('fullPathList') ? $request->request->get('fullPathList') : [],
  8141.                 "ret_data" => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8142.             );
  8143.             $dataSet[] = $singleDataSet;
  8144.         }
  8145. //        $lastResult = [
  8146. //            'identifier' => $identifier,
  8147. //            'dataSet' => $dataSet,
  8148. //        ];
  8149. //        return new JsonResponse($lastResult);
  8150.         $userId $request->getSession()->get(UserConstants::USER_ID);
  8151. //        public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [],$userId=0)
  8152.         foreach ($dataSet as $dsIndex => $dataConfig) {
  8153.             $companyId 0;
  8154.             $queryStringIndividual $queryStr;
  8155.             $data = [];
  8156.             $data_by_id = [];
  8157.             $setValueArray = [];
  8158.             $silentChangeSelectize 0;
  8159.             $setValue 0;
  8160.             $setValueType 0;// 0 for id , 1 for query
  8161.             $selectAll 0;
  8162.             $selectAllFound 0;
  8163.             if (isset($dataConfig['query']))
  8164.                 $queryStringIndividual $dataConfig['query'];
  8165.             if ((strpos($queryStringIndividual'_set_matching_value_') !== false)) {
  8166.                 $selectAllFound 1;
  8167.                 $queryStringIndividual str_ireplace('_set_matching_value_'''$queryStringIndividual);
  8168.             }
  8169.             if ($queryStringIndividual == '_EMPTY_')
  8170.                 $queryStringIndividual '';
  8171.             if ($queryStringIndividual == '_EMPTY_')
  8172.                 $queryStringIndividual '';
  8173.             $queryStringIndividual str_replace('_FSLASH_''/'$queryStringIndividual);
  8174.             if ($queryStringIndividual === '#setValue:') {
  8175.                 $queryStringIndividual '';
  8176.             }
  8177.             if (!(strpos($queryStringIndividual'_silent_change_') === false)) {
  8178.                 $silentChangeSelectize 1;
  8179.                 $queryStringIndividual str_ireplace('_silent_change_'''$queryStringIndividual);
  8180.             }
  8181.             if (!(strpos($queryStringIndividual'#setValue:') === false)) {
  8182.                 $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStringIndividual));
  8183.                 foreach ($setValueArrayBeforeFilter as $svf) {
  8184.                     if ($svf == '_ALL_') {
  8185.                         $selectAll 1;
  8186.                         $setValueArray = [];
  8187.                         continue;
  8188.                     }
  8189.                     if (is_numeric($svf)) {
  8190.                         $setValueArray[] = ($svf 1);
  8191.                         $setValue $svf 1;
  8192.                     }
  8193.                 }
  8194.                 $queryStringIndividual '';
  8195.             }
  8196.             $valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
  8197.             $headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''//Special Field
  8198.             $headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0//Special Field
  8199.             $itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
  8200.             $selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
  8201.             $textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
  8202.             $table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
  8203.             $isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
  8204.             $orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
  8205.             $andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
  8206.             $andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
  8207.             $mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
  8208.             $joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
  8209.             $renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
  8210.             $setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
  8211.             $dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
  8212.             $lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
  8213.             $parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
  8214.             $parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
  8215.             $skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
  8216.             $offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
  8217.             $returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
  8218.             $nextOffset 0;
  8219.             $totalMatchedEntries 0;
  8220.             $convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
  8221.             $convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
  8222.             $orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
  8223.             $convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
  8224.             $fullPathList = isset($dataConfig['fullPathList']) ? $dataConfig['fullPathList'] : [];
  8225.             if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  8226.             if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  8227.             if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  8228.             if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  8229.             if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  8230.             if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  8231.             if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  8232.             if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  8233.             if (is_string($fullPathList)) $fullPathList json_decode($fullPathListtrue);
  8234. //            return new JsonResponse(array(
  8235. //                'dataSet'=>$dataSet,
  8236. //                'dataConfig'=>$dataConfig,
  8237. //                'hi'=>$this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json',
  8238. //                'hiD'=>file_get_contents($this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json')
  8239. //            ));
  8240.             if ($table == '') {
  8241.                 $lastResult = array(
  8242.                     'success' => false,
  8243.                     'currentTs' => (new \Datetime())->format('U'),
  8244.                     'isMultiple' => $isMultiple,
  8245.                     'setValueArray' => $setValueArray,
  8246.                     'setValue' => $setValue,
  8247.                     'data' => $data,
  8248.                     'dataId' => $dataId,
  8249.                     'selectorId' => $selectorId,
  8250.                     'dataById' => $data_by_id,
  8251.                     'selectedId' => 0,
  8252.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8253.                 );
  8254.             } else {
  8255.                 $restrictionData = array(
  8256. //            'table'=>'relevantField in restriction'
  8257.                     'warehouse_action' => 'warehouseActionIds',
  8258.                     'branch' => 'branchIds',
  8259.                     'warehouse' => 'warehouseIds',
  8260.                     'production_process_settings' => 'productionProcessIds',
  8261.                 );
  8262.                 $restrictionIdList = [];
  8263.                 $filterQryForCriteria "select ";
  8264.                 $selectQry "";
  8265. //        $selectQry=" `$table`.* ";
  8266.                 $selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
  8267.                 $selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
  8268.                 if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  8269.                 foreach ($selectFieldList as $selFieldFull) {
  8270.                     if ($selectQry != '')
  8271.                         $selectQry .= ", ";
  8272.                     $selFieldArray explode(' '$selFieldFull);
  8273.                     $selField $selFieldArray[0];
  8274.                     $selFieldAlias $selFieldArray[1] ?? '';
  8275.                     if ($selField == '*')
  8276.                         $selectQry .= " `$table`.$selField ";
  8277.                     else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  8278.                         if ($selectPrefix == '')
  8279.                             $selectQry .= " count(*)  ";
  8280.                         else
  8281.                             $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  8282.                     } else {
  8283.                         if ($selectPrefix == '')
  8284.                             $selectQry .= " `$table`.`$selField`  $selFieldAlias";
  8285.                         else
  8286.                             $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  8287.                     }
  8288.                 }
  8289.                 $joinQry " from $table ";
  8290. //        $filterQryForCriteria = "select * from $table ";
  8291.                 foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  8292. //            $conditionStr.=' 1=1 ';
  8293.                     $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  8294.                     $joinTableAlias $joinTableName '_' $joinIndex;
  8295.                     $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  8296.                     $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  8297.                     $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  8298.                     $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  8299.                     $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  8300.                     $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  8301.                     $joinMustConditions = isset($joinTableDatum['joinMustConditions']) ? $joinTableDatum['joinMustConditions'] : [];
  8302.                     $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  8303.                     $joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
  8304.                     $joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
  8305.                     if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  8306.                     if (is_string($joinMustConditions)) $joinMustConditions json_decode($joinMustConditionstrue);
  8307.                     if (is_string($joinAndOrConditions)) $joinAndOrConditions json_decode($joinAndOrConditionstrue);
  8308.                     if (is_string($joinOrConditions)) $joinOrConditions json_decode($joinOrConditionstrue);
  8309.                     foreach ($selectFieldList as $selFieldFull) {
  8310.                         $selFieldArray explode(' '$selFieldFull);
  8311.                         $selField $selFieldArray[0];
  8312.                         $selFieldAlias $selFieldArray[1] ?? '';
  8313.                         if ($selField == '*')
  8314.                             $selectQry .= ", `$joinTableAlias`.$selField ";
  8315.                         else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  8316.                             if ($selectPrefix == '')
  8317.                                 $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  8318.                             else
  8319.                                 $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  8320.                         } else {
  8321.                             if ($selectPrefix == '')
  8322.                                 $selectQry .= ", `$joinTableAlias`.`$selField`  $selFieldAlias";
  8323.                             else
  8324.                                 $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  8325.                         }
  8326.                     }
  8327.                     $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  8328. //            if($joinTablePrimaryField!='')
  8329. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8330. //            $joinAndString = '';
  8331.                     $joinMustString '';
  8332.                     if ($joinTablePrimaryField != '') {
  8333.                         if (!(strpos($joinTablePrimaryField'.') === false)) {
  8334.                             $joinQry .= "  `$joinTableAlias`.`$joinTableOnField`  $fieldJoinType $joinTablePrimaryField ";
  8335.                         } else
  8336.                             $joinQry .= "  `$joinTableAlias`.`$joinTableOnField`  $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8337.                     }
  8338.                     foreach ($joinMustConditions as $mustCondition) {
  8339. //            $conditionStr.=' 1=1 ';
  8340.                         $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  8341.                         $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  8342.                         $aliasInCondition $table;
  8343.                         if (!(strpos($cfield'.') === false)) {
  8344.                             $fullCfieldArray explode('.'$cfield);
  8345.                             $aliasInCondition $fullCfieldArray[0];
  8346.                             $cfield $fullCfieldArray[1];
  8347.                         }
  8348.                         $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  8349.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8350.                             if ($joinMustString != '')
  8351.                                 $joinMustString .= " and ";
  8352.                             if ($ctype == 'like') {
  8353.                                 $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8354.                                 $wordsBySpaces explode(' '$cvalue);
  8355.                                 foreach ($wordsBySpaces as $word) {
  8356.                                     if ($joinMustString != '')
  8357.                                         $joinMustString .= " and ";
  8358.                                     $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8359.                                 }
  8360.                             } else if ($ctype == 'not like') {
  8361.                                 $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8362.                                 $wordsBySpaces explode(' '$cvalue);
  8363.                                 foreach ($wordsBySpaces as $word) {
  8364.                                     if ($joinMustString != '')
  8365.                                         $joinMustString .= " and ";
  8366.                                     $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8367.                                 }
  8368.                             } else if ($ctype == 'not_in') {
  8369.                                 $joinMustString .= " ( ";
  8370.                                 if (in_array('null'$cvalue)) {
  8371.                                     $joinMustString .= " `$joinTableAlias`.$cfield is not null";
  8372.                                     $cvalue array_diff($cvalue, ['null']);
  8373.                                     if (!empty($cvalue))
  8374.                                         $joinMustString .= " and ";
  8375.                                 }
  8376.                                 if (in_array(''$cvalue)) {
  8377.                                     $joinMustString .= "`$joinTableAlias`.$cfield != '' ";
  8378.                                     $cvalue array_diff($cvalue, ['']);
  8379.                                     if (!empty($cvalue))
  8380.                                         $joinMustString .= " and ";
  8381.                                 }
  8382.                                 $joinMustString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8383.                             } else if ($ctype == 'in') {
  8384.                                 if (in_array('null'$cvalue)) {
  8385.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null";
  8386.                                     $cvalue array_diff($cvalue, ['null']);
  8387.                                     if (!empty($cvalue))
  8388.                                         $joinMustString .= " and ";
  8389.                                 }
  8390.                                 if (in_array(''$cvalue)) {
  8391.                                     $joinMustString .= "`$joinTableAlias`.$cfield = '' ";
  8392.                                     $cvalue array_diff($cvalue, ['']);
  8393.                                     if (!empty($cvalue))
  8394.                                         $joinMustString .= " and ";
  8395.                                 }
  8396.                                 $joinMustString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8397.                             } else if ($ctype == '=') {
  8398. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8399. //                            $fullCfieldArray = explode('.', $cfield);
  8400. //                            $aliasInCondition = $fullCfieldArray[0];
  8401. //                            $cfield = $fullCfieldArray[1];
  8402. //                        }
  8403.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8404.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null ";
  8405.                                 else
  8406.                                     $joinMustString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8407.                             } else if ($ctype == '!=') {
  8408.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8409.                                     $joinMustString .= "`$joinTableAlias`.$cfield is not null ";
  8410.                                 else
  8411.                                     $joinMustString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8412.                             } else {
  8413.                                 if (is_string($cvalue))
  8414.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8415.                                 else
  8416.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8417.                             }
  8418.                         }
  8419.                     }
  8420. //            if ($joinMustString != '') {
  8421. //                if ($conditionStr != '')
  8422. //                    $conditionStr .= (" and (" . $joinMustString . ") ");
  8423. //                else
  8424. //                    $conditionStr .= ("  (" . $joinMustString . ") ");
  8425. //            }
  8426.                     if ($joinMustString != '') {
  8427.                         $joinQry .= (' and ' $joinMustString);
  8428. //                        $joinQry.=' and (';
  8429.                     }
  8430.                     $mustBracketDone 0;
  8431.                     $joinAndString '';
  8432. //                    if ($joinTablePrimaryField != '')
  8433. //                        $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8434.                     foreach ($joinAndConditions as $andCondition) {
  8435. //            $conditionStr.=' 1=1 ';
  8436.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  8437.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  8438.                         $aliasInCondition $table;
  8439.                         if (!(strpos($cfield'.') === false)) {
  8440.                             $fullCfieldArray explode('.'$cfield);
  8441.                             $aliasInCondition $fullCfieldArray[0];
  8442.                             $cfield $fullCfieldArray[1];
  8443.                         }
  8444.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  8445.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8446.                             if ($joinAndString != '')
  8447.                                 $joinAndString .= " and ";
  8448.                             if ($ctype == 'like') {
  8449.                                 $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8450.                                 $wordsBySpaces explode(' '$cvalue);
  8451.                                 foreach ($wordsBySpaces as $word) {
  8452.                                     if ($joinAndString != '')
  8453.                                         $joinAndString .= " and ";
  8454.                                     $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8455.                                 }
  8456.                             } else if ($ctype == 'not like') {
  8457.                                 $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8458.                                 $wordsBySpaces explode(' '$cvalue);
  8459.                                 foreach ($wordsBySpaces as $word) {
  8460.                                     if ($joinAndString != '')
  8461.                                         $joinAndString .= " and ";
  8462.                                     $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8463.                                 }
  8464.                             } else if ($ctype == 'not_in') {
  8465.                                 $joinAndString .= " ( ";
  8466.                                 if (in_array('null'$cvalue)) {
  8467.                                     $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  8468.                                     $cvalue array_diff($cvalue, ['null']);
  8469.                                     if (!empty($cvalue))
  8470.                                         $joinAndString .= " and ";
  8471.                                 }
  8472.                                 if (in_array(''$cvalue)) {
  8473.                                     $joinAndString .= "`$joinTableAlias`.$cfield != '' ";
  8474.                                     $cvalue array_diff($cvalue, ['']);
  8475.                                     if (!empty($cvalue))
  8476.                                         $joinAndString .= " and ";
  8477.                                 }
  8478.                                 $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8479.                             } else if ($ctype == 'in') {
  8480.                                 if (in_array('null'$cvalue)) {
  8481.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null";
  8482.                                     $cvalue array_diff($cvalue, ['null']);
  8483.                                     if (!empty($cvalue))
  8484.                                         $joinAndString .= " and ";
  8485.                                 }
  8486.                                 if (in_array(''$cvalue)) {
  8487.                                     $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  8488.                                     $cvalue array_diff($cvalue, ['']);
  8489.                                     if (!empty($cvalue))
  8490.                                         $joinAndString .= " and ";
  8491.                                 }
  8492.                                 $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8493.                             } else if ($ctype == '=') {
  8494. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8495. //                            $fullCfieldArray = explode('.', $cfield);
  8496. //                            $aliasInCondition = $fullCfieldArray[0];
  8497. //                            $cfield = $fullCfieldArray[1];
  8498. //                        }
  8499.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8500.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  8501.                                 else
  8502.                                     $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8503.                             } else if ($ctype == '!=') {
  8504.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8505.                                     $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  8506.                                 else
  8507.                                     $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8508.                             } else {
  8509.                                 if (is_string($cvalue))
  8510.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8511.                                 else
  8512.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8513.                             }
  8514.                         }
  8515.                     }
  8516. //            if ($joinAndString != '') {
  8517. //                if ($conditionStr != '')
  8518. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  8519. //                else
  8520. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  8521. //            }
  8522.                     if ($joinAndString != '') {
  8523.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  8524.                             $joinQry .= ' and (';
  8525.                             $mustBracketDone 1;
  8526.                         }
  8527.                         if ($joinQry != '')
  8528.                             $joinQry .= (" and (" $joinAndString ") ");
  8529.                         else
  8530.                             $joinQry .= ("  (" $joinAndString ") ");
  8531.                     }
  8532.                     $joinAndOrString "";
  8533.                     foreach ($joinAndOrConditions as $andOrCondition) {
  8534. //            $conditionStr.=' 1=1 ';
  8535.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  8536.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  8537.                         $aliasInCondition $table;
  8538.                         if (!(strpos($cfield'.') === false)) {
  8539.                             $fullCfieldArray explode('.'$cfield);
  8540.                             $aliasInCondition $fullCfieldArray[0];
  8541.                             $cfield $fullCfieldArray[1];
  8542.                         }
  8543.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  8544.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8545.                             if ($joinAndOrString != '')
  8546.                                 $joinAndOrString .= " or ";
  8547.                             if ($ctype == 'like') {
  8548.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8549.                                 $wordsBySpaces explode(' '$cvalue);
  8550.                                 foreach ($wordsBySpaces as $word) {
  8551.                                     if ($joinAndOrString != '')
  8552.                                         $joinAndOrString .= " or ";
  8553.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8554.                                 }
  8555.                             } else if ($ctype == 'not like') {
  8556.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8557.                                 $wordsBySpaces explode(' '$cvalue);
  8558.                                 foreach ($wordsBySpaces as $word) {
  8559.                                     if ($joinAndOrString != '')
  8560.                                         $joinAndOrString .= " or ";
  8561.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8562.                                 }
  8563.                             } else if ($ctype == 'not_in') {
  8564.                                 $joinAndOrString .= " ( ";
  8565.                                 if (in_array('null'$cvalue)) {
  8566.                                     $joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
  8567.                                     $cvalue array_diff($cvalue, ['null']);
  8568.                                     if (!empty($cvalue))
  8569.                                         $joinAndOrString .= " or ";
  8570.                                 }
  8571.                                 if (in_array(''$cvalue)) {
  8572.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != '' ";
  8573.                                     $cvalue array_diff($cvalue, ['']);
  8574.                                     if (!empty($cvalue))
  8575.                                         $joinAndOrString .= " or ";
  8576.                                 }
  8577.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8578.                             } else if ($ctype == 'in') {
  8579.                                 if (in_array('null'$cvalue)) {
  8580.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null";
  8581.                                     $cvalue array_diff($cvalue, ['null']);
  8582.                                     if (!empty($cvalue))
  8583.                                         $joinAndOrString .= " or ";
  8584.                                 }
  8585.                                 if (in_array(''$cvalue)) {
  8586.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  8587.                                     $cvalue array_diff($cvalue, ['']);
  8588.                                     if (!empty($cvalue))
  8589.                                         $joinAndOrString .= " or ";
  8590.                                 }
  8591.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8592.                             } else if ($ctype == '=') {
  8593. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8594. //                            $fullCfieldArray = explode('.', $cfield);
  8595. //                            $aliasInCondition = $fullCfieldArray[0];
  8596. //                            $cfield = $fullCfieldArray[1];
  8597. //                        }
  8598.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8599.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
  8600.                                 else
  8601.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8602.                             } else if ($ctype == '!=') {
  8603.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8604.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
  8605.                                 else
  8606.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8607.                             } else {
  8608.                                 if (is_string($cvalue))
  8609.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8610.                                 else
  8611.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8612.                             }
  8613.                         }
  8614.                     }
  8615. //            if ($joinAndOrString != '')
  8616. //                $joinQry .= $joinAndOrString;
  8617.                     if ($joinAndOrString != '') {
  8618.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  8619.                             $joinQry .= ' and (';
  8620.                             $mustBracketDone 1;
  8621.                         }
  8622.                         if ($joinQry != '')
  8623.                             $joinQry .= (" and (" $joinAndOrString ") ");
  8624.                         else
  8625.                             $joinQry .= ("  (" $joinAndOrString ") ");
  8626.                     }
  8627.                     //pika
  8628.                     $joinOrString "";
  8629.                     foreach ($joinOrConditions as $orCondition) {
  8630. //            $conditionStr.=' 1=1 ';
  8631.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  8632.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  8633.                         $aliasInCondition $table;
  8634.                         if (!(strpos($cfield'.') === false)) {
  8635.                             $fullCfieldArray explode('.'$cfield);
  8636.                             $aliasInCondition $fullCfieldArray[0];
  8637.                             $cfield $fullCfieldArray[1];
  8638.                         }
  8639.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  8640.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8641.                             if ($joinOrString != '' || $joinAndString != '' || $joinMustString != '')
  8642.                                 $joinOrString .= " or ";
  8643.                             if ($ctype == 'like') {
  8644.                                 $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8645.                                 $wordsBySpaces explode(' '$cvalue);
  8646.                                 foreach ($wordsBySpaces as $word) {
  8647.                                     if ($joinOrString != '')
  8648.                                         $joinOrString .= " or ";
  8649.                                     $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8650.                                 }
  8651.                             } else if ($ctype == 'not like') {
  8652.                                 $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8653.                                 $wordsBySpaces explode(' '$cvalue);
  8654.                                 foreach ($wordsBySpaces as $word) {
  8655.                                     if ($joinOrString != '')
  8656.                                         $joinOrString .= " or ";
  8657.                                     $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8658.                                 }
  8659.                             } else if ($ctype == 'not_in') {
  8660.                                 $joinOrString .= " ( ";
  8661.                                 if (in_array('null'$cvalue)) {
  8662.                                     $joinOrString .= " `$joinTableAlias`.$cfield is not null";
  8663.                                     $cvalue array_diff($cvalue, ['null']);
  8664.                                     if (!empty($cvalue))
  8665.                                         $joinOrString .= " or ";
  8666.                                 }
  8667.                                 if (in_array(''$cvalue)) {
  8668.                                     $joinOrString .= "`$joinTableAlias`.$cfield != '' ";
  8669.                                     $cvalue array_diff($cvalue, ['']);
  8670.                                     if (!empty($cvalue))
  8671.                                         $joinOrString .= " or ";
  8672.                                 }
  8673.                                 $joinOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8674.                             } else if ($ctype == 'in') {
  8675.                                 if (in_array('null'$cvalue)) {
  8676.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null";
  8677.                                     $cvalue array_diff($cvalue, ['null']);
  8678.                                     if (!empty($cvalue))
  8679.                                         $joinOrString .= " or ";
  8680.                                 }
  8681.                                 if (in_array(''$cvalue)) {
  8682.                                     $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  8683.                                     $cvalue array_diff($cvalue, ['']);
  8684.                                     if (!empty($cvalue))
  8685.                                         $joinOrString .= " or ";
  8686.                                 }
  8687.                                 $joinOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8688.                             } else if ($ctype == '=') {
  8689. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8690. //                            $fullCfieldArray = explode('.', $cfield);
  8691. //                            $aliasInCondition = $fullCfieldArray[0];
  8692. //                            $cfield = $fullCfieldArray[1];
  8693. //                        }
  8694.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8695.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null ";
  8696.                                 else
  8697.                                     $joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8698.                             } else if ($ctype == '!=') {
  8699.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8700.                                     $joinOrString .= "`$joinTableAlias`.$cfield is not null ";
  8701.                                 else
  8702.                                     $joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8703.                             } else {
  8704.                                 if (is_string($cvalue))
  8705.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8706.                                 else
  8707.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8708.                             }
  8709.                         }
  8710.                     }
  8711. //            if ($joinOrString != '')
  8712. //                $joinQry .= $joinOrString;
  8713.                     if ($joinOrString != '') {
  8714.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  8715.                             $joinQry .= ' and (';
  8716.                             $mustBracketDone 1;
  8717.                         }
  8718.                         if ($joinQry != '')
  8719.                             $joinQry .= (" or (" $joinOrString ") ");
  8720.                         else
  8721.                             $joinQry .= ("  (" $joinOrString ") ");
  8722.                     }
  8723.                     if ($joinMustString != '' && $mustBracketDone == 1) {
  8724.                         $joinQry .= ' ) ';
  8725.                     }
  8726. //
  8727. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8728.                 }
  8729.                 $filterQryForCriteria .= $selectQry;
  8730.                 $filterQryForCriteria .= $joinQry;
  8731.                 if ($skipDefaultCompanyId == && $companyId != && !isset($dataConfig['entity_group']))
  8732.                     $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  8733.                 else
  8734.                     $filterQryForCriteria .= " where 1=1 ";
  8735.                 $conditionStr "";
  8736.                 $aliasInCondition $table;
  8737.                 if ($headMarkers != '' && $table == 'acc_accounts_head') {
  8738.                     $markerList explode(','$headMarkers);
  8739.                     $spMarkerQry "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
  8740.                     $markerPassedHeads = [];
  8741.                     foreach ($markerList as $mrkr) {
  8742.                         $spMarkerQry .= " and marker_hash like '%" $mrkr "%'";
  8743.                     }
  8744.                     $spStmt $em->getConnection()->fetchAllAssociative($spMarkerQry);
  8745.                     $spStmtResults $spStmt;
  8746.                     foreach ($spStmtResults as $ggres) {
  8747.                         $markerPassedHeads[] = $ggres['accounts_head_id'];
  8748.                     }
  8749.                     if (!empty($markerPassedHeads)) {
  8750.                         if ($conditionStr != '')
  8751.                             $conditionStr .= " and (";
  8752.                         else
  8753.                             $conditionStr .= " (";
  8754.                         if ($headMarkersStrictMatch != 1) {
  8755.                             foreach ($markerPassedHeads as $mh) {
  8756.                                 $conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" $mh "/%' or ";
  8757.                             }
  8758.                         }
  8759.                         $conditionStr .= "  `$aliasInCondition`.`accounts_head_id` in (" implode(','$markerPassedHeads) . ") ";
  8760.                         $conditionStr .= " )";
  8761.                     }
  8762.                 }
  8763.                 if (isset($restrictionData[$table])) {
  8764.                     $userRestrictionData Users::getUserApplicationAccessSettings($em$userId)['options'];
  8765.                     if (isset($userRestrictionData[$restrictionData[$table]])) {
  8766.                         $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  8767.                         if ($restrictionIdList == null)
  8768.                             $restrictionIdList = [];
  8769.                     }
  8770.                     if (!empty($restrictionIdList)) {
  8771.                         if ($conditionStr != '')
  8772.                             $conditionStr .= " and ";
  8773.                         $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  8774.                     }
  8775.                 }
  8776. //        $aliasInCondition = $table;
  8777.                 if (!empty($setValueArray) || $selectAll == 1) {
  8778.                     if (!empty($setValueArray)) {
  8779.                         if ($conditionStr != '')
  8780.                             $conditionStr .= " and ";
  8781.                         $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  8782.                     }
  8783.                 } else {
  8784.                     $andString '';
  8785.                     foreach ($andConditions as $andCondition) {
  8786. //            $conditionStr.=' 1=1 ';
  8787.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  8788.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  8789.                         $aliasInCondition $table;
  8790.                         if (!(strpos($cfield'.') === false)) {
  8791.                             $fullCfieldArray explode('.'$cfield);
  8792.                             $aliasInCondition $fullCfieldArray[0];
  8793.                             $cfield $fullCfieldArray[1];
  8794.                         }
  8795.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  8796.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8797.                             if ($andString != '')
  8798.                                 $andString .= " and ";
  8799.                             if ($ctype == 'like') {
  8800.                                 $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8801.                                 $wordsBySpaces explode(' '$cvalue);
  8802.                                 foreach ($wordsBySpaces as $word) {
  8803.                                     if ($andString != '')
  8804.                                         $andString .= " and ";
  8805.                                     $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8806.                                 }
  8807.                             } else if ($ctype == 'not like') {
  8808.                                 $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8809.                                 $wordsBySpaces explode(' '$cvalue);
  8810.                                 foreach ($wordsBySpaces as $word) {
  8811.                                     if ($andString != '')
  8812.                                         $andString .= " and ";
  8813.                                     $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8814.                                 }
  8815.                             } else if ($ctype == 'not_in') {
  8816.                                 $andString .= " ( ";
  8817.                                 if (in_array('null'$cvalue)) {
  8818.                                     $andString .= " `$aliasInCondition`.$cfield is not null";
  8819.                                     $cvalue array_diff($cvalue, ['null']);
  8820.                                     if (!empty($cvalue))
  8821.                                         $andString .= " and ";
  8822.                                 }
  8823.                                 if (in_array(''$cvalue)) {
  8824.                                     $andString .= "`$aliasInCondition`.$cfield != '' ";
  8825.                                     $cvalue array_diff($cvalue, ['']);
  8826.                                     if (!empty($cvalue))
  8827.                                         $andString .= " and ";
  8828.                                 }
  8829.                                 $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8830.                             } else if ($ctype == 'in') {
  8831.                                 if (in_array('null'$cvalue)) {
  8832.                                     $andString .= "`$aliasInCondition`.$cfield is null";
  8833.                                     $cvalue array_diff($cvalue, ['null']);
  8834.                                     if (!empty($cvalue))
  8835.                                         $andString .= " and ";
  8836.                                 }
  8837.                                 if (in_array(''$cvalue)) {
  8838.                                     $andString .= "`$aliasInCondition`.$cfield = '' ";
  8839.                                     $cvalue array_diff($cvalue, ['']);
  8840.                                     if (!empty($cvalue))
  8841.                                         $andString .= " and ";
  8842.                                 }
  8843.                                 $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  8844.                             } else if ($ctype == '=') {
  8845.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8846.                                     $andString .= "`$aliasInCondition`.$cfield is null ";
  8847.                                 else
  8848.                                     if (is_string($cvalue))
  8849.                                         $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8850.                                     else
  8851.                                         $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8852.                             } else if ($ctype == '!=') {
  8853.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8854.                                     $andString .= "`$aliasInCondition`.$cfield is not null ";
  8855.                                 else
  8856.                                     $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8857.                             } else {
  8858.                                 if (is_string($cvalue))
  8859.                                     $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8860.                                 else
  8861.                                     $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8862.                             }
  8863.                         }
  8864.                     }
  8865.                     if ($andString != '') {
  8866.                         if ($conditionStr != '')
  8867.                             $conditionStr .= (" and (" $andString ") ");
  8868.                         else
  8869.                             $conditionStr .= ("  (" $andString ") ");
  8870.                     }
  8871.                     $orString '';
  8872.                     foreach ($orConditions as $orCondition) {
  8873.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  8874.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  8875.                         $aliasInCondition $table;
  8876.                         if (!(strpos($cfield'.') === false)) {
  8877.                             $fullCfieldArray explode('.'$cfield);
  8878.                             $aliasInCondition $fullCfieldArray[0];
  8879.                             $cfield $fullCfieldArray[1];
  8880.                         }
  8881.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  8882.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8883.                             if ($orString != '')
  8884.                                 $orString .= " or ";
  8885.                             if ($ctype == 'like') {
  8886.                                 $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8887.                                 $wordsBySpaces explode(' '$cvalue);
  8888.                                 foreach ($wordsBySpaces as $word) {
  8889.                                     if ($orString != '')
  8890.                                         $orString .= " or ";
  8891.                                     $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8892.                                 }
  8893.                             } else if ($ctype == 'not like') {
  8894.                                 $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8895.                                 $wordsBySpaces explode(' '$cvalue);
  8896.                                 foreach ($wordsBySpaces as $word) {
  8897.                                     if ($orString != '')
  8898.                                         $orString .= " or ";
  8899.                                     $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8900.                                 }
  8901.                             } else if ($ctype == 'not_in') {
  8902.                                 $orString .= " ( ";
  8903.                                 if (in_array('null'$cvalue)) {
  8904.                                     $orString .= " `$aliasInCondition`.$cfield is not null";
  8905.                                     $cvalue array_diff($cvalue, ['null']);
  8906.                                     if (!empty($cvalue))
  8907.                                         $orString .= " or ";
  8908.                                 }
  8909.                                 if (in_array(''$cvalue)) {
  8910.                                     $orString .= "`$aliasInCondition`.$cfield != '' ";
  8911.                                     $cvalue array_diff($cvalue, ['']);
  8912.                                     if (!empty($cvalue))
  8913.                                         $orString .= " or ";
  8914.                                 }
  8915.                                 $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8916.                             } else if ($ctype == 'in') {
  8917.                                 $orString .= " ( ";
  8918.                                 if (in_array('null'$cvalue)) {
  8919.                                     $orString .= " `$aliasInCondition`.$cfield is null";
  8920.                                     $cvalue array_diff($cvalue, ['null']);
  8921.                                     if (!empty($cvalue))
  8922.                                         $orString .= " or ";
  8923.                                 }
  8924.                                 if (in_array(''$cvalue)) {
  8925.                                     $orString .= "`$aliasInCondition`.$cfield = '' ";
  8926.                                     $cvalue array_diff($cvalue, ['']);
  8927.                                     if (!empty($cvalue))
  8928.                                         $orString .= " or ";
  8929.                                 }
  8930.                                 $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8931.                             } else if ($ctype == '=') {
  8932.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8933.                                     $orString .= "`$aliasInCondition`.$cfield is null ";
  8934.                                 else
  8935.                                     if (is_string($cvalue))
  8936.                                         $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8937.                                     else
  8938.                                         $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8939.                             } else if ($ctype == '!=') {
  8940.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8941.                                     $orString .= "`$aliasInCondition`.$cfield is not null ";
  8942.                                 else
  8943.                                     $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8944.                             } else {
  8945.                                 if (is_string($cvalue))
  8946.                                     $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8947.                                 else
  8948.                                     $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8949.                             }
  8950.                         }
  8951.                     }
  8952.                     if ($orString != '') {
  8953.                         if ($conditionStr != '')
  8954.                             $conditionStr .= (" or (" $orString ") ");
  8955.                         else
  8956.                             $conditionStr .= ("  (" $orString ") ");
  8957.                     }
  8958.                     $andOrString '';
  8959.                     foreach ($andOrConditions as $andOrCondition) {
  8960.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  8961.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  8962.                         $aliasInCondition $table;
  8963.                         if (!(strpos($cfield'.') === false)) {
  8964.                             $fullCfieldArray explode('.'$cfield);
  8965.                             $aliasInCondition $fullCfieldArray[0];
  8966.                             $cfield $fullCfieldArray[1];
  8967.                         }
  8968.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  8969.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8970.                             if ($andOrString != '')
  8971.                                 $andOrString .= " or ";
  8972.                             if ($ctype == 'like') {
  8973.                                 $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8974.                                 $wordsBySpaces explode(' '$cvalue);
  8975.                                 foreach ($wordsBySpaces as $word) {
  8976.                                     if ($andOrString != '')
  8977.                                         $andOrString .= " or ";
  8978.                                     $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8979.                                 }
  8980.                             } else if ($ctype == 'not like') {
  8981.                                 $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8982.                                 $wordsBySpaces explode(' '$cvalue);
  8983.                                 foreach ($wordsBySpaces as $word) {
  8984.                                     if ($andOrString != '')
  8985.                                         $andOrString .= " or ";
  8986.                                     $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8987.                                 }
  8988.                             } else if ($ctype == 'in') {
  8989.                                 $andOrString .= " ( ";
  8990.                                 if (in_array('null'$cvalue)) {
  8991.                                     $andOrString .= " `$aliasInCondition`.$cfield is null";
  8992.                                     $cvalue array_diff($cvalue, ['null']);
  8993.                                     if (!empty($cvalue))
  8994.                                         $andOrString .= " or ";
  8995.                                 }
  8996.                                 if (in_array(''$cvalue)) {
  8997.                                     $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  8998.                                     $cvalue array_diff($cvalue, ['']);
  8999.                                     if (!empty($cvalue))
  9000.                                         $andOrString .= " or ";
  9001.                                 }
  9002.                                 if (!empty($cvalue))
  9003.                                     $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  9004.                                 else
  9005.                                     $andOrString .= "  ) ";
  9006.                             } else if ($ctype == 'not_in') {
  9007.                                 $andOrString .= " ( ";
  9008.                                 if (in_array('null'$cvalue)) {
  9009.                                     $andOrString .= " `$aliasInCondition`.$cfield is not null";
  9010.                                     $cvalue array_diff($cvalue, ['null']);
  9011.                                     if (!empty($cvalue))
  9012.                                         $andOrString .= " or ";
  9013.                                 }
  9014.                                 if (in_array(''$cvalue)) {
  9015.                                     $andOrString .= "`$aliasInCondition`.$cfield != '' ";
  9016.                                     $cvalue array_diff($cvalue, ['']);
  9017.                                     if (!empty($cvalue))
  9018.                                         $andOrString .= " or ";
  9019.                                 }
  9020.                                 if (!empty($cvalue))
  9021.                                     $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  9022.                                 else
  9023.                                     $andOrString .= "  ) ";
  9024.                             } else if ($ctype == '=') {
  9025.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  9026.                                     $andOrString .= "`$aliasInCondition`.$cfield is null ";
  9027.                                 else
  9028.                                     if (is_string($cvalue))
  9029.                                         $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  9030.                                     else
  9031.                                         $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  9032.                             } else if ($ctype == '!=') {
  9033.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  9034.                                     $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  9035.                                 else
  9036.                                     $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  9037.                             } else {
  9038.                                 if (is_string($cvalue))
  9039.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  9040.                                 else
  9041.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  9042.                             }
  9043.                         }
  9044.                     }
  9045.                     if ($andOrString != '') {
  9046.                         if ($conditionStr != '')
  9047.                             $conditionStr .= (" and (" $andOrString ") ");
  9048.                         else
  9049.                             $conditionStr .= ("  (" $andOrString ") ");
  9050.                     }
  9051.                 }
  9052.                 $mustStr '';
  9053. ///now must conditions
  9054.                 foreach ($mustConditions as $mustCondition) {
  9055. //            $conditionStr.=' 1=1 ';
  9056.                     $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  9057.                     $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  9058.                     $aliasInCondition $table;
  9059.                     if (!(strpos($cfield'.') === false)) {
  9060.                         $fullCfieldArray explode('.'$cfield);
  9061.                         $aliasInCondition $fullCfieldArray[0];
  9062.                         $cfield $fullCfieldArray[1];
  9063.                     }
  9064.                     $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  9065.                     if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  9066.                         if ($mustStr != '')
  9067.                             $mustStr .= " and ";
  9068.                         if ($ctype == 'like') {
  9069.                             $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  9070.                             $wordsBySpaces explode(' '$cvalue);
  9071.                             foreach ($wordsBySpaces as $word) {
  9072.                                 if ($mustStr != '')
  9073.                                     $mustStr .= " or ";
  9074.                                 $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  9075.                             }
  9076.                             $mustStr .= " )";
  9077.                         } else if ($ctype == 'not like') {
  9078.                             $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  9079.                             $wordsBySpaces explode(' '$cvalue);
  9080.                             foreach ($wordsBySpaces as $word) {
  9081.                                 if ($mustStr != '')
  9082.                                     $mustStr .= " and ";
  9083.                                 $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  9084.                             }
  9085.                         } else if ($ctype == 'in') {
  9086.                             $mustStr .= " ( ";
  9087.                             if (in_array('null'$cvalue)) {
  9088.                                 $mustStr .= " `$aliasInCondition`.$cfield is null";
  9089.                                 $cvalue array_diff($cvalue, ['null']);
  9090.                                 if (!empty($cvalue))
  9091.                                     $mustStr .= " or ";
  9092.                             }
  9093.                             if (in_array(''$cvalue)) {
  9094.                                 $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  9095.                                 $cvalue array_diff($cvalue, ['']);
  9096.                                 if (!empty($cvalue))
  9097.                                     $mustStr .= " or ";
  9098.                             }
  9099.                             $formattedValues array_map(function ($val) {
  9100.                                 $val trim($val);
  9101.                                 if (is_numeric($val)) {
  9102.                                     return $val;
  9103.                                 }
  9104.                                 return "'" addslashes($val) . "'";
  9105.                             }, $cvalue);
  9106.                             $mustStr .= "`$aliasInCondition`.$cfield IN (" implode(','$formattedValues) . ") ) ";
  9107. //                            $mustStr .= "`$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ) ";
  9108.                         } else if ($ctype == 'not_in') {
  9109.                             $mustStr .= " ( ";
  9110.                             if (in_array('null'$cvalue)) {
  9111.                                 $mustStr .= " `$aliasInCondition`.$cfield is not null";
  9112.                                 $cvalue array_diff($cvalue, ['null']);
  9113.                                 if (!empty($cvalue))
  9114.                                     $mustStr .= " and ";
  9115.                             }
  9116.                             if (in_array(''$cvalue)) {
  9117.                                 $mustStr .= "`$aliasInCondition`.$cfield != '' ";
  9118.                                 $cvalue array_diff($cvalue, ['']);
  9119.                                 if (!empty($cvalue))
  9120.                                     $mustStr .= " and ";
  9121.                             }
  9122.                             $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  9123.                         } else if ($ctype == '=') {
  9124.                             if ($cvalue == 'null' || $cvalue == 'Null')
  9125.                                 $mustStr .= "`$aliasInCondition`.$cfield is null ";
  9126.                             else
  9127.                                 if (is_string($cvalue))
  9128.                                     $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  9129.                                 else
  9130.                                     $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  9131.                         } else if ($ctype == '!=') {
  9132.                             if ($cvalue == 'null' || $cvalue == 'Null')
  9133.                                 $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  9134.                             else
  9135.                                 $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  9136.                         } else {
  9137.                             if (is_string($cvalue))
  9138.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  9139.                             else
  9140.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  9141.                         }
  9142.                     }
  9143.                 }
  9144.                 if ($mustStr != '') {
  9145.                     if ($conditionStr != '')
  9146.                         $conditionStr .= (" and (" $mustStr ") ");
  9147.                     else
  9148.                         $conditionStr .= ("  (" $mustStr ") ");
  9149.                 }
  9150.                 if ($conditionStr != '')
  9151.                     $filterQryForCriteria .= (" and (" $conditionStr ") ");
  9152.                 if ($lastChildrenOnly == 1) {
  9153.                     if ($filterQryForCriteria != '')
  9154.                         $filterQryForCriteria .= ' and ';
  9155.                     $filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  9156.                 } else if ($parentOnly == 1) {
  9157.                     if ($filterQryForCriteria != '')
  9158.                         $filterQryForCriteria .= ' and ';
  9159.                     $filterQryForCriteria .= "`$table`.`$valueField`  in ( select distinct $parentIdField from  $table)";
  9160.                 }
  9161.                 if (!empty($orderByConditions)) {
  9162.                     $filterQryForCriteria .= "  order by ";
  9163.                     $fone 1;
  9164.                     foreach ($orderByConditions as $orderByCondition) {
  9165.                         if ($fone != 1) {
  9166.                             $filterQryForCriteria .= " , ";
  9167.                         }
  9168.                         if (isset($orderByCondition['valueList'])) {
  9169.                             if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  9170.                             if ($orderByCondition['valueList'] == null)
  9171.                                 $orderByCondition['valueList'] = [];
  9172.                             $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  9173.                         } else
  9174.                             $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  9175.                         $fone 0;
  9176.                     }
  9177.                 }
  9178.                 if ($returnTotalMatchedEntriesFlag == 1) {
  9179. //            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9180. //            
  9181. //            $get_kids = $stmt;
  9182.                 }
  9183.                 if ($filterQryForCriteria != '')
  9184.                     if (!empty($setValueArray) || $selectAll == 1) {
  9185.                     } else {
  9186.                         if ($itemLimit != '_ALL_')
  9187.                             $filterQryForCriteria .= "  limit $offset$itemLimit ";
  9188.                         else
  9189.                             $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  9190.                     }
  9191.                 $get_kids_sql $filterQryForCriteria;
  9192.                 $get_kids_sql str_ireplace('_set_matching_value_'''$get_kids_sql);
  9193.                 // TODO: This generic selector assembles SQL across many request-driven table branches.
  9194.                 // Converting it safely requires untangling the shared builder so each branch can bind
  9195.                 // its own parameters without changing selector behavior in unrelated endpoints.
  9196.                 $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9197.                 $get_kids $stmt;
  9198.                 $selectedId 0;
  9199.                 if ($table == 'warehouse_action') {
  9200.                     if (empty($get_kids)) {
  9201.                         $get_kids_sql_2 "select * from warehouse_action";
  9202.                         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql_2);
  9203.                         $get_kids2 $stmt;
  9204.                         if (empty($get_kids2))
  9205.                             $get_kids GeneralConstant::$warehouse_action_list;
  9206.                     }
  9207.                 }
  9208.                 if (!empty($get_kids)) {
  9209.                     $nextOffset $offset count($get_kids);
  9210.                     $nextOffset++;
  9211.                     foreach ($get_kids as $pa) {
  9212.                         if (!empty($setValueArray) && $selectAll == 0) {
  9213.                             if (!in_array($pa[$valueField], $setValueArray))
  9214.                                 continue;
  9215.                         }
  9216.                         if (!empty($restrictionIdList)) {
  9217.                             if (!in_array($pa[$valueField], $restrictionIdList))
  9218.                                 continue;
  9219.                         }
  9220.                         if ($selectAll == || $selectAllFound==1) {
  9221.                             $setValueArray[] = $pa[$valueField];
  9222.                             $setValue $pa[$valueField];
  9223.                         } else if (count($get_kids) == && $setDataForSingle == 1) {
  9224.                             $setValueArray[] = $pa[$valueField];
  9225.                             $setValue $pa[$valueField];
  9226.                         }
  9227.                         if ($valueField != '')
  9228.                             $pa['value'] = $pa[$valueField];
  9229.                         $renderedText $renderTextFormat;
  9230.                         $compare_array = [];
  9231.                         if ($renderTextFormat != '') {
  9232.                             $renderedText $renderTextFormat;
  9233.                             $compare_arrayFull = [];
  9234.                             $compare_array = [];
  9235.                             $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  9236.                             );
  9237.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  9238.                             if (isset($compare_arrayFull[0]))
  9239.                                 $compare_array $compare_arrayFull[0];
  9240. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  9241.                             foreach ($compare_array as $cmpdt) {
  9242.                                 $tbr str_replace("__"""$cmpdt);
  9243.                                 if ($tbr != '') {
  9244.                                     if (isset($pa[$tbr])) {
  9245.                                         if ($pa[$tbr] == null)
  9246.                                             $renderedText str_replace($cmpdt''$renderedText);
  9247.                                         else
  9248.                                             $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  9249.                                     } else {
  9250.                                         $renderedText str_replace($cmpdt''$renderedText);
  9251.                                     }
  9252.                                 }
  9253.                             }
  9254.                         }
  9255.                         $pa['rendered_text'] = $renderedText;
  9256.                         $pa['text'] = ($textField != '' $pa[$textField] : '');
  9257. //                $pa['compare_array'] = $compare_array;
  9258.                         foreach ($convertToObjectFieldList as $convField) {
  9259.                             if (isset($pa[$convField])) {
  9260.                                 $taA json_decode($pa[$convField], true);
  9261.                                 if ($taA == null$taA = [];
  9262.                                 $pa[$convField] = $taA;
  9263.                             } else {
  9264.                                 $pa[$convField] = [];
  9265.                             }
  9266.                         }
  9267.                         foreach ($convertDateToStringFieldList as $convField) {
  9268.                             if (is_array($convField)) {
  9269.                                 $fld $convField['field'];
  9270.                                 $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  9271.                             } else {
  9272.                                 $fld $convField;
  9273.                                 $frmt 'Y-m-d H:i:s';
  9274.                             }
  9275.                             if (isset($pa[$fld])) {
  9276.                                 $taA = new \DateTime($pa[$fld]);
  9277.                                 $pa[$fld] = $taA->format($frmt);
  9278.                             }
  9279.                         }
  9280.                         foreach ($convertToUrl as $convField) {
  9281. //
  9282. //                            $fld = $convField;
  9283. //
  9284. //
  9285. //                            if (isset($pa[$fld])) {
  9286. //
  9287. //
  9288. //                                $pa[$fld] =
  9289. //                                    $this->generateUrl(
  9290. //                                        'dashboard', [
  9291. //
  9292. //                                    ], UrlGenerator::ABSOLUTE_URL
  9293. //                                    ).'/'.$pa[$fld];
  9294. //
  9295. //                            }
  9296.                         }
  9297.                         foreach ($fullPathList as $pathField) {
  9298.                             $fld $pathField;
  9299.                             if (isset($pa[$fld])) {
  9300.                                 if ($pa[$fld] != '' && $pa[$fld] != null) {
  9301.                                     $pa[$fld] = ($this->generateUrl(
  9302.                                             'dashboard', [
  9303.                                         ], UrlGenerator::ABSOLUTE_URL
  9304.                                         ) . $pa[$fld]);
  9305.                                 }
  9306.                             }
  9307.                         }
  9308.                         $pa['currentTs'] = (new \Datetime())->format('U');
  9309.                         $data[] = $pa;
  9310.                         if ($valueField != '') {
  9311.                             $data_by_id[$pa[$valueField]] = $pa;
  9312.                             $selectedId $pa[$valueField];
  9313.                         }
  9314.                     }
  9315.                 }
  9316.                 if ($dataOnly == 1)
  9317.                     $lastResult = array(
  9318.                         'success' => true,
  9319.                         'data' => $data,
  9320.                         'currentTs' => (new \Datetime())->format('U'),
  9321.                         'restrictionIdList' => $restrictionIdList,
  9322.                         'nextOffset' => $nextOffset,
  9323.                         'totalMatchedEntries' => $totalMatchedEntries,
  9324.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  9325.                     );
  9326.                 else
  9327.                     $lastResult = array(
  9328.                         'success' => true,
  9329.                         'data' => $data,
  9330.                         'tableName' => $table,
  9331.                         'setValue' => $setValue,
  9332.                         'currentTs' => (new \Datetime())->format('U'),
  9333.                         'restrictionIdList' => $restrictionIdList,
  9334.                         'andConditions' => $andConditions,
  9335.                         'selectFieldList' => $selectFieldList,
  9336.                         'queryStr' => $queryStringIndividual,
  9337.                         'isMultiple' => $isMultiple,
  9338.                         'nextOffset' => $nextOffset,
  9339.                         'totalMatchedEntries' => $totalMatchedEntries,
  9340.                         'selectorId' => $selectorId,
  9341.                         'setValueArray' => $setValueArray,
  9342.                         'silentChangeSelectize' => $silentChangeSelectize,
  9343.                         'convertToObjectFieldList' => $convertToObjectFieldList,
  9344.                         'conditionStr' => $conditionStr,
  9345.                         'selectAll' => $selectAll,
  9346. //                    'andStr' => $andString,
  9347. //                    'andOrStr' => $andOrString,
  9348.                         'dataById' => $data_by_id,
  9349.                         'selectedId' => $selectedId,
  9350.                         'dataId' => $dataId,
  9351.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  9352.                     );
  9353.             }
  9354.             $allResult[] = $lastResult;
  9355.         }
  9356.         if ($isSingleDataset == 1)
  9357.             return new JsonResponse($lastResult);
  9358.         else
  9359.             return new JsonResponse($allResult);
  9360.     }
  9361.     public function updatePlanningItemSequenceAction(Request $request$queryStr '')
  9362.     {
  9363.         $em $this->getDoctrine()->getManager();
  9364.         $stmt $em->getConnection()->fetchAllAssociative("select  `id` , parent_id, sequence from planning_item where sequence is null 
  9365.             ORDER BY parent_id ASC, id ASC
  9366.                         ");
  9367.         $query_output $stmt;
  9368.         foreach ($query_output as $dupe) {
  9369.             System::updatePlanningItemSequence($em$dupe["id"]);
  9370.         }
  9371.         System::updatePlanningItemSequence(
  9372.             $em,
  9373.             $request->request->get('planningItemId'0),
  9374.             $request->request->get('assignType''_ASSIGN_')   ///can be _MOVE_UP_ or _MOVE_DOWN_
  9375.         );
  9376. //        if($request->query->has('returnJson'))
  9377.         return new JsonResponse(
  9378.             array(
  9379.                 'success' => true,
  9380.                 'data' => [],
  9381.             )
  9382.         );
  9383.     }
  9384.     public function insertDataAjaxAction(Request $request$queryStr '')
  9385.     {
  9386.         $em $this->getDoctrine()->getManager();
  9387. //        if($request->query->has('big_data_test'))
  9388. //        {
  9389. //            for($t=0;$t<$request->request->get('big_data_test',10000);$t++) {
  9390. //                $em = $this->getDoctrine()->getManager('company_group');
  9391. //                $NOTIFICATION = new EntityNotification();
  9392. //                $NOTIFICATION->setAppId(1);
  9393. //                $NOTIFICATION->setCompanyId(0);
  9394. //                $NOTIFICATION->setCompanyId(0);
  9395. //                $NOTIFICATION->setBody('Test Description'.$t);
  9396. //                $NOTIFICATION->setTitle('Test Title'.$t);
  9397. //                $NOTIFICATION->setExpireTs(0);
  9398. //                $NOTIFICATION->setIsBuddybee(0);
  9399. //                $NOTIFICATION->setType(0);
  9400. //                $em->persist($NOTIFICATION);
  9401. //                $em->flush();
  9402. //            }
  9403. //
  9404. //            return new JsonResponse(
  9405. //                array(
  9406. //                    'success' => true,
  9407. //                    'data' => [],
  9408. //
  9409. //
  9410. //                )
  9411. //            );
  9412. //
  9413. //
  9414. //        }
  9415.         if ($request->request->get('entity_group'0)) {
  9416.             $companyId 0;
  9417.             $em $this->getDoctrine()->getManager('company_group');
  9418.         } else
  9419.             $companyId $this->getLoggedUserCompanyId($request);
  9420.         if ($companyId) {
  9421.             $company_data = [];
  9422. //            $company_data = Company::getCompanyData($em, $companyId);
  9423.         } else {
  9424.             $companyId 0;
  9425.             $company_data = [];
  9426.         }
  9427. //        $theEntity= new EntityNotification();
  9428. //        $entityName = 'EntityNotification';
  9429. //
  9430. //        $className='\\CompanyGroupBundle\\Entity\\'.$entityName;
  9431. //
  9432. //
  9433. //            $theEntity= new $className();
  9434.         $dataToAdd $request->request->has('dataToAdd') ? $request->request->get('dataToAdd') : [];
  9435.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  9436.         if ($dataToAdd == null$dataToAdd = [];
  9437.         $dataToRemove $request->request->has('dataToRemove') ? $request->request->get('dataToRemove') : [];
  9438.         if (is_string($dataToRemove)) $dataToAdd json_decode($dataToRemovetrue);
  9439.         if ($dataToRemove == null$dataToRemove = [];
  9440.         $relData = [];
  9441.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  9442.         $updatedDataList = [];
  9443.         foreach ($dataToAdd as $dataInd => $dat) {
  9444.             $entityName $dat['entityName'];
  9445.             $idField $dat['idField'];
  9446.             $findByField = isset($dat['findByField']) ? $dat['findByField'] : '';
  9447.             $findByValue = isset($dat['findByValue']) ? $dat['findByValue'] : '';
  9448.             $returnRefIndex $dat['returnRefIndex'];
  9449.             $findById $dat['findId'];
  9450.             $dataFields = isset($dat['dataFields']) ? $dat['dataFields'] : [];
  9451.             $noCreation = isset($dat['noCreation']) ? $dat['noCreation'] : 0;
  9452.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  9453.             $preAdditionalSql = isset($dat['preAdditionalSql']) ? $dat['preAdditionalSql'] : '';
  9454.             if ($preAdditionalSql != '') {
  9455. //            if ($entityName == 'PlanningItem') {
  9456. //
  9457. //                $stmt='select disctinct parent_id from planning_item;';
  9458. //                
  9459. //                $get_kids = $stmt;
  9460. //                $p_ids=[];
  9461. //                foreach($get_kids as $g)
  9462. //                {
  9463. //                    $p_ids[]=$g['parent_id'];
  9464. //                }
  9465. //
  9466. //
  9467. //
  9468.                 $stmt $em->getConnection()->executeStatement($preAdditionalSql);
  9469. //
  9470. //
  9471.             }
  9472.             if ($entityName == 'PlanningItem') {
  9473.                 $stmt $em->getConnection()->fetchAllAssociative("select  `id` , parent_id, sequence from planning_item where sequence is null
  9474.             ORDER BY parent_id ASC, id ASC
  9475.                         ");
  9476.                 $query_output $stmt;
  9477.                 foreach ($query_output as $dupe) {
  9478.                     System::updatePlanningItemSequence($em$dupe["id"]);
  9479.                 }
  9480.             }
  9481.             $className = ($request->request->get('entity_group'0) ? '\\CompanyGroupBundle\\Entity\\' '\\ApplicationBundle\\Entity\\') . $entityName;
  9482.             if (
  9483.                 ($findById == || $findById == '_NA_') && $findByField == '' && $noCreation == 0
  9484.             ) {
  9485.                 $theEntity = new $className();
  9486. //                $theEntity= new EntityNotification();
  9487.             } else {
  9488.                 if ($findByField != '') {
  9489.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle\\Entity\\' 'ApplicationBundle\\Entity\\') . $entityName)->findOneBy(
  9490.                         array
  9491.                         (
  9492.                             $findByField => $findByValue,
  9493.                         )
  9494.                     );
  9495.                 } else {
  9496.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle\\Entity\\' 'ApplicationBundle\\Entity\\') . $entityName)->findOneBy(
  9497.                         array
  9498.                         (
  9499.                             $idField => $findById,
  9500.                         )
  9501.                     );
  9502.                 }
  9503.             }
  9504.             if (!$theEntity && $noCreation == 0)
  9505.                 $theEntity = new $className();
  9506.             foreach ($dataFields as $dt) {
  9507.                 $setMethod 'set' ucfirst($dt['field']);
  9508.                 $getMethod 'get' ucfirst($dt['field']);
  9509.                 $type = isset($dt['type']) ? $dt['type'] : '_VALUE_';
  9510.                 $action = isset($dt['action']) ? $dt['action'] : '_REPLACE_';
  9511.                 if (method_exists($theEntity$setMethod)) {
  9512.                     $oldValue $theEntity->{$getMethod}();
  9513.                     $newValue $oldValue;
  9514.                     if ($type == '_VALUE_') {
  9515.                         $newValue $dt['value'];
  9516.                     }
  9517.                     if ($type == '_DECIMAL_') {
  9518.                         $newValue $dt['value'];
  9519.                     }
  9520.                     if ($type == '_DATE_') {
  9521.                         $newValue = new \DateTime($dt['value']);
  9522.                     }
  9523.                     if ($type == '_ARRAY_') {
  9524.                         $oldValue json_decode($oldValue);
  9525.                         if ($oldValue == null$oldValue = [];
  9526.                         if ($action == '_REPLACE_') {
  9527.                             $newValue json_encode($dt['value']);
  9528.                         }
  9529.                         if ($action == '_APPEND_') {
  9530.                             $newValue array_merge($oldValuearray_values(array_diff([$dt['value']], $oldValue)));
  9531.                         }
  9532.                         if ($action == '_MERGE_') {
  9533.                             $newValue array_merge($oldValuearray_values(array_diff($dt['value'], $oldValue)));
  9534.                         }
  9535.                         if ($action == '_EXCLUDE_') {
  9536.                             $newValue array_values(array_diff($oldValue, [$dt['value']]));
  9537.                         }
  9538.                         if ($action == '_EXCLUDE_ARRAY_') {
  9539.                             $newValue array_values(array_diff($oldValue$dt['value']));
  9540.                         }
  9541.                         $newValue json_encode($newValue);
  9542.                     }
  9543.                     $theEntity->{$setMethod}($newValue); // `foo!`
  9544. //                    $theEntity->setCompletionPercentage(78); // `foo!`
  9545.                 }
  9546.             }
  9547.             if ($additionalSql != '') {
  9548. //            if ($entityName == 'PlanningItem') {
  9549. //
  9550. //                $stmt='select disctinct parent_id from planning_item;';
  9551. //                
  9552. //                $get_kids = $stmt;
  9553. //                $p_ids=[];
  9554. //                foreach($get_kids as $g)
  9555. //                {
  9556. //                    $p_ids[]=$g['parent_id'];
  9557. //                }
  9558. //
  9559. //
  9560. //
  9561.                 $stmt $em->getConnection()->fetchAllAssociative($additionalSql);
  9562. //
  9563. //
  9564.             }
  9565.             if (($findById == || $findById == '_NA_') && $noCreation == 0) {
  9566.                 $em->persist($theEntity);
  9567.                 $em->flush();
  9568.                 $getMethod 'get' ucfirst($idField);
  9569.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  9570.             } else if ($theEntity) {
  9571.                 $em->flush();
  9572.                 $getMethod 'get' ucfirst($idField);
  9573.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  9574.             }
  9575.             if ($entityName == 'PlanningItem') {
  9576.                 $stmt $em->getConnection()->fetchAllAssociative('select distinct parent_id from planning_item;');
  9577.                 $get_kids $stmt;
  9578.                 $p_ids = [];
  9579.                 foreach ($get_kids as $g) {
  9580.                     $p_ids[] = $g['parent_id'];
  9581.                 }
  9582.                 // Only real parent ids: strip NULL / 0 (top-level marker) so the IN list never has a
  9583.                 // stray/leading comma. Run as TWO separate statements â€” executeStatement is single-statement.
  9584.                 $p_ids array_values(array_unique(array_filter(array_map('intval'$p_ids))));
  9585.                 if (!empty($p_ids)) {
  9586.                     $idList implode(','$p_ids);
  9587.                     $em->getConnection()->executeStatement('UPDATE planning_item d SET d.`has_child` = 0 WHERE d.id NOT IN (' $idList ')');
  9588.                     $em->getConnection()->executeStatement('UPDATE planning_item d SET d.`has_child` = 1 WHERE d.id IN (' $idList ')');
  9589.                 } else {
  9590.                     // no parents recorded â†’ nothing has children
  9591.                     $em->getConnection()->executeStatement('UPDATE planning_item d SET d.`has_child` = 0');
  9592.                 }
  9593.                 $updatedData System::updatePlanningItemSequence($em$theEntity->getId());
  9594.                 $theEntity $updatedData['primaryOne'];
  9595.                 $theEntityUpdated $theEntity;
  9596.                 if ($theEntityUpdated->getEntryType() == 4)///cashflow
  9597.                 {
  9598.                     MiscActions::AddCashFlowProjection($em0, [
  9599.                         'planningItemId' => $theEntityUpdated->getId(),
  9600.                         'fundRequisitionId' => 0,
  9601.                         'concernedPersonId' => 0,
  9602.                         'type' => 1//exp
  9603.                         'subType' => 1//1== khoroch hobe 2: ashbe
  9604.                         'cashFlowType' => 1//2== RCV /in  1: Payment/out
  9605.                         'creationType' => 1//auto
  9606.                         'amountType' => 1//fund
  9607.                         'cashFlowAmount' => 0,
  9608.                         'expAstAmount' => 0,
  9609.                         'accumulatedCashFlowAmount' => 0,
  9610.                         'accumulatedCashFlowBalance' => 0,
  9611.                         'accumulatedExpAstAmount' => 0,
  9612.                         'relevantExpAstHeadId' => 0,
  9613.                         'balancingHeadId' => 0,
  9614.                         'cashFlowHeadId' => 0,
  9615.                         'cashFlowHeadType' => 1,
  9616.                         'relevantProductIds' => [],
  9617.                         'reminderDateTs' => 0,
  9618.                         'cashFlowDateTs' => 0,
  9619.                         'expAstRealizationDateTs' => 0,
  9620.                     ]);
  9621.                 }
  9622.             } else if ($entityName == 'TaskLog') {
  9623.                 $session $request->getSession();
  9624.                 if ($theEntity) {
  9625.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  9626.                     $currTime = new \DateTime();
  9627.                     $options = array(
  9628.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  9629.                         'notification_server' => $this->container->getParameter('notification_server'),
  9630.                     );
  9631.                     $positionsArray = [
  9632.                         array(
  9633.                             'employeeId' => $empId,
  9634.                             'userId' => $session->get(UserConstants::USER_ID0),
  9635.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  9636.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  9637.                             'lat' => 23.8623834,
  9638.                             'lng' => 90.3979294,
  9639.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING,
  9640. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  9641.                         )
  9642.                     ];
  9643.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  9644.                     if ($positionsArray == null$positionsArray = [];
  9645.                     $dataByAttId = [];
  9646.                     $workPlaceType '_UNSET_';
  9647.                     foreach ($positionsArray as $findex => $d) {
  9648.                         $sysUserId 0;
  9649.                         $userId 0;
  9650.                         $empId 0;
  9651.                         $dtTs 0;
  9652.                         $timeZoneStr '+0000';
  9653.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  9654.                         if (isset($d['userId'])) $userId $d['userId'];
  9655.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  9656.                         if (isset($d['tsMilSec'])) {
  9657.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  9658.                         }
  9659.                         if ($dtTs == 0) {
  9660.                             $currTsTime = new \DateTime();
  9661.                             $dtTs $currTsTime->format('U');
  9662.                         } else {
  9663.                             $currTsTime = new \DateTime('@' $dtTs);
  9664.                         }
  9665.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  9666.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  9667.                         $EmployeeAttendance $this->getDoctrine()
  9668.                             ->getRepository(EmployeeAttendance::class)
  9669.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  9670.                         if (!$EmployeeAttendance) {
  9671.                             $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9672.                             $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9673.                             $EmployeeAttendance = new EmployeeAttendance;
  9674.                         } else {
  9675.                             if ($EmployeeAttendance->getCurrentLocation() == 'out') {
  9676.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9677.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9678.                             } else {
  9679.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  9680.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  9681.                             }
  9682.                         }
  9683.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  9684.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  9685.                             $workPlaceType '_STATIC_';
  9686.                         }
  9687.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  9688.                             $dataByAttId[$attendanceInfo->getId()] = array(
  9689.                                 'attendanceInfo' => $attendanceInfo,
  9690.                                 'empId' => $empId,
  9691.                                 'lat' => 0,
  9692.                                 'lng' => 0,
  9693.                                 'address' => 0,
  9694.                                 'sysUserId' => $sysUserId,
  9695.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  9696.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  9697.                                 'positionArray' => []
  9698.                             );
  9699.                         $posData = array(
  9700.                             'ts' => $dtTs,
  9701.                             'lat' => $d['lat'],
  9702.                             'lng' => $d['lng'],
  9703.                             'marker' => $d['markerId'],
  9704.                             'src' => 2,
  9705.                         );
  9706.                         $posDataArray = array(
  9707.                             $dtTs,
  9708.                             $d['lat'],
  9709.                             $d['lng'],
  9710.                             $d['markerId'],
  9711.                             2
  9712.                         );
  9713.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  9714.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  9715.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  9716.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  9717.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  9718.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  9719.                         if (isset($d['address']))
  9720.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  9721. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  9722.                     }
  9723.                     $response = array(
  9724.                         'success' => true,
  9725.                     );
  9726.                     foreach ($dataByAttId as $attInfoId => $d) {
  9727.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  9728.                             $d['empId'],
  9729.                             $d['sysUserId'],
  9730.                             $d['companyId'],
  9731.                             $d['appId'],
  9732.                             $request,
  9733.                             $d['attendanceInfo'],
  9734.                             $options,
  9735.                             $d['positionArray'],
  9736.                             $d['lat'],
  9737.                             $d['lng'],
  9738.                             $d['address'],
  9739.                             $d['markerId']
  9740.                         );
  9741.                     }
  9742.                     $session->set(UserConstants::USER_CURRENT_TASK_ID$theEntity->getId());
  9743.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$theEntity->getPlanningItemId());
  9744.                 } else {
  9745.                     $session->set(UserConstants::USER_CURRENT_TASK_ID0);
  9746.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID0);
  9747.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  9748.                     $currTime = new \DateTime();
  9749.                     $options = array(
  9750.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  9751.                         'notification_server' => $this->container->getParameter('notification_server'),
  9752.                     );
  9753.                     $positionsArray = [
  9754.                         array(
  9755.                             'employeeId' => $empId,
  9756.                             'userId' => $session->get(UserConstants::USER_ID0),
  9757.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  9758.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  9759.                             'lat' => 23.8623834,
  9760.                             'lng' => 90.3979294,
  9761.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT,
  9762. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  9763.                         )
  9764.                     ];
  9765.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  9766.                     if ($positionsArray == null$positionsArray = [];
  9767.                     $dataByAttId = [];
  9768.                     $workPlaceType '_UNSET_';
  9769.                     foreach ($positionsArray as $findex => $d) {
  9770.                         $sysUserId 0;
  9771.                         $userId 0;
  9772.                         $empId 0;
  9773.                         $dtTs 0;
  9774.                         $timeZoneStr '+0000';
  9775.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  9776.                         if (isset($d['userId'])) $userId $d['userId'];
  9777.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  9778.                         if (isset($d['tsMilSec'])) {
  9779.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  9780.                         }
  9781.                         if ($dtTs == 0) {
  9782.                             $currTsTime = new \DateTime();
  9783.                             $dtTs $currTsTime->format('U');
  9784.                         } else {
  9785.                             $currTsTime = new \DateTime('@' $dtTs);
  9786.                         }
  9787.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  9788.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  9789.                         $EmployeeAttendance $this->getDoctrine()
  9790.                             ->getRepository(EmployeeAttendance::class)
  9791.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  9792.                         if (!$EmployeeAttendance) {
  9793.                             continue;
  9794.                         } else {
  9795.                         }
  9796.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  9797.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT) {
  9798.                             $workPlaceType '_STATIC_';
  9799.                         }
  9800.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  9801.                             $dataByAttId[$attendanceInfo->getId()] = array(
  9802.                                 'attendanceInfo' => $attendanceInfo,
  9803.                                 'empId' => $empId,
  9804.                                 'lat' => 0,
  9805.                                 'lng' => 0,
  9806.                                 'address' => 0,
  9807.                                 'sysUserId' => $sysUserId,
  9808.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  9809.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  9810.                                 'positionArray' => []
  9811.                             );
  9812.                         $posData = array(
  9813.                             'ts' => $dtTs,
  9814.                             'lat' => $d['lat'],
  9815.                             'lng' => $d['lng'],
  9816.                             'marker' => $d['markerId'],
  9817.                             'src' => 2,
  9818.                         );
  9819.                         $posDataArray = array(
  9820.                             $dtTs,
  9821.                             $d['lat'],
  9822.                             $d['lng'],
  9823.                             $d['markerId'],
  9824.                             2
  9825.                         );
  9826.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  9827.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  9828.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  9829.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  9830.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  9831.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  9832.                         if (isset($d['address']))
  9833.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  9834. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  9835.                     }
  9836.                     $response = array(
  9837.                         'success' => true,
  9838.                     );
  9839.                     foreach ($dataByAttId as $attInfoId => $d) {
  9840.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  9841.                             $d['empId'],
  9842.                             $d['sysUserId'],
  9843.                             $d['companyId'],
  9844.                             $d['appId'],
  9845.                             $request,
  9846.                             $d['attendanceInfo'],
  9847.                             $options,
  9848.                             $d['positionArray'],
  9849.                             $d['lat'],
  9850.                             $d['lng'],
  9851.                             $d['address'],
  9852.                             $d['markerId']
  9853.                         );
  9854.                     }
  9855.                 }
  9856.                 $theEntityUpdated $theEntity;
  9857.             } else
  9858.                 $theEntityUpdated $theEntity;
  9859. //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  9860.             $getters = [];
  9861.             if ($theEntityUpdated)
  9862.                 $getters array_filter(get_class_methods($theEntityUpdated), function ($method) {
  9863.                     return 'get' === substr($method03);
  9864.                 });
  9865.             $updatedData = [];
  9866.             foreach ($getters as $getter) {
  9867.                 $indForThis str_replace('get'''$getter);
  9868.                 $indForThis lcfirst($indForThis);
  9869.                 $updatedData[$indForThis] = $theEntityUpdated->{$getter}();
  9870.             }
  9871.             $updatedDataList[$dataInd] = $updatedData;
  9872.         }
  9873.         foreach ($dataToRemove as $dataInd => $dat) {
  9874.             $entityName $dat['entityName'];
  9875.             $idField $dat['idField'];
  9876.             $findById $dat['findId'];
  9877.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  9878.             $theEntityList $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle\\Entity\\' 'ApplicationBundle\\Entity\\') . $entityName)->findBy(
  9879.                 array
  9880.                 (
  9881.                     $idField => $findById,
  9882.                 )
  9883.             );
  9884.             foreach ($theEntityList as $dt) {
  9885.                 $em->remove($dt);
  9886.                 $em->flush();
  9887.             }
  9888.             if ($additionalSql != '') {
  9889. //            if ($entityName == 'PlanningItem') {
  9890. //
  9891. //                $stmt='select disctinct parent_id from planning_item;';
  9892. //                
  9893. //                $get_kids = $stmt;
  9894. //                $p_ids=[];
  9895. //                foreach($get_kids as $g)
  9896. //                {
  9897. //                    $p_ids[]=$g['parent_id'];
  9898. //                }
  9899. //
  9900. //
  9901. //
  9902.                 $stmt $em->getConnection()->fetchAllAssociative($additionalSql);
  9903. //
  9904. //
  9905.             }
  9906.             $updatedDataList[$dataInd] = [];
  9907.         }
  9908. //        if ($table == '') {
  9909. //            return new JsonResponse(
  9910. //                array(
  9911. //                    'success' => false,
  9912. ////                    'page_title' => 'Product Details',
  9913. ////                    'company_data' => $company_data,
  9914. //                    'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9915. //
  9916. //                )
  9917. //            );
  9918. //        }
  9919. //        if($request->query->has('returnJson'))
  9920.         return new JsonResponse(
  9921.             array(
  9922.                 'success' => true,
  9923.                 'data' => $relData,
  9924.                 'updatedDataList' => $updatedDataList,
  9925.             )
  9926.         );
  9927.     }
  9928.     public function GetAvailableQtyAction(Request $request$id 0)
  9929.     {
  9930.         $em $this->getDoctrine()->getManager();
  9931.         $productId $request->request->has('productId') ? $request->request->get('productId') : 0;
  9932.         $colorId $request->request->has('colorId') ? $request->request->get('colorId') : 0;
  9933.         $dataId $request->request->has('dataId') ? $request->request->get('dataId') : 0;
  9934.         $allowedWarehouseIds $request->request->has('warehouseId') ? [$request->request->get('warehouseId')] : [];
  9935.         $allowedWarehouseActionIds $request->request->has('warehouseActionId') ? [$request->request->get('warehouseActionId')] : [];
  9936.         $qty Inventory::getSellableProductQty($em$productId$allowedWarehouseIds$allowedWarehouseActionIds$colorId);
  9937.         return new JsonResponse(array("success" => true,
  9938.             "qty" => $qty,
  9939.             "dataId" => $dataId,
  9940.         ));
  9941.     }
  9942.     public
  9943.     function ProductListSelectAjaxAction(Request $request$queryStr '')
  9944.     {
  9945.         $em $this->getDoctrine()->getManager();
  9946.         $companyId $this->getLoggedUserCompanyId($request);
  9947.         $company_data Company::getCompanyData($em$companyId);
  9948.         $data = [];
  9949.         $data_by_id = [];
  9950.         $html '';
  9951.         $productByCodeData = [];
  9952.         if ($queryStr == '_EMPTY_')
  9953.             $queryStr '';
  9954.         if ($request->request->has('query') && $queryStr == '')
  9955.             $queryStr $request->request->get('queryStr');
  9956.         if ($queryStr == '_EMPTY_')
  9957.             $queryStr '';
  9958. //        $queryStr=urldecode($queryStr);
  9959.         $queryStr str_replace('_FSLASH_''/'$queryStr);
  9960.         $filterQryForCriteria "select * from inv_products where 1=1 ";
  9961.         $filterParams = array();
  9962.         if ($request->request->has('sellableOnly') && $request->request->get('sellableOnly') != 0)
  9963.             $filterQryForCriteria .= " and sellable=1";
  9964.         if ($request->request->has('categorizationValues') && $request->request->get('categorizationValues') != '') {
  9965.             foreach ($request->request->get('categorizationValues') as $level => $value) {
  9966.                 if ($value != '' && $value != 0) {
  9967.                     $searchParam GeneralConstant::$fdmSubCatMarkers[$level] . $value '_';
  9968.                     $paramName 'categorizationValue' $level;
  9969.                     $filterQryForCriteria .= " and product_fdm like :" $paramName " ";
  9970.                     $filterParams[$paramName] = '%' $searchParam '%';
  9971.                 }
  9972.             }
  9973.         }
  9974.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9975.             $filterQryForCriteria .= " and sub_category_id = :subCategoryId";
  9976.         else if ($request->request->has('categoryId') && $request->request->get('categoryId') != '')
  9977.             $filterQryForCriteria .= " and category_id = :categoryId";
  9978.         else if ($request->request->has('igId') && $request->request->get('igId') != '')
  9979.             $filterQryForCriteria .= " and ig_id = :igId";
  9980.         if ($request->request->has('brandId') && $request->request->get('brandId') != '')
  9981.             $filterQryForCriteria .= " and brand_company = :brandId";
  9982.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9983.             $filterParams['subCategoryId'] = (int) $request->request->get('subCategoryId');
  9984.         else if ($request->request->has('categoryId') && $request->request->get('categoryId') != '')
  9985.             $filterParams['categoryId'] = (int) $request->request->get('categoryId');
  9986.         else if ($request->request->has('igId') && $request->request->get('igId') != '')
  9987.             $filterParams['igId'] = (int) $request->request->get('igId');
  9988.         if ($request->request->has('brandId') && $request->request->get('brandId') != '')
  9989.             $filterParams['brandId'] = (int) $request->request->get('brandId');
  9990.         if ($request->request->has('restrictedBrandIds') && $request->request->get('restrictedBrandIds') != []) {
  9991.             $restrictedBrandIds $this->normalizeSqlIntList($request->request->get('restrictedBrandIds'));
  9992.             if (!empty($restrictedBrandIds)) {
  9993.                 $filterQryForCriteria .= " and brand_company in (" $this->buildNamedInClause($restrictedBrandIds'restrictedBrandId'$filterParams) . ")";
  9994.             }
  9995.         }
  9996.         if ($request->request->has('productIds')) {
  9997.             $productIds $this->normalizeSqlIntList($request->request->get('productIds'));
  9998.             if (!empty($productIds)) {
  9999.                 $filterQryForCriteria .= " and id in (" $this->buildNamedInClause($productIds'productId'$filterParams) . ") ";
  10000.             }
  10001.         } else if ($request->request->has('productCode')) {
  10002.             $filterQryForCriteria .= " and product_code like :productCode ";
  10003.             $filterParams['productCode'] = '%' $request->request->get('productCode') . '%';
  10004.         } else if ($queryStr != '') {
  10005.             $filterQryForCriteria .= " and  (product_code like :queryProductCode or `name` like :queryName or model_no like :queryModelNo) ";
  10006.             $filterParams['queryProductCode'] = '%' $queryStr '%';
  10007.             $filterParams['queryName'] = '%' $queryStr '%';
  10008.             $filterParams['queryModelNo'] = '%' $queryStr '%';
  10009.         }
  10010.         if ($filterQryForCriteria != '')
  10011.             $filterQryForCriteria .= "  limit 25";
  10012.         $get_kids_sql $filterQryForCriteria;
  10013. //        if ($request->request->has('productIds'))
  10014. //
  10015. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  10016. //        else if ($request->request->has('productCode'))
  10017. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  10018. //        else if ($filterQryForCriteria!='')
  10019. //            $get_kids_sql = $filterQryForCriteria;
  10020. //
  10021. //        else
  10022. //               $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";
  10023.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  10024.         $get_kids $stmt;
  10025.         $productId 0;
  10026.         if (!empty($get_kids)) {
  10027.             foreach ($get_kids as $product) {
  10028.                 $pa = array();
  10029.                 $pa['id'] = $product['id'];
  10030.                 $pa['name'] = $product['name'];
  10031.                 $pa['id_name'] = $product['id'] . '. ' $product['name'];
  10032.                 $pa['id_mn'] = $product['id'] . '. ' $product['model_no'];;
  10033.                 $pa['id_name_mn'] = $product['id'] . '. ' $product['name'] . ' ( ' $product['model_no'] . ' )';
  10034.                 $pa['globalId'] = $product['global_id'];
  10035.                 $pa['classSuffix'] = $product['class_suffix'];
  10036.                 $pa['productFdm'] = $product['product_fdm'];
  10037.                 $pa['modelNo'] = $product['model_no'];
  10038.                 $pa['partId'] = $product['part_id'];
  10039.                 $pa['hsCode'] = $product['hs_code'];
  10040.                 $pa['productCode'] = $product['product_code'];
  10041.                 $pa['text'] = $product['name'];
  10042.                 $pa['value'] = $product['id'];
  10043.                 $pa['tac'] = $product['tac'];
  10044.                 $pa['igId'] = $product['ig_id'];
  10045.                 $pa['categoryId'] = $product['category_id'];
  10046.                 $pa['subCategoryId'] = $product['sub_category_id'];
  10047.                 $pa['brandCompany'] = $product['brand_company'];
  10048.                 $pa['sales_price'] = $product['curr_sales_price'];
  10049.                 $pa['purchase_price'] = $product['curr_purchase_price'];
  10050.                 $pa['unit_type'] = $product['unit_type_id'];
  10051.                 $pa['single_weight'] = $product['single_weight'];
  10052.                 $pa['single_weight_variance_type'] = $product['single_weight_variance_type'];
  10053.                 $pa['single_weight_variance_value'] = $product['single_weight_variance_value'];
  10054.                 $pa['weight'] = $product['weight'];
  10055.                 $pa['weight_variance_type'] = $product['weight_variance_type'];
  10056.                 $pa['weight_variance_value'] = $product['weight_variance_value'];
  10057.                 $pa['carton_capacity_count'] = $product['carton_capacity_count'];
  10058.                 $pa['type'] = $product['type'];
  10059.                 $pa['qty'] = $product['qty'];
  10060. //                $pa['alias'] = '';
  10061.                 $pa['alias'] = $product['alias'];
  10062.                 $pa['note'] = $product['note'];
  10063.                 $pa['defaultTaxConfigId'] = $product['default_tax_config_id'] == null $product['default_tax_config_id'];
  10064.                 $pa['defaultPurchaseTaxConfigId'] = $product['default_purchase_tax_config_id'] == null $product['default_purchase_tax_config_id'];
  10065.                 $tax_config_ids json_decode($product['tax_config_ids'], true);
  10066.                 if ($tax_config_ids == null)
  10067.                     $tax_config_ids = [];
  10068.                 $pa['taxConfigIds'] = $tax_config_ids;
  10069.                 $purchase_tax_config_ids json_decode($product['purchase_tax_config_ids'], true);
  10070.                 if ($purchase_tax_config_ids == null)
  10071.                     $purchase_tax_config_ids = [];
  10072.                 $pa['purchaseTaxConfigIds'] = $tax_config_ids;
  10073.                 $inco_terms json_decode($product['inco_terms'], true);
  10074.                 if ($inco_terms == null)
  10075.                     $inco_terms = [];
  10076.                 $pa['incoTerms'] = $inco_terms;
  10077.                 $pa['defaultIncoTerm'] = $product['default_inco_term'] == null $product['default_inco_term'];
  10078.                 $pa['has_serial'] = $product['has_serial'];
  10079.                 $pa['expiry_days'] = $product['expiry_days'];
  10080.                 $pa['image'] = $product['default_image'];
  10081.                 $pa['sales_warranty'] = $product['sales_warranty_months'];;
  10082.                 $pa['defaultColorId'] = $product['default_color_id'];;
  10083.                 $allowedColorIds json_decode($product['colors'], true);
  10084.                 if ($allowedColorIds == null$allowedColorIds = [];
  10085.                 if (!in_array($product['default_color_id'], $allowedColorIds))
  10086.                     $allowedColorIds[] = $product['default_color_id'];
  10087.                 $pa['allowedColorIds'] = $allowedColorIds;;
  10088.                 $data[] = $pa;
  10089.                 $data_by_id[$product['id']] = $pa;
  10090.                 $productId $product['id'];
  10091.             }
  10092.         }
  10093. //        if($request->query->has('returnJson'))
  10094.         {
  10095.             return new JsonResponse(
  10096.                 array(
  10097.                     'success' => true,
  10098. //                    'page_title' => 'Product Details',
  10099. //                    'company_data' => $company_data,
  10100.                     'data' => $data,
  10101.                     'dataById' => $data_by_id,
  10102.                     'productId' => $productId,
  10103.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10104. //                    'exId'=>$id,
  10105. //                'productByCodeData' => $productByCodeData,
  10106. //                'productData' => $productData,
  10107. //                'currInvList' => $currInvList,
  10108. //                'productList' => Inventory::ProductList($em, $companyId),
  10109. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10110. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10111. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10112. //                'unitList' => Inventory::UnitTypeList($em),
  10113. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10114. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10115. //                'warehouseList' => Inventory::WarehouseList($em),
  10116.                 )
  10117.             );
  10118.         }
  10119.     }
  10120.     public function SearchByPopulateQueryAction(Request $request$queryStr '')
  10121.     {
  10122.         $em $this->getDoctrine()->getManager();
  10123.         $companyId $this->getLoggedUserCompanyId($request);
  10124.         $company_data Company::getCompanyData($em$companyId);
  10125.         $data = [];
  10126.         //1st search in products
  10127.         foreach ($request->request->get('queryData', []) as $item) {
  10128.             $dt = array(
  10129.                 'dataId' => $item['dataId'] ?? 0,
  10130.                 'id' => 0,
  10131.                 'fdm' => '',
  10132.             );
  10133.             $qryStrForSearch $item['value'] ?? '';
  10134.             $qryArray explode(','$qryStrForSearch);
  10135.             $checkFields = ['name'];
  10136.             list($qryForSearch$queryParams) = $this->buildTokenizedLikeSearchFragment($checkFields$qryArray'or''populateQueryGroup');
  10137.             //selct item group
  10138.             $igId 0;
  10139.             $catId 0;
  10140.             $parId 0;
  10141.             $brandId 0;
  10142.             $fdmSearchQry = [];
  10143.             $result $em->getConnection()->fetchAllAssociative("select * from inv_item_group where 1=0   " $qryForSearch " limit 1"$queryParams);
  10144.             if (!empty($result)) {
  10145.                 $dt['fdm'] .= ('I' $result[0]['id'] . '_');
  10146.                 $fdmSearchQry[] = ('I' $result[0]['id'] . '_');
  10147.                 $igId $result[0]['id'];
  10148.             }
  10149.             list($qryForSearch$queryParams) = $this->buildTokenizedLikeSearchFragment($checkFields$qryArray'and''populateScopedQueryGroup');
  10150.             //then category
  10151.             $result $em->getConnection()->fetchAllAssociative(
  10152.                 "select * from inv_product_categories where ig_id = :igId " $qryForSearch " limit 1",
  10153.                 array_merge(array('igId' => (int) $igId), $queryParams)
  10154.             );
  10155.             if (!empty($result)) {
  10156.                 $dt['fdm'] .= ('C' $result[0]['id'] . '_');
  10157.                 $fdmSearchQry[] = ('C' $result[0]['id'] . '_');
  10158.                 $catId $result[0]['id'];
  10159.             }
  10160.             //then sub category
  10161.             foreach (GeneralConstant::$fdmSubCatMarkers as $ind => $marker) {
  10162.                 $result $em->getConnection()->fetchAllAssociative(
  10163.                     "select * from inv_product_sub_categories where ig_id = :igId and category_id = :catId and parent_id = :parId " $qryForSearch " limit 1",
  10164.                     array_merge(array(
  10165.                         'igId' => (int) $igId,
  10166.                         'catId' => (int) $catId,
  10167.                         'parId' => (int) $parId,
  10168.                     ), $queryParams)
  10169.                 );
  10170.                 if (!empty($result)) {
  10171.                     $dt['fdm'] .= ($marker $result[0]['id'] . '_');
  10172.                     $fdmSearchQry[] = ($marker $result[0]['id'] . '_');
  10173.                     $parId $result[0]['id'];
  10174.                 }
  10175.             }
  10176.             $result $em->getConnection()->fetchAllAssociative("select * from brand_company where 1=1   " $qryForSearch " limit 1"$queryParams);
  10177.             if (!empty($result)) {
  10178.                 $dt['fdm'] .= ('B' $result[0]['id'] . '_');
  10179.                 $fdmSearchQry[] = ('B' $result[0]['id'] . '_');
  10180.                 $brandId $result[0]['id'];
  10181.             }
  10182.             list($qryForSearch$fdmSearchParams) = $this->buildConjunctiveLikeFragment('product_fdm'$fdmSearchQry'populateFdm');
  10183.             $result $em->getConnection()->fetchAllAssociative("select * from inv_products where 1=1   " $qryForSearch " limit 1"$fdmSearchParams);
  10184.             if (!empty($result)) {
  10185.                 $dt['id'] .= $result[0]['id'];
  10186.             }
  10187.             $data[] = $dt;
  10188.         }
  10189.         return new JsonResponse(
  10190.             array(
  10191.                 'success' => !empty($data) ? true false,
  10192.                 'data' => $data
  10193.             )
  10194.         );
  10195.     }
  10196.     public function addProductByGeneralDataAction(Request $request$queryStr '')
  10197.     {
  10198.         $em $this->getDoctrine()->getManager();
  10199.         $companyId $this->getLoggedUserCompanyId($request);
  10200.         $company_data Company::getCompanyData($em$companyId);
  10201.         $data = [];
  10202.         //1st search in products
  10203.         foreach ($request->request->get('dataList', []) as $item) {
  10204. //            $item=Inventory::GetImmutableKeysForProductSyncFromCentralToLocal();
  10205.             //add each part and if not exists, add it
  10206.             $currProductInfo = array(
  10207.                 'dataId' => $item['dataId'] ?? 0,
  10208.                 'id' => 0,
  10209.                 'igId' => 0,
  10210.                 'categoryId' => 0,
  10211.                 'subCategoryIds' => [
  10212.                     => 0,
  10213.                 ],
  10214.                 'fdm' => '',
  10215.             );
  10216.             //iten group
  10217.             if (isset($item['ItemGroup'])) {
  10218.                 $result $em->getConnection()->fetchAllAssociative(
  10219.                     "select * from inv_item_group where id = :itemGroupId or name like :itemGroupName limit 1",
  10220.                     array(
  10221.                         'itemGroupId' => (int) ($item['ItemGroup']['Id'] ?? 0),
  10222.                         'itemGroupName' => (string) ($item['ItemGroup']['Name'] ?? 0),
  10223.                     )
  10224.                 );
  10225.                 if (!empty($result)) {
  10226.                     $currProductInfo['igId'] = $result[0]['id'];
  10227.                 } else {
  10228.                     Inventory::CreateItemGroup($em1);
  10229.                 }
  10230.             }
  10231.             $dt = array(
  10232.                 'dataId' => $item['dataId'] ?? 0,
  10233.                 'id' => 0,
  10234.                 'fdm' => '',
  10235.             );
  10236.             $qryStrForSearch $item['value'] ?? '';
  10237.             $qryArray explode(','$qryStrForSearch);
  10238.             $checkFields = ['name'];
  10239.             list($qryForSearch$queryParams) = $this->buildFlatLikeSearchFragment($checkFields$qryArray'and''generalDataQuery');
  10240.             //selct item group
  10241.             $igId 0;
  10242.             $catId 0;
  10243.             $parId 0;
  10244.             $brandId 0;
  10245.             $fdmSearchQry = [];
  10246.             $result $em->getConnection()->fetchAllAssociative("select * from inv_item_group where 1=1 " $qryForSearch " limit 1"$queryParams);
  10247.             if (!empty($result)) {
  10248.                 $dt['fdm'] .= ('I' $result[0]['id'] . '_');
  10249.                 $fdmSearchQry[] = ('I' $result[0]['id'] . '_');
  10250.                 $igId $result[0]['id'];
  10251.             }
  10252.             //then category
  10253.             $result $em->getConnection()->fetchAllAssociative(
  10254.                 "select * from inv_product_categories where ig_id = :igId " $qryForSearch " limit 1",
  10255.                 array_merge(array('igId' => (int) $igId), $queryParams)
  10256.             );
  10257.             if (!empty($result)) {
  10258.                 $dt['fdm'] .= ('C' $result[0]['id'] . '_');
  10259.                 $fdmSearchQry[] = ('C' $result[0]['id'] . '_');
  10260.                 $catId $result[0]['id'];
  10261.             }
  10262.             //then sub category
  10263.             foreach (GeneralConstant::$fdmSubCatMarkers as $ind => $marker) {
  10264.                 $result $em->getConnection()->fetchAllAssociative(
  10265.                     "select * from inv_product_sub_categories where ig_id = :igId and category_id = :catId and parent_id = :parId " $qryForSearch " limit 1",
  10266.                     array_merge(array(
  10267.                         'igId' => (int) $igId,
  10268.                         'catId' => (int) $catId,
  10269.                         'parId' => (int) $parId,
  10270.                     ), $queryParams)
  10271.                 );
  10272.                 if (!empty($result)) {
  10273.                     $dt['fdm'] .= ($marker $result[0]['id'] . '_');
  10274.                     $fdmSearchQry[] = ($marker $result[0]['id'] . '_');
  10275.                     $parId $result[0]['id'];
  10276.                 }
  10277.             }
  10278.             $result $em->getConnection()->fetchAllAssociative("select * from brand_company where 1=1 " $qryForSearch " limit 1"$queryParams);
  10279.             if (!empty($result)) {
  10280.                 $dt['fdm'] .= ('B' $result[0]['id'] . '_');
  10281.                 $fdmSearchQry[] = ('B' $result[0]['id'] . '_');
  10282.                 $brandId $result[0]['id'];
  10283.             }
  10284.             list($qryForSearch$fdmSearchParams) = $this->buildConjunctiveLikeFragment('product_fdm'$fdmSearchQry'generalDataFdm');
  10285.             $result $em->getConnection()->fetchAllAssociative("select * from inv_products where 1=1 " $qryForSearch " limit 1"$fdmSearchParams);
  10286.             if (!empty($result)) {
  10287.                 $dt['id'] .= $result[0]['id'];
  10288.             }
  10289.             $data[] = $dt;
  10290.         }
  10291.         return new JsonResponse(
  10292.             array(
  10293.                 'success' => empty($data) ? true false,
  10294.                 'data' => $data
  10295.             )
  10296.         );
  10297.     }
  10298.     public function labelFormatSelectAjaxAction(Request $request$queryStr '')
  10299.     {
  10300.         $em $this->getDoctrine()->getManager();
  10301.         $companyId $this->getLoggedUserCompanyId($request);
  10302.         $company_data Company::getCompanyData($em$companyId);
  10303.         $data = [];
  10304.         $data_by_id = [];
  10305.         $html '';
  10306.         $productByCodeData = [];
  10307.         if ($queryStr == '_EMPTY_')
  10308.             $queryStr '';
  10309.         if ($request->request->has('query') && $queryStr == '')
  10310.             $queryStr $request->request->get('queryStr');
  10311.         if ($queryStr == '_EMPTY_')
  10312.             $queryStr '';
  10313.         $filterQryForCriteria "select * from label_format where company_id = :companyId ";
  10314.         $filterParams = array(
  10315.             'companyId' => (int) $companyId,
  10316.         );
  10317.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  10318.             $filterQryForCriteria .= " and label_type = :dataType";
  10319.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  10320.             $filterQryForCriteria .= " and format_id = :formatId";
  10321.         else if ($queryStr != '') {
  10322.             $filterQryForCriteria .= " and (`name` like :labelNameQuery or `format_code` like :labelCodeQuery) ";
  10323.             $filterParams['labelNameQuery'] = '%' $queryStr '%';
  10324.             $filterParams['labelCodeQuery'] = '%' $queryStr '%';
  10325.         }
  10326.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  10327.             $filterParams['dataType'] = (int) $request->request->get('dataType');
  10328.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  10329.             $filterParams['formatId'] = (int) $request->request->get('formatId');
  10330.         if ($filterQryForCriteria != '')
  10331.             $filterQryForCriteria .= "  limit 25";
  10332.         $get_kids_sql $filterQryForCriteria;
  10333. //        if ($request->request->has('productIds'))
  10334. //
  10335. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  10336. //        else if ($request->request->has('productCode'))
  10337. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  10338. //        else if ($filterQryForCriteria!='')
  10339. //            $get_kids_sql = $filterQryForCriteria;
  10340. //
  10341. //        else
  10342. //               $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";
  10343.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  10344.         $get_kids $stmt;
  10345.         $productId 0;
  10346.         if (!empty($get_kids)) {
  10347.             foreach ($get_kids as $product) {
  10348.                 $pa = array();
  10349.                 $pa['id'] = $product['format_id'];
  10350.                 $pa['name'] = $product['name'];
  10351.                 $pa['format_code'] = $product['format_code'] . '. ' $product['name'];
  10352.                 $pa['id_code_name'] = $product['format_id'] . '. ' $product['format_code'] . ' - ' $product['name'] . ' ';
  10353.                 $pa['text'] = $product['name'];
  10354.                 $pa['value'] = $product['format_id'];
  10355.                 $data[] = $pa;
  10356.                 $data_by_id[$product['format_id']] = $pa;
  10357.                 $productId $product['format_id'];
  10358.             }
  10359.         }
  10360. //        if($request->query->has('returnJson'))
  10361.         {
  10362.             return new JsonResponse(
  10363.                 array(
  10364.                     'success' => true,
  10365. //                    'page_title' => 'Product Details',
  10366. //                    'company_data' => $company_data,
  10367.                     'data' => $data,
  10368.                     'dataById' => $data_by_id,
  10369.                     'productId' => $productId,
  10370.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10371. //                    'exId'=>$id,
  10372. //                'productByCodeData' => $productByCodeData,
  10373. //                'productData' => $productData,
  10374. //                'currInvList' => $currInvList,
  10375. //                'productList' => Inventory::ProductList($em, $companyId),
  10376. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10377. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10378. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10379. //                'unitList' => Inventory::UnitTypeList($em),
  10380. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10381. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10382. //                'warehouseList' => Inventory::WarehouseList($em),
  10383.                 )
  10384.             );
  10385.         }
  10386.     }
  10387.     public function CategoryListSelectAjaxAction(Request $request$queryStr '')
  10388.     {
  10389.         $em $this->getDoctrine()->getManager();
  10390.         $companyId $this->getLoggedUserCompanyId($request);
  10391.         $company_data Company::getCompanyData($em$companyId);
  10392.         $data = [];
  10393.         $data_by_id = [];
  10394.         $html '';
  10395.         $productByCodeData = [];
  10396.         if ($queryStr == '_EMPTY_')
  10397.             $queryStr '';
  10398.         if ($request->request->has('query') && $queryStr == '')
  10399.             $queryStr $request->request->get('queryStr');
  10400.         if ($queryStr == '_EMPTY_')
  10401.             $queryStr '';
  10402.         $filterQryForCriteria "select * from inv_product_categories where company_id = :companyId ";
  10403.         $filterParams = array(
  10404.             'companyId' => (int) $companyId,
  10405.             'categoryNameQuery' => '%' $queryStr '%',
  10406.         );
  10407.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10408.             $filterQryForCriteria .= " and ig_id = :igId";
  10409.         $filterQryForCriteria .= " and (`name` like :categoryNameQuery) ";
  10410.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10411.             $filterParams['igId'] = (int) $request->request->get('igId');
  10412.         if ($filterQryForCriteria != '')
  10413.             $filterQryForCriteria .= "  limit 25";
  10414.         $get_kids_sql $filterQryForCriteria;
  10415. //        if ($request->request->has('productIds'))
  10416. //
  10417. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  10418. //        else if ($request->request->has('productCode'))
  10419. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  10420. //        else if ($filterQryForCriteria!='')
  10421. //            $get_kids_sql = $filterQryForCriteria;
  10422. //
  10423. //        else
  10424. //               $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";
  10425.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  10426.         $get_kids $stmt;
  10427.         $productId 0;
  10428.         if (!empty($get_kids)) {
  10429.             foreach ($get_kids as $product) {
  10430.                 $pa = array();
  10431.                 $pa['id'] = $product['id'];
  10432.                 $pa['name'] = $product['name'];
  10433.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  10434.                 $pa['globalId'] = $product['global_id'];
  10435.                 $pa['text'] = $product['name'];
  10436.                 $pa['value'] = $product['id'];
  10437.                 $pa['igId'] = $product['ig_id'];
  10438. //                $pa['categoryId'] = $product['category_id'];
  10439. //                $pa['subCategoryId'] = $product['sub_category_id'];
  10440.                 $data[] = $pa;
  10441.                 $data_by_id[$product['id']] = $pa;
  10442.                 $productId $product['id'];
  10443.             }
  10444.         }
  10445. //        if($request->query->has('returnJson'))
  10446.         {
  10447.             return new JsonResponse(
  10448.                 array(
  10449.                     'success' => true,
  10450. //                    'page_title' => 'Product Details',
  10451. //                    'company_data' => $company_data,
  10452.                     'data' => $data,
  10453.                     'dataById' => $data_by_id,
  10454.                     'productId' => $productId,
  10455.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10456. //                    'exId'=>$id,
  10457. //                'productByCodeData' => $productByCodeData,
  10458. //                'productData' => $productData,
  10459. //                'currInvList' => $currInvList,
  10460. //                'productList' => Inventory::ProductList($em, $companyId),
  10461. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10462. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10463. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10464. //                'unitList' => Inventory::UnitTypeList($em),
  10465. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10466. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10467. //                'warehouseList' => Inventory::WarehouseList($em),
  10468.                 )
  10469.             );
  10470.         }
  10471.     }
  10472.     public function SubCategoryListSelectAjaxAction(Request $request$queryStr '')
  10473.     {
  10474.         $em $this->getDoctrine()->getManager();
  10475.         $companyId $this->getLoggedUserCompanyId($request);
  10476.         $company_data Company::getCompanyData($em$companyId);
  10477.         $data = [];
  10478.         $data_by_id = [];
  10479.         $html '';
  10480.         $productByCodeData = [];
  10481.         if ($queryStr == '_EMPTY_')
  10482.             $queryStr '';
  10483.         if ($request->request->has('query') && $queryStr == '')
  10484.             $queryStr $request->request->get('queryStr');
  10485.         if ($queryStr == '_EMPTY_')
  10486.             $queryStr '';
  10487.         $filterQryForCriteria "select * from inv_product_sub_categories where company_id = :companyId ";
  10488.         $filterParams = array(
  10489.             'companyId' => (int) $companyId,
  10490.             'subCategoryNameQuery' => '%' $queryStr '%',
  10491.         );
  10492.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  10493.             $filterQryForCriteria .= " and sub_category_id = :subCategoryId";
  10494.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  10495.             $filterQryForCriteria .= " and category_id = :categoryId";
  10496.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10497.             $filterQryForCriteria .= " and ig_id = :igId";
  10498.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  10499.             if ($request->request->get('parentId') != 0)
  10500.                 $filterQryForCriteria .= " and parent_id = :parentId";
  10501.             else
  10502.                 $filterQryForCriteria .= " and ( parent_id =0 or parent_id is null ) ";
  10503.         if ($request->request->has('level') && $request->request->get('level') != '')
  10504.             if ($request->request->get('level') != 0)
  10505.                 $filterQryForCriteria .= " and level = :level";
  10506.             else
  10507.                 $filterQryForCriteria .= " and ( level =0 or level is null) ";
  10508.         $filterQryForCriteria .= " and (`name` like :subCategoryNameQuery) ";
  10509.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  10510.             $filterParams['subCategoryId'] = (int) $request->request->get('subCategoryId');
  10511.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  10512.             $filterParams['categoryId'] = (int) $request->request->get('categoryId');
  10513.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10514.             $filterParams['igId'] = (int) $request->request->get('igId');
  10515.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  10516.             if ($request->request->get('parentId') != 0)
  10517.                 $filterParams['parentId'] = (int) $request->request->get('parentId');
  10518.         if ($request->request->has('level') && $request->request->get('level') != '')
  10519.             if ($request->request->get('level') != 0)
  10520.                 $filterParams['level'] = (int) $request->request->get('level');
  10521.         if ($filterQryForCriteria != '')
  10522.             $filterQryForCriteria .= "  limit 25";
  10523.         $get_kids_sql $filterQryForCriteria;
  10524. //        if ($request->request->has('productIds'))
  10525. //
  10526. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  10527. //        else if ($request->request->has('productCode'))
  10528. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  10529. //        else if ($filterQryForCriteria!='')
  10530. //            $get_kids_sql = $filterQryForCriteria;
  10531. //
  10532. //        else
  10533. //               $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";
  10534.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  10535.         $get_kids $stmt;
  10536.         $productId 0;
  10537.         if (!empty($get_kids)) {
  10538.             foreach ($get_kids as $product) {
  10539.                 $pa = array();
  10540.                 $pa['id'] = $product['id'];
  10541.                 $pa['name'] = $product['name'];
  10542.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  10543.                 $pa['globalId'] = $product['global_id'];
  10544.                 $pa['parentId'] = $product['parent_id'];
  10545.                 $pa['text'] = $product['name'];
  10546.                 $pa['value'] = $product['id'];
  10547.                 $pa['igId'] = $product['ig_id'];
  10548.                 $pa['categoryId'] = $product['category_id'];
  10549. //                $pa['subCategoryId'] = $product['sub_category_id'];
  10550.                 $data[] = $pa;
  10551.                 $data_by_id[$product['id']] = $pa;
  10552.                 $productId $product['id'];
  10553.             }
  10554.         }
  10555. //        if($request->query->has('returnJson'))
  10556.         {
  10557.             return new JsonResponse(
  10558.                 array(
  10559.                     'success' => true,
  10560. //                    'page_title' => 'Product Details',
  10561. //                    'company_data' => $company_data,
  10562.                     'data' => $data,
  10563.                     'dataById' => $data_by_id,
  10564.                     'productId' => $productId,
  10565.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10566. //                    'exId'=>$id,
  10567. //                'productByCodeData' => $productByCodeData,
  10568. //                'productData' => $productData,
  10569. //                'currInvList' => $currInvList,
  10570. //                'productList' => Inventory::ProductList($em, $companyId),
  10571. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10572. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10573. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10574. //                'unitList' => Inventory::UnitTypeList($em),
  10575. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10576. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10577. //                'warehouseList' => Inventory::WarehouseList($em),
  10578.                 )
  10579.             );
  10580.         }
  10581.     }
  10582.     public
  10583.     function ProductByCodeViewAction(Request $request$id 0)
  10584.     {
  10585.         $em $this->getDoctrine()->getManager();
  10586.         $companyId $this->getLoggedUserCompanyId($request);
  10587.         $company_data Company::getCompanyData($em$companyId);
  10588.         $data = [];
  10589.         $html '';
  10590.         $productByCodeData = [];
  10591.         if ($id != 0) {
  10592.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10593.                 ->findOneBy(
  10594.                     array(
  10595.                         'productByCodeId' => $id
  10596.                     )
  10597.                 );
  10598.         } else {
  10599.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10600.                 ->findOneBy(
  10601.                     array(
  10602. //                        'productByCodeId' => $id,
  10603.                         'CompanyId' => $companyId
  10604.                     ), array(
  10605.                         'productByCodeId' => 'DESC'
  10606.                     )
  10607.                 );
  10608.             if ($productByCodeData)
  10609.                 $id $productByCodeData->getProductByCodeId();
  10610.         }
  10611.         if ($id != 0) {
  10612.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  10613.                 ->findOneBy(
  10614.                     array(
  10615.                         'id' => $productByCodeData->getProductId()
  10616.                     )
  10617.                 );
  10618.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  10619.                 ->findBy(
  10620.                     array(
  10621.                         'productId' => $id
  10622.                     )
  10623.                 );
  10624.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  10625.                 array(
  10626.                     'page_title' => 'Product Details',
  10627.                     'company_data' => $company_data,
  10628.                     'productByCodeData' => $productByCodeData,
  10629.                     'productData' => $productData,
  10630.                     'currInvList' => $currInvList,
  10631.                     'exId' => $id,
  10632.                     'clientList' => Client::GetExistingClientList($em$companyId),
  10633.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  10634.                     'productList' => Inventory::ProductList($em$companyId),
  10635.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10636.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10637.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10638.                     'unitList' => Inventory::UnitTypeList($em),
  10639.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10640.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10641.                     'warehouseList' => Inventory::WarehouseList($em),
  10642.                 )
  10643.             );
  10644.         } else {
  10645.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  10646.                 array(
  10647.                     'exId' => $id,
  10648.                 )
  10649.             );
  10650.         }
  10651.         if ($request->query->has('returnJson')) {
  10652.             return new JsonResponse(
  10653.                 array(
  10654.                     'success' => true,
  10655.                     'page_title' => 'Product Details',
  10656.                     'company_data' => $company_data,
  10657.                     'renderedHtml' => $html,
  10658.                     'exId' => $id,
  10659. //                'productByCodeData' => $productByCodeData,
  10660. //                'productData' => $productData,
  10661. //                'currInvList' => $currInvList,
  10662. //                'productList' => Inventory::ProductList($em, $companyId),
  10663. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10664. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10665. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10666. //                'unitList' => Inventory::UnitTypeList($em),
  10667. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10668. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10669. //                'warehouseList' => Inventory::WarehouseList($em),
  10670.                 )
  10671.             );
  10672.         } else {
  10673. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10674. //                ->findBy(
  10675. //                    array(
  10676. ////                        'productByCodeId' => $id,
  10677. //                    'CompanyId'=>$companyId
  10678. //                    )
  10679. //                );
  10680.             $productByCodeList = []; //called by ajax
  10681.             return $this->render('@Inventory/pages/views/product_by_code_view.html.twig',
  10682.                 array(
  10683.                     'page_title' => 'Product Details',
  10684.                     'company_data' => $company_data,
  10685.                     'renderedHtml' => $html,
  10686.                     'exId' => $id,
  10687.                     'productByCodeList' => $productByCodeList,
  10688. //                'productByCodeData' => $productByCodeData,
  10689. //                'productData' => $productData,
  10690. //                'currInvList' => $currInvList,
  10691. //                'productList' => Inventory::ProductList($em, $companyId),
  10692. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10693. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10694. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10695. //                'unitList' => Inventory::UnitTypeList($em),
  10696. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10697. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10698. //                'warehouseList' => Inventory::WarehouseList($em),
  10699.                 )
  10700.             );
  10701.         }
  10702.     }
  10703.     public
  10704.     function ConsumptionSettingsAction(Request $request$id)
  10705.     {
  10706.         $cc_id '';
  10707.         $cc_name '';
  10708.         $em $this->getDoctrine()->getManager();
  10709.         $companyId $this->getLoggedUserCompanyId($request);
  10710.         $consumptionTypeId 0;
  10711.         if ($request->isMethod('POST')) {
  10712.             $new_cc = [];
  10713.             if ($request->request->get('consumptionTypeId') != '' && $request->request->get('consumptionTypeId') != 0) {
  10714.                 $em $this->getDoctrine()->getManager();
  10715.                 $new_cc $this->getDoctrine()
  10716.                     ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  10717.                     ->findOneBy(
  10718.                         array(
  10719.                             'consumptionTypeId' => $request->request->get('consumptionTypeId'),
  10720.                         )
  10721.                     );
  10722.                 $new_cc->setName($request->request->get('name'));
  10723.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  10724.                 $new_cc->setCompanyId($companyId);
  10725.                 $em->flush();
  10726.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  10727.                 $this->addFlash(
  10728.                     'success',
  10729.                     'Consumption Information Updated'
  10730.                 );
  10731.             } else {
  10732.                 $new_cc = new ConsumptionType();
  10733.                 $new_cc->setName($request->request->get('name'));
  10734.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  10735.                 $new_cc->setCompanyId($companyId);
  10736.                 $em->persist($new_cc);
  10737.                 $em->flush();
  10738.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  10739.                 $em->flush();
  10740.                 $this->addFlash(
  10741.                     'success',
  10742.                     'New Consumption Type Added'
  10743.                 );
  10744.             }
  10745.         }
  10746.         $extData = [];
  10747.         if ($id != 0) {
  10748.             $extData $this->getDoctrine()
  10749.                 ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  10750.                 ->findOneBy(
  10751.                     array(
  10752.                         'consumptionTypeId' => $id
  10753.                     )
  10754.                 );
  10755. //            $cc_data_list = [];
  10756. //            foreach ($cc_data as $value) {
  10757. //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  10758. //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  10759. //
  10760. //                if ($value->getSupplierCategoryId() == $id) {
  10761. //                    $cc_id = $value->getSupplierCategoryId();
  10762. //                    $cc_name = $value->getName();
  10763. //                }
  10764. //            }
  10765.         }
  10766.         return $this->render('@Inventory/pages/input_forms/consumption_settings.html.twig',
  10767.             array(
  10768.                 'page_title' => 'Consumption Settings',
  10769.                 'consumptionTypeList' => $this->getDoctrine()
  10770.                     ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  10771.                     ->findBy(
  10772.                         array(
  10773.                             'CompanyId' => $companyId
  10774.                         )
  10775.                     ),
  10776.                 'extData' => $extData,
  10777.                 'headList' => Accounts::getParentLedgerHeads($em),
  10778. //                'countryList'=>SalesOrderM::Co
  10779.             )
  10780.         );
  10781.     }
  10782.     public
  10783.     function ProductByCodeCheckAssignPrintAction(Request $request$id 0)
  10784.     {
  10785.         $em $this->getDoctrine()->getManager();
  10786.         $companyId $this->getLoggedUserCompanyId($request);
  10787.         $company_data Company::getCompanyData($em$companyId);
  10788.         $data = [];
  10789.         $html '';
  10790.         $productByCodeData = [];
  10791.         $productDataWeightPackageGm '';
  10792.         $productDataWeightVarianceValue 0;
  10793.         $productDataWeightVarianceType 0;
  10794.         $productByCodeDataObj = [];
  10795.         $dr_id 0;//for dr_id
  10796.         $skipRenderData 0;
  10797.         if ($request->query->has('skipRenderData'))
  10798.             $skipRenderData $request->query->get('skipRenderData');
  10799.         if ($id != 0) {
  10800.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10801.                 ->findOneBy(
  10802.                     array(
  10803.                         'productByCodeId' => $id
  10804.                     )
  10805.                 );
  10806.         } else {
  10807.             if ($request->query->has('scanCode')) {
  10808.                 $query $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10809.                     ->createQueryBuilder('p');
  10810.                 if ($request->query->has('assigned')) {
  10811.                     $query->where('p.assigned > :av')
  10812.                         ->setParameter('av'$request->query->get('assigned'));
  10813.                 } else
  10814.                     $query->where("1=0");
  10815.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  10816.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  10817.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  10818.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  10819.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  10820.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  10821.                 $query->setMaxResults(1);
  10822.                 $results $query->getQuery()->getResult();
  10823.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  10824.             } else
  10825.                 $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10826.                     ->findOneBy(
  10827.                         array(
  10828. //                        'productByCodeId' => $id,
  10829.                             'CompanyId' => $companyId
  10830.                         ), array(
  10831.                             'productByCodeId' => 'DESC'
  10832.                         )
  10833.                     );
  10834.             if ($productByCodeData)
  10835.                 $id $productByCodeData->getProductByCodeId();
  10836.         }
  10837.         if ($id != 0) {
  10838.             $productByCodeDataObj = array(
  10839.                 'salesCode' => $productByCodeData->getSalesCode(),
  10840.                 'sales_code' => $productByCodeData->getSalesCode(),
  10841.                 'sn' => $productByCodeData->getSerialNo(),
  10842.                 'serialNo' => $productByCodeData->getSerialNo(),
  10843.                 'imei1' => $productByCodeData->getImei1(),
  10844.                 'imei2' => $productByCodeData->getImei2(),
  10845.                 'soId' => $productByCodeData->getSalesOrderId(),
  10846.                 'poId' => $productByCodeData->getPurchaseOrderId(),
  10847.                 'irrId' => $productByCodeData->getIrrId(),
  10848.                 'productId' => $productByCodeData->getProductId(),
  10849.                 'productByCodeId' => $productByCodeData->getProductByCodeId(),
  10850.                 'warehouseId' => $productByCodeData->getWarehouseId(),
  10851.                 'warehouseActionId' => $productByCodeData->getWarehouseActionId(),
  10852.                 'stId' => $productByCodeData->getStockTransferId(),
  10853.                 'srId' => $productByCodeData->getStockReceivedNoteId(),
  10854.                 'scmpId' => $productByCodeData->getStockConsumptionNoteId(),
  10855.                 'clientId' => $productByCodeData->getClientId(),
  10856.                 'supplierId' => $productByCodeData->getSupplierId(),
  10857.                 'drId' => $productByCodeData->getDeliveryReceiptId(),
  10858.                 'consumerName' => $productByCodeData->getConsumerName(),
  10859.                 'drItemData' => [],
  10860. //                'salesCodes' => $productByCodeData->getDeliveryReceiptId(),
  10861.             );
  10862.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  10863.                 ->findOneBy(
  10864.                     array(
  10865.                         'id' => $productByCodeData->getProductId()
  10866.                     )
  10867.                 );
  10868.             if ($productByCodeData->getProductionId() != null) {
  10869.                 $productionDataHere $em->getRepository('ApplicationBundle\\Entity\\Production')
  10870.                     ->findOneBy(
  10871.                         array(
  10872.                             'productionId' => $productByCodeData->getProductionId()
  10873.                         )
  10874.                     );
  10875.                 if ($productionDataHere) {
  10876.                     $productDataWeightPackageGm $productionDataHere->getPackageWeight();
  10877.                     $productDataWeightVarianceValue $productionDataHere->getPackageWeightVarianceValue();
  10878.                     $productDataWeightVarianceType $productionDataHere->getPackageWeightVarianceType();
  10879.                 }
  10880.             } else {
  10881.                 if ($productData) {
  10882.                     $productDataWeightPackageGm $productData->getWeight();
  10883.                     $productDataWeightVarianceValue $productData->getWeightVarianceValue();
  10884.                     $productDataWeightVarianceType $productData->getWeightVarianceType();
  10885.                 }
  10886.             }
  10887.             if ($productData) {
  10888.                 $productByCodeDataObj['unitTypeId'] = $productData->getUnitTypeId();
  10889.                 $productByCodeDataObj['purchasePrice'] = $productData->getPurchasePrice();
  10890.                 $productByCodeDataObj['productFdm'] = $productData->getProductFdm();
  10891.                 $productByCodeDataObj['productName'] = $productData->getName();
  10892.                 if ($request->request->has('forSalesReturn') || $request->query->has('forSalesReturn')) {
  10893.                     $QD $this->getDoctrine()
  10894.                         ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  10895.                         ->findOneBy(
  10896.                             array(
  10897.                                 'deliveryReceiptId' => $productByCodeData->getDeliveryReceiptId(),
  10898.                                 'productId' => $productByCodeData->getProductId(),
  10899.                             )
  10900.                         );
  10901. //            if($request->request->get('wareHouseId')!='')
  10902.                     if ($QD) {
  10903.                         $new_pid $QD->getProductId();
  10904.                         $sales_code_range = [];
  10905.                         if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  10906.                             $sales_code_range json_decode($QD->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  10907.                         } else {
  10908.                             $max_int_length strlen((string)PHP_INT_MAX) - 1;
  10909.                             $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$QD->getSalesCodeRange());
  10910.                             $sales_code_range json_decode($json_without_bigintstrue);
  10911.                         }
  10912.                         $p_data = array(
  10913.                             'details_id' => $QD->getId(),
  10914.                             'productId' => $new_pid,
  10915.                             'dr_id' => $productByCodeData->getDeliveryReceiptId(),
  10916.                             'product_name' => $productData->getName(),
  10917.                             'qty' => $QD->getQty(),
  10918.                             'delivered' => $QD->getDelivered(),
  10919.                             'unitTypeId' => $QD->getUnitTypeId(),
  10920.                             'deliverable' => $QD->getDeliverable(),
  10921.                             'balance' => $QD->getBalance(),
  10922.                             'salesCodeRangeStr' => $QD->getSalesCodeRange(),
  10923.                             'salesCodeRange' => $sales_code_range,
  10924.                             'sales_codes' => $sales_code_range,
  10925.                             'sales_price' => $QD->getPrice(),
  10926.                             'purchase_price' => $QD->getCurrentPurchasePrice()
  10927. //                        'delivered'=>$product->getDelivered(),
  10928.                         );
  10929.                         $productByCodeDataObj['drItemData'][] = $p_data;
  10930.                     }
  10931.                 }
  10932.             }
  10933.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  10934.                 ->findBy(
  10935.                     array(
  10936.                         'productId' => $id
  10937.                     )
  10938.                 );
  10939.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  10940.                 array(
  10941.                     'page_title' => 'Details',
  10942.                     'company_data' => $company_data,
  10943.                     'productByCodeData' => $productByCodeData,
  10944.                     'productByCodeDataObj' => $productByCodeDataObj,
  10945.                     'productData' => $productData,
  10946.                     'currInvList' => $currInvList,
  10947.                     'productDataWeightPackageGm' => $productDataWeightPackageGm,
  10948.                     'productDataWeightVarianceValue' => $productDataWeightVarianceValue,
  10949.                     'productDataWeightVarianceType' => $productDataWeightVarianceType,
  10950.                     'exId' => $id,
  10951.                     'clientList' => Client::GetExistingClientList($em$companyId),
  10952.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  10953.                     'productList' => Inventory::ProductList($em$companyId),
  10954.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10955.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10956.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10957.                     'unitList' => Inventory::UnitTypeList($em),
  10958.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10959.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10960.                     'warehouseList' => Inventory::WarehouseList($em),
  10961.                 )
  10962.             ));
  10963.         } else {
  10964.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  10965.                 array(
  10966.                     'exId' => $id,
  10967.                 )
  10968.             ));
  10969.         }
  10970.         if ($request->query->has('returnJson')) {
  10971.             return new JsonResponse(
  10972.                 array(
  10973.                     'success' => true,
  10974.                     'page_title' => 'Product Details',
  10975.                     'company_data' => $company_data,
  10976.                     'renderedHtml' => $html,
  10977.                     'exId' => $id,
  10978.                     'productByCodeDataObj' => $productByCodeDataObj,
  10979. //                'productData' => $productData,
  10980. //                'currInvList' => $currInvList,
  10981. //                'productList' => Inventory::ProductList($em, $companyId),
  10982. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10983. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10984. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10985. //                'unitList' => Inventory::UnitTypeList($em),
  10986. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10987. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10988. //                'warehouseList' => Inventory::WarehouseList($em),
  10989.                 )
  10990.             );
  10991.         } else {
  10992. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10993. //                ->findBy(
  10994. //                    array(
  10995. ////                        'productByCodeId' => $id,
  10996. //                    'CompanyId'=>$companyId
  10997. //                    )
  10998. //                );
  10999.             $productByCodeList = []; //called by ajax
  11000.             return $this->render('@Inventory/pages/views/product_by_code_assign_check_print.html.twig',
  11001.                 array(
  11002.                     'page_title' => 'Serial Manager',
  11003.                     'company_data' => $company_data,
  11004.                     'renderedHtml' => $html,
  11005.                     'exId' => $id,
  11006.                     'productByCodeList' => $productByCodeList,
  11007.                     'productByCodeDataObj' => $productByCodeDataObj,
  11008. //                'productByCodeData' => $productByCodeData,
  11009. //                'productData' => $productData,
  11010. //                'currInvList' => $currInvList,
  11011. //                'productList' => Inventory::ProductList($em, $companyId),
  11012. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11013. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11014. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11015. //                'unitList' => Inventory::UnitTypeList($em),
  11016. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11017. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11018. //                'warehouseList' => Inventory::WarehouseList($em),
  11019.                 )
  11020.             );
  11021.         }
  11022.     }
  11023.     public
  11024.     function TestProductByCodeCheckAssignPrintAction(Request $request$id 0)
  11025.     {
  11026.         $em $this->getDoctrine()->getManager();
  11027.         $companyId $this->getLoggedUserCompanyId($request);
  11028.         $company_data Company::getCompanyData($em$companyId);
  11029.         $data = [];
  11030.         $html '';
  11031.         $productByCodeData = [];
  11032.         $productByCodeDataObj = [];
  11033.         if ($id != 0) {
  11034.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11035.                 ->findOneBy(
  11036.                     array(
  11037.                         'productByCodeId' => $id
  11038.                     )
  11039.                 );
  11040.         } else {
  11041.             if ($request->query->has('scanCode')) {
  11042.                 $query $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11043.                     ->createQueryBuilder('p');
  11044.                 if ($request->query->has('assigned')) {
  11045.                     $query->where('p.assigned > :av')
  11046.                         ->setParameter('av'$request->query->get('assigned'));
  11047.                 } else
  11048.                     $query->where("1=0");
  11049.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  11050.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  11051.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  11052.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  11053.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  11054.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  11055.                 $query->setMaxResults(1);
  11056.                 $results $query->getQuery()->getResult();
  11057.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  11058.             } else
  11059.                 $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11060.                     ->findOneBy(
  11061.                         array(
  11062. //                        'productByCodeId' => $id,
  11063.                             'CompanyId' => $companyId
  11064.                         ), array(
  11065.                             'productByCodeId' => 'DESC'
  11066.                         )
  11067.                     );
  11068.             if ($productByCodeData)
  11069.                 $id $productByCodeData->getProductByCodeId();
  11070.         }
  11071.         if ($id != 0) {
  11072.             $productByCodeDataObj = array(
  11073.                 'sn' => $productByCodeData->getSalesCode(),
  11074.                 'imei1' => $productByCodeData->getImei1(),
  11075.                 'imei2' => $productByCodeData->getImei2(),
  11076.                 'colorId' => $productByCodeData->getColorId(),
  11077.             );
  11078.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  11079.                 ->findOneBy(
  11080.                     array(
  11081.                         'id' => $productByCodeData->getProductId()
  11082.                     )
  11083.                 );
  11084.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  11085.                 ->findBy(
  11086.                     array(
  11087.                         'productId' => $id
  11088.                     )
  11089.                 );
  11090.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  11091.                 array(
  11092.                     'page_title' => 'Details',
  11093.                     'company_data' => $company_data,
  11094.                     'productByCodeData' => $productByCodeData,
  11095.                     'productData' => $productData,
  11096.                     'currInvList' => $currInvList,
  11097.                     'exId' => $id,
  11098.                     'clientList' => Client::GetExistingClientList($em$companyId),
  11099.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  11100.                     'productList' => Inventory::ProductList($em$companyId),
  11101.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  11102.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  11103.                     'igList' => Inventory::ItemGroupList($em$companyId),
  11104.                     'unitList' => Inventory::UnitTypeList($em),
  11105.                     'brandList' => Inventory::GetBrandList($em$companyId),
  11106.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  11107.                     'warehouseList' => Inventory::WarehouseList($em),
  11108.                 )
  11109.             );
  11110.         } else {
  11111.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  11112.                 array(
  11113.                     'exId' => $id,
  11114.                 )
  11115.             );
  11116.         }
  11117.         if ($request->query->has('returnJson')) {
  11118.             return new JsonResponse(
  11119.                 array(
  11120.                     'success' => true,
  11121.                     'page_title' => 'Product Details',
  11122.                     'company_data' => $company_data,
  11123.                     'renderedHtml' => $html,
  11124.                     'exId' => $id,
  11125.                     'productByCodeDataObj' => $productByCodeDataObj,
  11126. //                'productData' => $productData,
  11127. //                'currInvList' => $currInvList,
  11128. //                'productList' => Inventory::ProductList($em, $companyId),
  11129. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11130. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11131. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11132. //                'unitList' => Inventory::UnitTypeList($em),
  11133. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11134. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11135. //                'warehouseList' => Inventory::WarehouseList($em),
  11136.                 )
  11137.             );
  11138.         } else {
  11139. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11140. //                ->findBy(
  11141. //                    array(
  11142. ////                        'productByCodeId' => $id,
  11143. //                    'CompanyId'=>$companyId
  11144. //                    )
  11145. //                );
  11146.             $productByCodeList = []; //called by ajax
  11147.             return $this->render('@Inventory/pages/views/test_product_by_code_assign_check_print.html.twig',
  11148.                 array(
  11149.                     'page_title' => ' Test Serial Manager',
  11150.                     'company_data' => $company_data,
  11151.                     'renderedHtml' => $html,
  11152.                     'exId' => $id,
  11153.                     'productByCodeList' => $productByCodeList,
  11154.                     'productByCodeDataObj' => $productByCodeDataObj,
  11155. //                'productByCodeData' => $productByCodeData,
  11156. //                'productData' => $productData,
  11157. //                'currInvList' => $currInvList,
  11158. //                'productList' => Inventory::ProductList($em, $companyId),
  11159. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11160. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11161. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11162. //                'unitList' => Inventory::UnitTypeList($em),
  11163. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11164. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11165. //                'warehouseList' => Inventory::WarehouseList($em),
  11166.                 )
  11167.             );
  11168.         }
  11169.     }
  11170.     public function DeleteProductAction(Request $request$id '')
  11171.     {
  11172.         $em $this->getDoctrine()->getManager();
  11173.         $idListArray = [];
  11174.         if ($request->isMethod('POST')) {
  11175.             if ($id == 0)
  11176.                 $id $request->request->get('productId');
  11177.             //now check the product closing , if nothing then we cna remove it
  11178.             $query_here $this->getDoctrine()
  11179.                 ->getRepository('ApplicationBundle\\Entity\\InvClosingBalance')
  11180.                 ->findBy(
  11181.                     array(
  11182.                         'productId' => $request->request->get('productId')
  11183.                     )
  11184.                 );
  11185.             if (!empty($query_here)) {
  11186.                 return new JsonResponse(
  11187.                     array(
  11188.                         'success' => false,
  11189.                     )
  11190.                 );
  11191.             } else {
  11192.                 $qry $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')->findBy(array(
  11193.                     'productId' => $id
  11194.                 ));
  11195.                 foreach ($qry as $det) {
  11196.                     //remove any barcoded products
  11197.                     $em->remove($det);
  11198.                     $em->flush();
  11199.                 }
  11200.                 $qry $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findBy(array(
  11201.                     'id' => $id
  11202.                 ));
  11203.                 foreach ($qry as $det) {
  11204.                     //remove any barcoded products
  11205.                     $em->remove($det);
  11206.                     $em->flush();
  11207.                 }
  11208.                 $qry $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')->findBy(array(
  11209.                     'productId' => $id
  11210.                 ));
  11211.                 foreach ($qry as $det) {
  11212.                     //remove any barcoded products
  11213.                     $em->remove($det);
  11214.                     $em->flush();
  11215.                 }
  11216.                 return new JsonResponse(
  11217.                     array(
  11218.                         'success' => true,
  11219.                     )
  11220.                 );
  11221.             }
  11222.         }
  11223.         return new JsonResponse(
  11224.             array(
  11225.                 'success' => false,
  11226.             )
  11227.         );
  11228.     }
  11229.     public
  11230.     function RegisterProductAction(Request $request$idListStr '')
  11231.     {
  11232.         $em $this->getDoctrine()->getManager();
  11233.         $companyId $this->getLoggedUserCompanyId($request);
  11234.         $company_data Company::getCompanyData($em$companyId);
  11235.         $session $request->getSession();
  11236. //        System::setSessionForUser($session );
  11237.         $idListArray = [];
  11238.         if ($idListStr != '')
  11239.             $idListArray explode(','$idListStr);
  11240.         $data = [];
  11241. //        if ($request->isMethod('POST')) {
  11242. //            $post = $request->request;
  11243. //            if ($request->request->get('formatId') != '') {
  11244. //                $query_here = $this->getDoctrine()
  11245. //                    ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  11246. //                    ->findOneBy(
  11247. //                        array(
  11248. //                            'formatId' => $request->request->get('formatId')
  11249. //                        )
  11250. //                    );
  11251. //                if (!empty($query_here))
  11252. //                    $new = $query_here;
  11253. //            } else
  11254. //                $new = new CheckFormat();
  11255. //            $new->setName($request->request->get('name'));
  11256. //            $new->setWidth($request->request->get('width'));
  11257. //            $new->setHeight($request->request->get('height'));
  11258. //            $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
  11259. //            $new->setCheckPayToTop($request->request->get('checkPayToTop'));
  11260. //            $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
  11261. //            $new->setCheckAmountTop($request->request->get('checkAmountTop'));
  11262. //            $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
  11263. //            $new->setCheckAiWTop($request->request->get('checkAiWTop'));
  11264. //            $new->setCheckDateLeft($request->request->get('checkDateLeft'));
  11265. //            $new->setCheckDateTop($request->request->get('checkDateTop'));
  11266. //            $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
  11267. //            $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
  11268. //            $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
  11269. //            $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
  11270. //            $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
  11271. //            $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
  11272. //            $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
  11273. //            $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
  11274. //            $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
  11275. //            $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
  11276. //            $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 1 : 0);
  11277. //            $new->setCheckImage($request->request->get('checkImage'));
  11278. //
  11279. //            $em = $this->getDoctrine()->getManager();
  11280. //            $em->persist($new);
  11281. //            $em->flush();
  11282. //
  11283. //        }
  11284. //        if (!empty($idListArray)) {
  11285. //            $query_here = $this->getDoctrine()
  11286. //                ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11287. //                ->findBy(
  11288. //                    array(
  11289. //                        'productByCodeId' => $idListArray
  11290. //                    )
  11291. //                );
  11292. //            if (!empty($query_here))
  11293. //                $data = $query_here;
  11294. //
  11295. //        }
  11296. //        else if ($request->query->has('formatId')) {
  11297. //            $query_here = $this->getDoctrine()
  11298. //                ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  11299. //                ->findOneBy(
  11300. //                    array(
  11301. //                        'formatId' => $request->query->get('formatId')
  11302. //                    )
  11303. //                );
  11304. //            if (!empty($query_here))
  11305. //                $data = $query_here;
  11306. //        }
  11307.         $data = [];
  11308.         $html '';
  11309.         $productByCodeData = [];
  11310.         if ($request->query->has('returnJson')) {
  11311.             return new JsonResponse(
  11312.                 array(
  11313.                     'success' => true,
  11314.                     'page_title' => 'Product Details',
  11315.                     'company_data' => $company_data,
  11316.                     'renderedHtml' => $html,
  11317.                     'data' => $data,
  11318.                     'idListArray' => $idListArray,
  11319. //                    'exId'=>$id,
  11320. //                'productByCodeData' => $productByCodeData,
  11321. //                'productData' => $productData,
  11322. //                'currInvList' => $currInvList,
  11323. //                'productList' => Inventory::ProductList($em, $companyId),
  11324. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11325. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11326. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11327. //                'unitList' => Inventory::UnitTypeList($em),
  11328. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11329. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11330. //                'warehouseList' => Inventory::WarehouseList($em),
  11331.                 )
  11332.             );
  11333.         } else {
  11334.             return $this->render('@Inventory/pages/input_forms/register_product.html.twig',
  11335.                 array(
  11336.                     'page_title' => 'Register Product',
  11337.                     'company_data' => $company_data,
  11338.                     'renderedHtml' => $html,
  11339. //                    'exIdList'=>$i,
  11340.                     'idListArray' => $idListArray,
  11341.                     'data' => $data,
  11342.                     'productByCodeList' => [],
  11343.                     'productByCodeData' => [],
  11344.                     'productList' => Inventory::ProductList($em$companyId),
  11345.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  11346.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  11347.                     'igList' => Inventory::ItemGroupList($em$companyId),
  11348.                     'unitList' => Inventory::UnitTypeList($em),
  11349.                     'brandList' => Inventory::GetBrandList($em$companyId),
  11350.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  11351.                     'warehouseList' => Inventory::WarehouseList($em),
  11352.                 )
  11353.             );
  11354.         }
  11355.     }
  11356.     public
  11357.     function BrandViewAction(Request $request)
  11358.     {
  11359.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  11360.             array(
  11361.                 'page_title' => 'Stock Return'
  11362.             )
  11363.         );
  11364.     }
  11365.     public
  11366.     function PrintTableDataAction(Request $request)
  11367.     {
  11368.         $em $this->getDoctrine()->getManager();
  11369.         $company_data Company::getCompanyData($em1);
  11370.         $data = [];
  11371.         $print_title "test";
  11372.         $document_mark = array(
  11373.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11374.             'copy' => ''
  11375.         );
  11376.         $mis_data = [];
  11377.         $p 1;
  11378.         return $this->render('@Inventory/pages/print/print_table_data.html.twig',
  11379.             array(
  11380.                 'page_title' => 'Data Report',
  11381.                 'data' => $data,
  11382.                 'page_header' => 'Report',
  11383.                 'print_title' => $print_title,
  11384.                 'document_type' => 'Journal voucher',
  11385.                 'document_mark_image' => $document_mark['original'],
  11386.                 'page_header_sub' => 'Add',
  11387. //                'type_list'=>$type_list,
  11388.                 'mis_data' => $mis_data,
  11389.                 'item_data' => [],
  11390.                 'received' => 2,
  11391.                 'return' => 1,
  11392.                 'total_w_vat' => 1,
  11393.                 'total_vat' => 1,
  11394.                 'total_wo_vat' => 1,
  11395.                 'invoice_id' => 'abcd1234',
  11396.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11397.                 'created_by' => 'created by',
  11398.                 'created_at' => '',
  11399.                 'red' => 0,
  11400.                 'company_name' => $company_data->getName(),
  11401.                 'company_data' => $company_data,
  11402.                 'company_address' => $company_data->getAddress(),
  11403.                 'company_image' => $company_data->getImage(),
  11404.                 'p' => $p
  11405.             )
  11406.         );
  11407.     }
  11408.     public
  11409.     function ReplacementReportAction(Request $request)
  11410.     {
  11411.         $qry_data = array(
  11412.             'warehouseId' => [0],
  11413.             'igId' => [0],
  11414.             'brandId' => [0],
  11415.             'categoryId' => [0],
  11416.             'actionTagId' => [0],
  11417.         );
  11418.         $em $this->getDoctrine()->getManager();
  11419.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  11420.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  11421.         $data_searched = [];
  11422.         $companyId $this->getLoggedUserCompanyId($request);
  11423.         $company_data Company::getCompanyData($em$companyId);
  11424.         $data = [];
  11425.         $print_title "Inventory Report";
  11426.         $document_mark = array(
  11427.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11428.             'copy' => ''
  11429.         );
  11430.         $post_data $request->request;
  11431.         $start_date $post_data->has('start_date') ? $post_data->get('start_date') : '';
  11432.         $end_date $post_data->has('end_date') ? $post_data->get('end_date') : '';
  11433.         if ($request->isMethod('POST'))
  11434.             $method 'POST';
  11435.         else
  11436.             $method 'GET';
  11437.         {
  11438. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  11439.             $data_searched Inventory::GetReplacementReportData($this->getDoctrine()->getManager(),
  11440.                 $request->request$method,
  11441.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  11442.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  11443.                 return new JsonResponse(
  11444.                     array(
  11445.                         'page_title' => 'Inventory ',
  11446.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11447.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11448.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11449.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11450.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11451.                         'action_tag' => $warehouse_action_list,
  11452.                         'start_date' => $start_date,
  11453.                         'end_date' => $end_date,
  11454.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11455.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11456.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11457.                         'data_searched' => $data_searched,
  11458.                         'success' => empty($data_searched['query_result']) ? false true
  11459.                     )
  11460.                 );
  11461.             }
  11462.             if ($request->request->get('print_data_enabled') == 1) {
  11463.                 $print_sub_title "";
  11464.                 return $this->render('@Inventory/pages/print/print_replacement_report.html.twig',
  11465.                     array(
  11466.                         'page_title' => 'Replacement Report',
  11467.                         'page_header' => 'Report',
  11468.                         'print_title' => $print_title,
  11469.                         'document_type' => 'Journal voucher',
  11470.                         'document_mark_image' => $document_mark['original'],
  11471.                         'page_header_sub' => 'Add',
  11472.                         'item_data' => [],
  11473.                         'received' => 2,
  11474.                         'return' => 1,
  11475.                         'total_w_vat' => 1,
  11476.                         'total_vat' => 1,
  11477.                         'total_wo_vat' => 1,
  11478.                         'invoice_id' => 'abcd1234',
  11479.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  11480.                         'created_by' => 'created by',
  11481.                         'created_at' => '',
  11482.                         'red' => 0,
  11483.                         'company_name' => $company_data->getName(),
  11484.                         'company_data' => $company_data,
  11485.                         'company_address' => $company_data->getAddress(),
  11486.                         'company_image' => $company_data->getImage(),
  11487.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11488.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11489.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11490.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11491.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11492.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11493.                         'action_tag' => $warehouse_action_list,
  11494.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11495.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11496.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11497.                         'start_date' => $start_date,
  11498.                         'end_date' => $end_date,
  11499.                         'data_searched' => $data_searched
  11500.                     )
  11501.                 );
  11502.             }
  11503.         }
  11504.         return $this->render('@Inventory/pages/report/replacement_report.html.twig',
  11505.             array(
  11506.                 'page_title' => 'Replacement Report',
  11507.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11508.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11509.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11510.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11511.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11512. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11513.                 'action_tag' => $warehouse_action_list,
  11514.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11515.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11516.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11517.                 'start_date' => $start_date,
  11518.                 'end_date' => $end_date,
  11519.                 'data_searched' => $data_searched,
  11520.                 'success' => empty($data_searched['query_result']) ? false true
  11521.             )
  11522.         );
  11523.     }
  11524.     public
  11525.     function InventoryViewAction(Request $request)
  11526.     {
  11527.         $qry_data = array(
  11528.             'warehouseId' => [0],
  11529.             'igId' => [0],
  11530.             'brandId' => [0],
  11531.             'categoryId' => [0],
  11532.             'actionTagId' => [0],
  11533.         );
  11534.         $em $this->getDoctrine()->getManager();
  11535.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  11536.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  11537.         $data_searched = [];
  11538.         $companyId $this->getLoggedUserCompanyId($request);
  11539.         $company_data Company::getCompanyData($em$companyId);
  11540.         $data = [];
  11541.         $print_title "Inventory Report";
  11542.         $document_mark = array(
  11543.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11544.             'copy' => ''
  11545.         );
  11546.         if ($request->isMethod('POST'))
  11547.             $method 'POST';
  11548.         else
  11549.             $method 'GET';
  11550.         {
  11551. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  11552.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  11553.                 $request->request$method,
  11554.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  11555.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  11556.                 return new JsonResponse(
  11557.                     array(
  11558.                         'page_title' => 'Inventory ',
  11559.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11560.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11561.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11562.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11563.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11564.                         'action_tag' => $warehouse_action_list,
  11565.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11566.                         'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  11567.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11568.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11569.                         'data_searched' => $data_searched,
  11570.                         'success' => empty($data_searched['query_result']) ? false true
  11571.                     )
  11572.                 );
  11573.             }
  11574.             if ($request->request->get('print_data_enabled') == 1) {
  11575.                 $print_sub_title "";
  11576.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  11577.                     array(
  11578.                         'page_title' => 'Inventory Report',
  11579.                         'page_header' => 'Report',
  11580.                         'print_title' => $print_title,
  11581.                         'document_type' => 'Journal voucher',
  11582.                         'document_mark_image' => $document_mark['original'],
  11583.                         'page_header_sub' => 'Add',
  11584.                         'item_data' => [],
  11585.                         'received' => 2,
  11586.                         'return' => 1,
  11587.                         'total_w_vat' => 1,
  11588.                         'total_vat' => 1,
  11589.                         'total_wo_vat' => 1,
  11590.                         'invoice_id' => 'abcd1234',
  11591.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  11592.                         'created_by' => 'created by',
  11593.                         'created_at' => '',
  11594.                         'red' => 0,
  11595.                         'company_name' => $company_data->getName(),
  11596.                         'company_data' => $company_data,
  11597.                         'company_address' => $company_data->getAddress(),
  11598.                         'company_image' => $company_data->getImage(),
  11599.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11600.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11601.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11602.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11603.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11604.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11605.                         'action_tag' => $warehouse_action_list,
  11606.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11607.                         'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  11608.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11609.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11610.                         'data_searched' => $data_searched
  11611.                     )
  11612.                 );
  11613.             }
  11614.         }
  11615.         return $this->render('@Inventory/pages/report/inventory_view.html.twig',
  11616.             array(
  11617.                 'page_title' => 'Inventory',
  11618.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11619.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11620.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11621.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11622.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11623. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11624.                 'action_tag' => $warehouse_action_list,
  11625.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11626.                 'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  11627.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11628.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11629.                 'data_searched' => $data_searched
  11630.             )
  11631.         );
  11632.     }
  11633.     public
  11634.     function GrnListAction(Request $request)
  11635.     {
  11636.         $q $this->getDoctrine()
  11637.             ->getRepository('ApplicationBundle\\Entity\\Grn')
  11638.             ->findBy(
  11639.                 array(
  11640.                     'status' => GeneralConstant::ACTIVE,
  11641. //                    'approved' =>  GeneralConstant::APPROVED,
  11642.                 )
  11643.             );
  11644.         $stage_list = array(
  11645.             => 'Pending',
  11646.             => 'Pending',
  11647.             => 'Complete',
  11648.             => 'Partial',
  11649.         );
  11650.         $data = [];
  11651.         foreach ($q as $entry) {
  11652.             $data[] = array(
  11653.                 'doc_date' => $entry->getGrnDate(),
  11654.                 'id' => $entry->getGrnId(),
  11655.                 'doc_hash' => $entry->getDocumentHash(),
  11656.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  11657.                 'stage' => GeneralConstant::stageLabel($stage_list$entry->getStage())
  11658.             );
  11659.         }
  11660.         return $this->render('@Inventory/pages/views/grn_list.html.twig',
  11661.             array(
  11662.                 'page_title' => 'Grn List',
  11663.                 'data' => $data
  11664.             )
  11665.         );
  11666.     }
  11667.     public
  11668.     function ViewGrnAction(Request $request$id)
  11669.     {
  11670.         $em $this->getDoctrine()->getManager();
  11671.         $dt Inventory::GetGrnDetails($em$id);
  11672.         return $this->render(
  11673.             '@Inventory/pages/views/view_grn.html.twig',
  11674.             array(
  11675.                 'page_title' => 'View',
  11676.                 'data' => $dt,
  11677.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  11678.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11679.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11680.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11681.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  11682.                     $id,
  11683.                     $dt['created_by'],
  11684.                     $dt['edited_by'])
  11685.             )
  11686.         );
  11687.     }
  11688.     public
  11689.     function PrintGrnAction(Request $request$id)
  11690.     {
  11691.         $em $this->getDoctrine()->getManager();
  11692.         $dt Inventory::GetGrnDetails($em$id);
  11693.         $company_data Company::getCompanyData($em1);
  11694.         $document_mark = array(
  11695.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11696.             'copy' => ''
  11697.         );
  11698.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11699.             $html $this->renderView('@Inventory/pages/print/print_received_note.html.twig',
  11700.                 array(
  11701.                     //full array here
  11702.                     'pdf' => true,
  11703.                     'page_title' => 'Grn',
  11704.                     'export' => 'pdf,print',
  11705.                     'data' => $dt,
  11706.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11707.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11708.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11709.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  11710.                         $id,
  11711.                         $dt['created_by'],
  11712.                         $dt['edited_by']),
  11713.                     'document_mark_image' => $document_mark['original'],
  11714.                     'company_name' => $company_data->getName(),
  11715.                     'company_data' => $company_data,
  11716.                     'company_address' => $company_data->getAddress(),
  11717.                     'company_image' => $company_data->getImage(),
  11718.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11719.                     'red' => 0
  11720.                 )
  11721.             );
  11722.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11723. //                'orientation' => 'landscape',
  11724. //                'enable-javascript' => true,
  11725. //                'javascript-delay' => 1000,
  11726.                 'no-stop-slow-scripts' => false,
  11727.                 'no-background' => false,
  11728.                 'lowquality' => false,
  11729.                 'encoding' => 'utf-8',
  11730. //            'images' => true,
  11731. //            'cookie' => array(),
  11732.                 'dpi' => 300,
  11733.                 'image-dpi' => 300,
  11734. //                'enable-external-links' => true,
  11735. //                'enable-internal-links' => true
  11736.             ));
  11737.             return new Response(
  11738.                 $pdf_response,
  11739.                 200,
  11740.                 array(
  11741.                     'Content-Type' => 'application/pdf',
  11742.                     'Content-Disposition' => 'attachment; filename="grn.pdf"'
  11743.                 )
  11744.             );
  11745.         }
  11746.         return $this->render('@Inventory/pages/print/print_received_note.html.twig',
  11747.             array(
  11748.                 'page_title' => 'Grn',
  11749.                 'export' => 'pdf,print',
  11750.                 'data' => $dt,
  11751.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11752.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11753.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11754.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  11755.                     $id,
  11756.                     $dt['created_by'],
  11757.                     $dt['edited_by']),
  11758.                 'document_mark_image' => $document_mark['original'],
  11759.                 'company_name' => $company_data->getName(),
  11760.                 'company_data' => $company_data,
  11761.                 'company_address' => $company_data->getAddress(),
  11762.                 'company_image' => $company_data->getImage(),
  11763.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11764.                 'red' => 0
  11765.             )
  11766.         );
  11767.     }
  11768.     public
  11769.     function PrintGrnBarcodeAction(Request $request$id)
  11770.     {
  11771.         $em $this->getDoctrine()->getManager();
  11772.         $dt Inventory::GetGrnDetails($em$id);
  11773.         $company_data Company::getCompanyData($em1);
  11774.         $repeatCount 1;
  11775.         if ($request->query->has('repeatCount'))
  11776.             $repeatCount $request->query->get('repeatCount');
  11777.         $document_mark = array(
  11778.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11779.             'copy' => ''
  11780.         );
  11781.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11782.             $html $this->renderView('@Inventory/pages/print/print_grn_barcodes.html.twig',
  11783.                 array(
  11784.                     //full array here
  11785.                     'pdf' => true,
  11786.                     'page_title' => 'Grn Barcodes',
  11787.                     'export' => 'print',
  11788.                     'data' => $dt,
  11789.                     'repeatCount' => $repeatCount,
  11790.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11791.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11792.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11793.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  11794.                         $id,
  11795.                         $dt['created_by'],
  11796.                         $dt['edited_by']),
  11797.                     'document_mark_image' => $document_mark['original'],
  11798.                     'company_name' => $company_data->getName(),
  11799.                     'company_data' => $company_data,
  11800.                     'company_address' => $company_data->getAddress(),
  11801.                     'company_image' => $company_data->getImage(),
  11802.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11803.                     'red' => 0
  11804.                 )
  11805.             );
  11806.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11807. //                'orientation' => 'landscape',
  11808.                 'enable-javascript' => true,
  11809. //                'javascript-delay' => 1000,
  11810.                 'no-stop-slow-scripts' => false,
  11811.                 'no-background' => false,
  11812.                 'lowquality' => false,
  11813.                 'encoding' => 'utf-8',
  11814. //            'images' => true,
  11815. //            'cookie' => array(),
  11816.                 'dpi' => 300,
  11817.                 'image-dpi' => 300,
  11818. //                'enable-external-links' => true,
  11819. //                'enable-internal-links' => true
  11820.             ));
  11821.             return new Response(
  11822.                 $pdf_response,
  11823.                 200,
  11824.                 array(
  11825.                     'Content-Type' => 'application/pdf',
  11826.                     'Content-Disposition' => 'attachment; filename="grn_barcodes.pdf"'
  11827.                 )
  11828.             );
  11829.         }
  11830.         return $this->render('@Inventory/pages/print/print_grn_barcodes.html.twig',
  11831.             array(
  11832.                 'page_title' => 'Grn barcodes',
  11833. //                'export'=>'pdf,print',
  11834.                 'data' => $dt,
  11835.                 'repeatCount' => $repeatCount,
  11836.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11837.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11838.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11839.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  11840.                     $id,
  11841.                     $dt['created_by'],
  11842.                     $dt['edited_by']),
  11843.                 'document_mark_image' => $document_mark['original'],
  11844.                 'company_name' => $company_data->getName(),
  11845.                 'company_data' => $company_data,
  11846.                 'company_address' => $company_data->getAddress(),
  11847.                 'company_image' => $company_data->getImage(),
  11848.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11849.                 'red' => 0
  11850.             )
  11851.         );
  11852.     }
  11853.     public function GenerateBarcodeAction(Request $request$type$id$item_id)
  11854.     {
  11855.         $em $this->getDoctrine()->getManager();
  11856.         $repeatCount 1;
  11857.         $spec_item_id 0;
  11858.         $skip_ids = [];
  11859.         $clearUnnecessaryOnly 0;
  11860.         if ($request->query->has('skipIds'))
  11861.             $skip_ids $request->query->get('skipIds');
  11862.         if ($request->query->has('clearUnnecessaryOnly'))
  11863.             $clearUnnecessaryOnly $request->query->get('clearUnnecessaryOnly');
  11864.         if ($type == 'srcv') {
  11865.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')->findOneBy(
  11866.                 array(
  11867.                     'stockReceivedNoteId' => $id
  11868.                 )
  11869.             );
  11870.             if ($item_id == '_single_') {
  11871.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findBy(
  11872.                     array(
  11873.                         'stockReceivedNoteId' => $id,
  11874. //                        'id' => $item_id
  11875.                     )
  11876.                 );
  11877.             } else {
  11878.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findBy(
  11879.                     array(
  11880.                         'stockReceivedNoteId' => $id,
  11881.                         'id' => $item_id
  11882.                     )
  11883.                 );
  11884.             }
  11885.             $inv_acc_data = [
  11886.                 'fa_amount' => 0,
  11887.                 'tg_amount' => 0,
  11888.             ];
  11889.             $inv_acc_data_by_head = [
  11890.             ];
  11891.             $new_non_delivered_sales_code_range = [];
  11892.             foreach ($doc_item_data as $entry) {
  11893.                 //adding transaction
  11894.                 $sales_code_range_ser = [];
  11895.                 if (in_array($entry->getId(), $skip_ids))
  11896.                     continue;
  11897.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  11898.                     ->findOneBy(
  11899.                         array(
  11900.                             'id' => $entry->getProductId()
  11901.                         )
  11902.                     );
  11903.                 $stitem $em->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  11904.                     ->findOneBy(
  11905.                         array(
  11906.                             'id' => $entry->getStockTransferItemId(),
  11907.                             'productId' => $entry->getProductId()
  11908.                         )
  11909.                     );
  11910.                 if ($product) {
  11911.                     if ($product->getHasSerial() == 1) {
  11912.                         //clear if exists
  11913.                         if ($clearUnnecessaryOnly == 1) {
  11914.                             $get_kids_sql "DELETE FROM product_by_code
  11915.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  11916. //                $get_kids_sql .=' ORDER BY name ASC';
  11917.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  11918.                             $em->flush();
  11919.                         } else {
  11920.                             $get_kids_sql "DELETE FROM product_by_code
  11921.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  11922. //                $get_kids_sql .=' ORDER BY name ASC';
  11923.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  11924.                             $em->flush();
  11925.                         }
  11926. //                        $check_here = $stmt;
  11927.                         //now addng product by code
  11928.                         $sales_code_range = [];
  11929.                         if ($doc_data->getType() == || $doc_data->getType() == 4) {
  11930. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  11931. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  11932.                             $product_action_tag_id $entry->getWarehouseActionId();
  11933.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getQty(),
  11934.                                 $doc_data->getStockReceivedNoteDate(), $entry->getWarrantyMon(), 0$doc_data->getCompanyId(), $entry->getWarehouseId(),
  11935.                                 $entry->getWarehouseActionId(), $entry->getPurchaseCodeRange(), nullnullnullnull$doc_data->getStockReceivedNoteId()
  11936.                             );
  11937.                             $sales_code_range $barcodeData['sales_code_range'];
  11938.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  11939.                             $em->flush();
  11940.                         }
  11941. //                        else {
  11942. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11943. //
  11944. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11945. //                            } else {
  11946. //
  11947. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11948. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  11949. //                                $sales_code_range = json_decode($json_without_bigints, true);
  11950. //                            }
  11951. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11952. //
  11953. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11954. //                            } else {
  11955. //
  11956. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11957. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  11958. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  11959. //                            }
  11960. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  11961. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  11962. //                            $new_non_delivered_sales_code_range = [];
  11963. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  11964. //                                if (!(in_array($ndsc, $sales_code_range)))
  11965. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  11966. //                            }
  11967. //                            if ($sales_code_range != null) {
  11968. //                                foreach ($sales_code_range as $ind => $dt) {
  11969. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11970. //                                        ->findOneBy(
  11971. //                                            array(
  11972. //                                                'salesCode' => [$dt],
  11973. //                                                'productId' => $entry->getProductId()
  11974. //                                            )
  11975. //                                        );
  11976. //
  11977. //                                    if ($np) {
  11978. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  11979. //                                        $np->setProductId($entry->getProductId());
  11980. //                                        $np->setWarehouseId($entry->getWarehouseId());
  11981. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  11982. //                                        $np->setPosition(1);//in warehouse
  11983. //                                        $np->setStockReceivedNoteId($id);
  11984. //
  11985. //
  11986. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  11987. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  11988. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  11989. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  11990. //                                            'direction' => 'in',
  11991. //                                            'warehouseId' => $entry->getWarehouseId(),
  11992. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  11993. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  11994. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  11995. //                                        );
  11996. //                                        $np->setTransactionHistory(json_encode(
  11997. //                                            $trans_history
  11998. //                                        ));
  11999. //
  12000. //
  12001. //                                        $em->persist($np);
  12002. //                                        $em->flush();
  12003. //                                    }
  12004. //                                }
  12005. //                            }
  12006. //                        }
  12007.                     }
  12008.                 }
  12009.                 //adding transaction
  12010.                 if ($stitem) {
  12011.                     $stitem->setNonDeliveredSalesCodeRange(json_encode($new_non_delivered_sales_code_range));
  12012.                 }
  12013.                 $spec_item_id $entry->getId();
  12014.                 if ($item_id == '_single_') {
  12015.                     break;
  12016.                 }
  12017.             }
  12018.         }
  12019.         if ($type == 'irr') {
  12020.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacement')->findOneBy(
  12021.                 array(
  12022.                     'itemReceivedAndReplacementId' => $id
  12023.                 )
  12024.             );
  12025.             if ($item_id == '_single_') {
  12026.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacementItem')->findBy(
  12027.                     array(
  12028.                         'itemReceivedAndReplacementId' => $id,
  12029. //                        'id' => $item_id
  12030.                     )
  12031.                 );
  12032.             } else {
  12033.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacementItem')->findBy(
  12034.                     array(
  12035.                         'itemReceivedAndReplacementId' => $id,
  12036.                         'id' => $item_id
  12037.                     )
  12038.                 );
  12039.             }
  12040.             $inv_acc_data = [
  12041.                 'fa_amount' => 0,
  12042.                 'tg_amount' => 0,
  12043.             ];
  12044.             $inv_acc_data_by_head = [
  12045.             ];
  12046.             $new_non_delivered_sales_code_range = [];
  12047.             foreach ($doc_item_data as $entry) {
  12048.                 //adding transaction
  12049.                 $sales_code_range_ser = [];
  12050.                 if (in_array($entry->getId(), $skip_ids))
  12051.                     continue;
  12052.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12053.                     ->findOneBy(
  12054.                         array(
  12055.                             'id' => $entry->getReceivedProductId()
  12056.                         )
  12057.                     );
  12058.                 if ($product) {
  12059.                     if ($product->getHasSerial() == 1) {
  12060.                         //clear if exists
  12061. //                        if($clearUnnecessaryOnly==1) {
  12062. //                            $get_kids_sql = "DELETE FROM product_by_code
  12063. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12064. ////                $get_kids_sql .=' ORDER BY name ASC';
  12065. //
  12066. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12067. //                            
  12068. //                            $em->flush();
  12069. //                        }
  12070. //                        else{
  12071. //                            $get_kids_sql = "DELETE FROM product_by_code
  12072. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12073. ////                $get_kids_sql .=' ORDER BY name ASC';
  12074. //
  12075. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12076. //                            
  12077. //                            $em->flush();
  12078. //                        }
  12079. //                        $check_here = $stmt;
  12080.                         //now addng product by code
  12081.                         $sales_code_range = [];
  12082.                         if ($entry->getReceivedQty() > 0) {
  12083. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  12084. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  12085. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  12086.                             $barcodeData Inventory::GenerateBarcode($em$entry->getReceivedProductId(), $entry->getReceivedQty(),
  12087.                                 $doc_data->getItemReceivedAndReplacementDate(), 00$doc_data->getCompanyId(), $entry->getReceivedWarehouseId(),
  12088.                                 $entry->getReceivedWarehouseActionId(), nullnullnullnullnullnullnullnull$doc_data->getItemReceivedAndReplacementId()
  12089.                             );
  12090.                             $sales_code_range $barcodeData['sales_code_range'];
  12091.                             $entry->setReceivedCodeRange(json_encode($sales_code_range));
  12092.                             $em->flush();
  12093.                         }
  12094. //                        else {
  12095. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12096. //
  12097. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12098. //                            } else {
  12099. //
  12100. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12101. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  12102. //                                $sales_code_range = json_decode($json_without_bigints, true);
  12103. //                            }
  12104. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12105. //
  12106. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12107. //                            } else {
  12108. //
  12109. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12110. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  12111. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  12112. //                            }
  12113. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  12114. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  12115. //                            $new_non_delivered_sales_code_range = [];
  12116. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  12117. //                                if (!(in_array($ndsc, $sales_code_range)))
  12118. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  12119. //                            }
  12120. //                            if ($sales_code_range != null) {
  12121. //                                foreach ($sales_code_range as $ind => $dt) {
  12122. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12123. //                                        ->findOneBy(
  12124. //                                            array(
  12125. //                                                'salesCode' => [$dt],
  12126. //                                                'productId' => $entry->getProductId()
  12127. //                                            )
  12128. //                                        );
  12129. //
  12130. //                                    if ($np) {
  12131. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  12132. //                                        $np->setProductId($entry->getProductId());
  12133. //                                        $np->setWarehouseId($entry->getWarehouseId());
  12134. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  12135. //                                        $np->setPosition(1);//in warehouse
  12136. //                                        $np->setStockReceivedNoteId($id);
  12137. //
  12138. //
  12139. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  12140. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  12141. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  12142. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  12143. //                                            'direction' => 'in',
  12144. //                                            'warehouseId' => $entry->getWarehouseId(),
  12145. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  12146. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  12147. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  12148. //                                        );
  12149. //                                        $np->setTransactionHistory(json_encode(
  12150. //                                            $trans_history
  12151. //                                        ));
  12152. //
  12153. //
  12154. //                                        $em->persist($np);
  12155. //                                        $em->flush();
  12156. //                                    }
  12157. //                                }
  12158. //                            }
  12159. //                        }
  12160.                     }
  12161.                 }
  12162.                 //adding transaction
  12163.                 $spec_item_id $entry->getId();
  12164.                 if ($item_id == '_single_') {
  12165.                     break;
  12166.                 }
  12167.             }
  12168.         }
  12169.         if ($type == 'prdcn') {
  12170.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\Production')->findOneBy(
  12171.                 array(
  12172.                     'productionId' => $id
  12173.                 )
  12174.             );
  12175.             if ($item_id == '_single_') {
  12176.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findBy(
  12177.                     array(
  12178.                         'productionId' => $id,
  12179. //                        'id' => $item_id
  12180.                     )
  12181.                 );
  12182.             } else {
  12183.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findBy(
  12184.                     array(
  12185.                         'productionId' => $id,
  12186.                         'id' => $item_id
  12187.                     )
  12188.                 );
  12189.             }
  12190.             $inv_acc_data = [
  12191.                 'fa_amount' => 0,
  12192.                 'tg_amount' => 0,
  12193.             ];
  12194.             $inv_acc_data_by_head = [
  12195.             ];
  12196.             $new_non_delivered_sales_code_range = [];
  12197.             foreach ($doc_item_data as $entry) {
  12198.                 //adding transaction
  12199.                 $sales_code_range_ser = [];
  12200.                 if (in_array($entry->getId(), $skip_ids))
  12201.                     continue;
  12202.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12203.                     ->findOneBy(
  12204.                         array(
  12205.                             'id' => $entry->getProductId()
  12206.                         )
  12207.                     );
  12208.                 if ($product) {
  12209.                     if ($product->getHasSerial() == 1) {
  12210.                         //clear if exists
  12211. //                        if($clearUnnecessaryOnly==1) {
  12212. //                            $get_kids_sql = "DELETE FROM product_by_code
  12213. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12214. ////                $get_kids_sql .=' ORDER BY name ASC';
  12215. //
  12216. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12217. //                            
  12218. //                            $em->flush();
  12219. //                        }
  12220. //                        else{
  12221. //                            $get_kids_sql = "DELETE FROM product_by_code
  12222. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12223. ////                $get_kids_sql .=' ORDER BY name ASC';
  12224. //
  12225. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12226. //                            
  12227. //                            $em->flush();
  12228. //                        }
  12229. //                        $check_here = $stmt;
  12230.                         //now addng product by code
  12231.                         $sales_code_range = [];
  12232.                         if ($entry->getProducedQty() > 0) {
  12233. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  12234. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  12235. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  12236.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getProducedQty(),
  12237.                                 $doc_data->getProductionDate(), 00$doc_data->getCompanyId(), $entry->getWarehouseId(),
  12238.                                 $entry->getProducedItemActionTagId(), nullnullnullnullnullnullnull$doc_data->getProductionId(), null
  12239.                             );
  12240.                             $sales_code_range $barcodeData['sales_code_range'];
  12241.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  12242.                             $em->flush();
  12243.                         }
  12244. //                        else {
  12245. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12246. //
  12247. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12248. //                            } else {
  12249. //
  12250. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12251. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  12252. //                                $sales_code_range = json_decode($json_without_bigints, true);
  12253. //                            }
  12254. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12255. //
  12256. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12257. //                            } else {
  12258. //
  12259. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12260. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  12261. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  12262. //                            }
  12263. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  12264. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  12265. //                            $new_non_delivered_sales_code_range = [];
  12266. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  12267. //                                if (!(in_array($ndsc, $sales_code_range)))
  12268. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  12269. //                            }
  12270. //                            if ($sales_code_range != null) {
  12271. //                                foreach ($sales_code_range as $ind => $dt) {
  12272. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12273. //                                        ->findOneBy(
  12274. //                                            array(
  12275. //                                                'salesCode' => [$dt],
  12276. //                                                'productId' => $entry->getProductId()
  12277. //                                            )
  12278. //                                        );
  12279. //
  12280. //                                    if ($np) {
  12281. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  12282. //                                        $np->setProductId($entry->getProductId());
  12283. //                                        $np->setWarehouseId($entry->getWarehouseId());
  12284. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  12285. //                                        $np->setPosition(1);//in warehouse
  12286. //                                        $np->setStockReceivedNoteId($id);
  12287. //
  12288. //
  12289. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  12290. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  12291. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  12292. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  12293. //                                            'direction' => 'in',
  12294. //                                            'warehouseId' => $entry->getWarehouseId(),
  12295. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  12296. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  12297. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  12298. //                                        );
  12299. //                                        $np->setTransactionHistory(json_encode(
  12300. //                                            $trans_history
  12301. //                                        ));
  12302. //
  12303. //
  12304. //                                        $em->persist($np);
  12305. //                                        $em->flush();
  12306. //                                    }
  12307. //                                }
  12308. //                            }
  12309. //                        }
  12310.                     }
  12311.                 }
  12312.                 //adding transaction
  12313.                 $spec_item_id $entry->getId();
  12314.                 if ($item_id == '_single_') {
  12315.                     break;
  12316.                 }
  12317.             }
  12318.         }
  12319.         return new JsonResponse(array(
  12320.             'success' => $spec_item_id != true false,
  12321.             'skipIds' => [],
  12322.             'spec_item_id' => $spec_item_id
  12323.         ));
  12324. //        return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12325. //            array(
  12326. //                'page_title' => 'Srcv barcodes',
  12327. ////                'export'=>'pdf,print',
  12328. //                'data' => $dt,
  12329. //                'repeatCount' => $repeatCount,
  12330. //                'item_id' => $item_id,
  12331. //                'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12332. //                    $id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12333. //                'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12334. //                    array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12335. //                    $id,
  12336. //                    $dt['created_by'],
  12337. //                    $dt['edited_by']),
  12338. //                'document_mark_image' => $document_mark['original'],
  12339. //                                    'company_name' => $company_data->getName(),
  12340. //                    'company_data'=>$company_data,
  12341. //                'company_address' => $company_data->getAddress(),
  12342. //                'company_image' => $company_data->getImage(),
  12343. //                'invoice_footer' => $company_data->getInvoiceFooter(),
  12344. //                'red' => 0
  12345. //
  12346. //            )
  12347. //        );
  12348.     }
  12349.     public
  12350.     function PrintLabelAction(Request $request$id)
  12351.     {
  12352.         $em $this->getDoctrine()->getManager();
  12353. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12354.         $repeatCount 1;
  12355.         $assignProductId '';
  12356.         $productByCodeIds = [];
  12357.         $print_selection_type 1;
  12358.         $print_selection_string 1;
  12359.         $assignLabelFormatId 0;
  12360.         $assignColorId 0;
  12361.         $assignProductionScheduleId 0;
  12362.         $warehouseId '';
  12363.         $warehouseActionId '';
  12364.         $toAssignPosition '';
  12365.         $printFlag $request->request->has('printFlag') ? $request->request->get('printFlag') : 1;
  12366.         $returnJson $request->request->has('returnJson') ? $request->request->get('returnJson') : 0;
  12367.         if ($returnJson == 1)
  12368.             $printFlag 0;
  12369.         $companyId $this->getLoggedUserCompanyId($request);
  12370.         if ($request->query->has('repeatCount'))
  12371.             $repeatCount $request->query->get('repeatCount');
  12372.         if ($request->request->has('print_selection_type'))
  12373.             $print_selection_type $request->request->get('print_selection_type');
  12374.         if ($request->request->has('print_selection_string'))
  12375.             $print_selection_string $request->request->get('print_selection_string');
  12376.         if ($request->request->has('productByCodeIds'))
  12377.             $productByCodeIds json_decode($request->request->get('productByCodeIds'), true);
  12378.         if ($request->request->has('formatId'))
  12379.             $assignLabelFormatId $request->request->get('formatId');
  12380.         if ($printFlag == 0) {
  12381.             if ($request->request->has('productSelector'))
  12382.                 $assignProductId $request->request->get('productSelector');
  12383.             if ($request->request->has('colorId'))
  12384.                 $assignColorId $request->request->get('colorId');
  12385.             if ($request->request->has('productionScheduleId'))
  12386.                 $assignProductionScheduleId $request->request->get('productionScheduleId');
  12387.             if ($request->request->has('warehouseId'))
  12388.                 $warehouseId $request->request->get('warehouseId');
  12389.             if ($request->request->has('warehouseActionId'))
  12390.                 $warehouseActionId $request->request->get('warehouseActionId');
  12391.             if ($request->request->has('position'))
  12392.                 $toAssignPosition $request->request->get('position');
  12393.             if ($assignColorId == '')
  12394.                 $assignColorId 0;
  12395.         }
  12396.         if ($productByCodeIds == null)
  12397.             $productByCodeIds = [];
  12398.         $productByCodeData = [];
  12399.         $productList = [];
  12400.         $productIds = [];
  12401.         if ($print_selection_type == 2) {
  12402.             //range
  12403.             $productByCodeIds Inventory::getIdsFromIdSelectionStr($print_selection_string);
  12404.         }
  12405.         $labelData = [
  12406.             'formatId' => 0
  12407.         ];
  12408.         $formatId 0;
  12409.         if (!empty($productByCodeIds)) {
  12410.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12411.                 ->findBy(
  12412.                     array(
  12413.                         'productByCodeId' => $productByCodeIds
  12414.                     )
  12415.                 );
  12416.             foreach ($productByCodeData as $d) {
  12417.                 if ($d->getStage() < 10$d->setStage(11);
  12418.                 if ($assignProductId != '') {
  12419.                     $d->setProductId($assignProductId);
  12420.                 }
  12421.                 if ($assignColorId != 0) {
  12422.                     $d->setColorId($assignColorId);
  12423.                 } else {
  12424.                     $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12425.                         ->findOneBy(
  12426.                             array(
  12427.                                 'id' => $assignProductId
  12428.                             )
  12429.                         );
  12430.                     if ($productData) {
  12431.                         $d->setColorId($productData->getDefaultColorId());
  12432.                     }
  12433.                 }
  12434.                 if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  12435.                     $d->setDefaultLabelFormatId($assignLabelFormatId);
  12436.                     $d->setDeviceLabelFormatId($assignLabelFormatId);
  12437.                 }
  12438.                 $toAssignPosition != '' $d->setPosition($toAssignPosition) : '';
  12439.                 $warehouseId != '' $d->setWarehouseId($warehouseId) : '';
  12440.                 $warehouseActionId != '' $d->setWarehouseActionId($warehouseActionId) : '';
  12441.                 if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  12442.                     $d->setProductionScheduleId($assignProductionScheduleId);
  12443.                     $productionSchedule $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  12444.                         ->findOneBy(
  12445.                             array(
  12446.                                 'productionScheduleId' => $assignProductionScheduleId
  12447.                             )
  12448.                         );
  12449.                     if ($productionSchedule) {
  12450.                         if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  12451.                             //becuase it will assigned at previous lines
  12452.                         } else {
  12453.                             $d->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  12454.                             $d->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  12455.                         }
  12456.                         $d->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  12457.                         $d->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  12458.                     }
  12459.                 }
  12460.                 $em->flush();
  12461.                 if ($d->getProductId() != '' || $d->getProductId() != null)
  12462.                     $productIds[] = $d->getProductId();
  12463.                 $formatId $d->getDeviceLabelFormatId();
  12464.             }
  12465.         }
  12466.         $labelFormatHere $em->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  12467.             ->findOneBy(
  12468.                 array(
  12469.                     'formatId' => $formatId,
  12470. //                        'CompanyId' => $companyId
  12471.                 )
  12472.             );
  12473.         if ($labelFormatHere) {
  12474.             $formatData json_decode($labelFormatHere->getFormatData(), true);
  12475.             if ($formatData == null$formatData = [];
  12476.             $labelData = array(
  12477.                 'id' => $labelFormatHere->getFormatId(),
  12478.                 'formatId' => $labelFormatHere->getFormatId(),
  12479.                 'labelType' => $labelFormatHere->getLabelType(),
  12480.                 'name' => $labelFormatHere->getName(),
  12481.                 'width' => $labelFormatHere->getWidth(),
  12482.                 'pageWidth' => $labelFormatHere->getPageWidth(),
  12483.                 'height' => $labelFormatHere->getheight(),
  12484.                 'pageHeight' => $labelFormatHere->getPageHeight(),
  12485.                 'formatData' => $formatData,
  12486.             );
  12487.         }
  12488.         $productList Inventory::ProductList($em$this->getLoggedUserCompanyId($request), 10''$productIds);
  12489.         $company_data Company::getCompanyData($em1);
  12490.         $document_mark = array(
  12491.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12492.             'copy' => ''
  12493.         );
  12494.         $dt $productByCodeData;
  12495.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12496.             $html $this->renderView('@Inventory/pages/print/print_label.html.twig',
  12497.                 array(
  12498.                     //full array here
  12499.                     'pdf' => true,
  12500.                     'page_title' => 'Device Labels',
  12501.                     'export' => 'print',
  12502.                     'repeatCount' => $repeatCount,
  12503.                     'labelData' => $labelData,
  12504.                     'brandList' => Inventory::GetBrandList($em$companyId),
  12505. //                    'item_id' => $item_id,
  12506.                     'data' => $dt,
  12507.                     'productList' => $productList,
  12508.                     'approval_data' => [],
  12509.                     'document_log' => [],
  12510.                     'document_mark_image' => $document_mark['original'],
  12511.                     'company_name' => $company_data->getName(),
  12512.                     'company_data' => $company_data,
  12513.                     'company_address' => $company_data->getAddress(),
  12514.                     'company_image' => $company_data->getImage(),
  12515.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12516.                     'red' => 0
  12517.                 )
  12518.             );
  12519.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12520. //                'orientation' => 'landscape',
  12521.                 'enable-javascript' => true,
  12522. //                'javascript-delay' => 1000,
  12523.                 'no-stop-slow-scripts' => false,
  12524.                 'no-background' => false,
  12525.                 'lowquality' => false,
  12526.                 'encoding' => 'utf-8',
  12527. //            'images' => true,
  12528. //            'cookie' => array(),
  12529.                 'dpi' => 300,
  12530.                 'image-dpi' => 300,
  12531. //                'enable-external-links' => true,
  12532. //                'enable-internal-links' => true
  12533.             ));
  12534.             return new Response(
  12535.                 $pdf_response,
  12536.                 200,
  12537.                 array(
  12538.                     'Content-Type' => 'application/pdf',
  12539.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  12540.                 )
  12541.             );
  12542.         }
  12543.         $url $this->generateUrl(
  12544.             'print_label'
  12545.         );
  12546.         if ($returnJson == && $printFlag == 0) {
  12547. //                    $dr = $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findBy(
  12548. //                        array(
  12549. //                            'salesOrderId' => $orderId, ///material
  12550. //
  12551. //                        )
  12552. //                    );
  12553.             return new JsonResponse(array(
  12554.                 'success' => true,
  12555. //                        'documentHash' => $order->getDocumentHash(),
  12556. //                'documentId' => $receiptId,
  12557. //                'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
  12558. //
  12559. //                'viewUrl' => $url . "/" . $receiptId,
  12560.             ));
  12561.         } else return $this->render('@Inventory/pages/print/print_label.html.twig',
  12562.             array(
  12563.                 'page_title' => 'Product Labels',
  12564. //                'export'=>'pdf,print',
  12565.                 'data' => $dt,
  12566.                 'productList' => $productList,
  12567.                 'repeatCount' => $repeatCount,
  12568. //                'item_id' => $item_id,
  12569.                 'labelData' => $labelData,
  12570.                 'brandList' => Inventory::GetBrandList($em$companyId),
  12571.                 'approval_data' => [],
  12572.                 'document_log' => [],
  12573.                 'document_mark_image' => $document_mark['original'],
  12574.                 'company_name' => $company_data->getName(),
  12575.                 'company_data' => $company_data,
  12576.                 'company_address' => $company_data->getAddress(),
  12577.                 'company_image' => $company_data->getImage(),
  12578.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12579.                 'red' => 0
  12580.             )
  12581.         );
  12582.     }
  12583.     public
  12584.     function PrintCartonLabelAction(Request $request$id)
  12585.     {
  12586.         $em $this->getDoctrine()->getManager();
  12587. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12588.         $repeatCount 1;
  12589.         $assignProductId '';
  12590.         $productByCodeIds = [];
  12591.         $cartonId 0;
  12592.         if ($id != 0)
  12593.             $cartonId $id;
  12594.         $colorText '';
  12595.         $weightText '';
  12596.         if ($request->query->has('repeatCount'))
  12597.             $repeatCount $request->query->get('repeatCount');
  12598.         if ($request->request->has('printCartonId'))
  12599.             $cartonId $request->request->get('printCartonId');
  12600.         if ($request->request->has('printCartonColorText'))
  12601.             $colorText $request->request->get('printCartonColorText');
  12602.         if ($request->request->has('printCartonWeightText'))
  12603.             $weightText $request->request->get('printCartonWeightText');
  12604.         $labelData = [
  12605.             'formatId' => 0
  12606.         ];
  12607.         if ($productByCodeIds == null)
  12608.             $productByCodeIds = [];
  12609.         $productByCodeData = [];
  12610.         $cartonData = [];
  12611.         $product = [];
  12612.         if ($cartonId != 0) {
  12613.             $cartonData $em->getRepository('ApplicationBundle\\Entity\\Carton')
  12614.                 ->findOneBy(
  12615.                     array(
  12616.                         'id' => $cartonId
  12617.                     )
  12618.                 );
  12619.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12620.                 ->findBy(
  12621.                     array(
  12622.                         'cartonId' => $cartonId
  12623.                     )
  12624.                 );
  12625. //            if(!empty($productByCodeData))
  12626. //                $product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12627. //                ->findOneBy(
  12628. //                    array(
  12629. //                        'id' => $productByCodeData[0]->getProductId()
  12630. //                    )
  12631. //                );
  12632. //            else
  12633.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12634.                 ->findOneBy(
  12635.                     array(
  12636.                         'id' => $cartonData->getProductId()
  12637.                     )
  12638.                 );
  12639.             $formatId $cartonData->getCartonLabelFormatId();
  12640.             $labelFormatHere $em->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  12641.                 ->findOneBy(
  12642.                     array(
  12643.                         'formatId' => $formatId,
  12644. //                        'CompanyId' => $companyId
  12645.                     )
  12646.                 );
  12647.             if ($labelFormatHere) {
  12648.                 $formatData json_decode($labelFormatHere->getFormatData(), true);
  12649.                 if ($formatData == null$formatData = [];
  12650.                 $labelData = array(
  12651.                     'id' => $labelFormatHere->getFormatId(),
  12652.                     'formatId' => $labelFormatHere->getFormatId(),
  12653.                     'labelType' => $labelFormatHere->getLabelType(),
  12654.                     'name' => $labelFormatHere->getName(),
  12655.                     'width' => $labelFormatHere->getWidth(),
  12656.                     'pageWidth' => $labelFormatHere->getPageWidth(),
  12657.                     'height' => $labelFormatHere->getheight(),
  12658.                     'pageHeight' => $labelFormatHere->getPageHeight(),
  12659.                     'formatData' => $formatData,
  12660.                 );
  12661.             }
  12662.         }
  12663.         $company_data Company::getCompanyData($em1);
  12664.         $document_mark = array(
  12665.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12666.             'copy' => ''
  12667.         );
  12668.         $dt $productByCodeData;
  12669.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12670.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  12671.                 array(
  12672.                     //full array here
  12673.                     'pdf' => true,
  12674.                     'page_title' => 'Carton Labels',
  12675.                     'export' => 'print',
  12676.                     'labelData' => $labelData,
  12677.                     'repeatCount' => $repeatCount,
  12678. //                    'item_id' => $item_id,
  12679.                     'data' => $dt,
  12680.                     'cartonData' => $cartonData,
  12681.                     'product' => $product,
  12682.                     'colorText' => $colorText,
  12683.                     'weightText' => $weightText,
  12684.                     'approval_data' => [],
  12685.                     'document_log' => [],
  12686.                     'document_mark_image' => $document_mark['original'],
  12687.                     'company_name' => $company_data->getName(),
  12688.                     'company_data' => $company_data,
  12689.                     'company_address' => $company_data->getAddress(),
  12690.                     'company_image' => $company_data->getImage(),
  12691.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12692.                     'red' => 0
  12693.                 )
  12694.             );
  12695.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12696. //                'orientation' => 'landscape',
  12697.                 'enable-javascript' => true,
  12698. //                'javascript-delay' => 1000,
  12699.                 'no-stop-slow-scripts' => false,
  12700.                 'no-background' => false,
  12701.                 'lowquality' => false,
  12702.                 'encoding' => 'utf-8',
  12703. //            'images' => true,
  12704. //            'cookie' => array(),
  12705.                 'dpi' => 300,
  12706.                 'image-dpi' => 300,
  12707. //                'enable-external-links' => true,
  12708. //                'enable-internal-links' => true
  12709.             ));
  12710.             return new Response(
  12711.                 $pdf_response,
  12712.                 200,
  12713.                 array(
  12714.                     'Content-Type' => 'application/pdf',
  12715.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  12716.                 )
  12717.             );
  12718.         }
  12719.         if ($request->query->has('previewOnly')) {
  12720.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  12721.                 array(
  12722.                     'page_title' => 'Carton Labels',
  12723. //                'export'=>'pdf,print',
  12724.                     'data' => $dt,
  12725.                     'skip_parameters' => 1,
  12726.                     'labelData' => $labelData,
  12727.                     'cartonData' => $cartonData,
  12728.                     'product' => $product,
  12729.                     'colorText' => $colorText,
  12730.                     'weightText' => $weightText,
  12731.                     'repeatCount' => $repeatCount,
  12732. //                'item_id' => $item_id,
  12733.                     'approval_data' => [],
  12734.                     'document_log' => [],
  12735.                     'document_mark_image' => $document_mark['original'],
  12736.                     'company_name' => $company_data->getName(),
  12737.                     'company_data' => $company_data,
  12738.                     'company_address' => $company_data->getAddress(),
  12739.                     'company_image' => $company_data->getImage(),
  12740.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12741.                     'red' => 0
  12742.                 )
  12743.             );
  12744.             if ($request->query->has('returnJson')) {
  12745.                 return new JsonResponse(
  12746.                     array(
  12747.                         'success' => true,
  12748.                         'page_title' => 'Product Details',
  12749.                         'company_data' => $company_data,
  12750.                         'renderedHtml' => $html,
  12751. //                'productData' => $productData,
  12752. //                'currInvList' => $currInvList,
  12753. //                'productList' => Inventory::ProductList($em, $companyId),
  12754. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  12755. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  12756. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  12757. //                'unitList' => Inventory::UnitTypeList($em),
  12758. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  12759. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  12760. //                'warehouseList' => Inventory::WarehouseList($em),
  12761.                     )
  12762.                 );
  12763.             }
  12764.         }
  12765.         return $this->render('@Inventory/pages/print/print_carton_label.html.twig',
  12766.             array(
  12767.                 'page_title' => 'Carton Labels',
  12768. //                'export'=>'pdf,print',
  12769.                 'data' => $dt,
  12770.                 'cartonData' => $cartonData,
  12771.                 'product' => $product,
  12772. //                'productByCodeData' => $productByCodeData,
  12773.                 'colorText' => $colorText,
  12774.                 'weightText' => $weightText,
  12775.                 'repeatCount' => $repeatCount,
  12776.                 'labelData' => $labelData,
  12777. //                'item_id' => $item_id,
  12778.                 'approval_data' => [],
  12779.                 'document_log' => [],
  12780.                 'document_mark_image' => $document_mark['original'],
  12781.                 'company_name' => $company_data->getName(),
  12782.                 'company_data' => $company_data,
  12783.                 'company_address' => $company_data->getAddress(),
  12784.                 'company_image' => $company_data->getImage(),
  12785.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12786.                 'red' => 0
  12787.             )
  12788.         );
  12789.     }
  12790.     public function AssignInfoToProductByCodeAction(Request $request$id)
  12791.     {
  12792.         $em $this->getDoctrine()->getManager();
  12793.         $companyId $this->getLoggedUserCompanyId($request);
  12794. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12795.         $cartonId '';
  12796.         $passStatus 5;
  12797.         $assignProductId '';
  12798.         $assignProductionId '';
  12799.         $assignProductionScheduleId '';
  12800.         $gbWeightGm '';
  12801.         $dvWeightGm '';
  12802.         $cartonWeightGm '';
  12803.         if ($request->request->has('cartonId'))
  12804.             $cartonId $request->request->get('cartonId');
  12805.         if ($request->request->has('passStatus'))
  12806.             $passStatus $request->request->get('passStatus');
  12807.         if ($request->request->has('productByCodeId'))
  12808.             $id $request->request->get('productByCodeId');
  12809.         if ($request->request->has('productId'))
  12810.             $assignProductId $request->request->get('productId');
  12811.         if ($request->request->has('productionId'))
  12812.             $assignProductionId $request->request->get('productionId');
  12813.         if ($request->request->has('productionScheduleId'))
  12814.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  12815.         if ($request->request->has('gbWeightGm'))
  12816.             $gbWeightGm $request->request->get('gbWeightGm');
  12817.         if ($request->request->has('dvWeightGm'))
  12818.             $dvWeightGm $request->request->get('dvWeightGm');
  12819.         if ($request->request->has('cartonWeightGm'))
  12820.             $cartonWeightGm $request->request->get('cartonWeightGm');
  12821.         $cartonAssignedAlready 0;
  12822.         $otherData = array(
  12823.             'currentCartonBalance' => 0,
  12824.             'currentCartonCapacity' => 0,
  12825.             'currentCartonAssigned' => 0,
  12826.             'currentCartonFull' => 0,
  12827.         );
  12828.         if ($id != && $id != '') {
  12829.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12830.                 ->findOneBy(
  12831.                     array(
  12832.                         'productByCodeId' => $id
  12833.                     )
  12834.                 );
  12835.             if ($assignProductId != ''$productByCodeData->setProductId($assignProductId);
  12836.             if ($productByCodeData->getCartonId() != '' || $productByCodeData->getCartonId() != null)
  12837.                 $cartonAssignedAlready 1;
  12838.             else if ($cartonId != ''$productByCodeData->setCartonId($cartonId);
  12839.             if ($dvWeightGm != ''$productByCodeData->setSingleWeightGm($dvWeightGm);
  12840.             if ($gbWeightGm != '') {
  12841.                 $productByCodeData->setPackagedWeightGm($gbWeightGm);
  12842.             }
  12843.             $colorText '_NA_';
  12844.             if ($passStatus != 5$productByCodeData->setStage($passStatus);
  12845.             $productByCodeData->setCompanyId($companyId);
  12846.             if ($assignProductionId != '') {
  12847.                 $productByCodeData->setProductionId($assignProductionId);
  12848.                 $productionData $em->getRepository('ApplicationBundle\\Entity\\Production')
  12849.                     ->findOneBy(
  12850.                         array(
  12851.                             'productionId' => $assignProductionId
  12852.                         )
  12853.                     );
  12854.                 if ($assignProductId != '' && $assignProductId != null && $assignProductId != 0)
  12855.                     $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  12856.                         array(
  12857.                             'productionId' => $assignProductionId,
  12858.                             'productId' => $assignProductId,
  12859.                             'type' => 1,
  12860.                         )
  12861.                     );
  12862.                 else
  12863.                     $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  12864.                         array(
  12865.                             'productionId' => $assignProductionId,
  12866. //                            'productId' => $assignProductId,
  12867.                             'type' => 1,
  12868.                         )
  12869.                     );
  12870.                 $assignProductionScheduleId $productionData->getProductionScheduleId();
  12871.                 if ($productionItemData) {
  12872.                     $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  12873.                     $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  12874.                     $productByCodeData->setPosition(1);//in inventory
  12875.                     $productByCodeData->setSerialAssigned(1);
  12876.                     $productByCodeData->setColorId($productionItemData->getColorId());
  12877.                     $productByCodeData->setColorText($productionItemData->getColorText());
  12878.                     $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  12879.                     $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  12880.                     if ($passStatus == 1)//passed
  12881.                     {
  12882. //                    $transDate = new \DateTime();
  12883. //                    Inventory::addItemToInventoryCompact($em,
  12884. //                        $productionItemData->getProductId(),
  12885. //                        $productionItemData->getWarehouseId(),
  12886. //                        $productionItemData->getWarehouseId(),
  12887. //                        $productionData->getProducedItemActionTagId(),
  12888. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  12889. //                        $transDate,
  12890. //                        1,
  12891. //                        1,
  12892. //                        $entry['valueAdd'],
  12893. //                        $entry['valueSub'],
  12894. //                        $entry['price'],
  12895. //                        $this->getLoggedUserCompanyId($request),
  12896. //                        0,
  12897. //                        $entry['entity'],
  12898. //                        $entry['entityId'],
  12899. //                        $entry['entityDocHash']
  12900. //                    );
  12901.                     }
  12902.                     $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  12903.                     if ($transHistory == null)
  12904.                         $transHistory = [];
  12905.                     $transHistory[] = array(
  12906.                         'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  12907.                         'direction' => 'in',
  12908.                         'warehouseId' => $productionItemData->getWarehouseId(),
  12909.                         'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  12910.                         'fromWarehouseId' => 0,
  12911.                         'fromWarehouseActionId' => //stock of goods
  12912.                     );
  12913.                     $productByCodeData->setTransactionHistory(json_encode($transHistory));
  12914.                 }
  12915.             }
  12916.             if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  12917.                 $productByCodeData->setProductionScheduleId($assignProductionScheduleId);
  12918.                 $productionSchedule $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  12919.                     ->findOneBy(
  12920.                         array(
  12921.                             'productionScheduleId' => $assignProductionScheduleId
  12922.                         )
  12923.                     );
  12924.                 if ($productionSchedule) {
  12925.                     $productByCodeData->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  12926.                     $productByCodeData->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  12927.                     $productByCodeData->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  12928.                     $productByCodeData->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  12929.                     if ($productByCodeData->getProductionId() == null || $productByCodeData->getProductionId() == '' || $productByCodeData->getProductionId() == 0) {
  12930.                         $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  12931.                             array(
  12932.                                 'productionScheduleId' => $assignProductionScheduleId,
  12933.                                 'productId' => $productionSchedule->getProducedProductId(),
  12934.                                 'type' => 1,
  12935.                             )
  12936.                         );
  12937. //                        $assignProductionScheduleId=$productionData->getProductionScheduleId();
  12938.                         if ($productionItemData) {
  12939.                             $productByCodeData->setProductionId($productionItemData->getProductionId());
  12940.                             $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  12941.                             $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  12942.                             $productByCodeData->setPosition(1);//in inventory
  12943.                             $productByCodeData->setSerialAssigned(1);
  12944.                             $productByCodeData->setColorId($productionItemData->getColorId());
  12945.                             $productByCodeData->setColorText($productionItemData->getColorText());
  12946.                             $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  12947.                             $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  12948.                             if ($passStatus == 1)//passed
  12949.                             {
  12950. //                    $transDate = new \DateTime();
  12951. //                    Inventory::addItemToInventoryCompact($em,
  12952. //                        $productionItemData->getProductId(),
  12953. //                        $productionItemData->getWarehouseId(),
  12954. //                        $productionItemData->getWarehouseId(),
  12955. //                        $productionData->getProducedItemActionTagId(),
  12956. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  12957. //                        $transDate,
  12958. //                        1,
  12959. //                        1,
  12960. //                        $entry['valueAdd'],
  12961. //                        $entry['valueSub'],
  12962. //                        $entry['price'],
  12963. //                        $this->getLoggedUserCompanyId($request),
  12964. //                        0,
  12965. //                        $entry['entity'],
  12966. //                        $entry['entityId'],
  12967. //                        $entry['entityDocHash']
  12968. //                    );
  12969.                             }
  12970.                             $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  12971.                             if ($transHistory == null)
  12972.                                 $transHistory = [];
  12973.                             $transHistory[] = array(
  12974.                                 'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  12975.                                 'direction' => 'in',
  12976.                                 'warehouseId' => $productionItemData->getWarehouseId(),
  12977.                                 'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  12978.                                 'fromWarehouseId' => 0,
  12979.                                 'fromWarehouseActionId' => //stock of goods
  12980.                             );
  12981.                             $productByCodeData->setTransactionHistory(json_encode($transHistory));
  12982.                         }
  12983.                     }
  12984.                 }
  12985.             }
  12986. //                $productByCodeData->setPurchaseWarrantyLastDate($new_pwld);
  12987.             $em->flush();
  12988.             //now adding carton
  12989.         }
  12990.         if ($cartonId != '') {
  12991.             $carton $em->getRepository('ApplicationBundle\\Entity\\Carton')
  12992.                 ->findOneBy(
  12993.                     array(
  12994.                         'id' => $cartonId
  12995.                     )
  12996.                 );
  12997.             if ($cartonWeightGm != ''$carton->setCartonWeightGm($cartonWeightGm);
  12998.             $otherData['currentCartonCapacity'] = $carton->getCartonCapacityCount();
  12999.             if ($cartonAssignedAlready == 0)
  13000.                 $carton->setCartonAssignedCount(($carton->getCartonAssignedCount()) + 1);
  13001.             $otherData['currentCartonAssigned'] = $carton->getCartonAssignedCount();
  13002.             $otherData['currentCartonBalance'] = $otherData['currentCartonCapacity'] - $otherData['currentCartonAssigned'];
  13003.             if ($otherData['currentCartonAssigned'] >= $otherData['currentCartonCapacity'])
  13004.                 $otherData['currentCartonFull'] = 1;
  13005.             $em->flush();
  13006.         }
  13007.         if ($cartonId != '') {
  13008. //                    if($cartonAssignedAlready==1)
  13009. //                    {
  13010.             $productByCodeDataListForThisCarton $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  13011.                 ->findBy(
  13012.                     array(
  13013.                         'cartonId' => $cartonId
  13014.                     )
  13015.                 );
  13016.             $carton $em->getRepository('ApplicationBundle\\Entity\\Carton')
  13017.                 ->findOneBy(
  13018.                     array(
  13019.                         'id' => $cartonId
  13020.                     )
  13021.                 );
  13022.             $total_carton_predicted_weight 0;
  13023.             $colorTextList = [];
  13024.             $cartonProductByCodeIds = [];
  13025.             foreach ($productByCodeDataListForThisCarton as $pikamaster) {
  13026.                 if (!in_array($pikamaster->getProductByCodeId(), $cartonProductByCodeIds))
  13027.                     $cartonProductByCodeIds[] = $pikamaster->getProductByCodeId();
  13028.                 if (!in_array($pikamaster->getColorText(), $colorTextList) && $pikamaster->getColorText() != null)
  13029.                     $colorTextList[] = $pikamaster->getColorText();
  13030.                 $total_carton_predicted_weight += ($pikamaster->getPackagedWeightGm());
  13031.                 if ($passStatus != 5)
  13032.                     if ($pikamaster->getStage() < $passStatus)
  13033.                         $pikamaster->setStage($passStatus);
  13034.             }
  13035.             if ($carton)
  13036.                 $carton->setCartonCalculatedWeightGm($total_carton_predicted_weight);
  13037.             if ($passStatus != 5)
  13038.                 $carton->setStage($passStatus);
  13039.             $carton->setColors(implode(','$colorTextList));
  13040.             $carton->setCartonProductByCodeIds(json_encode($cartonProductByCodeIds));
  13041.             $em->flush();
  13042.         }
  13043.         return new JsonResponse(array(
  13044.             'success' => true,
  13045.             'otherData' => $otherData,
  13046.         ));
  13047.     }
  13048.     public function RefreshCartonListAction(Request $request$id)
  13049.     {
  13050.         $em $this->getDoctrine()->getManager();
  13051. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  13052.         $cartonListArray = [];
  13053.         $cartonList = [];
  13054.         $assignableCartonList = [];
  13055.         $assignableCartonListArray = [];
  13056.         $assignable 0;
  13057.         $cartonId '';
  13058.         $passStatus 5;
  13059.         $assignProductId '';
  13060.         $assignProductionId '';
  13061.         $assignProductionScheduleId '';
  13062.         if ($request->request->has('productionId'))
  13063.             $assignProductionId $request->request->get('productionId');
  13064.         if ($request->request->has('productionScheduleId'))
  13065.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  13066.         if ($request->request->has('assignable'))
  13067.             $assignable $request->request->get('assignable');
  13068.         $cartonAssignedAlready 0;
  13069.         $otherData = array(
  13070.             'currentCartonBalance' => 0,
  13071.             'currentCartonCapacity' => 0,
  13072.             'currentCartonAssigned' => 0,
  13073.             'currentCartonFull' => 0,
  13074.         );
  13075.         //1st get all cartons for this production id
  13076.         $cartonList $em->getRepository('ApplicationBundle\\Entity\\Carton')
  13077.             ->findBy(
  13078.                 array(
  13079. //                    'productionId' => $assignProductionId,
  13080.                     'productionScheduleId' => $assignProductionScheduleId
  13081.                 )
  13082.             );
  13083.         $foundAssignable 0;
  13084.         $setId 0;
  13085.         $lastdmySer '';
  13086.         foreach ($cartonList as $carton) {
  13087.             $cartonData = array(
  13088.                 'id' => $carton->getId(),
  13089.                 'name' => $carton->getCartonNumber(),
  13090.                 'colors' => $carton->getColors(),
  13091.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  13092.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  13093.             );
  13094.             $cartonListArray[] = $cartonData;
  13095.             $cartonList[$cartonData['id']] = $cartonData;
  13096.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  13097.                 $foundAssignable 1;
  13098.                 $setId $cartonData['id'];
  13099.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  13100.                 $assignableCartonListArray[] = $cartonData;
  13101.             }
  13102.         }
  13103.         if ($assignable == && $foundAssignable == 0) {
  13104. //            $productionData = $em->getRepository('ApplicationBundle\\Entity\\Production')
  13105. //                ->findOneBy(
  13106. //                    array(
  13107. //                        'productionId' => $assignProductionId
  13108. //                    )
  13109. //                );
  13110.             $productionScheduleData $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  13111.                 ->findOneBy(
  13112.                     array(
  13113.                         'productionScheduleId' => $assignProductionScheduleId
  13114.                     )
  13115.                 );
  13116.             $productId 0;
  13117.             $product = [];
  13118.             $productModel '';
  13119.             if ($productionScheduleData)
  13120.                 $productId $productionScheduleData->getProducedProductId();
  13121. //            $productionItem = $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')
  13122. //                ->findOneBy(
  13123. //                    array(
  13124. //                        'productionId' => $assignProductionId,
  13125. //                        'type' => 1
  13126. //                    )
  13127. //                );
  13128.             if ($productId != 0) {
  13129. //                    $productId = $productionItem->getProductId();
  13130.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  13131.                     ->findOneBy(
  13132.                         array(
  13133.                             'id' => $productId,
  13134.                         )
  13135.                     );
  13136.                 $productModel $product->getModelNo();
  13137.             }
  13138.             $carton = new Carton();
  13139.             $carton_capacity $productionScheduleData->getCartonCapacity();
  13140.             $carton->setProductId($productId);
  13141.             $carton->setProductionId($assignProductionId);
  13142.             $carton->setProductionScheduleId($assignProductionScheduleId);
  13143.             if ($productionScheduleData) {
  13144.                 $carton->setCartonLabelFormatId($productionScheduleData->getCartonLabelFormatId());
  13145.             }
  13146.             $carton->setCartonCapacityCount($carton_capacity == null $carton_capacity);
  13147.             $carton->setCartonAssignedCount(0);
  13148.             $carton->setCompanyId($this->getLoggedUserCompanyId($request));
  13149.             $today = new \DateTime();
  13150.             $dmy $productModel '-' . ($today->format('m')) . '-' . ($today->format('Y')) . '-' $productionScheduleData->getBatchNumber();
  13151.             $ser 0;
  13152.             $carton->setCartonNumberDmy($dmy);
  13153.             $carton->setCartonNumberLastSer(* (($today->format('h')) . '' . ($today->format('i'))));
  13154.             $carton->setCartonNumber($dmy '-' . ($today->format('h')) . '' . ($today->format('i')));
  13155.             $em->persist($carton);
  13156.             $em->flush();
  13157.             $cartonData = array(
  13158.                 'id' => $carton->getId(),
  13159.                 'name' => $carton->getCartonNumber(),
  13160.                 'colors' => $carton->getColors(),
  13161.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  13162.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  13163.             );
  13164.             $cartonListArray[] = $cartonData;
  13165.             $cartonList[$cartonData['id']] = $cartonData;
  13166.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  13167.                 $foundAssignable 1;
  13168.                 $setId $cartonData['id'];
  13169.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  13170.                 $assignableCartonListArray[] = $cartonData;
  13171.             }
  13172.         }
  13173.         return new JsonResponse(array(
  13174.             'success' => true,
  13175.             'cartonList' => $cartonList,
  13176.             'cartonListArray' => $cartonListArray,
  13177.             'assignableCartonList' => $assignableCartonList,
  13178.             'assignableCartonListArray' => $assignableCartonListArray,
  13179.             'setId' => $setId,
  13180.         ));
  13181.     }
  13182.     public
  13183.     function PrintDrBarcodeAction(Request $request$id$item_id)
  13184.     {
  13185.         $em $this->getDoctrine()->getManager();
  13186.         $dt Inventory::GetDrDetails($em$id$item_id);
  13187.         $repeatCount 1;
  13188.         if ($request->query->has('repeatCount'))
  13189.             $repeatCount $request->query->get('repeatCount');
  13190.         $company_data Company::getCompanyData($em1);
  13191.         $document_mark = array(
  13192.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13193.             'copy' => ''
  13194.         );
  13195.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13196.             $html $this->renderView('@Inventory/pages/print/print_dr_barcodes.html.twig',
  13197.                 array(
  13198.                     //full array here
  13199.                     'pdf' => true,
  13200.                     'page_title' => 'Challan Barcodes',
  13201.                     'export' => 'print',
  13202.                     'repeatCount' => $repeatCount,
  13203.                     'item_id' => $item_id,
  13204.                     'data' => $dt,
  13205.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13206.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13207.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13208.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  13209.                         $id,
  13210.                         $dt['created_by'],
  13211.                         $dt['edited_by']),
  13212.                     'document_mark_image' => $document_mark['original'],
  13213.                     'company_name' => $company_data->getName(),
  13214.                     'company_data' => $company_data,
  13215.                     'company_address' => $company_data->getAddress(),
  13216.                     'company_image' => $company_data->getImage(),
  13217.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13218.                     'red' => 0
  13219.                 )
  13220.             );
  13221.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13222. //                'orientation' => 'landscape',
  13223.                 'enable-javascript' => true,
  13224. //                'javascript-delay' => 1000,
  13225.                 'no-stop-slow-scripts' => false,
  13226.                 'no-background' => false,
  13227.                 'lowquality' => false,
  13228.                 'encoding' => 'utf-8',
  13229. //            'images' => true,
  13230. //            'cookie' => array(),
  13231.                 'dpi' => 300,
  13232.                 'image-dpi' => 300,
  13233. //                'enable-external-links' => true,
  13234. //                'enable-internal-links' => true
  13235.             ));
  13236.             return new Response(
  13237.                 $pdf_response,
  13238.                 200,
  13239.                 array(
  13240.                     'Content-Type' => 'application/pdf',
  13241.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  13242.                 )
  13243.             );
  13244.         }
  13245.         return $this->render('@Inventory/pages/print/print_dr_barcodes.html.twig',
  13246.             array(
  13247.                 'page_title' => 'Challan barcodes',
  13248. //                'export'=>'pdf,print',
  13249.                 'data' => $dt,
  13250.                 'repeatCount' => $repeatCount,
  13251.                 'item_id' => $item_id,
  13252.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13253.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13254.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13255.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  13256.                     $id,
  13257.                     $dt['created_by'],
  13258.                     $dt['edited_by']),
  13259.                 'document_mark_image' => $document_mark['original'],
  13260.                 'company_name' => $company_data->getName(),
  13261.                 'company_data' => $company_data,
  13262.                 'company_address' => $company_data->getAddress(),
  13263.                 'company_image' => $company_data->getImage(),
  13264.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13265.                 'red' => 0
  13266.             )
  13267.         );
  13268.     }
  13269.     public
  13270.     function PrintIrrBarcodeAction(Request $request$id$item_id)
  13271.     {
  13272.         $em $this->getDoctrine()->getManager();
  13273.         $dt Inventory::GetIrrDetails($em$id$item_id);
  13274.         $repeatCount 1;
  13275.         if ($request->query->has('repeatCount'))
  13276.             $repeatCount $request->query->get('repeatCount');
  13277.         $company_data Company::getCompanyData($em1);
  13278.         $document_mark = array(
  13279.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13280.             'copy' => ''
  13281.         );
  13282.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13283.             $html $this->renderView('@Inventory/pages/print/print_irr_barcodes.html.twig',
  13284.                 array(
  13285.                     //full array here
  13286.                     'pdf' => true,
  13287.                     'page_title' => 'Sales Return Barcodes',
  13288.                     'export' => 'print',
  13289.                     'repeatCount' => $repeatCount,
  13290.                     'item_id' => $item_id,
  13291.                     'data' => $dt,
  13292.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13293.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13294.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13295.                         array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13296.                         $id,
  13297.                         $dt['created_by'],
  13298.                         $dt['edited_by']),
  13299.                     'document_mark_image' => $document_mark['original'],
  13300.                     'company_name' => $company_data->getName(),
  13301.                     'company_data' => $company_data,
  13302.                     'company_address' => $company_data->getAddress(),
  13303.                     'company_image' => $company_data->getImage(),
  13304.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13305.                     'red' => 0
  13306.                 )
  13307.             );
  13308.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13309. //                'orientation' => 'landscape',
  13310.                 'enable-javascript' => true,
  13311. //                'javascript-delay' => 1000,
  13312.                 'no-stop-slow-scripts' => false,
  13313.                 'no-background' => false,
  13314.                 'lowquality' => false,
  13315.                 'encoding' => 'utf-8',
  13316. //            'images' => true,
  13317. //            'cookie' => array(),
  13318.                 'dpi' => 300,
  13319.                 'image-dpi' => 300,
  13320. //                'enable-external-links' => true,
  13321. //                'enable-internal-links' => true
  13322.             ));
  13323.             return new Response(
  13324.                 $pdf_response,
  13325.                 200,
  13326.                 array(
  13327.                     'Content-Type' => 'application/pdf',
  13328.                     'Content-Disposition' => 'attachment; filename="irr_barcodes.pdf"'
  13329.                 )
  13330.             );
  13331.         }
  13332.         return $this->render('@Inventory/pages/print/print_irr_barcodes.html.twig',
  13333.             array(
  13334.                 'page_title' => 'Sales Return barcodes',
  13335. //                'export'=>'pdf,print',
  13336.                 'data' => $dt,
  13337.                 'repeatCount' => $repeatCount,
  13338.                 'item_id' => $item_id,
  13339.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13340.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13341.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13342.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13343.                     $id,
  13344.                     $dt['created_by'],
  13345.                     $dt['edited_by']),
  13346.                 'document_mark_image' => $document_mark['original'],
  13347.                 'company_name' => $company_data->getName(),
  13348.                 'company_data' => $company_data,
  13349.                 'company_address' => $company_data->getAddress(),
  13350.                 'company_image' => $company_data->getImage(),
  13351.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13352.                 'red' => 0
  13353.             )
  13354.         );
  13355.     }
  13356.     public
  13357.     function PrintSrcvBarcodeAction(Request $request$id$item_id)
  13358.     {
  13359.         $em $this->getDoctrine()->getManager();
  13360.         $dt Inventory::GetSrcvDetails($em$id$item_id);
  13361.         $repeatCount 1;
  13362.         if ($request->query->has('repeatCount'))
  13363.             $repeatCount $request->query->get('repeatCount');
  13364.         $company_data Company::getCompanyData($em1);
  13365.         $document_mark = array(
  13366.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13367.             'copy' => ''
  13368.         );
  13369.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13370.             $html $this->renderView('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  13371.                 array(
  13372.                     //full array here
  13373.                     'pdf' => true,
  13374.                     'page_title' => 'Grn Barcodes',
  13375.                     'export' => 'print',
  13376.                     'repeatCount' => $repeatCount,
  13377.                     'item_id' => $item_id,
  13378.                     'data' => $dt,
  13379.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13380.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13381.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13382.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13383.                         $id,
  13384.                         $dt['created_by'],
  13385.                         $dt['edited_by']),
  13386.                     'document_mark_image' => $document_mark['original'],
  13387.                     'company_name' => $company_data->getName(),
  13388.                     'company_data' => $company_data,
  13389.                     'company_address' => $company_data->getAddress(),
  13390.                     'company_image' => $company_data->getImage(),
  13391.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13392.                     'red' => 0
  13393.                 )
  13394.             );
  13395.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13396. //                'orientation' => 'landscape',
  13397.                 'enable-javascript' => true,
  13398. //                'javascript-delay' => 1000,
  13399.                 'no-stop-slow-scripts' => false,
  13400.                 'no-background' => false,
  13401.                 'lowquality' => false,
  13402.                 'encoding' => 'utf-8',
  13403. //            'images' => true,
  13404. //            'cookie' => array(),
  13405.                 'dpi' => 300,
  13406.                 'image-dpi' => 300,
  13407. //                'enable-external-links' => true,
  13408. //                'enable-internal-links' => true
  13409.             ));
  13410.             return new Response(
  13411.                 $pdf_response,
  13412.                 200,
  13413.                 array(
  13414.                     'Content-Type' => 'application/pdf',
  13415.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  13416.                 )
  13417.             );
  13418.         }
  13419.         return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  13420.             array(
  13421.                 'page_title' => 'Srcv barcodes',
  13422. //                'export'=>'pdf,print',
  13423.                 'data' => $dt,
  13424.                 'repeatCount' => $repeatCount,
  13425.                 'item_id' => $item_id,
  13426.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13427.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13428.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13429.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13430.                     $id,
  13431.                     $dt['created_by'],
  13432.                     $dt['edited_by']),
  13433.                 'document_mark_image' => $document_mark['original'],
  13434.                 'company_name' => $company_data->getName(),
  13435.                 'company_data' => $company_data,
  13436.                 'company_address' => $company_data->getAddress(),
  13437.                 'company_image' => $company_data->getImage(),
  13438.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13439.                 'red' => 0
  13440.             )
  13441.         );
  13442.     }
  13443. //product by code
  13444.     public function ImeiListExcelUploadAction(Request $request)
  13445.     {
  13446.         $lastIndex $request->request->get('lastIndex'0);
  13447.         if ($request->isMethod('POST')) {
  13448.             $post $request->request;
  13449.             if ($request->request->has('chunkData')) {
  13450.                 //now getting the relevant checks
  13451.                 $check_list = [];
  13452.                 $csv_data $request->request->get('chunkData', []);
  13453.                 $em $this->getDoctrine()->getManager();
  13454.                 foreach ($csv_data as $ind => $data_row) {
  13455. //                    if ($ind == 1)
  13456. //                        continue;
  13457.                     $np $this->getDoctrine()
  13458.                         ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  13459.                         ->findOneBy(
  13460.                             array(
  13461.                                 'salesCode' => isset($data_row[4]) ? $data_row[4] : 0,
  13462. //                    'approved' =>  GeneralConstant::APPROVED,
  13463.                             )
  13464.                         );
  13465.                     if (!$np)
  13466.                         $np = new ProductByCode();
  13467. //                    $np = new ProductByCode();
  13468.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  13469.                     if (isset($data_row[1])) $np->setProductId($data_row[1]);
  13470.                     if (isset($data_row[0])) $np->setLcNumber($data_row[0]);
  13471.                     if (isset($data_row[2])) $np->setCartonNumber($data_row[2]);
  13472.                     if (isset($data_row[3])) $np->setSerialNo($data_row[3]);
  13473.                     $np->setSerialAssigned(isset($data_row[10]) ? $data_row[10] : 0);
  13474.                     if (isset($data_row[4])) $np->setImei1($data_row[4]);
  13475.                     if (isset($data_row[5])) $np->setImei2($data_row[5]);
  13476.                     if (isset($data_row[6])) $np->setImei3($data_row[6]);
  13477.                     if (isset($data_row[7])) $np->setImei4($data_row[7]);
  13478.                     if (isset($data_row[8])) $np->setBtMac($data_row[8]);
  13479.                     if (isset($data_row[9])) $np->setWlanMac($data_row[9]);
  13480.                     $np->setWarehouseId(isset($data_row[11]) ? $data_row[11] : 0);
  13481.                     $np->setWarehouseActionId(isset($data_row[12]) ? $data_row[12] : 0);
  13482.                     $np->setPosition(isset($data_row[13]) ? $data_row[13] : 0);//in inventory
  13483.                     $np->setPurchaseOrderId(0);
  13484.                     $np->setGrnId(0);
  13485.                     $np->setStage(0);
  13486.                     if (isset($data_row[3])) $np->setSalesCodeRange(json_encode([$data_row[3]]));
  13487. //                $np->setSalesCode($data_row[3]);
  13488.                     if (isset($data_row[4])) $np->setSalesCode($data_row[4]); //IMEI
  13489.                     $np->setSalesCodeSer(0);
  13490.                     $np->setSalesCodeDmy('');
  13491.                     $np->setPurchaseCodeRange("");
  13492.                     $np->setPurchaseReceiptDate(null);
  13493.                     $np->setLastInDate(null);
  13494.                     $np->setStatus(GeneralConstant::ACTIVE);
  13495.                     $np->setTransactionHistory(json_encode([
  13496.                         ]
  13497.                     ));
  13498.                     $np->setPurchaseWarrantyLastDate(null);
  13499.                     $em->persist($np);
  13500.                     $em->flush();
  13501.                 }
  13502.                 return new JsonResponse(array(
  13503.                     "success" => true,
  13504.                     "lastIndex" => $lastIndex,
  13505.                     "file_path" => '',
  13506.                     "csv_data" => $csv_data,
  13507.                     //                "debug_data"=>System::encryptSignature($r)
  13508.                 ));
  13509.             } else {
  13510.                 $path "";
  13511.                 $file_path "";
  13512.                 //            var_dump($request->files);
  13513.                 //        var_dump($request->getFile());
  13514.                 foreach ($request->files as $uploadedFile) {
  13515.                     //            if($uploadedFile->getImage())
  13516.                     //                var_dump($uploadedFile->getFile());
  13517.                     //                var_dump($uploadedFile);
  13518.                     if ($uploadedFile != null) {
  13519.                         $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  13520.                         $path $fileName;
  13521.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  13522.                         if (!file_exists($upl_dir)) {
  13523.                             mkdir($upl_dir0777true);
  13524.                         }
  13525.                         $file $uploadedFile->move($upl_dir$path);
  13526.                     }
  13527.                 }
  13528.                 //        print_r($file);
  13529.                 if ($path != "")
  13530.                     $file_path 'uploads/FileUploads/' $path;
  13531.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  13532.                 //
  13533.                 //            $img_file = file_get_contents($g_path);
  13534.                 //            $r=base64_encode($img_file);
  13535.                 $row 1;
  13536.                 $csv_data = [];
  13537.                 if (($handle fopen($g_path"r")) !== FALSE) {
  13538.                     while (($data fgetcsv($handle1000",")) !== FALSE) {
  13539.                         $num count($data);
  13540.                         $csv_data[$row] = $data;
  13541.                         //                    echo "<p> $num fields in line $row: <br /></p>\n";
  13542.                         $row++;
  13543.                         //                    for ($c=0; $c < $num; $c++) {
  13544.                         //                        echo $data[$c] . "<br />\n";
  13545.                         //                    }
  13546.                     }
  13547.                     fclose($handle);
  13548.                 }
  13549.                 //now getting the relevant checks
  13550.                 $check_list = [];
  13551.                 $em $this->getDoctrine()->getManager();
  13552.                 foreach ($csv_data as $ind => $data_row) {
  13553.                     if ($ind == 1)
  13554.                         continue;
  13555.                     $np = new ProductByCode();
  13556.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  13557.                     $np->setProductId($data_row[1]);
  13558.                     $np->setLcNumber($data_row[0]);
  13559.                     $np->setCartonNumber($data_row[2]);
  13560.                     $np->setSerialNo($data_row[3]);
  13561.                     $np->setSerialAssigned(0);
  13562.                     $np->setImei1($data_row[4]);
  13563.                     $np->setImei2($data_row[5]);
  13564.                     $np->setImei3($data_row[6]);
  13565.                     $np->setImei4($data_row[7]);
  13566.                     $np->setBtMac($data_row[8]);
  13567.                     $np->setWlanMac($data_row[9]);
  13568.                     $np->setWarehouseId(0);
  13569.                     $np->setWarehouseActionId(0);
  13570.                     $np->setPosition(0);//in inventory
  13571.                     $np->setPurchaseOrderId(0);
  13572.                     $np->setGrnId(0);
  13573.                     $np->setStage(0);
  13574.                     $np->setSalesCodeRange(json_encode([$data_row[3]]));
  13575. //                $np->setSalesCode($data_row[3]);
  13576.                     $np->setSalesCode($data_row[4]); //IMEI
  13577.                     $np->setSalesCodeSer(0);
  13578.                     $np->setSalesCodeDmy('');
  13579.                     $np->setPurchaseCodeRange("");
  13580.                     $np->setPurchaseReceiptDate(null);
  13581.                     $np->setLastInDate(null);
  13582.                     $np->setStatus(GeneralConstant::ACTIVE);
  13583.                     $np->setTransactionHistory(json_encode([
  13584.                         ]
  13585.                     ));
  13586.                     $np->setPurchaseWarrantyLastDate(null);
  13587.                     $em->persist($np);
  13588.                     $em->flush();
  13589.                 }
  13590.                 return new JsonResponse(array(
  13591.                     "success" => true,
  13592.                     "lastIndex" => $lastIndex,
  13593.                     "file_path" => $file_path,
  13594.                     "csv_data" => $csv_data,
  13595.                     //                "debug_data"=>System::encryptSignature($r)
  13596.                 ));
  13597.             }
  13598.         }
  13599.         return new JsonResponse(array(
  13600.             "success" => false,
  13601.             "file_path" => '',
  13602.             "csv_data" => [],
  13603.             "lastIndex" => $lastIndex,
  13604.         ));
  13605.     }
  13606.     public
  13607.     function ProductByCodeListAction(Request $request)
  13608.     {
  13609.         $em $this->getDoctrine()->getManager();
  13610.         $companyId $this->getLoggedUserCompanyId($request);
  13611.         $listData Inventory::GetProductListForProductByCodeListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  13612.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  13613.             if ($request->query->has('dataTableQry')) {
  13614.                 return new JsonResponse(
  13615.                     $listData
  13616.                 );
  13617.             }
  13618.         }
  13619.         $q = [];
  13620. //        $q = $this->getDoctrine()
  13621. //            ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  13622. //            ->findBy(
  13623. //                array(
  13624. //                    'status' => GeneralConstant::ACTIVE,
  13625. ////                    'approved' =>  GeneralConstant::APPROVED,
  13626. //                )
  13627. //
  13628. //            );
  13629.         //temp start
  13630. //        foreach($q as $np) {
  13631. //            if($np->getPosition()==1) {   /// only starting ones or in warehouse ones
  13632. //                $temp_obj = json_decode($np->getTransactionHistory());
  13633. //                if ($temp_obj != null) {
  13634. //                    $transHistory = [];
  13635. //                    $transHistory[] = $temp_obj;
  13636. //                    $np->setTransactionHistory(json_encode($transHistory));
  13637. //                }
  13638. //            }
  13639. //            $em->flush();
  13640. //        }
  13641.         ///temp end
  13642.         $stage_list = array(
  13643.             => 'Pending',
  13644.             => 'Pending',
  13645.             => 'Complete',
  13646.             => 'Partial',
  13647.         );
  13648.         $data = [];
  13649. //        foreach($q as $entry)
  13650. //        {
  13651. //            $data[]=array(
  13652. //                'doc_date'=>$entry->getStockRequisitionDate(),
  13653. //                'id'=>$entry->getStockRequisitionId(),
  13654. //                'doc_hash'=>$entry->getDocumentHash(),
  13655. //                'approval_status'=>GeneralConstant::$approvalStatus[$entry->getApproved()],
  13656. //                'stage'=>$stage_list[$entry->getStage()]
  13657. //
  13658. //            );
  13659. //        }
  13660.         return $this->render('@Inventory/pages/views/product_by_code_list.html.twig',
  13661.             array(
  13662.                 'page_title' => 'Product List',
  13663.                 'data' => $q,
  13664. //                'listData' => $listData,
  13665.                 'products' => Inventory::ProductList($em),
  13666.                 'warehouseList' => Inventory::WarehouseList($em)
  13667.             )
  13668.         );
  13669.     }
  13670. //SR
  13671.     public
  13672.     function SrListAction(Request $request)
  13673.     {
  13674.         $q $this->getDoctrine()
  13675.             ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  13676.             ->findBy(
  13677.                 array(
  13678.                     'status' => GeneralConstant::ACTIVE,
  13679. //                    'approved' =>  GeneralConstant::APPROVED,
  13680.                 )
  13681.                 ,
  13682.                 array(
  13683.                     'stockRequisitionDate' => 'DESC'
  13684.                 )
  13685.             );
  13686.         $stage_list = array(
  13687.             => 'Pending',
  13688.             => 'Pending',
  13689.             => 'Complete',
  13690.             => 'Partial',
  13691.         );
  13692.         $data = [];
  13693.         foreach ($q as $entry) {
  13694.             $data[] = array(
  13695.                 'doc_date' => $entry->getStockRequisitionDate(),
  13696.                 'id' => $entry->getStockRequisitionId(),
  13697.                 'doc_hash' => $entry->getDocumentHash(),
  13698.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13699.                 'stage' => GeneralConstant::stageLabel($stage_list$entry->getStage()),
  13700.                 'indentTagged' => $entry->getIndentTagged(),
  13701.                 'srIds' => $entry->getSrIds(),
  13702.                 'irIds' => $entry->getIrIds(),
  13703.                 'prIds' => $entry->getPrIds(),
  13704.                 'poIds' => $entry->getPoIds(),
  13705.             );
  13706.         }
  13707.         return $this->render('@Inventory/pages/views/sr_list.html.twig',
  13708.             array(
  13709.                 'page_title' => 'Stock Requisition List',
  13710.                 'data' => $data
  13711.             )
  13712.         );
  13713.     }
  13714.     public
  13715.     function ViewSrAction(Request $request$id)
  13716.     {
  13717.         $em $this->getDoctrine()->getManager();
  13718.         $dt Inventory::GetSrDetails($em$id);
  13719.         return $this->render(
  13720.             '@Inventory/pages/views/view_stock_requisition.html.twig',
  13721.             array(
  13722.                 'page_title' => 'Stock requisition',
  13723.                 'data' => $dt,
  13724.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13725.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13726.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13727.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13728.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13729.                     $id,
  13730.                     $dt['created_by'],
  13731.                     $dt['edited_by'])
  13732.             )
  13733.         );
  13734.     }
  13735.     public
  13736.     function PrintSrAction(Request $request$id)
  13737.     {
  13738.         $em $this->getDoctrine()->getManager();
  13739.         $dt Inventory::GetSrDetails($em$id);
  13740.         $company_data Company::getCompanyData($em1);
  13741.         $document_mark = array(
  13742.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13743.             'copy' => ''
  13744.         );
  13745.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13746.             $html $this->renderView('@Inventory/pages/print/print_sr.html.twig',
  13747.                 array(
  13748.                     //full array here
  13749.                     'pdf' => true,
  13750.                     'page_title' => 'Stock Requisition',
  13751.                     'export' => 'pdf,print',
  13752.                     'data' => $dt,
  13753.                     'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13754.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13755.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13756.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13757.                         array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13758.                         $id,
  13759.                         $dt['created_by'],
  13760.                         $dt['edited_by']),
  13761.                     'document_mark_image' => $document_mark['original'],
  13762.                     'company_name' => $company_data->getName(),
  13763.                     'company_data' => $company_data,
  13764.                     'company_address' => $company_data->getAddress(),
  13765.                     'company_image' => $company_data->getImage(),
  13766.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13767.                     'red' => 0
  13768.                 )
  13769.             );
  13770.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13771.                 //     'orientation' => 'landscape',
  13772.                 //     'enable-javascript' => true,
  13773.                 //     'javascript-delay' => 1000,
  13774.                 'no-stop-slow-scripts' => false,
  13775.                 'no-background' => false,
  13776.                 'lowquality' => false,
  13777.                 'encoding' => 'utf-8',
  13778.                 //    'images' => true,
  13779.                 //    'cookie' => array(),
  13780.                 'dpi' => 300,
  13781.                 'image-dpi' => 300,
  13782.                 //    'enable-external-links' => true,
  13783.                 //    'enable-internal-links' => true
  13784.             ));
  13785.             return new Response(
  13786.                 $pdf_response,
  13787.                 200,
  13788.                 array(
  13789.                     'Content-Type' => 'application/pdf',
  13790.                     'Content-Disposition' => 'attachment; filename="stock_requisition_' $id '.pdf"'
  13791.                 )
  13792.             );
  13793.         }
  13794.         return $this->render('@Inventory/pages/print/print_sr.html.twig',
  13795.             array(
  13796.                 'page_title' => 'Stock Requisition',
  13797.                 'export' => 'pdf,print',
  13798.                 'data' => $dt,
  13799.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13800.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13801.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13802.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13803.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13804.                     $id,
  13805.                     $dt['created_by'],
  13806.                     $dt['edited_by']),
  13807.                 'document_mark_image' => $document_mark['original'],
  13808.                 'company_name' => $company_data->getName(),
  13809.                 'company_data' => $company_data,
  13810.                 'company_address' => $company_data->getAddress(),
  13811.                 'company_image' => $company_data->getImage(),
  13812.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13813.                 'red' => 0
  13814.             )
  13815.         );
  13816.     }
  13817. //IR
  13818.     public
  13819.     function IrListAction(Request $request)
  13820.     {
  13821.         $q $this->getDoctrine()
  13822.             ->getRepository('ApplicationBundle\\Entity\\StoreRequisition')
  13823.             ->findBy(
  13824.                 array(
  13825.                     'status' => GeneralConstant::ACTIVE,
  13826. //                    'approved' =>  GeneralConstant::APPROVED,
  13827.                 ),
  13828.                 array(
  13829.                     'storeRequisitionDate' => 'DESC'
  13830.                 )
  13831.             );
  13832.         $stage_list = array(
  13833.             => 'Pending',
  13834.             => 'Pending',
  13835.             => 'Complete',
  13836.             => 'Partial',
  13837.         );
  13838.         $data = [];
  13839.         foreach ($q as $entry) {
  13840.             $data[] = array(
  13841.                 'doc_date' => $entry->getStoreRequisitionDate(),
  13842.                 'id' => $entry->getStoreRequisitionId(),
  13843.                 'doc_hash' => $entry->getDocumentHash(),
  13844.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13845.                 'stage' => GeneralConstant::stageLabel($stage_list$entry->getStage()),
  13846.                 'prTagged' => $entry->getIndentTagged(),
  13847.                 'srIds' => $entry->getSrIds(),
  13848.                 'irIds' => $entry->getIrIds(),
  13849.                 'prIds' => $entry->getPrIds(),
  13850.                 'poIds' => $entry->getPoIds(),
  13851.             );
  13852.         }
  13853.         return $this->render('@Inventory/pages/views/ir_list.html.twig',
  13854.             array(
  13855.                 'page_title' => 'Indent Requisition List',
  13856.                 'data' => $data
  13857.             )
  13858.         );
  13859.     }
  13860.     public
  13861.     function ViewIrAction(Request $request$id)
  13862.     {
  13863.         $em $this->getDoctrine()->getManager();
  13864.         $dt Inventory::GetIrDetails($em$id);
  13865.         return $this->render(
  13866.             '@Inventory/pages/views/view_indent_requisition.html.twig',
  13867.             array(
  13868.                 'page_title' => 'Indent',
  13869.                 'data' => $dt,
  13870.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13871.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13872.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13873.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13874.                     $id,
  13875.                     $dt['created_by'],
  13876.                     $dt['edited_by'])
  13877.             )
  13878.         );
  13879.     }
  13880.     public
  13881.     function PrintIrAction(Request $request$id)
  13882.     {
  13883.         $em $this->getDoctrine()->getManager();
  13884.         $dt Inventory::GetIrDetails($em$id);
  13885.         $company_data Company::getCompanyData($em1);
  13886.         $document_mark = array(
  13887.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13888.             'copy' => ''
  13889.         );
  13890.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13891.             $html $this->renderView('@Inventory/pages/print/print_ir.html.twig',
  13892.                 array(
  13893.                     //full array here
  13894.                     'pdf' => true,
  13895.                     'page_title' => 'Indent Requisition',
  13896.                     'export' => 'pdf,print',
  13897.                     'data' => $dt,
  13898.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13899.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13900.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13901.                         array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13902.                         $id,
  13903.                         $dt['created_by'],
  13904.                         $dt['edited_by']),
  13905.                     'document_mark_image' => $document_mark['original'],
  13906.                     'company_name' => $company_data->getName(),
  13907.                     'company_data' => $company_data,
  13908.                     'company_address' => $company_data->getAddress(),
  13909.                     'company_image' => $company_data->getImage(),
  13910.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13911.                     'red' => 0
  13912.                 )
  13913.             );
  13914.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13915. //                'orientation' => 'landscape',
  13916. //                'enable-javascript' => true,
  13917. //                'javascript-delay' => 1000,
  13918.                 'no-stop-slow-scripts' => false,
  13919.                 'no-background' => false,
  13920.                 'lowquality' => false,
  13921.                 'encoding' => 'utf-8',
  13922. //            'images' => true,
  13923. //            'cookie' => array(),
  13924.                 'dpi' => 300,
  13925.                 'image-dpi' => 300,
  13926. //                'enable-external-links' => true,
  13927. //                'enable-internal-links' => true
  13928.             ));
  13929.             return new Response(
  13930.                 $pdf_response,
  13931.                 200,
  13932.                 array(
  13933.                     'Content-Type' => 'application/pdf',
  13934.                     'Content-Disposition' => 'attachment; filename="indent_' $id '.pdf"'
  13935.                 )
  13936.             );
  13937.         }
  13938.         return $this->render('@Inventory/pages/print/print_ir.html.twig',
  13939.             array(
  13940.                 'page_title' => 'Indent Requisition',
  13941.                 'export' => 'pdf,print',
  13942.                 'data' => $dt,
  13943.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13944.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13945.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13946.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13947.                     $id,
  13948.                     $dt['created_by'],
  13949.                     $dt['edited_by']),
  13950.                 'document_mark_image' => $document_mark['original'],
  13951.                 'company_name' => $company_data->getName(),
  13952.                 'company_data' => $company_data,
  13953.                 'company_address' => $company_data->getAddress(),
  13954.                 'company_image' => $company_data->getImage(),
  13955.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13956.                 'red' => 0
  13957.             )
  13958.         );
  13959.     }
  13960. //PR
  13961.     public
  13962.     function PrListAction(Request $request)
  13963.     {
  13964.         $q $this->getDoctrine()
  13965.             ->getRepository('ApplicationBundle\\Entity\\PurchaseRequisition')
  13966.             ->findBy(
  13967.                 array(
  13968.                     'status' => GeneralConstant::ACTIVE,
  13969. //                    'approved' =>  GeneralConstant::APPROVED,
  13970.                 ),
  13971.                 array(
  13972.                     'purchaseRequisitionDate' => 'DESC'
  13973.                 )
  13974.             );
  13975.         $stage_list = array(
  13976.             => 'Pending',
  13977.             => 'Pending',
  13978.             => 'Complete',
  13979.             => 'Partial',
  13980.         );
  13981.         $data = [];
  13982.         foreach ($q as $entry) {
  13983.             $data[] = array(
  13984.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  13985.                 'id' => $entry->getPurchaseRequisitionId(),
  13986.                 'doc_hash' => $entry->getDocumentHash(),
  13987.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13988.                 'acquisition_status' => $entry->getAcquisitionStatus(),
  13989.                 'acquisition_start_date' => $entry->getAcquisitionStartDate(),
  13990.                 'acquisition_end_date' => $entry->getAcquisitionEndDate(),
  13991.                 'acquisition_method' => $entry->getquotationAcquisitionMethod(),
  13992.                 'poTagged' => $entry->getPoTagged(),
  13993.                 'typeHash' => $entry->getTypehash(),
  13994.                 'srIds' => $entry->getSrIds(),
  13995.                 'irIds' => $entry->getIrIds(),
  13996.                 'prIds' => $entry->getPrIds(),
  13997.                 'poIds' => $entry->getPoIds(),
  13998.             );
  13999.         }
  14000.         return $this->render('@Inventory/pages/views/pr_list.html.twig',
  14001.             array(
  14002.                 'page_title' => 'Purchase Requisition List',
  14003.                 'data' => $data
  14004.             )
  14005.         );
  14006.     }
  14007.     public
  14008.     function ServiceRequisitionListAction(Request $request)
  14009.     {
  14010.         $q $this->getDoctrine()
  14011.             ->getRepository('ApplicationBundle\\Entity\\PurchaseRequisition')
  14012.             ->findBy(
  14013.                 array(
  14014.                     'status' => GeneralConstant::ACTIVE,
  14015. //                    'approved' =>  GeneralConstant::APPROVED,
  14016.                 ),
  14017.                 array(
  14018.                     'purchaseRequisitionDate' => 'DESC'
  14019.                 )
  14020.             );
  14021.         $stage_list = array(
  14022.             => 'Pending',
  14023.             => 'Pending',
  14024.             => 'Complete',
  14025.             => 'Partial',
  14026.         );
  14027.         $data = [];
  14028.         foreach ($q as $entry) {
  14029.             $data[] = array(
  14030.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  14031.                 'id' => $entry->getPurchaseRequisitionId(),
  14032.                 'doc_hash' => $entry->getDocumentHash(),
  14033.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  14034.                 'poTagged' => $entry->getPoTagged(),
  14035.                 'typeHash' => $entry->getTypehash(),
  14036.                 'srIds' => $entry->getSrIds(),
  14037.                 'irIds' => $entry->getIrIds(),
  14038.                 'prIds' => $entry->getPrIds(),
  14039.                 'poIds' => $entry->getPoIds(),
  14040.             );
  14041.         }
  14042.         return $this->render('@Inventory/pages/views/service_requisition_list.html.twig',
  14043.             array(
  14044.                 'page_title' => 'Service Requisition List',
  14045.                 'data' => $data
  14046.             )
  14047.         );
  14048.     }
  14049.     public
  14050.     function ViewPrAction(Request $request$id)
  14051.     {
  14052.         $em $this->getDoctrine()->getManager();
  14053.         $dt Inventory::GetPrDetails($em$id);
  14054.         $companyId $this->getLoggedUserCompanyId($request);
  14055.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  14056.             array(
  14057.                 'page_title' => 'Purchase Requisition',
  14058.                 'data' => $dt,
  14059.                 'branchList' => Client::BranchList($em$companyId),
  14060.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  14061.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14062.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14063.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14064.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14065.                     $id,
  14066.                     $dt['created_by'],
  14067.                     $dt['edited_by'])
  14068.             )
  14069.         );
  14070.     }
  14071.     public
  14072.     function ViewServiceRequisitionAction(Request $request$id)
  14073.     {
  14074.         $em $this->getDoctrine()->getManager();
  14075.         $dt Inventory::GetPrDetails($em$id);
  14076.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  14077.             array(
  14078.                 'page_title' => 'Service Requisition',
  14079.                 'data' => $dt,
  14080.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14081.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14082.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14083.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14084.                     $id,
  14085.                     $dt['created_by'],
  14086.                     $dt['edited_by'])
  14087.             )
  14088.         );
  14089.     }
  14090.     public
  14091.     function PrintPrAction(Request $request$id)
  14092.     {
  14093.         $em $this->getDoctrine()->getManager();
  14094.         $dt Inventory::GetPrDetails($em$id);
  14095.         $companyId $this->getLoggedUserCompanyId($request);
  14096.         $company_data Company::getCompanyData($em$companyId);
  14097.         $document_mark = array(
  14098.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  14099.             'copy' => ''
  14100.         );
  14101.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  14102.             $html $this->renderView('@Inventory/pages/print/print_pr.html.twig',
  14103.                 array(
  14104.                     //full array here
  14105.                     'pdf' => true,
  14106.                     'page_title' => 'Purchase Requisition',
  14107.                     'export' => 'pdf,print',
  14108.                     'data' => $dt,
  14109.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14110.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14111.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14112.                         array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14113.                         $id,
  14114.                         $dt['created_by'],
  14115.                         $dt['edited_by']),
  14116.                     'document_mark_image' => $document_mark['original'],
  14117.                     'branchList' => Client::BranchList($em$companyId),
  14118.                     'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  14119.                     'company_name' => $company_data->getName(),
  14120.                     'company_data' => $company_data,
  14121.                     'company_address' => $company_data->getAddress(),
  14122.                     'company_image' => $company_data->getImage(),
  14123.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  14124.                     'red' => 0
  14125.                 )
  14126.             );
  14127.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  14128. //                'orientation' => 'landscape',
  14129. //                'enable-javascript' => true,
  14130. //                'javascript-delay' => 1000,
  14131.                 'no-stop-slow-scripts' => false,
  14132.                 'no-background' => false,
  14133.                 'lowquality' => false,
  14134.                 'encoding' => 'utf-8',
  14135. //            'images' => true,
  14136. //            'cookie' => array(),
  14137.                 'dpi' => 300,
  14138.                 'image-dpi' => 300,
  14139. //                'enable-external-links' => true,
  14140. //                'enable-internal-links' => true
  14141.             ));
  14142.             return new Response(
  14143.                 $pdf_response,
  14144.                 200,
  14145.                 array(
  14146.                     'Content-Type' => 'application/pdf',
  14147.                     'Content-Disposition' => 'attachment; filename="purchase_requisition_' $id '.pdf"'
  14148.                 )
  14149.             );
  14150.         }
  14151.         return $this->render('@Inventory/pages/print/print_pr.html.twig',
  14152.             array(
  14153.                 'page_title' => 'Purchase Requisition',
  14154.                 'export' => 'pdf,print',
  14155.                 'data' => $dt,
  14156.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14157.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14158.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14159.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14160.                     $id,
  14161.                     $dt['created_by'],
  14162.                     $dt['edited_by']),
  14163.                 'document_mark_image' => $document_mark['original'],
  14164.                 'company_name' => $company_data->getName(),
  14165.                 'company_data' => $company_data,
  14166.                 'branchList' => Client::BranchList($em$companyId),
  14167.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  14168.                 'company_address' => $company_data->getAddress(),
  14169.                 'company_image' => $company_data->getImage(),
  14170.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  14171.                 'red' => 0
  14172.             )
  14173.         );
  14174.     }
  14175.     public
  14176.     function CreateSecondaryDeliveryReceiptAction(Request $request)
  14177.     {
  14178.         $em $this->getDoctrine()->getManager();
  14179.         $companyId $this->getLoggedUserCompanyId($request);
  14180.         $userBranchIdList $request->getSession()->get('branchIdList');
  14181.         if ($userBranchIdList == null$userBranchIdList = [];
  14182.         $userBranchId $request->getSession()->get('branchId');
  14183.         if ($request->isMethod('POST')) {
  14184.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  14185.             $dochash $request->request->get('docHash'); //change
  14186.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14187.             $approveRole 1;  //created
  14188.             $approveHash $request->request->get('approvalHash');
  14189.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  14190.                 $loginId$approveRole$approveHash)
  14191.             ) {
  14192.                 $this->addFlash(
  14193.                     'error',
  14194.                     'Sorry Couldnot insert Data.'
  14195.                 );
  14196.             } else {
  14197.                 $receiptId SalesOrderM::CreateNewSecondaryDeliveryReceipt($this->getDoctrine()->getManager(), $request->request,
  14198.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  14199.                     $this->getLoggedUserCompanyId($request));
  14200.                 //now add Approval info
  14201.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14202.                 $approveRole 1;  //created
  14203.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  14204.                     $receiptId,
  14205.                     $loginId,
  14206.                     $approveRole,
  14207.                     $request->request->get('approvalHash'));
  14208.                 $options = array(
  14209.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  14210.                     'notification_server' => $this->container->getParameter('notification_server'),
  14211.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  14212.                     'url' => $this->generateUrl(
  14213.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  14214.                         ['entity_view_route_path_name']
  14215.                     )
  14216.                 );
  14217.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  14218.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  14219.                     $receiptId,
  14220.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  14221.                 );
  14222.                 $this->addFlash(
  14223.                     'success',
  14224.                     'New Delivery Receipt Created'
  14225.                 );
  14226.                 $url $this->generateUrl(
  14227.                     'view_delivery_receipt'
  14228.                 );
  14229.                 return $this->redirect($url "/" $receiptId);
  14230.             }
  14231.         }
  14232.         $debugData = [];
  14233. //        $dr_data=$em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findOneBy(
  14234. //            array(
  14235. //                'deliveryReceiptId'=>$dr_id
  14236. //            )
  14237. //        );
  14238.         $new_swld = new \DateTime('2017-07-09');
  14239. //        if ($entry->getWarranty() > 0)
  14240. //            $new_swld->modify('+' . $entry->getWarranty() . ' month');
  14241.         $debugData[] = $new_swld->format('Y-m-d');
  14242.         $debugData[] = $new_swld;
  14243. //        $debugData[]=$dr_data->getDeliveryReceiptDate();
  14244.         $debugData[] = '+' '1' ' month';
  14245.         $branchList Client::BranchList($em$companyId, [], $userBranchIdList);
  14246.         $warehouseIds = [];
  14247.         foreach ($branchList as $br) {
  14248.             $warehouseIds[] = $br['warehouseId'];
  14249.         }
  14250.         return $this->render('@Inventory/pages/input_forms/secondaryDeliveryReceipt.html.twig',
  14251.             array(
  14252.                 'page_title' => 'New Delivery Receipt',
  14253.                 'ExistingClients' => Accounts::getClientLedgerHeads($em),
  14254.                 'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($em),
  14255.                 'ClientList' => SalesOrderM::GetSecondaryClientList($em),
  14256.                 'warehouse' => Inventory::WarehouseList($em$companyId$warehouseIds),
  14257.                 'salesOrders' => SalesOrderM::SecondarySalesOrderListPendingDelivery($em$warehouseIds),
  14258.                 'salesOrdersArray' => SalesOrderM::SecondarySalesOrderListPendingDeliveryArray($em$warehouseIds),
  14259.                 'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
  14260.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
  14261.                 'debugData' => $debugData,
  14262.             )
  14263.         );
  14264.     }
  14265.     public function AddUnitTypeAction(Request $request$id 0)
  14266.     {
  14267.         $em $this->getDoctrine()->getManager();
  14268.         $unitType $id != $em->getRepository(UnitType::class)->find($id) : null;
  14269.         if ($request->isMethod('POST')) {
  14270.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14271.             Inventory::CreateUnitType($em$id$request->request$loginId);
  14272.             $this->addFlash(
  14273.                 'success',
  14274.                 $id != 'Unit Type Updated' 'Unit Type Added'
  14275.             );
  14276.             $unitType $id != $em->getRepository(UnitType::class)->find($id) : null;
  14277.         }
  14278.         $unitTypeDetails $em->getRepository(UnitType::class)->findBy(array(), array('name' => 'ASC'));
  14279.         $existingConversionMap = [];
  14280.         if ($unitType && $unitType->getConversion() != '') {
  14281.             $existingConversionMap json_decode($unitType->getConversion(), true);
  14282.             if ($existingConversionMap == null) {
  14283.                 $existingConversionMap = [];
  14284.             }
  14285.         }
  14286.         return $this->render('@Inventory/pages/input_forms/addUnitType.html.twig',
  14287.             array(
  14288.                 'page_title' => $id != 'Edit Unit Type' 'Add Unit Type',
  14289.                 'ex_id' => $id,
  14290.                 'ex_det' => $unitType,
  14291.                 'existingConversionMap' => $existingConversionMap,
  14292.                 'unitTypeDetails' => $unitTypeDetails,
  14293.                 'unitTypeRecords' => $unitTypeDetails
  14294.             )
  14295.         );
  14296.     }
  14297.     public function AddCurrencyAction(Request $request$id 0)
  14298.     {
  14299.         $em $this->getDoctrine()->getManager();
  14300.         $currency $id != $em->getRepository(Currencies::class)->find($id) : null;
  14301.         if ($request->isMethod('POST')) {
  14302.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14303.             Inventory::CreateCurrency($em$id$request->request$loginId);
  14304.             $this->addFlash(
  14305.                 'success',
  14306.                 $id != 'Currency Updated' 'Currency Added'
  14307.             );
  14308.             $currency $id != $em->getRepository(Currencies::class)->find($id) : null;
  14309.         }
  14310.         $currencyDetails $em->getRepository(Currencies::class)->findBy(array(), array('code' => 'ASC'));
  14311.         $existingConversionMap = [];
  14312.         if ($currency && $currency->getConversionData() != '') {
  14313.             $existingConversionMap json_decode($currency->getConversionData(), true);
  14314.             if ($existingConversionMap == null) {
  14315.                 $existingConversionMap = [];
  14316.             }
  14317.         }
  14318.         return $this->render('@Inventory/pages/input_forms/addCurrency.html.twig',
  14319.             array(
  14320.                 'page_title' => $id != 'Edit Currency' 'Add Currency',
  14321.                 'ex_id' => $id,
  14322.                 'ex_det' => $currency,
  14323.                 'existingConversionMap' => $existingConversionMap,
  14324.                 'currencyDetails' => $currencyDetails,
  14325.                 'currencyRecords' => $currencyDetails
  14326.             )
  14327.         );
  14328.     }
  14329.     public
  14330.     function SubcategoryListAction()
  14331.     {
  14332.         return $this->render('@Inventory/pages/input_forms/subCategoryList.html.twig',
  14333.             array(
  14334.                 'page_title' => 'Sub Category List',
  14335.             )
  14336.         );
  14337.     }
  14338. //    public function getInventoryProductList(Request $request)
  14339. //    {
  14340. //        $em = $this->getDoctrine()->getManager();
  14341. //
  14342. //        $page = (int) $request->query->get('page', 1);     // Default page = 1
  14343. //        $limit = (int) $request->query->get('limit', 10);   // Default limit = 10
  14344. //        $offset = ($page - 1) * $limit;
  14345. //
  14346. //        // First, get the total count of products
  14347. //        $totalQuery = $em->createQueryBuilder()
  14348. //            ->select('COUNT(i.id)')
  14349. //            ->from('ApplicationBundle:InventoryStorage', 'i')
  14350. //            ->where('i.qty > :minQty')
  14351. //            ->setParameter('minQty', 0)
  14352. //            ->getQuery();
  14353. //
  14354. //        $totalRecords = (int) $totalQuery->getSingleScalarResult();
  14355. //        $totalPages = $limit > 0 ? (int) ceil($totalRecords / $limit) : 1;
  14356. //
  14357. //        // Then, get the paginated data
  14358. //        $qb = $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->createQueryBuilder('i')
  14359. //            ->select([
  14360. //                'i.productId AS productId',
  14361. //                'COALESCE(ig.name, \'\') AS itemGroupName',
  14362. //                'COALESCE(w.name, \'\') AS wareHouseName',
  14363. //                'i.qty AS quantity',
  14364. //                'COALESCE(b.name, \'\') AS brandName',
  14365. //                'COALESCE(u.name, \'\') AS UnitName',
  14366. //                'COALESCE(c.name, \'\') AS color',
  14367. //                'COALESCE(s.name, \'\') AS size',
  14368. //                'COALESCE(i.salesPrice, 0) AS salesPrice',
  14369. //                'COALESCE(p.name, \'\') AS productName'
  14370. //            ])
  14371. //            ->leftJoin('ApplicationBundle:InvProducts', 'p', 'WITH', 'i.productId = p.id')
  14372. //            ->leftJoin('ApplicationBundle:InvItemGroup', 'ig', 'WITH', 'i.igId = ig.id')
  14373. //            ->leftJoin('ApplicationBundle:Warehouse', 'w', 'WITH', 'i.warehouseId = w.id')
  14374. //            ->leftJoin('ApplicationBundle:BrandCompany', 'b', 'WITH', 'i.brandId = b.id')
  14375. //            ->leftJoin('ApplicationBundle:UnitType', 'u', 'WITH', 'i.unitTypeId = u.id')
  14376. //            ->leftJoin('ApplicationBundle:Colors', 'c', 'WITH', 'i.color = c.id')
  14377. //            ->leftJoin('ApplicationBundle:ProductSizes', 's', 'WITH', 'i.size = s.id')
  14378. //            ->where('i.qty > :minQty')
  14379. //            ->setParameter('minQty', 0)
  14380. //            ->setFirstResult($offset)
  14381. //            ->setMaxResults($limit);
  14382. //
  14383. //        $inventoryData = $qb->getQuery()->getResult();
  14384. //
  14385. //        return $this->json([
  14386. //            'page' => $page,
  14387. //            'limit' => $limit,
  14388. //            'totalRecords' => $totalRecords,
  14389. //            'totalPages' => $totalPages,
  14390. //            'data' => $inventoryData,
  14391. //        ]);
  14392. //    }
  14393.     /**
  14394.      * SW3 â€” the caller's product law for a picker, or '' when nothing should be filtered.
  14395.      * One resolver, both endpoints; FAILS OPEN on any error (a picker that silently empties
  14396.      * is worse than an unfiltered one).
  14397.      */
  14398.     private function wsProductClause(Request $request$idExpr)
  14399.     {
  14400.         try {
  14401.             $svc = new \ApplicationBundle\Modules\SalesWorkspace\Service\WorkspaceAdminService($this->getDoctrine()->getManager());
  14402.             $uid = (int) $this->getLoggedUserLoginId($request);
  14403.             $allowed $svc->allowedIdsFor($uid$svc->isAdminUser($uid));
  14404.             return \ApplicationBundle\Modules\SalesWorkspace\Support\WorkspaceScope::productDqlPredicate($idExpr$allowed);
  14405.         } catch (\Throwable $e) {
  14406.             return '';
  14407.         }
  14408.     }
  14409.     public function getInventoryProductList(Request $request)
  14410.     {
  14411.         $em $this->getDoctrine()->getManager();
  14412.         $page = (int)$request->query->get('page'1);
  14413.         $limit = (int)$request->query->get('limit'10);
  14414.         $offset = ($page 1) * $limit;
  14415.         $totalQuery $em->createQueryBuilder()
  14416.             ->select('COUNT(i.id)')
  14417.             ->from('ApplicationBundle:InventoryStorage''i')
  14418.             ->where('i.qty > :minQty')
  14419.             ->setParameter('minQty'0)
  14420.             ->getQuery();
  14421.         $totalRecords = (int)$totalQuery->getSingleScalarResult();
  14422.         $totalPages $limit ? (int)ceil($totalRecords $limit) : 1;
  14423.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14424.         $qb $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->createQueryBuilder('i')
  14425.             ->select([
  14426.                 'i.productId AS productId',
  14427.                 'COALESCE(ig.name, \'\') AS itemGroupName',
  14428.                 'COALESCE(w.name, \'\') AS wareHouseName',
  14429.                 'COALESCE(wa.name, \'\') AS subWareHouseName',
  14430.                 'i.qty AS quantity',
  14431.                 'i.qty AS lastSold',
  14432.                 'i.qty AS lastPurchase',
  14433.                 'COALESCE(b.name, \'\') AS brandName',
  14434.                 'COALESCE(u.name, \'\') AS UnitName',
  14435.                 'COALESCE(c.name, \'\') AS color',
  14436.                 'COALESCE(s.name, \'\') AS size',
  14437.                 'COALESCE(i.purchasePrice, 0) AS purchasePrice',
  14438.                 'COALESCE(i.salesPrice, 0) AS salesPrice',
  14439.                 'COALESCE(p.name, \'\') AS productName',
  14440.                 'COALESCE(p.productCode, \'\') AS productCode',
  14441.                 "CASE 
  14442.                 WHEN p.images IS NOT NULL AND p.images <> '' 
  14443.                 THEN p.images 
  14444.                 ELSE '$defaultImage
  14445.             END AS image"
  14446.             ])
  14447.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  14448.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''i.igId = ig.id')
  14449.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''i.warehouseId = w.id')
  14450.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''i.actionTagId = wa.id')
  14451.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''i.brandId = b.id')
  14452.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''i.unitTypeId = u.id')
  14453.             ->leftJoin('ApplicationBundle:Colors''c''WITH''i.color = c.id')
  14454.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''i.size = s.id')
  14455.             ->where('i.qty > :minQty')
  14456.             ->setParameter('minQty'0)
  14457.             ->setFirstResult($offset)
  14458.             ->setMaxResults($limit);
  14459.         // SW3: only this line's catalog (untagged products stay offerable everywhere).
  14460.         $wsProdClause $this->wsProductClause($request'i.productId');
  14461.         if ($wsProdClause !== '') { $qb->andWhere($wsProdClause); }
  14462.         $inventoryData $qb->getQuery()->getResult();
  14463.         return $this->json([
  14464.             'page' => $page,
  14465.             'limit' => $limit,
  14466.             'totalRecords' => $totalRecords,
  14467.             'totalPages' => $totalPages,
  14468.             'data' => $inventoryData,
  14469.         ]);
  14470.     }
  14471.     public function CreateStockTransferForAppAction(Request $request)
  14472.     {
  14473.         $em $this->getDoctrine()->getManager();
  14474.         $companyId $this->getLoggedUserCompanyId($request);
  14475.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  14476.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  14477.         if ($request->isMethod('POST')) {
  14478.             $em $this->getDoctrine()->getManager();
  14479.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  14480.             $dochash $request->request->get('docHash'); //change
  14481.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14482.             $approveRole $request->request->get('approvalRole');
  14483.             $approveHash $request->request->get('approvalHash');
  14484.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  14485.                 $loginId$approveRole$approveHash)
  14486.             ) {
  14487.                 $this->addFlash(
  14488.                     'error',
  14489.                     'Sorry Couldnot insert Data.'
  14490.                 );
  14491.             } else {
  14492.                 if ($request->request->has('check_allowed'))
  14493.                     $check_allowed 1;
  14494.                 $StID Inventory::CreateNewStockTransferForAPP(
  14495.                     $this->getDoctrine()->getManager(),
  14496.                     $request->request,
  14497.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  14498.                     $this->getLoggedUserCompanyId($request)
  14499.                 );
  14500.                 //now add Approval info
  14501.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14502.                 $approveRole 1;  //created
  14503.                 $options = array(
  14504.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  14505.                     'notification_server' => $this->container->getParameter('notification_server'),
  14506.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  14507.                     'url' => $this->generateUrl(
  14508.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  14509.                         ['entity_view_route_path_name']
  14510.                     )
  14511.                 );
  14512.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  14513.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  14514.                     $StID,
  14515.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  14516.                 );
  14517.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  14518.                     $loginId,
  14519.                     $approveRole,
  14520.                     $request->request->get('approvalHash'));
  14521.                 $this->addFlash(
  14522.                     'success',
  14523.                     'Stock Transfer Added.'
  14524.                 );
  14525.                 $url $this->generateUrl(
  14526.                     'view_st'
  14527.                 );
  14528. //                return $this->redirect($url . "/" . $StID);
  14529.                 return $this->json(['success' => true]);
  14530.             }
  14531.         }
  14532.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  14533.             array(
  14534.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  14535.             )
  14536.         );
  14537.         $INVLIST = [];
  14538.         foreach ($slotList as $slot) {
  14539.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  14540.         }
  14541.         return $this->json(['success' => true]);
  14542. //       return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  14543. //           array(
  14544. //         'page_title' => 'Stock Transfer Note',
  14545. //               'warehouseList' => Inventory::WarehouseList($em),
  14546. //        'warehouseListArray' => Inventory::WarehouseListArray($em),
  14547. //               'colorList' => Inventory::GetColorList($em),
  14548. //               'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  14549. //                'srList' => [],
  14550. //               'warehouseActionList' => $warehouse_action_list,
  14551. //                'warehouseActionListArray' => $warehouse_action_list_array,
  14552. //                'item_list' => Inventory::ItemGroupList($em),
  14553. //                'item_list_array' => Inventory::ItemGroupListArray($em),
  14554. //               'category_list_array' => Inventory::ProductCategoryListArray($em),
  14555. //              'product_list_array' => Inventory::ProductListDetailedArray($em),
  14556. ////               'product_list_array' => [],
  14557. //               'product_list' => Inventory::ProductList($em, $companyId),
  14558. ////                'product_list' => [],
  14559. //               'prefix_list' => array(
  14560. //                   [
  14561. //                       'id' => 1,
  14562. //                       'value' => 'GN',
  14563. //                        'text' => 'GN'
  14564. //
  14565. //                   ]
  14566. //              ),
  14567. //              'assoc_list' => array(
  14568. //                  [
  14569. //                       'id' => 1,
  14570. //                        'value' => 1,
  14571. //                        'text' => 'GN'
  14572. //
  14573. //                  ]
  14574. //               ),
  14575. //              'INVLIST' => $INVLIST
  14576. //           )
  14577. //      );
  14578.     }
  14579.     public function getWarehouseList(Request $request)
  14580.     {
  14581.         $em $this->getDoctrine()->getManager();
  14582.         $warehouses $em->getRepository('ApplicationBundle\\Entity\\Warehouse')
  14583.             ->createQueryBuilder('w')
  14584.             ->select('w.id''w.name')
  14585.             ->orderBy('w.name''ASC')
  14586.             ->getQuery()
  14587.             ->getResult();
  14588.         return $this->json($warehouses);
  14589.     }
  14590.     public function getSubWarehouseList(Request $request)
  14591.     {
  14592.         $em $this->getDoctrine()->getManager();
  14593.         $warehouses $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')
  14594.             ->createQueryBuilder('w')
  14595.             ->select('w.id''w.name')
  14596. //            ->orderBy('w.name', 'ASC')
  14597.             ->getQuery()
  14598.             ->getResult();
  14599.         return $this->json($warehouses);
  14600.     }
  14601.     public function getStockReceiveList(Request $request)
  14602.     {
  14603.         $list GeneralConstant::$stockReceiveType;
  14604.         return $this->json($list);
  14605.     }
  14606.     public function getOrderListByStockReceiveId(Request $request)
  14607.     {
  14608.         $em $this->getDoctrine()->getManager();
  14609.         $typeName $request->request->get('type');
  14610.         $typeId $request->request->get('id');
  14611.         $document null;
  14612.         if ($typeName == 'From Stock Transfer' || $typeId == 1) {
  14613.             $document $em->getRepository('ApplicationBundle\\Entity\\StockTransfer')->createQueryBuilder('s')->select('s.stockTransferId''s.documentHash')->where('s.approved !=1')->getQuery()->getResult();
  14614.         } else if ($typeName == 'For Stock In' || $typeId == 3) {
  14615.             $document $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->createQueryBuilder('a')->select('a.accountsHeadId''a.name')->getQuery()->getResult();
  14616.         } else if ($typeName == 'For Opening Entity' || $typeId == 4) {
  14617.             $document $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')
  14618.                 ->createQueryBuilder('w')
  14619.                 ->select('w.id''w.name')
  14620.                 ->getQuery()
  14621.                 ->getResult();
  14622.         }
  14623.         return $this->json($document);
  14624.     }
  14625.     public function GetProductFromInvStorage(Request $request)
  14626.     {
  14627.         $em $this->getDoctrine()->getManager();
  14628.         $searchTerm trim($request->get('name'));
  14629.         // Fetch all or filtered products. SW3: BOTH branches (search AND browse) run through
  14630.         // one builder so the business-line catalog clause covers them equally - a picker that
  14631.         // filters only when you type is a picker that leaks the moment you clear the box.
  14632.         $qbProducts $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->createQueryBuilder('p');
  14633.         if ($searchTerm) {
  14634.             $qbProducts->where('p.name LIKE :term')->setParameter('term''%' $searchTerm '%');
  14635.         }
  14636.         $wsSearchClause $this->wsProductClause($request'p.id');
  14637.         if ($wsSearchClause !== '') { $qbProducts->andWhere($wsSearchClause); }
  14638.         $products $qbProducts->getQuery()->getResult();
  14639.         $response = [];
  14640.         foreach ($products as $product) {
  14641.             // All InventoryStorage entries for the product
  14642.             $invStorageItems $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy([
  14643.                 'productId' => $product->getId()
  14644.             ]);
  14645.             $inventoryList = [];
  14646.             foreach ($invStorageItems as $item) {
  14647.                 $warehouse $em->getRepository('ApplicationBundle\\Entity\\Warehouse')->find($item->getWarehouseId());
  14648.                 $subWarehouse $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')->find($item->getActionTagId());
  14649.                 $inventoryList[] = [
  14650.                     'warehouse_id' => $item->getWarehouseId(),
  14651.                     'warehouse_name' => $warehouse $warehouse->getName() : '',
  14652.                     'sub_warehouse_id' => $item->getActionTagId(),
  14653.                     'sub_warehouse_name' => $subWarehouse $subWarehouse->getName() : '',
  14654.                     'quantity' => $item->getQty(),
  14655.                     'lastSold' => $item->getNonInvoicedQty(),
  14656.                     'lastPurchase' => $item->getPhysicalQty(),
  14657.                     'purchasePrice' => $item->getPurchasePrice(),
  14658.                     'salesPrice' => $item->getSalesPrice(),
  14659.                     'brandName' => $item->getBrandId(),
  14660.                     'unitName' => 'pcs'// Optional: Resolve via Unit table
  14661.                 ];
  14662.             }
  14663.             $response[] = [
  14664.                 'productId' => $product->getId(),
  14665.                 'itemGroupName' => $product->getIgId(),
  14666.                 'productName' => $product->getName(),
  14667.                 'productCode' => $product->getProductCode(),
  14668.                 'color' => $product->getColors(),
  14669.                 'size' => $product->getSizes(),
  14670.                 'image' => $product->getDefaultImage(),
  14671.                 'inventory' => $inventoryList
  14672.             ];
  14673.         }
  14674.         return new JsonResponse($response);
  14675.     }
  14676.     public function getProductByDocumentId(Request $request)
  14677.     {
  14678.         $em $this->getDoctrine()->getManager();
  14679.         $documentId $request->request->get('documentId');
  14680.         $accountsHeadId $request->request->get('accountsHeadId');
  14681.         if ($documentId) {
  14682.             $productIdRows $em->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  14683.                 ->createQueryBuilder('s')
  14684.                 ->select('s.productId')
  14685.                 ->where('s.stockTransferId = :documentId')
  14686.                 ->setParameter('documentId'$documentId)
  14687.                 ->getQuery()
  14688.                 ->getResult();
  14689.             $fromWarehouseRow $em->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  14690.                 ->createQueryBuilder('s')
  14691.                 ->select('s.warehouseId''s.toWarehouseId''s.warehouseActionId''s.toWarehouseActionId''s.qty''s.price')
  14692.                 ->where('s.stockTransferId = :documentId')
  14693.                 ->setParameter('documentId'$documentId)
  14694.                 ->setMaxResults(1)
  14695.                 ->getQuery()
  14696.                 ->getOneOrNullResult();
  14697.             $productIds array_map(function ($row) {
  14698.                 return $row['productId'];
  14699.             }, $productIdRows);
  14700.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findBy([
  14701.                 'id' => $productIds
  14702.             ]);
  14703.             $productData array_map(function ($p) {
  14704.                 return [
  14705.                     'id' => $p->getId(),
  14706.                     'name' => $p->getName(),
  14707.                     'modelNo' => $p->getModelNo(),
  14708.                     'sku' => $p->getSkuCode(),
  14709.                     'productCode' => $p->getProductCode(),
  14710.                     'purchasePrice' => $p->getPurchasePrice(),
  14711.                     'salesPrice' => $p->getSalesPrice(),
  14712.                     'purchasePriceWoExpense' => $p->getPurchasePriceWoExpense(),
  14713.                     'qty' => $p->getQty(),
  14714.                     'nonInvoicedQty' => $p->getNonInvoicedQty(),
  14715.                     'nonSalesInvoicedQty' => $p->getNonSalesInvoicedQty(),
  14716.                     'unitTypeId' => $p->getUnitTypeId(),
  14717.                     'dimension' => $p->getDimension(),
  14718.                     'dimensionUnitTypeId' => $p->getDimensionUnitTypeId(),
  14719.                     'weight' => $p->getWeight(),
  14720.                     'categoryId' => $p->getCategoryId(),
  14721.                     'subCategoryId' => $p->getSubCategoryId(),
  14722.                     'brandCompany' => $p->getBrandCompany(),
  14723.                     'warehouseId' => $p->getWarehouseId(),
  14724.                     'reorderLevel' => $p->getReorderLevel(),
  14725.                     'defaultImage' => $p->getDefaultImage(),
  14726.                     'status' => $p->getStatus()
  14727.                 ];
  14728.             }, $product);
  14729.             return $this->json([
  14730.                 'warehouseId' => $fromWarehouseRow['warehouseId'],
  14731.                 'toWarehouseId' => $fromWarehouseRow['toWarehouseId'],
  14732.                 'warehouseActionId' => $fromWarehouseRow['warehouseActionId'],
  14733.                 'toWarehouseActionId' => $fromWarehouseRow['toWarehouseActionId'],
  14734.                 'quantity' => $fromWarehouseRow['qty'],
  14735.                 'price' => $fromWarehouseRow['price'],
  14736.                 'products' => $productData
  14737.             ]);
  14738.         } else if ($accountsHeadId) {
  14739.             $products $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findAll();
  14740.             $productData array_map(function ($p) {
  14741.                 return [
  14742.                     'id' => $p->getId(),
  14743.                     'name' => $p->getName(),
  14744.                     'modelNo' => $p->getModelNo(),
  14745.                     'sku' => $p->getSkuCode(),
  14746.                     'productCode' => $p->getProductCode(),
  14747.                     'purchasePrice' => $p->getPurchasePrice(),
  14748.                     'salesPrice' => $p->getSalesPrice(),
  14749.                     'purchasePriceWoExpense' => $p->getPurchasePriceWoExpense(),
  14750.                     'qty' => $p->getQty(),
  14751.                     'nonInvoicedQty' => $p->getNonInvoicedQty(),
  14752.                     'nonSalesInvoicedQty' => $p->getNonSalesInvoicedQty(),
  14753.                     'unitTypeId' => $p->getUnitTypeId(),
  14754.                     'dimension' => $p->getDimension(),
  14755.                     'dimensionUnitTypeId' => $p->getDimensionUnitTypeId(),
  14756.                     'weight' => $p->getWeight(),
  14757.                     'categoryId' => $p->getCategoryId(),
  14758.                     'subCategoryId' => $p->getSubCategoryId(),
  14759.                     'brandCompany' => $p->getBrandCompany(),
  14760.                     'warehouseId' => $p->getWarehouseId(),
  14761.                     'reorderLevel' => $p->getReorderLevel(),
  14762.                     'defaultImage' => $p->getDefaultImage(),
  14763.                     'status' => $p->getStatus()
  14764.                 ];
  14765.             }, $products);
  14766.             return $this->json($productData);
  14767.         } else {
  14768.             return new JsonResponse([
  14769.                 "status" => false,
  14770.                 "message" => "Please insert valid documentId or accountsHead!"
  14771.             ]);
  14772.         }
  14773.     }
  14774.     public function getQuantityBasedOnSubWareHouse(Request $request)
  14775.     {
  14776.         $em $this->getDoctrine()->getManager();
  14777.         $productId $request->get('product_id');
  14778.         $productName trim($request->get('product_name'));
  14779.         $warehouseId $request->get('warehouse_id');
  14780.         $warehouseActionId $request->get('warehouse_action_id');
  14781.         if (!$productId && $productName) {
  14782.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  14783.                 ->createQueryBuilder('p')
  14784.                 ->where('p.name LIKE :name')
  14785.                 ->setParameter('name''%' $productName '%')
  14786.                 ->setMaxResults(1)
  14787.                 ->getQuery()
  14788.                 ->getOneOrNullResult();
  14789.             if ($product) {
  14790.                 $productId $product->getId();
  14791.             }
  14792.         }
  14793.         if (!$productId || !$warehouseId || !$warehouseActionId) {
  14794.             return new JsonResponse(['error' => 'Product ID, Warehouse ID, and Action Tag ID are required'], 400);
  14795.         }
  14796.         $criteria = [
  14797.             'productId' => $productId,
  14798.             'warehouseId' => $warehouseId,
  14799.             'actionTagId' => $warehouseActionId,
  14800.         ];
  14801.         $invStorageItems $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy($criteria);
  14802.         if (empty($invStorageItems)) {
  14803.             return new JsonResponse([
  14804.                 'product_id' => $productId,
  14805.                 'quantities' => []
  14806.             ]);
  14807.         }
  14808.         $totalQty 0;
  14809.         $totalNonInvoicedQty 0;
  14810.         $totalPhysicalQty 0;
  14811.         $purchasePrice null;
  14812.         $salesPrice null;
  14813.         foreach ($invStorageItems as $item) {
  14814.             $totalQty += $item->getQty();
  14815.             $totalNonInvoicedQty += $item->getNonInvoicedQty();
  14816.             $totalPhysicalQty += $item->getPhysicalQty();
  14817.             $purchasePrice $item->getPurchasePrice();
  14818.             $salesPrice $item->getSalesPrice();
  14819.         }
  14820.         $subWarehouse $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')->find($warehouseActionId);
  14821.         $quantitiesBySubWarehouse = [[
  14822.             'action_tag_id' => $warehouseActionId,
  14823.             'sub_warehouse' => $subWarehouse $subWarehouse->getName() : '',
  14824.             'qty' => $totalQty,
  14825.             'non_invoiced_qty' => $totalNonInvoicedQty,
  14826.             'physical_qty' => $totalPhysicalQty,
  14827.             'purchase_price' => $purchasePrice,
  14828.             'sales_price' => $salesPrice,
  14829.         ]];
  14830.         return new JsonResponse([
  14831.             'product_id' => $productId,
  14832.             'quantities' => $quantitiesBySubWarehouse
  14833.         ]);
  14834.     }
  14835.     public function getPriceByWareHouseId(Request $request)
  14836.     {
  14837.         $em $this->getDoctrine()->getManager();
  14838.         $warehouseId $request->request->get('warehouseId');
  14839.         $productId $request->request->get('productId');
  14840.         $actionTagId $request->request->get('actionTagId');
  14841.         $unitPrice $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->createQueryBuilder('st')
  14842.             ->select('st.purchasePrice AS purchasePrice')
  14843.             ->where('st.productId = :productId')
  14844.             ->andWhere('st.warehouseId = :warehouseId')
  14845.             ->andWhere('st.actionTagId = :actionTagId')
  14846.             ->setParameter('productId'$productId)
  14847.             ->setParameter('warehouseId'$warehouseId)
  14848.             ->setParameter('actionTagId'$actionTagId)
  14849.             ->setMaxResults(1)
  14850.             ->getQuery()
  14851.             ->getOneOrNullResult();
  14852.         return new JsonResponse([
  14853.             'purchasePrice' => $unitPrice $unitPrice['purchasePrice'] : null
  14854.         ]);
  14855.     }
  14856.     public function getStockTransferList(Request $request)
  14857.     {
  14858.         $em $this->getDoctrine()->getManager();
  14859.         $warehouses $em->getRepository('ApplicationBundle\\Entity\\StockTransfer')
  14860.             ->createQueryBuilder('s')
  14861.             ->select('s.stockTransferId''s.documentHash')
  14862. //            ->orderBy('s.name', 'ASC')
  14863.             ->getQuery()
  14864.             ->getResult();
  14865.         return $this->json($warehouses);
  14866.     }
  14867.     public function stockTransferItemList(Request $request)
  14868.     {
  14869.         $em $this->getDoctrine()->getManager();
  14870.         $stockTransferId $request->query->get('stockTransferId');
  14871.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14872.         $qb $em->createQueryBuilder();
  14873.         $qb->select(
  14874.             'sti.id AS id',
  14875.             'sti.productId AS productId',
  14876.             'sti.stockTransferId AS stockTransferId',
  14877.             'p.name AS productName',
  14878.             'sti.price AS price',
  14879.             'p.images AS images',
  14880.             'ig.name AS itemGroupName',
  14881.             'w.name AS wareHouseName',
  14882.             'sti.warehouseId AS warehouseId',
  14883.             'wa.name AS subWareHouseName',
  14884.             'sti.warehouseActionId AS warehouseActionId',
  14885.             'sti.qty AS quantity',
  14886.             'b.name AS brandName',
  14887.             'u.name AS UnitName',
  14888.             'c.name AS color',
  14889.             's.name AS size'
  14890.         )
  14891.             ->from('ApplicationBundle:StockTransferItem''sti')
  14892.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''sti.productId = p.id')
  14893.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''p.igId = ig.id')
  14894.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''sti.warehouseId = w.id')
  14895.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''sti.warehouseActionId = wa.id')
  14896.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''p.brandCompany = b.id')
  14897.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''p.unitTypeId = u.id')
  14898.             ->leftJoin('ApplicationBundle:Colors''c''WITH''sti.colorId = c.id')
  14899.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''sti.sizeId = s.id')
  14900.             ->where('sti.stockTransferId = :stockTransferId')
  14901.             ->setParameter('stockTransferId'$stockTransferId);
  14902.         $results $qb->getQuery()->getResult();
  14903.         $response = [];
  14904.         foreach ($results as $item) {
  14905.             $response[] = [
  14906.                 'id' => $item['id'],
  14907.                 'stockTransferId' => $item['stockTransferId'],
  14908.                 'productId' => (int)$item['productId'],
  14909.                 'itemGroupName' => $item['itemGroupName'] ?? '',
  14910.                 'wareHouseName' => $item['wareHouseName'] ?? '',
  14911.                 'wareHouseId' => $item['warehouseId'] ?? '',
  14912.                 'subWareHouseName' => $item['subWareHouseName'] ?? '',
  14913.                 'subWareHouseId' => $item['warehouseActionId'] ?? '',
  14914.                 'quantity' => (int)$item['quantity'],
  14915.                 'brandName' => $item['brandName'] ?? '',
  14916.                 'UnitName' => $item['UnitName'] ?? '',
  14917.                 'color' => $item['color'] ?? '',
  14918.                 'size' => $item['size'] ?? '',
  14919.                 'price' => (float)$item['price'],
  14920.                 'productName' => $item['productName'] ?? '',
  14921.                 'image' => !empty($item['images']) ? $item['images'] : $defaultImage,
  14922.             ];
  14923.         }
  14924.         return $this->json($response);
  14925.     }
  14926.     public function inventoryStorageFilter(Request $request)
  14927.     {
  14928.         $em $this->getDoctrine()->getManager();
  14929.         $qb $em->createQueryBuilder();
  14930.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14931.         $qb->select(
  14932.             'i.productId',
  14933.             'ig.name AS itemGroupName',
  14934.             'w.name AS wareHouseName',
  14935.             'wa.name AS subWareHouseName',
  14936.             'i.qty AS quantity',
  14937.             'b.name AS brandName',
  14938.             'u.name AS UnitName',
  14939.             'c.name AS color',
  14940.             's.name AS size',
  14941.             'i.purchasePrice AS price',
  14942.             'p.name AS productName',
  14943.             'p.images'
  14944.         )
  14945.             ->from('ApplicationBundle:InventoryStorage''i')
  14946.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  14947.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''i.igId = ig.id')
  14948.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''i.warehouseId = w.id')
  14949.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''i.brandId = b.id')
  14950.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''i.unitTypeId = u.id')
  14951.             ->leftJoin('ApplicationBundle:Colors''c''WITH''i.color = c.id')
  14952.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''i.size = s.id')
  14953.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''i.actionTagId = wa.id');
  14954.         // Define available filters with their mappings
  14955.         $filters = [
  14956.             'itemGroup' => 'ig.id',
  14957.             'category' => 'p.categoryId',
  14958.             'warehouse' => 'w.id',
  14959.             'storageType' => 'i.actionTagId',
  14960.             'brand' => 'b.id',
  14961.             'color' => 'c.id',
  14962.             'colorCode' => 'c.hexCode',
  14963.             'size' => 's.id',
  14964.         ];
  14965.         foreach ($filters as $param => $field) {
  14966.             $value $request->query->get($param);
  14967.             if ($value !== null) {
  14968.                 $values array_map('trim'explode(','$value));
  14969.                 if (count($values) > 1) {
  14970.                     $qb->andWhere($qb->expr()->in($field":$param"))
  14971.                         ->setParameter($param$values);
  14972.                 } else {
  14973.                     $qb->andWhere("$field = :$param")
  14974.                         ->setParameter($param$values[0]);
  14975.                 }
  14976.             }
  14977.         }
  14978.         $rawResult $qb->getQuery()->getArrayResult();
  14979.         $finalResult = [];
  14980.         foreach ($rawResult as $row) {
  14981.             $finalResult[] = [
  14982.                 'productId' => $row['productId'],
  14983.                 'itemGroupName' => $row['itemGroupName'],
  14984.                 'wareHouseName' => $row['wareHouseName'],
  14985.                 'subWareHouseName' => $row['subWareHouseName'],
  14986.                 'quantity' => $row['quantity'],
  14987.                 'brandName' => $row['brandName'],
  14988.                 'UnitName' => $row['UnitName'],
  14989.                 'color' => $row['color'] ?? '',
  14990.                 'size' => $row['size'] ?? '',
  14991.                 'price' => $row['price'],
  14992.                 'productName' => $row['productName'],
  14993.                 'image' => !empty($row['images']) ? $row['images'] : $defaultImage,
  14994.             ];
  14995.         }
  14996.         // Check if finalResult is empty
  14997.         if (empty($finalResult)) {
  14998.             return $this->json([
  14999.                 'success' => false,
  15000.                 'message' => 'No inventory items found matching your criteria'
  15001.             ]);
  15002.         }
  15003.         return $this->json([
  15004.             'success' => true,
  15005.             'data' => $finalResult
  15006.         ]);
  15007.     }
  15008. //    public function inventoryStorageFilter(Request $request)
  15009. //    {
  15010. //        $em = $this->getDoctrine()->getManager();
  15011. //        $qb = $em->createQueryBuilder();
  15012. //        $defaultImage = 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  15013. //
  15014. //        $qb->select(
  15015. //            'i.productId',
  15016. //            'ig.name AS itemGroupName',
  15017. //            'w.name AS wareHouseName',
  15018. //            'wa.name AS subWareHouseName',
  15019. //            'i.qty AS quantity',
  15020. //            'b.name AS brandName',
  15021. //            'u.name AS UnitName',
  15022. //            'c.name AS color',
  15023. //            's.name AS size',
  15024. //            'i.purchasePrice AS price',
  15025. //            'p.name AS productName',
  15026. //            'p.images'
  15027. //        )
  15028. //            ->from('ApplicationBundle:InventoryStorage', 'i')
  15029. //            ->leftJoin('ApplicationBundle:InvProducts', 'p', 'WITH', 'i.productId = p.id')
  15030. //            ->leftJoin('ApplicationBundle:InvItemGroup', 'ig', 'WITH', 'i.igId = ig.id')
  15031. //            ->leftJoin('ApplicationBundle:Warehouse', 'w', 'WITH', 'i.warehouseId = w.id')
  15032. //            ->leftJoin('ApplicationBundle:BrandCompany', 'b', 'WITH', 'i.brandId = b.id')
  15033. //            ->leftJoin('ApplicationBundle:UnitType', 'u', 'WITH', 'i.unitTypeId = u.id')
  15034. //            ->leftJoin('ApplicationBundle:Colors', 'c', 'WITH', 'i.color = c.id')
  15035. //            ->leftJoin('ApplicationBundle:ProductSizes', 's', 'WITH', 'i.size = s.id')
  15036. //            ->leftJoin('ApplicationBundle:WarehouseAction', 'wa', 'WITH', 'i.actionTagId = wa.id');
  15037. //
  15038. //        // Define available filters with their mappings
  15039. //        $filters = [
  15040. //            'itemGroup'    => 'ig.id',
  15041. //            'category'     => 'p.categoryId',
  15042. //            'warehouse'    => 'w.id',
  15043. //            'storageType'  => 'i.actionTagId',
  15044. //            'brand'        => 'b.id',
  15045. //            'color'        => 'c.id',
  15046. //            'colorCode'    => 'c.hexCode',
  15047. //            'size'         => 's.id',
  15048. //        ];
  15049. //
  15050. //        foreach ($filters as $param => $field) {
  15051. //            $value = $request->query->get($param);
  15052. //
  15053. //            if ($value !== null) {
  15054. //                $values = array_map('trim', explode(',', $value)); // handle multiple
  15055. //                if (count($values) > 1) {
  15056. //                    $qb->andWhere($qb->expr()->in($field, ":$param"))
  15057. //                        ->setParameter($param, $values);
  15058. //                } else {
  15059. //                    $qb->andWhere("$field = :$param")
  15060. //                        ->setParameter($param, $values[0]);
  15061. //                }
  15062. //            }
  15063. //        }
  15064. //
  15065. //        $rawResult = $qb->getQuery()->getArrayResult();
  15066. //
  15067. //        // Now process for validation (color, size, images)
  15068. //        $finalResult = [];
  15069. //
  15070. //        foreach ($rawResult as $row) {
  15071. //            $finalResult[] = [
  15072. //                'productId'     => $row['productId'],
  15073. //                'itemGroupName' => $row['itemGroupName'],
  15074. //                'wareHouseName' => $row['wareHouseName'],
  15075. //                'subWareHouseName' => $row['subWareHouseName'],
  15076. //                'quantity'      => $row['quantity'],
  15077. //                'brandName'     => $row['brandName'],
  15078. //                'UnitName'      => $row['UnitName'],
  15079. //                'color'         => $row['color'] ?? '',
  15080. //                'size'          => $row['size'] ?? '',
  15081. //                'price'         => $row['price'],
  15082. //                'productName'   => $row['productName'],
  15083. //                'image'         => !empty($row['images']) ? $row['images'] : $defaultImage,
  15084. //            ];
  15085. //        }
  15086. //
  15087. //
  15088. //
  15089. //        return $this->json($finalResult);
  15090. //    }
  15091.     public function getItemGroupList()
  15092.     {
  15093.         $em $this->getDoctrine()->getManager();
  15094.         $itemGroups $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')
  15095.             ->createQueryBuilder('ig')
  15096.             ->select('ig.id''ig.name')
  15097.             ->getQuery()
  15098.             ->getResult();
  15099.         return $this->json($itemGroups);
  15100.     }
  15101.     public function getProductCategoryList()
  15102.     {
  15103.         $em $this->getDoctrine()->getManager();
  15104.         $categories $em->getRepository('ApplicationBundle\\Entity\\InvProductCategories')
  15105.             ->createQueryBuilder('pc')
  15106.             ->select('pc.id''pc.name')
  15107.             ->getQuery()
  15108.             ->getResult();
  15109.         return $this->json($categories);
  15110.     }
  15111.     public function getBrandList()
  15112.     {
  15113.         $em $this->getDoctrine()->getManager();
  15114.         $brands $em->getRepository('ApplicationBundle\\Entity\\BrandCompany')
  15115.             ->createQueryBuilder('b')
  15116.             ->select('b.id''b.name')
  15117.             ->getQuery()
  15118.             ->getResult();
  15119.         return $this->json($brands);
  15120.     }
  15121.     public function getColorList()
  15122.     {
  15123.         $em $this->getDoctrine()->getManager();
  15124.         $colors $em->getRepository('ApplicationBundle\\Entity\\Colors')
  15125.             ->createQueryBuilder('c')
  15126.             ->select('c.id''c.name')
  15127.             ->getQuery()
  15128.             ->getResult();
  15129.         return $this->json($colors);
  15130.     }
  15131.     public function getColorCodeList()
  15132.     {
  15133.         $em $this->getDoctrine()->getManager();
  15134.         $colorCodes $em->getRepository('ApplicationBundle\\Entity\\Colors')
  15135.             ->createQueryBuilder('c')
  15136.             ->select('c.id''c.hexCode')
  15137.             ->getQuery()
  15138.             ->getResult();
  15139.         return $this->json($colorCodes);
  15140.     }
  15141.     public function getSizeList()
  15142.     {
  15143.         $em $this->getDoctrine()->getManager();
  15144.         $sizes $em->getRepository('ApplicationBundle\\Entity\\ProductSizes')
  15145.             ->createQueryBuilder('s')
  15146.             ->select('s.id''s.name')
  15147.             ->getQuery()
  15148.             ->getResult();
  15149.         if (empty($sizes)) {
  15150.             return $this->json([
  15151.                 'success' => false,
  15152.                 'message' => 'No data found'
  15153.             ]);
  15154.         }
  15155.         return $this->json($sizes);
  15156.     }
  15157.     public function productCodeList()
  15158.     {
  15159.         $em $this->getDoctrine()->getManager();
  15160.         $productCode $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  15161.             ->createQueryBuilder('p')
  15162.             ->select('p.productByCodeId''p.productId''p.salesCode')
  15163.             ->getQuery()
  15164.             ->getResult();
  15165.         if (empty($productCode)) {
  15166.             return $this->json([
  15167.                 'success' => false,
  15168.                 'message' => 'No data found'
  15169.             ]);
  15170.         }
  15171.         return $this->json($productCode);
  15172.     }
  15173.     public function getItemInOutHistory(Request $request)
  15174.     {
  15175.         $em $this->getDoctrine()->getManager();
  15176.         $qb $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')->createQueryBuilder('i')
  15177.             ->select([
  15178.                 'i.productId AS productId',
  15179.                 'i.transactionType AS transactionType',
  15180.                 'i.transactionDate AS transactionDate',
  15181.                 'toWarehouse.name AS toWarehouseId',
  15182.                 'toSubWarehouse.name AS toSubWarehouseId',
  15183.                 'fromWarehouse.name AS fromWarehouseId',
  15184.                 'fromSubWarehouse.name AS fromSubWarehouseId',
  15185.                 'i.qty AS quantity',
  15186.                 'i.entityDocHash AS document',
  15187.                 'i.entity AS entity',
  15188.                 'i.entityId AS entityId',
  15189.                 'p.name AS productName',
  15190.             ])
  15191.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  15192.             ->leftJoin('ApplicationBundle:Warehouse''toWarehouse''WITH''i.warehouseId = toWarehouse.id')
  15193.             ->leftJoin('ApplicationBundle:WarehouseAction''toSubWarehouse''WITH''i.actionTagId = toSubWarehouse.id')
  15194.             ->leftJoin('ApplicationBundle:Warehouse''fromWarehouse''WITH''i.fromWarehouseId = fromWarehouse.id')
  15195.             ->leftJoin('ApplicationBundle:WarehouseAction''fromSubWarehouse''WITH''i.fromActionTagId = fromSubWarehouse.id');
  15196.         // Parse dd-mm-yyyy to Y-m-d
  15197.         $startDateStr $request->query->get('startDate');
  15198.         $endDateStr $request->query->get('endDate');
  15199.         if ($startDateStr && $endDateStr) {
  15200.             try {
  15201.                 $startDate = \DateTime::createFromFormat('d-m-Y'$startDateStr)->setTime(000);
  15202.                 $endDate = \DateTime::createFromFormat('d-m-Y'$endDateStr)->setTime(235959);
  15203.                 $qb->andWhere('i.transactionDate BETWEEN :startDate AND :endDate')
  15204.                     ->setParameter('startDate'$startDate)
  15205.                     ->setParameter('endDate'$endDate);
  15206.             } catch (\Exception $e) {
  15207.                 return $this->json(['error' => 'Invalid date format. Use dd-mm-yyyy.'], 400);
  15208.             }
  15209.         }
  15210.         $results $qb->getQuery()->getResult();
  15211.         $data array_map(function ($item) {
  15212.             return [
  15213.                 'productId' => $item['productId'],
  15214.                 'transactionType' => $item['transactionType'] == 'IN' 'OUT',
  15215.                 'transactionDate' => $item['transactionDate']->format('Y-m-d'),
  15216.                 'toWarehouseId' => $item['toWarehouseId'] ?? '',
  15217.                 'toSubWarehouseId' => $item['toSubWarehouseId'] ?? '',
  15218.                 'toSubWarehouseShortName' => $item['toSubWarehouseId'] ?? '',
  15219.                 'fromWarehouseId' => $item['fromWarehouseId'] ?? '',
  15220.                 'fromSubWarehouseId' => $item['fromSubWarehouseId'] ?? '',
  15221.                 'fromSubWarehouseShortName' => $item['fromSubWarehouseId'] ?? '',
  15222.                 'quantity' => $item['quantity'],
  15223.                 'document' => !empty($item['document']) ? $item['document'] : 0,
  15224.                 'entity' => !empty($item['entity']) ? $item['entity'] : 0,
  15225.                 'entityId' => !empty($item['entityId']) ? $item['entityId'] : 0,
  15226.                 'productName' => $item['productName'],
  15227.             ];
  15228.         }, $results);
  15229.         return $this->json($data);
  15230.     }
  15231.     public function CreateStockReceivedNoteForApp(Request $request$id 0)
  15232.     {
  15233.         $em $this->getDoctrine()->getManager();
  15234.         $companyId $this->getLoggedUserCompanyId($request);
  15235.         $extDocData = [];
  15236.         $userId $request->getSession()->get(UserConstants::USER_ID);
  15237.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  15238.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  15239. //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  15240.         $userBranchIdList $request->getSession()->get('branchIdList');
  15241.         if ($userBranchIdList == null$userBranchIdList = [];
  15242.         $userBranchId $request->getSession()->get('branchId');
  15243.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  15244.             $em $this->getDoctrine()->getManager();
  15245.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //change
  15246.             $dochash $request->request->get('docHash'); //change
  15247.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  15248.             $approveRole $request->request->get('approvalRole');
  15249.             $approveHash $request->request->get('approvalHash');
  15250.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  15251.                 $loginId$approveRole$approveHash$id)
  15252.             ) {
  15253.                 if ($request->request->has('returnJson')) {
  15254.                     return new JsonResponse(array(
  15255.                         'success' => false,
  15256.                         'documentHash' => 0,
  15257.                         'documentId' => 0,
  15258.                         'billIds' => [],
  15259.                         'drIds' => [],
  15260.                         'pmntTransIds' => [],
  15261.                         'viewUrl' => '',
  15262.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  15263.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  15264.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  15265.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  15266.                     ));
  15267.                 } else
  15268.                     $this->addFlash(
  15269.                         'error',
  15270.                         'Sorry Could not insert Data.'
  15271.                     );
  15272.             } else {
  15273.                 if ($request->request->has('check_allowed'))
  15274.                     $check_allowed 1;
  15275.                 $StID Inventory::CreateNewStockReceivedNoteForApp(
  15276.                     $this->getDoctrine()->getManager(),
  15277.                     $request->request,
  15278.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  15279.                     $this->getLoggedUserCompanyId($request)
  15280.                 );
  15281.                 //now add Approval info
  15282.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  15283.                 $approveRole 1;  //created
  15284.                 $options = array(
  15285.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  15286.                     'notification_server' => $this->container->getParameter('notification_server'),
  15287.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  15288.                     'url' => $this->generateUrl(
  15289.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  15290.                         ['entity_view_route_path_name']
  15291.                     )
  15292.                 );
  15293.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  15294.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  15295.                     $StID,
  15296.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  15297.                 );
  15298.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  15299.                     $loginId,
  15300.                     $approveRole,
  15301.                     $request->request->get('approvalHash'));
  15302.                 $url $this->generateUrl(
  15303.                     'view_srcv'
  15304.                 );
  15305.                 if ($request->request->has('returnJson')) {
  15306.                     return new JsonResponse(array(
  15307.                         'success' => true,
  15308.                         'documentHash' => $dochash,
  15309.                         'documentId' => $StID,
  15310. //                        'viewUrl' => $url . "/" . $StID,
  15311.                     ));
  15312.                 } else {
  15313.                     $this->addFlash(
  15314.                         'success',
  15315.                         'Stock Received Note Added.'
  15316.                     );
  15317.                     return $this->redirect($url "/" $StID);
  15318.                 }
  15319.             }
  15320.         }
  15321.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  15322.             array(
  15323.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  15324.             )
  15325.         );
  15326.         if ($id == 0) {
  15327.         } else {
  15328.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')->findOneBy(
  15329.                 array(
  15330.                     'stockReceivedNoteId' => $id,
  15331.                 )
  15332.             );
  15333.             //now if its not editable, redirect to view
  15334.             if ($extDoc) {
  15335.                 if ($extDoc->getEditFlag() != 1) {
  15336.                     $url $this->generateUrl(
  15337.                         'view_srcv'
  15338.                     );
  15339.                     return $this->redirect($url "/" $id);
  15340.                 } else {
  15341.                     $extDocData $extDoc;
  15342.                     $extDocDataDetails $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findOneBy(
  15343.                         array(
  15344.                             'stockReceivedNoteId' => $id///material
  15345.                         )
  15346.                     );
  15347.                 }
  15348.             } else {
  15349.             }
  15350.         }
  15351.         $INVLIST = [];
  15352.         foreach ($slotList as $slot) {
  15353.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  15354.         }
  15355.         $dataArray = array(
  15356.             'page_title' => 'Stock Received Note',
  15357. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  15358.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  15359.             'users' => Users::getUserListById($em),
  15360.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  15361.             'warehouseList' => Inventory::WarehouseList($em),
  15362.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  15363.             'warehouseActionList' => $warehouse_action_list,
  15364.             'warehouseActionListArray' => $warehouse_action_list_array,
  15365.             'extDocData' => $extDocData,
  15366.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  15367.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  15368.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  15369.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  15370. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  15371. //            'product_list' => Inventory::ProductList($em, $companyId),
  15372.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  15373.             'prefix_list' => array(
  15374.                 [
  15375.                     'id' => 1,
  15376.                     'value' => 'GN',
  15377.                     'text' => 'GN'
  15378.                 ]
  15379.             ),
  15380.             'assoc_list' => array(
  15381.                 [
  15382.                     'id' => 1,
  15383.                     'value' => 1,
  15384.                     'text' => 'GN'
  15385.                 ]
  15386.             ),
  15387.             'INVLIST' => $INVLIST,
  15388.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  15389.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  15390.             'userBranchIdList' => $userBranchIdList,
  15391.             'userBranchId' => $userBranchId,
  15392. //            'headList' => Accounts::HeadList($em),
  15393.         );
  15394.         //json
  15395.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  15396.         {
  15397.             $dataArray['success'] = true;
  15398.             return new JsonResponse(
  15399.                 $dataArray
  15400.             );
  15401.         }
  15402.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  15403.             $dataArray
  15404.         );
  15405.     }
  15406.     public function RefreshTaskOnSessionAction(Request $request)
  15407.     {
  15408.         $session $request->getSession();
  15409.         $em $this->getDoctrine()->getManager();
  15410.         $currentPlanningItemId 0;
  15411.         $currentTaskId 0;
  15412.         $taskActualStartTs 0;
  15413.         $currentTask $em->getRepository('ApplicationBundle\\Entity\\TaskLog')
  15414.             ->findOneBy(
  15415.                 array(
  15416.                     'userId' => $session->get(UserConstants::USER_ID),
  15417.                     'workingStatus' => 1
  15418.                 )
  15419.             );
  15420.         if ($currentTask) {
  15421.             $currentTaskId $currentTask->getId();
  15422.             $currentPlanningItemId $currentTask->getPlanningItemId();
  15423.             $taskActualStartTs $currentTask->getActualStartTs();
  15424.         }
  15425.         $session->set(UserConstants::USER_CURRENT_TASK_ID$currentTaskId);
  15426.         $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$currentPlanningItemId);
  15427.         return new JsonResponse(
  15428.             array(
  15429.                 'currentPlanningItemId' => $currentPlanningItemId,
  15430.                 'currentTaskId' => $currentTaskId,
  15431.                 'taskActualStartTs' => $taskActualStartTs,
  15432.             )
  15433.         );
  15434.     }
  15435.     private function getProductFormDefaults($em$companyId$loginId)
  15436.     {
  15437.         $defaults = array(
  15438.             'unitTypeId' => 0,
  15439.             'defaultTaxConfigId' => 0,
  15440.             'defaultPurchaseTaxConfigId' => 0,
  15441.             'defaultPurchaseActionTagId' => 0
  15442.         );
  15443.         if ($loginId != '' && $loginId != null) {
  15444.             $pref $em->getRepository('ApplicationBundle\\Entity\\InvProductFormPreference')->findOneBy(array(
  15445.                 'companyId' => $companyId,
  15446.                 'loginId' => $loginId
  15447.             ));
  15448.             if ($pref) {
  15449.                 $defaults['unitTypeId'] = (int) $pref->getUnitTypeId();
  15450.                 $defaults['defaultTaxConfigId'] = (int) $pref->getDefaultTaxConfigId();
  15451.                 $defaults['defaultPurchaseTaxConfigId'] = (int) $pref->getDefaultPurchaseTaxConfigId();
  15452.                 $defaults['defaultPurchaseActionTagId'] = (int) $pref->getDefaultPurchaseActionTagId();
  15453.             }
  15454.         }
  15455.         if ($defaults['unitTypeId'] == 0) {
  15456.             $defaults['unitTypeId'] = $this->resolveDefaultPcsUnitTypeId($em);
  15457.         }
  15458.         if ($defaults['defaultTaxConfigId'] == || $defaults['defaultPurchaseTaxConfigId'] == || $defaults['defaultPurchaseActionTagId'] == 0) {
  15459.             $defaultItemGroup $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(array(
  15460.                 'CompanyId' => $companyId,
  15461.                 'status' => GeneralConstant::ACTIVE
  15462.             ));
  15463.             if ($defaultItemGroup) {
  15464.                 if ($defaults['defaultTaxConfigId'] == 0) {
  15465.                     $defaults['defaultTaxConfigId'] = (int) $defaultItemGroup->getDefaultTaxConfigId();
  15466.                 }
  15467.                 if ($defaults['defaultPurchaseTaxConfigId'] == 0) {
  15468.                     $defaults['defaultPurchaseTaxConfigId'] = (int) $defaultItemGroup->getDefaultPurchaseTaxConfigId();
  15469.                 }
  15470.                 if ($defaults['defaultPurchaseActionTagId'] == 0) {
  15471.                     $defaults['defaultPurchaseActionTagId'] = (int) $defaultItemGroup->getDefaultPurchaseActionTagId();
  15472.                 }
  15473.                 if ($defaults['unitTypeId'] == 0) {
  15474.                     $defaults['unitTypeId'] = (int) $defaultItemGroup->getUnitTypeId();
  15475.                 }
  15476.             }
  15477.         }
  15478.         return $defaults;
  15479.     }
  15480.     private function resolveDefaultPcsUnitTypeId($em)
  15481.     {
  15482.         $unitTypes Inventory::UnitTypeList($em);
  15483.         foreach ($unitTypes as $unitType) {
  15484.             $name = isset($unitType['name']) ? strtoupper(trim($unitType['name'])) : '';
  15485.             $suffix = isset($unitType['classSuffix']) ? strtoupper(trim($unitType['classSuffix'])) : '';
  15486.             if ($name === 'PCS' || $suffix === 'PCS') {
  15487.                 return (int) $unitType['id'];
  15488.             }
  15489.         }
  15490.         foreach ($unitTypes as $unitType) {
  15491.             if (isset($unitType['id']) && $unitType['id'] != && $unitType['id'] != '') {
  15492.                 return (int) $unitType['id'];
  15493.             }
  15494.         }
  15495.         return 0;
  15496.     }
  15497.     private function saveProductFormDefaults($em$companyId$loginId$savedEntityRequest $request)
  15498.     {
  15499.         if ($loginId == '' || $loginId == null) {
  15500.             return;
  15501.         }
  15502.         $unitTypeId 0;
  15503.         $defaultTaxConfigId 0;
  15504.         $defaultPurchaseTaxConfigId 0;
  15505.         $defaultPurchaseActionTagId 0;
  15506.         if ($savedEntity) {
  15507.             if (method_exists($savedEntity'getUnitTypeId')) {
  15508.                 $unitTypeId = (int) $savedEntity->getUnitTypeId();
  15509.             }
  15510.             if (method_exists($savedEntity'getDefaultTaxConfigId')) {
  15511.                 $defaultTaxConfigId = (int) $savedEntity->getDefaultTaxConfigId();
  15512.             }
  15513.             if (method_exists($savedEntity'getDefaultPurchaseTaxConfigId')) {
  15514.                 $defaultPurchaseTaxConfigId = (int) $savedEntity->getDefaultPurchaseTaxConfigId();
  15515.             }
  15516.             if (method_exists($savedEntity'getDefaultPurchaseActionTagId')) {
  15517.                 $defaultPurchaseActionTagId = (int) $savedEntity->getDefaultPurchaseActionTagId();
  15518.             }
  15519.         }
  15520.         if ($unitTypeId == 0) {
  15521.             $unitTypeId = (int) $request->request->get('unitTypeId'0);
  15522.         }
  15523.         if ($defaultTaxConfigId == 0) {
  15524.             $defaultTaxConfigId = (int) $request->request->get('defaultTaxConfigId'0);
  15525.             if ($defaultTaxConfigId == 0) {
  15526.                 $taxConfigIds $request->request->get('taxConfigIds', array());
  15527.                 if (!empty($taxConfigIds)) {
  15528.                     $defaultTaxConfigId = (int) $taxConfigIds[0];
  15529.                 }
  15530.             }
  15531.         }
  15532.         if ($defaultPurchaseTaxConfigId == 0) {
  15533.             $defaultPurchaseTaxConfigId = (int) $request->request->get('defaultPurchaseTaxConfigId'0);
  15534.             if ($defaultPurchaseTaxConfigId == 0) {
  15535.                 $purchaseTaxConfigIds $request->request->get('purchaseTaxConfigIds', array());
  15536.                 if (!empty($purchaseTaxConfigIds)) {
  15537.                     $defaultPurchaseTaxConfigId = (int) $purchaseTaxConfigIds[0];
  15538.                 }
  15539.             }
  15540.         }
  15541.         if ($defaultPurchaseActionTagId == 0) {
  15542.             $defaultPurchaseActionTagId = (int) $request->request->get('defaultPurchaseActionTagId'0);
  15543.         }
  15544.         $pref $em->getRepository('ApplicationBundle\\Entity\\InvProductFormPreference')->findOneBy(array(
  15545.             'companyId' => $companyId,
  15546.             'loginId' => $loginId
  15547.         ));
  15548.         if (!$pref) {
  15549.             $pref = new \ApplicationBundle\Entity\InvProductFormPreference();
  15550.             $pref->setCompanyId($companyId);
  15551.             $pref->setLoginId($loginId);
  15552.             $em->persist($pref);
  15553.         }
  15554.         $pref->setUnitTypeId($unitTypeId);
  15555.         $pref->setDefaultTaxConfigId($defaultTaxConfigId);
  15556.         $pref->setDefaultPurchaseTaxConfigId($defaultPurchaseTaxConfigId);
  15557.         $pref->setDefaultPurchaseActionTagId($defaultPurchaseActionTagId);
  15558.         $em->flush();
  15559.     }
  15560.     // â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  15561.     // S2.2 â€” EPC Category catalog
  15562.     // â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  15563.     public function EpcCategoryListAction(Request $request)
  15564.     {
  15565.         $em $this->getDoctrine()->getManager();
  15566.         $categories $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')
  15567.             ->findBy([], ['displayOrder' => 'ASC''code' => 'ASC']);
  15568.         return $this->render('@Inventory/pages/list/list_epc_categories.html.twig', [
  15569.             'page_title'  => 'EPC Category Catalog',
  15570.             'categories'  => $categories,
  15571.         ]);
  15572.     }
  15573.     public function EpcCategoryEditAction(Request $request$id 0)
  15574.     {
  15575.         $em $this->getDoctrine()->getManager();
  15576.         $ex_id = (int)($request->request->get('ex_id'$id));
  15577.         $cat   null;
  15578.         if ($ex_id 0) {
  15579.             $cat $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')->find($ex_id);
  15580.         }
  15581.         if ($request->isMethod('POST')) {
  15582.             $entity $cat ?? new \ApplicationBundle\Entity\EpcCategory();
  15583.             $entity->setCode(strtoupper(trim($request->request->get('code'''))));
  15584.             $entity->setName(trim($request->request->get('name''')));
  15585.             $entity->setDescription(trim($request->request->get('description''')));
  15586.             $entity->setDisplayOrder((int)$request->request->get('display_order'99));
  15587.             $entity->setActive($request->request->get('active') ? 0);
  15588.             if (!$cat) {
  15589.                 $entity->setCreatedAt(new \DateTime());
  15590.                 $entity->setCreatedLoginId((int)$request->getSession()->get(UserConstants::USER_LOGIN_ID0));
  15591.             }
  15592.             $em->persist($entity);
  15593.             $em->flush();
  15594.             $this->addFlash('success''EPC Category saved.');
  15595.             return $this->redirectToRoute('epc_category_list');
  15596.         }
  15597.         return $this->render('@Inventory/pages/input_forms/edit_epc_category.html.twig', [
  15598.             'page_title' => $ex_id 'Edit EPC Category' 'New EPC Category',
  15599.             'ex_id'      => $ex_id,
  15600.             'cat'        => $cat,
  15601.         ]);
  15602.     }
  15603.     public function EpcCategoryGetAllAction(Request $request)
  15604.     {
  15605.         $em $this->getDoctrine()->getManager();
  15606.         $cats $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')
  15607.             ->findBy(['active' => 1], ['displayOrder' => 'ASC']);
  15608.         $data = [];
  15609.         foreach ($cats as $c) {
  15610.             $data[] = ['code' => $c->getCode(), 'name' => $c->getName()];
  15611.         }
  15612.         return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => true'categories' => $data]);
  15613.     }
  15614.     // â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  15615.     // S2.1 â€” Article Translation endpoints
  15616.     // â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  15617.     public function SuggestProductsFromCentralAction(Request $request)
  15618.     {
  15619.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15620.         if ($systemType === '_CENTRAL_') {
  15621.             return new JsonResponse(['success' => false'message' => 'Not applicable on central'], 403);
  15622.         }
  15623.         $em        $this->getDoctrine()->getManager();
  15624.         $companyId $this->getLoggedUserCompanyId($request);
  15625.         $query     trim($request->request->get('query'''));
  15626.         $igName    trim($request->request->get('igName'''));
  15627.         $modelNo   trim($request->request->get('modelNo'''));
  15628.         if (strlen($query) < && !$modelNo) {
  15629.             return new JsonResponse(['success' => true'results' => []]);
  15630.         }
  15631.         $results Inventory::SearchProductsOnCentral($query$igName$modelNo10);
  15632.         // filter out products already local for this company
  15633.         $filtered = [];
  15634.         foreach ($results as $row) {
  15635.             $globalId = (int)($row['globalId'] ?? 0);
  15636.             if ($globalId 0) {
  15637.                 $local $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  15638.                 if ($local) continue;
  15639.             }
  15640.             $filtered[] = $row;
  15641.         }
  15642.         return new JsonResponse(['success' => true'results' => $filtered]);
  15643.     }
  15644.     public function ImportProductFromCentralAction(Request $request)
  15645.     {
  15646.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15647.         if ($systemType === '_CENTRAL_') {
  15648.             return new JsonResponse(['success' => false'message' => 'Not applicable on central'], 403);
  15649.         }
  15650.         $em        $this->getDoctrine()->getManager();
  15651.         $companyId $this->getLoggedUserCompanyId($request);
  15652.         $globalId  = (int)$request->request->get('globalId'0);
  15653.         if ($globalId <= 0) {
  15654.             return new JsonResponse(['success' => false'message' => 'globalId is required'], 400);
  15655.         }
  15656.         // check idempotency
  15657.         $existing $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  15658.         if ($existing) {
  15659.             return new JsonResponse(['success' => true'productId' => $existing->getId(), 'message' => 'already_exists']);
  15660.         }
  15661.         // fetch the full row from central by globalId
  15662.         $centralUrl = \ApplicationBundle\Constants\GeneralConstant::HONEYBEE_CENTRAL_SERVER;
  15663.         $curl curl_init();
  15664.         curl_setopt_array($curl, [
  15665.             CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  15666.             CURLOPT_URL => $centralUrl '/api/search_global_products',
  15667.             CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 12,
  15668.             CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  15669.             CURLOPT_POSTFIELDS => http_build_query(['globalId' => $globalId]),
  15670.         ]);
  15671.         $response  curl_exec($curl);
  15672.         $curlError curl_error($curl);
  15673.         curl_close($curl);
  15674.         if ($curlError || !$response) {
  15675.             return new JsonResponse(['success' => false'message' => 'Central server unreachable'], 503);
  15676.         }
  15677.         $data json_decode($responsetrue);
  15678.         if (!is_array($data) || empty($data['success']) || empty($data['results'])) {
  15679.             return new JsonResponse(['success' => false'message' => 'Product not found on central'], 404);
  15680.         }
  15681.         try {
  15682.             $productId Inventory::MaterializeProductFromCentral($em$companyId$data['results'][0]);
  15683.         } catch (\Throwable $e) {
  15684.             return new JsonResponse(['success' => false'message' => $e->getMessage()], 500);
  15685.         }
  15686.         return new JsonResponse(['success' => true'productId' => $productId'message' => 'imported']);
  15687.     }
  15688.     /**
  15689.      * Dev-admin only: proxy a central product search so the create-product form can
  15690.      * "Load from Central". Returns the central rows (igName/categoryName/specDataNamed
  15691.      * + descriptive fields) for the JS to populate the form. No DB write happens here â€”
  15692.      * the user reviews and Saves to materialize. Gated by devAdminMode.
  15693.      */
  15694.     public function SearchCentralProductsAction(Request $request)
  15695.     {
  15696.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15697.         if ($systemType === '_CENTRAL_') {
  15698.             return new JsonResponse(['success' => false'message' => 'Not applicable on central'], 403);
  15699.         }
  15700.         if ((int) $request->getSession()->get('devAdminMode'0) !== 1) {
  15701.             return new JsonResponse(['success' => false'message' => 'Requires devAdmin mode (open with ?devAdminOn=1)'], 403);
  15702.         }
  15703.         $query    trim($request->request->get('query'''));
  15704.         $globalId = (int) $request->request->get('globalId'0);
  15705.         if ($globalId <= && strlen($query) < 2) {
  15706.             return new JsonResponse(['success' => false'message' => 'query must be at least 2 characters'], 400);
  15707.         }
  15708.         $centralUrl = \ApplicationBundle\Constants\GeneralConstant::HONEYBEE_CENTRAL_SERVER;
  15709.         $curl curl_init();
  15710.         curl_setopt_array($curl, [
  15711.             CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  15712.             CURLOPT_URL => $centralUrl '/api/search_global_products',
  15713.             CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 15,
  15714.             CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  15715.             CURLOPT_POSTFIELDS => http_build_query($globalId ? ['globalId' => $globalId] : ['query' => $query'limit' => 20]),
  15716.         ]);
  15717.         $response  curl_exec($curl);
  15718.         $curlError curl_error($curl);
  15719.         curl_close($curl);
  15720.         if ($curlError || !$response) {
  15721.             return new JsonResponse(['success' => false'message' => 'Central server unreachable' . ($curlError ': ' $curlError '')], 503);
  15722.         }
  15723.         $data json_decode($responsetrue);
  15724.         if (!is_array($data)) {
  15725.             return new JsonResponse(['success' => false'message' => 'Bad response from central'], 502);
  15726.         }
  15727.         return new JsonResponse($data);
  15728.     }
  15729.     public function ArticleTranslationSaveAction(Request $request)
  15730.     {
  15731.         $em        $this->getDoctrine()->getManager();
  15732.         $articleId = (int)$request->request->get('article_id'0);
  15733.         $data      $request->request->get('translations', []);
  15734.         $loginId   = (int)$request->getSession()->get(UserConstants::USER_LOGIN_ID0);
  15735.         if ($articleId === || !is_array($data)) {
  15736.             return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => false'message' => 'Invalid input']);
  15737.         }
  15738.         Inventory::saveArticleTranslations($em$articleId$data$loginId);
  15739.         return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => true]);
  15740.     }
  15741.     public function ArticleTranslationGetAction(Request $request$articleId 0)
  15742.     {
  15743.         $em $this->getDoctrine()->getManager();
  15744.         $translations Inventory::getArticleTranslations($em, (int)$articleId);
  15745.         return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => true'translations' => $translations]);
  15746.     }
  15747.     // ===== Global-product / central-product-control cluster â€” moved from the legacy
  15748.     // ApplicationBundle\Controller\InventoryController (2026-07-03 consolidation). Behavior
  15749.     // preserved verbatim; routes repointed here. =====
  15750.     public function SyncProductAction(Request $request$id)
  15751.     {
  15752.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15753.         $em_local $this->getDoctrine()->getManager();
  15754.         if ($systemType == '_ERP_') {
  15755.             $product $em_local->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($id);
  15756.             if (!$product) {
  15757.                 return new JsonResponse(['error' => 'Product not found'], 404);
  15758.             }
  15759.             // Get category details
  15760.             $category $em_local->getRepository('ApplicationBundle\\Entity\\InvProductCategories')->find($product->getCategoryId());
  15761.             $brand $em_local -> getRepository('ApplicationBundle\\Entity\\BrandCompany')->find($product->getBrandCompany());
  15762.             $productData = [];
  15763.             $categoryData = [];
  15764.             $brandData = [];
  15765.             // Get product fields
  15766.             $reflectionClass = new \ReflectionClass($product);
  15767.             foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  15768.                 if (strpos($method->getName(), 'get') === 0) {
  15769.                     $property lcfirst(str_replace('get'''$method->getName()));
  15770.                     $productData[$property] = $method->invoke($product);
  15771.                 }
  15772.             }
  15773.             // Get category fields
  15774.             if ($category) {
  15775.                 $categoryReflection = new \ReflectionClass($category);
  15776.                 foreach ($categoryReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  15777.                     if (strpos($method->getName(), 'get') === 0) {
  15778.                         $property lcfirst(str_replace('get'''$method->getName()));
  15779.                         $categoryData[$property] = $method->invoke($category);
  15780.                     }
  15781.                 }
  15782.             }
  15783.             // Brand data
  15784.             if ($brand) {
  15785.                 $brandReflection = new \ReflectionClass($brand);
  15786.                 foreach ($brandReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  15787.                     if (strpos($method->getName(), 'get') === 0) {
  15788.                         $property lcfirst(str_replace('get'''$method->getName()));
  15789.                         $brandData[$property] = $method->invoke($brand);
  15790.                     }
  15791.                 }
  15792.             }
  15793.             // Store product data in pending_data
  15794.             $product->setPendingData(json_encode($productData));
  15795.             $em_local->flush();
  15796.             // Send  product,brand & category to central
  15797.             $syncData = [
  15798.                 'product' => $productData,
  15799.                 'category' => $categoryData,
  15800.                 'brand' => $brandData
  15801.             ];
  15802.             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/product_sync/' $id;
  15803.             $curl curl_init();
  15804.             curl_setopt_array($curl, [
  15805.                 CURLOPT_RETURNTRANSFER => true,
  15806.                 CURLOPT_POST => true,
  15807.                 CURLOPT_URL => $urlToCall,
  15808.                 CURLOPT_CONNECTTIMEOUT => 10,
  15809.                 CURLOPT_SSL_VERIFYPEER => false,
  15810.                 CURLOPT_SSL_VERIFYHOST => false,
  15811.                 CURLOPT_HTTPHEADER => [],
  15812.                 CURLOPT_POSTFIELDS => ['syncData' => json_encode($syncData)]
  15813.             ]);
  15814.             $retData curl_exec($curl);
  15815.             $errData curl_error($curl);
  15816.             curl_close($curl);
  15817.             if ($errData) {
  15818.                 return new JsonResponse(['error' => $errData], 500);
  15819.             }
  15820.             $retDataObj json_decode($retDatatrue);
  15821.             if (isset($retDataObj['globalId'])) {
  15822.                 $product->setGlobalId($retDataObj['globalId']);
  15823.                 $em_local->flush();
  15824.             }
  15825.             return new JsonResponse(['message' => 'Product (pending) and category synced to central server!']);
  15826.         }
  15827.         // CENTRAL SYSTEM PROCESSING
  15828.         else if ($systemType == '_CENTRAL_') {
  15829.             $requestData $request->get('syncData');
  15830.             if (!$requestData) {
  15831.                 return new JsonResponse(['error' => 'Invalid data received'], 400);
  15832.             }
  15833.             $requestData json_decode($requestDatatrue);
  15834.             $productData $requestData['product'] ?? null;
  15835.             $categoryData $requestData['category'] ?? null;
  15836.             $brandData $requestData['brand'] ?? null;
  15837.             if (!$productData) {
  15838.                 return new JsonResponse(['error' => 'Product data missing'], 400);
  15839.             }
  15840.             // Process product (Store in pending_data)
  15841.             $product $em_local->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($productData['id']) ?? new InvProducts();
  15842.             // Store in pending_data until approval
  15843.             $product->setPendingData(json_encode($productData));
  15844.             $this->ApproveProductAction($id);
  15845.             $em_local->persist($product);
  15846.             // Process category (Save directly)
  15847.             if ($categoryData) {
  15848.                 $category $em_local->getRepository('ApplicationBundle\\Entity\\InvProductCategories')->find($categoryData['id']) ?? new InvProductCategories();
  15849.                 foreach ($categoryData as $field => $value) {
  15850.                     if ($field === 'id') continue;
  15851.                     $setterMethod 'set' ucfirst($field);
  15852.                     if (method_exists($category$setterMethod)) {
  15853.                         $category->$setterMethod($value);
  15854.                     }
  15855.                 }
  15856.                 $em_local->persist($category);
  15857.             }
  15858.             // process brand data
  15859.             if($brandData){
  15860.                 $brand $em_local->getRepository('ApplicationBundle\\Entity\\BrandCompany')->find($brandData['id']) ?? new BrandCompany();
  15861.                 foreach ($brandData as $field => $value){
  15862.                     if($field === 'id') continue;
  15863.                     $setterMethod 'set'.ucfirst($field);
  15864.                     if(method_exists($brand,$setterMethod)){
  15865.                         $brand->$setterMethod($value);
  15866.                     }
  15867.                 }
  15868.                 $em_local->persist($brand);
  15869.             }
  15870.             $em_local->flush();
  15871.             return new JsonResponse(['globalId' => $product->getId()]);
  15872.         }
  15873.         return new JsonResponse("Product (pending) and category updated successfully in central!");
  15874.     }
  15875.     public function CheckGlobalProductAction(Request $request)
  15876.     {
  15877.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15878.         if ($systemType !== '_CENTRAL_') {
  15879.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  15880.         }
  15881.         $em $this->getDoctrine()->getManager();
  15882.         $igName      trim($request->request->get('igName'''));
  15883.         $productName trim($request->request->get('productName'''));
  15884.         $modelNo     trim($request->request->get('modelNo'''));
  15885.         if (!$igName || !$productName) {
  15886.             return new JsonResponse(['success' => false'found' => false'message' => 'igName and productName are required']);
  15887.         }
  15888.         $ig $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(['name' => $igName'type' => 1]);
  15889.         if (!$ig) {
  15890.             return new JsonResponse(['success' => true'found' => false]);
  15891.         }
  15892.         $product null;
  15893.         if ($modelNo) {
  15894.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'modelNo' => $modelNo]);
  15895.         }
  15896.         if (!$product) {
  15897.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'name' => $productName]);
  15898.         }
  15899.         if (!$product) {
  15900.             return new JsonResponse(['success' => true'found' => false]);
  15901.         }
  15902.         return new JsonResponse(['success' => true'found' => true'globalId' => $product->getGlobalId() ?: $product->getId()]);
  15903.     }
  15904.     /** Tenant-side: pull this product's canonical version from the central catalog, overwriting local drift. */
  15905.     public function ResetProductFromCentralAction(Request $request$id)
  15906.     {
  15907.         $em $this->getDoctrine()->getManager();
  15908.         $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find((int) $id);
  15909.         if (!$product) {
  15910.             return new JsonResponse(['success' => false'message' => 'Product not found.'], 404);
  15911.         }
  15912.         $res = \ApplicationBundle\Modules\Inventory\Inventory::ResetLocalProductFromCentral($em$product);
  15913.         return new JsonResponse($res, !empty($res['success']) ? 200 400);
  15914.     }
  15915.     public function SearchGlobalProductsAction(Request $request)
  15916.     {
  15917.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15918.         if ($systemType !== '_CENTRAL_') {
  15919.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  15920.         }
  15921.         $em          $this->getDoctrine()->getManager();
  15922.         $query       trim($request->request->get('query'''));
  15923.         $igName      trim($request->request->get('igName'''));
  15924.         $modelNo     trim($request->request->get('modelNo'''));
  15925.         $globalId    = (int)$request->request->get('globalId'0);
  15926.         $limit       min((int)$request->request->get('limit'10), 25);
  15927.         if ($globalId 0) {
  15928.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  15929.             if (!$product) {
  15930.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  15931.             }
  15932.             if (!$product) {
  15933.                 return new JsonResponse(['success' => true'count' => 0'results' => []]);
  15934.             }
  15935.             $ig $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->find($product->getIgId());
  15936.             return new JsonResponse(['success' => true'count' => 1'results' => [
  15937.                 $this->buildGlobalProductRow($em$product$ig),
  15938.             ]]);
  15939.         }
  15940.         if (strlen($query) < && !$modelNo) {
  15941.             return new JsonResponse(['success' => false'message' => 'query must be at least 2 characters'], 400);
  15942.         }
  15943.         $conn $em->getConnection();
  15944.         // The central catalog DB is lean â€” it may not carry the full ERP inventory schema
  15945.         // (e.g. inv_product_brand). A LEFT JOIN still hard-fails on a missing table, so only join
  15946.         // the enrichment tables that actually exist; absent ones fall back to an empty literal.
  15947.         $existingTables = [];
  15948.         $productCols = [];
  15949.         try {
  15950.             foreach ($this->dbalFetchAllAssoc(
  15951.                 $conn,
  15952.                 "SELECT table_name AS t FROM information_schema.tables WHERE table_schema = DATABASE()"
  15953.             ) as $r) {
  15954.                 $existingTables[strtolower($r['t'])] = true;
  15955.             }
  15956.             // Also detect which COLUMNS exist on inv_products â€” a lean central may be missing
  15957.             // optional columns (description, alias, model_no, global_id, sync_flag, â€¦).
  15958.             foreach ($this->dbalFetchAllAssoc(
  15959.                 $conn,
  15960.                 "SELECT column_name AS c FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'inv_products'"
  15961.             ) as $r) {
  15962.                 $productCols[strtolower($r['c'])] = true;
  15963.             }
  15964.         } catch (\Throwable $e) { /* detection failed â†’ assume everything exists (old behaviour) */ }
  15965.         $hasTable = function ($t) use ($existingTables) {
  15966.             return empty($existingTables) || isset($existingTables[strtolower($t)]);
  15967.         };
  15968.         $hasCol = function ($c) use ($productCols) {
  15969.             return empty($productCols) || isset($productCols[strtolower($c)]);
  15970.         };
  15971.         $hasModelNo $hasCol('model_no');
  15972.         $where = [];
  15973.         $params = [];
  15974.         if ($query !== '') {
  15975.             $where[] = $hasModelNo '(p.name LIKE :q OR p.model_no LIKE :q)' 'p.name LIKE :q';
  15976.             $params['q'] = '%' $query '%';
  15977.         }
  15978.         if ($modelNo !== '' && $hasModelNo) {
  15979.             $where[] = 'p.model_no LIKE :model';
  15980.             $params['model'] = '%' $modelNo '%';
  15981.         }
  15982.         if ($igName !== '' && $hasTable('inv_item_group')) {
  15983.             $where[] = 'ig.name = :igName';
  15984.             $params['igName'] = $igName;
  15985.         }
  15986.         $whereSql $where ? ('WHERE ' implode(' AND '$where)) : '';
  15987.         // Base columns on inv_products â€” include only those that exist; missing ones become ''.
  15988.         $baseColumns = [
  15989.             ['id',          'p.id'],
  15990.             ['name',        'p.name'],
  15991.             ['modelNo',     'p.model_no'],
  15992.             ['productFdm',  'p.product_fdm'],
  15993.             ['globalId',    'p.global_id'],
  15994.             ['syncFlag',    'p.sync_flag'],
  15995.             ['description''p.description'],
  15996.             ['alias',       'p.alias'],
  15997.         ];
  15998.         $selects = [];
  15999.         foreach ($baseColumns as $bc) {
  16000.             list($as$col) = $bc;
  16001.             $rawCol substr($col2); // strip "p."
  16002.             if ($hasCol($rawCol)) {
  16003.                 $selects[] = ($rawCol === $as) ? $col : ($col ' AS ' $as);
  16004.             } else {
  16005.                 $selects[] = "'' AS $as";
  16006.             }
  16007.         }
  16008.         $joins '';
  16009.         $enrich = [
  16010.             ['inv_item_group',            'ig',  'ig.id = p.ig_id',                              'ig.name',       'igName'],
  16011.             ['inv_product_categories',    'cat''cat.id = p.category_id',                       'cat.name',      'categoryName'],
  16012.             ['inv_product_sub_categories','sub''sub.id = p.sub_category_id',                   'sub.name',      'subCategoryName'],
  16013.             ['brand_company',             'br',  'br.id = p.brand_company',                      'br.name',       'brandName'],
  16014.             ['unit_type',                 'ut',  'ut.id = p.unit_type_id',                       'ut.name',       'uomName'],
  16015.             ['inv_product_images',        'img''img.product_id = p.id AND img.is_default = 1''img.file_name''image'],
  16016.         ];
  16017.         foreach ($enrich as $e) {
  16018.             list($tbl$alias$on$col$as) = $e;
  16019.             if ($hasTable($tbl)) {
  16020.                 $selects[] = "$col AS $as";
  16021.                 $joins   .= "\n                LEFT JOIN $tbl $alias ON $on";
  16022.             } else {
  16023.                 $selects[] = "'' AS $as";
  16024.             }
  16025.         }
  16026.         // ORDER BY: exact-name first; the model_no tier only when that column exists.
  16027.         $orderSql "ORDER BY CASE WHEN p.name = :exactName THEN 0 ";
  16028.         if ($hasModelNo) {
  16029.             $orderSql .= "WHEN p.model_no = :exactModel THEN 1 ";
  16030.         }
  16031.         $orderSql .= "ELSE 2 END, p.name ASC";
  16032.         $sql "SELECT " implode(', '$selects) . "
  16033.                 FROM inv_products p" $joins "
  16034.                 $whereSql
  16035.                 $orderSql
  16036.                 LIMIT :lim";
  16037.         $params['exactName']  = $query ?: '';
  16038.         if ($hasModelNo) {
  16039.             $params['exactModel'] = $modelNo ?: $query;
  16040.         }
  16041.         $params['lim']        = $limit;
  16042.         $types = [];
  16043.         foreach ($params as $key => $val) {
  16044.             $types[$key] = is_int($val) ? \PDO::PARAM_INT : \PDO::PARAM_STR;
  16045.         }
  16046.         $rows $this->dbalFetchAllAssoc($conn$sql$params$types);
  16047.         foreach ($rows as &$row) {
  16048.             $row['globalId'] = (int)($row['globalId'] ?: $row['id']);
  16049.         }
  16050.         return new JsonResponse(['success' => true'count' => count($rows), 'results' => $rows]);
  16051.     }
  16052.     /**
  16053.      * Fetch all rows as associative arrays, portable across Doctrine DBAL versions.
  16054.      * The central server runs an older DBAL where fetchAllAssociative() does not exist â€” fall
  16055.      * back to the legacy Connection::fetchAll(). Both accept ($sql, $params, $types).
  16056.      */
  16057.     private function dbalFetchAllAssoc($conn$sql, array $params = [], array $types = [])
  16058.     {
  16059.         if (method_exists($conn'fetchAllAssociative')) {
  16060.             return $conn->fetchAllAssociative($sql$params$types);
  16061.         }
  16062.         return $conn->fetchAll($sql$params$types);
  16063.     }
  16064.     private function buildGlobalProductRow($em$product$ig)
  16065.     {
  16066.         $categoryName '';
  16067.         $subCategoryName '';
  16068.         $brandName '';
  16069.         $uomName '';
  16070.         // Enrichment tables may be absent on a lean central DB â€” never let a missing one break the row.
  16071.         try {
  16072.             if ($product->getCategoryId()) {
  16073.                 $cat $em->getRepository('ApplicationBundle\\Entity\\InvProductCategories')->find($product->getCategoryId());
  16074.                 if ($cat$categoryName $cat->getName();
  16075.             }
  16076.         } catch (\Throwable $e) { /* table absent */ }
  16077.         try {
  16078.             if ($product->getSubCategoryId()) {
  16079.                 $sub $em->getRepository('ApplicationBundle\\Entity\\InvProductSubCategories')->find($product->getSubCategoryId());
  16080.                 if ($sub$subCategoryName $sub->getName();
  16081.             }
  16082.         } catch (\Throwable $e) { /* table absent */ }
  16083.         try {
  16084.             if ($product->getBrandCompany()) {
  16085.                 $br $em->getRepository('ApplicationBundle\\Entity\\BrandCompany')->find($product->getBrandCompany());
  16086.                 if ($br$brandName $br->getName();
  16087.             }
  16088.         } catch (\Throwable $e) { /* table absent */ }
  16089.         try {
  16090.             if ($product->getUnitTypeId()) {
  16091.                 $ut $em->getRepository('ApplicationBundle\\Entity\\UnitType')->find($product->getUnitTypeId());
  16092.                 if ($ut$uomName $ut->getName();
  16093.             }
  16094.         } catch (\Throwable $e) { /* table absent */ }
  16095.         $row = [
  16096.             'id'              => $product->getId(),
  16097.             'globalId'        => $product->getGlobalId() ?: $product->getId(),
  16098.             'name'            => $product->getName(),
  16099.             'modelNo'         => $product->getModelNo(),
  16100.             'productFdm'      => $product->getProductFdm(),
  16101.             'description'     => $product->getNote(),
  16102.             'alias'           => $product->getAlias(),
  16103.             'igName'          => $ig $ig->getName() : '',
  16104.             'categoryName'    => $categoryName,
  16105.             'subCategoryName' => $subCategoryName,
  16106.             'brandName'       => $brandName,
  16107.             'uomName'         => $uomName,
  16108.             'image'           => '',
  16109.         ];
  16110.         // Publish the full descriptive catalog field set (specs, sizes, weights,
  16111.         // crate data, etc.) so a synced ERP can mirror almost the entire record.
  16112.         foreach (\ApplicationBundle\Modules\Inventory\Inventory::globalCatalogFields() as $field) {
  16113.             $getter 'get' ucfirst($field);
  16114.             if (method_exists($product$getter)) {
  16115.                 $row[$field] = $product->$getter();
  16116.             }
  16117.         }
  16118.         // Publish the spec table resolved to spec-type NAMES so a synced ERP can
  16119.         // recreate any missing spec type and carry the full spec table.
  16120.         $specDataNamed = [];
  16121.         try {
  16122.             $specArr $product->getSpecData() ? json_decode($product->getSpecData(), true) : [];
  16123.             if (is_array($specArr)) {
  16124.                 foreach ($specArr as $sd) {
  16125.                     $sid = isset($sd['id']) ? $sd['id'] : null;
  16126.                     if (!$sid) continue;
  16127.                     $st $em->getRepository('ApplicationBundle\\Entity\\SpecType')->find($sid);
  16128.                     $specDataNamed[] = ['name' => $st $st->getName() : '''value' => isset($sd['value']) ? $sd['value'] : ''];
  16129.                 }
  16130.             }
  16131.         } catch (\Throwable $e) { /* spec table absent on lean central */ }
  16132.         $row['specDataNamed'] = $specDataNamed;
  16133.         return $row;
  16134.     }
  16135.     public function RegisterGlobalProductAction(Request $request)
  16136.     {
  16137.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16138.         if ($systemType !== '_CENTRAL_') {
  16139.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16140.         }
  16141.         $em $this->getDoctrine()->getManager();
  16142.         $igName      trim($request->request->get('igName'''));
  16143.         $productName trim($request->request->get('productName'''));
  16144.         $modelNo     trim($request->request->get('modelNo'''));
  16145.         $productFdm  $request->request->get('productFdm''');
  16146.         if (!$igName || !$productName) {
  16147.             return new JsonResponse(['success' => false'message' => 'igName and productName are required'], 400);
  16148.         }
  16149.         $ig $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(['name' => $igName'type' => 1]);
  16150.         if (!$ig) {
  16151.             $ig = new \ApplicationBundle\Entity\InvItemGroup();
  16152.             $ig->setName($igName);
  16153.             $ig->setType(1);
  16154.             $em->persist($ig);
  16155.             $em->flush();
  16156.             $ig->setGlobalId($ig->getId());
  16157.             $em->flush();
  16158.         }
  16159.         // Race-condition guard: check again after potential ig creation
  16160.         $existing null;
  16161.         if ($modelNo) {
  16162.             $existing $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'modelNo' => $modelNo]);
  16163.         }
  16164.         if (!$existing) {
  16165.             $existing $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'name' => $productName]);
  16166.         }
  16167.         if ($existing) {
  16168.             return new JsonResponse(['success' => true'globalId' => $existing->getGlobalId() ?: $existing->getId()]);
  16169.         }
  16170.         $product = new \ApplicationBundle\Entity\InvProducts();
  16171.         $product->setName($productName);
  16172.         $product->setModelNo($modelNo);
  16173.         $product->setProductFdm($productFdm);
  16174.         $product->setIgId($ig->getId());
  16175.         $product->setSyncFlag(2);
  16176.         $em->persist($product);
  16177.         $em->flush();
  16178.         $product->setGlobalId($product->getId());
  16179.         $em->flush();
  16180.         return new JsonResponse(['success' => true'globalId' => $product->getId()]);
  16181.     }
  16182.     public function PushGlobalProductToErpsAction(Request $request)
  16183.     {
  16184.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16185.         if ($systemType !== '_CENTRAL_') {
  16186.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16187.         }
  16188.         $globalId = (int)$request->request->get('globalId'0);
  16189.         $data     $request->request->get('data', []);
  16190.         if (!$globalId) {
  16191.             return new JsonResponse(['success' => false'message' => 'globalId is required'], 400);
  16192.         }
  16193.         // Build the full central record ONCE (descriptive fields + igName/category +
  16194.         // named spec list) so each tenant sync applies it without calling back.
  16195.         $em $this->getDoctrine()->getManager();
  16196.         $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  16197.         if (!$product$product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  16198.         if (!$product) {
  16199.             return new JsonResponse(['success' => false'message' => 'Central product not found for globalId ' $globalId], 404);
  16200.         }
  16201.         $ig  $product->getIgId() ? $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->find($product->getIgId()) : null;
  16202.         $row $this->buildGlobalProductRow($em$product$ig);
  16203.         $em_goc $this->getDoctrine()->getManager('company_group');
  16204.         $em_goc->getConnection()->connect();
  16205.         if (!$em_goc->getConnection()->isConnected()) {
  16206.             return new JsonResponse(['success' => false'message' => 'Cannot connect to company_group DB'], 500);
  16207.         }
  16208.         $gocList $em_goc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy(['active' => 1]);
  16209.         // Tenants live on DIFFERENT servers (their DBs are localhost to THEIR server,
  16210.         // not to central). So push once to each distinct server, and let that server's
  16211.         // receiver update ALL of its own local tenants. Resolve the address from
  16212.         // company_group_server_address â€” the field that's actually populated; the old
  16213.         // loop read *_domain_full_link (NULL for everyone), which is why it collapsed
  16214.         // to "1 server" and never reached SG.
  16215.         $seen = [];
  16216.         $servers = [];
  16217.         foreach ($gocList as $entry) {
  16218.             $addr rtrim(
  16219.                 ($entry->getCompanyGroupServerAddress() ?: $entry->getCurrentServerAddress())
  16220.                 ?: ($entry->getCurrentServerDomainFullLink() ?: ($entry->getCompanyGroupServerDomainFullLink() ?: '')),
  16221.                 '/'
  16222.             );
  16223.             if (!$addr || isset($seen[$addr])) continue;
  16224.             $seen[$addr] = true;
  16225.             $servers[] = $addr;
  16226.         }
  16227.         $results = [];
  16228.         $tenantsUpdated 0;
  16229.         foreach ($servers as $addr) {
  16230.             $curl curl_init();
  16231.             curl_setopt_array($curl, [
  16232.                 CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  16233.                 CURLOPT_URL => $addr '/api/sync_product_from_central',
  16234.                 CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 90// receiver loops its tenants
  16235.                 CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  16236.                 CURLOPT_POSTFIELDS => http_build_query(['globalId' => $globalId'data' => $row'force' => 1]),
  16237.             ]);
  16238.             $response  curl_exec($curl);
  16239.             $curlError curl_error($curl);
  16240.             curl_close($curl);
  16241.             $decoded $curlError ? ['error' => $curlError] : json_decode($responsetrue);
  16242.             $results[$addr] = $decoded;
  16243.             if (is_array($decoded) && !empty($decoded['tenants_updated'])) {
  16244.                 $tenantsUpdated += (int) $decoded['tenants_updated'];
  16245.             }
  16246.         }
  16247.         return new JsonResponse([
  16248.             'success'         => true,
  16249.             'globalId'        => $globalId,
  16250.             'pushed'          => count($servers),   // UI label: "Pushed to N server(s)"
  16251.             'servers'         => count($servers),
  16252.             'tenants_updated' => $tenantsUpdated,
  16253.             'results'         => $results,
  16254.         ]);
  16255.     }
  16256.     public function SuggestProductUpdateAction(Request $request)
  16257.     {
  16258.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16259.         if ($systemType !== '_CENTRAL_') {
  16260.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16261.         }
  16262.         $em             $this->getDoctrine()->getManager();
  16263.         $globalId       = (int)$request->request->get('globalId'0);
  16264.         $suggestedFields $request->request->get('suggestedFields', []);
  16265.         $suggestedBy    = (int)$request->request->get('suggestedBy'0);
  16266.         $sourceNote     trim($request->request->get('sourceNote'''));
  16267.         if (!$globalId || empty($suggestedFields)) {
  16268.             return new JsonResponse(['success' => false'message' => 'globalId and suggestedFields are required'], 400);
  16269.         }
  16270.         // validate: igId and modelNo cannot be suggested for change
  16271.         $forbidden = ['igId''ig_id''modelNo''model_no'];
  16272.         foreach ($forbidden as $f) {
  16273.             if (isset($suggestedFields[$f])) {
  16274.                 return new JsonResponse(['success' => false'message' => "Field '{$f}' is a global identity anchor and cannot be changed"], 422);
  16275.             }
  16276.         }
  16277.         $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  16278.         if (!$product) {
  16279.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  16280.         }
  16281.         if (!$product) {
  16282.             return new JsonResponse(['success' => false'message' => 'Product not found on central'], 404);
  16283.         }
  16284.         $suggestion = new \ApplicationBundle\Entity\InvProductCentralSuggestion();
  16285.         $suggestion->setGlobalId($globalId);
  16286.         $suggestion->setSuggestedFields(json_encode($suggestedFields));
  16287.         $suggestion->setSuggestedBy($suggestedBy ?: null);
  16288.         $suggestion->setSourceNote($sourceNote ?: null);
  16289.         $suggestion->setStatus(\ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_PENDING);
  16290.         $em->persist($suggestion);
  16291.         $em->flush();
  16292.         return new JsonResponse(['success' => true'suggestionId' => $suggestion->getId()]);
  16293.     }
  16294.     public function ApproveProductAction(Request $request$id)
  16295.     {
  16296.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16297.         if ($systemType !== '_CENTRAL_') {
  16298.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16299.         }
  16300.         $em         $this->getDoctrine()->getManager();
  16301.         $approvedBy = (int)$request->request->get('approvedBy'0);
  16302.         $suggestion $em->getRepository('ApplicationBundle\\Entity\\InvProductCentralSuggestion')->find((int)$id);
  16303.         if (!$suggestion) {
  16304.             return new JsonResponse(['error' => 'Suggestion not found'], 404);
  16305.         }
  16306.         if ($suggestion->getStatus() !== \ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_PENDING) {
  16307.             return new JsonResponse(['error' => 'Suggestion already ' $suggestion->getStatus()], 409);
  16308.         }
  16309.         $globalId $suggestion->getGlobalId();
  16310.         $product  $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  16311.         if (!$product) {
  16312.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  16313.         }
  16314.         if (!$product) {
  16315.             return new JsonResponse(['error' => 'Central product not found for globalId ' $globalId], 404);
  16316.         }
  16317.         $fields   $suggestion->getSuggestedFieldsArray();
  16318.         $locked   = ['igId''ig_id''modelNo''model_no''id''globalId'];
  16319.         $applied  = [];
  16320.         foreach ($fields as $field => $value) {
  16321.             if (in_array($field$lockedtrue)) continue;
  16322.             $setter 'set' ucfirst($field);
  16323.             if (method_exists($product$setter)) {
  16324.                 $product->$setter($value);
  16325.                 $applied[$field] = $value;
  16326.             }
  16327.         }
  16328.         $em->flush();
  16329.         // mark suggestion approved
  16330.         $suggestion->setStatus(\ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_APPROVED);
  16331.         $suggestion->setApprovedBy($approvedBy ?: null);
  16332.         $suggestion->setApprovedAt(new \DateTime());
  16333.         $em->flush();
  16334.         // propagate approved changes to all linked ERP servers
  16335.         $em_goc $this->getDoctrine()->getManager('company_group');
  16336.         $gocList = [];
  16337.         try {
  16338.             $gocList $em_goc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy(['active' => 1]);
  16339.         } catch (\Exception $e) {}
  16340.         $seenServers = [];
  16341.         $pushResults = [];
  16342.         foreach ($gocList as $entry) {
  16343.             $serverAddress rtrim(
  16344.                 $entry->getCurrentServerDomainFullLink() ?: $entry->getCompanyGroupServerDomainFullLink(),
  16345.                 '/'
  16346.             );
  16347.             if (!$serverAddress || isset($seenServers[$serverAddress])) continue;
  16348.             $seenServers[$serverAddress] = true;
  16349.             $curl curl_init();
  16350.             curl_setopt_array($curl, [
  16351.                 CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  16352.                 CURLOPT_URL => $serverAddress '/api/sync_product_from_central',
  16353.                 CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 15,
  16354.                 CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  16355.                 CURLOPT_POSTFIELDS => http_build_query(['globalId' => $globalId'data' => $applied]),
  16356.             ]);
  16357.             $response  curl_exec($curl);
  16358.             $curlError curl_error($curl);
  16359.             curl_close($curl);
  16360.             $pushResults[$serverAddress] = $curlError
  16361.                 ? ['error' => $curlError]
  16362.                 : json_decode($responsetrue);
  16363.         }
  16364.         return new JsonResponse([
  16365.             'success'     => true,
  16366.             'globalId'    => $globalId,
  16367.             'appliedFields' => array_keys($applied),
  16368.             'pushedTo'    => count($seenServers),
  16369.             'pushResults' => $pushResults,
  16370.         ]);
  16371.     }
  16372.     public function RejectProductSuggestionAction(Request $request$id)
  16373.     {
  16374.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16375.         if ($systemType !== '_CENTRAL_') {
  16376.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16377.         }
  16378.         $em           $this->getDoctrine()->getManager();
  16379.         $rejectedBy   = (int)$request->request->get('rejectedBy'0);
  16380.         $rejectionNote trim($request->request->get('rejectionNote'''));
  16381.         $suggestion $em->getRepository('ApplicationBundle\\Entity\\InvProductCentralSuggestion')->find((int)$id);
  16382.         if (!$suggestion) {
  16383.             return new JsonResponse(['error' => 'Suggestion not found'], 404);
  16384.         }
  16385.         if ($suggestion->getStatus() !== \ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_PENDING) {
  16386.             return new JsonResponse(['error' => 'Suggestion already ' $suggestion->getStatus()], 409);
  16387.         }
  16388.         $suggestion->setStatus(\ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_REJECTED);
  16389.         $suggestion->setRejectedBy($rejectedBy ?: null);
  16390.         $suggestion->setRejectedAt(new \DateTime());
  16391.         $suggestion->setRejectionNote($rejectionNote ?: null);
  16392.         $em->flush();
  16393.         return new JsonResponse(['success' => true'suggestionId' => $suggestion->getId()]);
  16394.     }
  16395. }