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

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.         $em $this->getDoctrine()->getManager();
  1325.         $refreshed_opening 0;
  1326.         $last_refresh_date "";
  1327.         $last_refresh_date_obj "";
  1328.         $terminate 0;
  1329.         $companyId $this->getLoggedUserCompanyId($request);
  1330.         $modifyAccTransaction $request->request->has('modify_acc_trans_flag') ? $request->request->get('modify_acc_trans_flag') : 0;
  1331.         $modifyProductionPrice $request->request->has('modify_production_price') ? $request->request->get('modify_production_price') : 0;
  1332. //        $last_refresh_date="";
  1333.         if ($request->isMethod('POST')) {
  1334.             //steps
  1335.             //1. set all inventory to their opening position
  1336.             $assign_list = array();
  1337.             $data = array();
  1338.             if ($request->request->has('inventory_refreshed'))
  1339.                 $refreshed_opening $request->request->get('inventory_refreshed');
  1340.             if ($request->request->has('last_refresh_date'))
  1341.                 $last_refresh_date $request->request->get('last_refresh_date');
  1342.             if ($refreshed_opening == 0) {
  1343. //                System::log_it($this->container->getParameter('kernel.root_dir'), "",
  1344. //                    'inventory_refresh_debug', 0); //last er 1 is append
  1345.                 $new_cc $em
  1346.                     ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  1347.                     ->findOneBy(
  1348.                         array(
  1349.                             'name' => 'accounting_year_start',
  1350.                         )
  1351.                     );
  1352.                 $date_start = new \DateTime($new_cc->getData());
  1353.                 $date_start_str $date_start->format('Y-m-d');
  1354.                 $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  1355. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  1356.                 $stmt $em->getConnection()->fetchAllAssociative($closingQuery);
  1357.                 $iniClosing $stmt;
  1358. //                $stmt = $em->getConnection()->fetchAllAssociative($transQuery);
  1359. //                
  1360. //                $iniTrans = $stmt;
  1361.                 $singleClosing_byProductId = array();
  1362.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1363.                 foreach ($iniClosing as $item) {
  1364.                     if (!isset($singleClosing_byProductId[$item['product_id']])) {
  1365.                         $singleClosing_byProductId[$item['product_id']] = array(
  1366.                             'date' => $item['date'],
  1367.                             'qtyAdd' => $item['qty_addition'],
  1368.                             'qtySub' => '0',
  1369.                             'valueAdd' => $item['addition'],
  1370.                             'valueSub' => '0',
  1371.                             'fromWarehouse' => 0,
  1372.                             'toWarehouse' => $item['warehouse_id'],
  1373.                             'fromWarehouseSub' => 0,
  1374.                             'toWarehouseSub' => $item['action_tag_id'],
  1375.                             'price' => $item['qty_addition'] != ? ($item['addition'] / $item['qty_addition']) : $item['addition']
  1376.                         );
  1377.                     }
  1378.                 }
  1379.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1380. //                foreach ($iniTrans as $item) {
  1381. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  1382. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  1383. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  1384. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  1385. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  1386. //                    }
  1387. //                }
  1388.                 foreach ($singleClosing_byProductId as $key => $item) {
  1389.                     if (!isset($data[$key])) {
  1390.                         $data[$key][] = $item;
  1391.                     }
  1392.                 }
  1393.                 //new one
  1394.                 //chekc if ultra opening stock received note exists if not create it
  1395.                 $mo $em
  1396.                     ->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')
  1397.                     ->findOneBy(
  1398.                         array(
  1399.                             'documentHash' => '_MASTER_OPENING_',
  1400.                             'typeHash' => 'SR',
  1401.                             'prefixHash' => 4,
  1402.                             'assocHash' => '_MASTER_OPENING_',
  1403.                             'numberHash' => 1,
  1404.                         )
  1405.                     );
  1406.                 if (!$mo) {
  1407.                     //doensot exist to add :)
  1408. //                    $products = $post_data->get('products');
  1409. //                    $qty = $post_data->get('qty');
  1410. //                    $note = $post_data->get('note');
  1411.                     $new = new StockReceivedNote();
  1412.                     $new->setStockReceivedNoteDate(new \DateTime($date_start_str));
  1413.                     $new->setCompanyId($companyId);
  1414.                     $new->setDocumentHash('_MASTER_OPENING_');
  1415.                     $new->setTypeHash('SR');
  1416.                     $new->setPrefixHash(4);
  1417.                     $new->setAssocHash('_MASTER_OPENING_');
  1418.                     $new->setNumberHash(1);
  1419.                     $new->setCreditHeadId(0);
  1420.                     $new->setStockTransferId(0);
  1421.                     $new->setSalesOrderId(0);
  1422.                     $new->setType(4);
  1423.                     $new->setStatus(GeneralConstant::ACTIVE);
  1424.                     $new->setWarehouseId(0);
  1425.                     $new->setNote('');
  1426.                     $new->setAutoCreated(1);
  1427.                     $new->setApproved(GeneralConstant::APPROVED);
  1428. //        $new->setIndentTagged(0);
  1429.                     $new->setStage(GeneralConstant::STAGE_COMPLETE);
  1430.                     $new->setCreatedLoginId(0);
  1431.                     $new->setEditedLoginId(0);
  1432.                     $em->persist($new);
  1433.                     $em->flush();
  1434.                     $SRID $new->getStockReceivedNoteId();
  1435.                     $last_refresh_date_obj $new->getStockReceivedNoteDate();
  1436.                     //now add items to details
  1437.                     foreach ($data as $key => $item) {
  1438.                         if (!empty($item)) {
  1439.                             foreach ($item as $entry) {
  1440.                                 $transDate = new \DateTime($entry['date']);
  1441.                                 if ($last_refresh_date_obj == '') {
  1442.                                     $last_refresh_date_obj $transDate;
  1443.                                 } else if ($transDate $last_refresh_date_obj) {
  1444.                                     $last_refresh_date_obj $transDate;
  1445.                                 }
  1446.                                 $new = new StockReceivedNoteItem();
  1447.                                 $new->setStockReceivedNoteId($SRID);
  1448.                                 $new->setStockTransferItemId(0);
  1449.                                 $salesCodeRange = [];
  1450.                                 $salesCodeRangeStr '';
  1451.                                 $new->setSalesCodeRange("[" $salesCodeRangeStr "]");
  1452.                                 $new->setQty($entry['qtyAdd']);
  1453.                                 $new->setPrice($entry['price']);
  1454.                                 $new->setBalance($entry['qtyAdd']);
  1455.                                 $new->setProductId($key);
  1456.                                 $new->setWarrantyMon(0);
  1457.                                 $new->setWarehouseId($entry['toWarehouse']);
  1458.                                 $new->setWarehouseActionId($entry['toWarehouseSub']);
  1459.                                 $em->persist($new);
  1460.                                 $em->flush();
  1461.                             }
  1462.                         }
  1463.                     }
  1464. //                    for ($i = 0; $i < count($products); $i++) {
  1465. //
  1466. //
  1467. //                        $srItem = self::CreateNewStockReceivedNoteItem($em, $post_data, $i, $new->getStockReceivedNoteId(), $LoginID);
  1468. //                    }
  1469.                 }
  1470.                 if ($mo)
  1471.                     $last_refresh_date_obj $mo->getStockReceivedNoteDate();
  1472.                 $last_refresh_date_obj->modify('-1 day');///new so that it willstart form this day on next call
  1473.                 //new ends
  1474.                 //now that we go the data we can empty the closing table
  1475.                 $get_kids_sql "UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  1476. UPDATE `purchase_order` SET expense_amount=0, expense_pending_balance_amount=0, grn_tag_pending_expense_invoice_ids='[]' WHERE 1;
  1477.     truncate `inv_closing_balance`;
  1478.     truncate `inventory_storage`;
  1479.     truncate `inv_item_transaction`;";
  1480. //                $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1481.                 $stmt $em->getConnection()->executeStatement($get_kids_sql);
  1482. //                $stmt;
  1483. //                foreach ($data as $key => $item) {
  1484. //                    if (!empty($item)) {
  1485. //                        foreach ($item as $entry) {
  1486. //                            $transDate = new \DateTime($entry['date']);
  1487. //                            Inventory::addItemToInventoryCompact($em,
  1488. //                                $key,
  1489. //                                $entry['fromWarehouse'],
  1490. //                                $entry['toWarehouse'],
  1491. //                                $entry['fromWarehouseSub'],
  1492. //                                $entry['toWarehouseSub'],
  1493. //                                $transDate,
  1494. //                                $entry['qtyAdd'],
  1495. //                                $entry['qtySub'],
  1496. //                                $entry['valueAdd'],
  1497. //                                $entry['valueSub'],
  1498. //                                $entry['price'],
  1499. //                                $this->getLoggedUserCompanyId($request));
  1500. //                            if ($last_refresh_date_obj == '') {
  1501. //                                $last_refresh_date_obj = $transDate;
  1502. //                            } else if ($transDate < $last_refresh_date_obj) {
  1503. //                                $last_refresh_date_obj = $transDate;
  1504. //                            }
  1505. //                        }
  1506. //                    }
  1507. //                }
  1508.                 $refreshed_opening 1;
  1509. //                $terminate=1;
  1510.                 if ($last_refresh_date_obj == "") {
  1511.                     $last_refresh_date $date_start_str;
  1512.                 } else {
  1513.                     $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1514.                 }
  1515.                 return new JsonResponse(array(
  1516.                     "success" => true,
  1517.                     "last_refresh_date" => $last_refresh_date,
  1518.                     "inventory_refreshed" => $refreshed_opening
  1519.                 ));
  1520.                 //now call the function which will add the 1st ever entry or opening entry
  1521.             }
  1522.             //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  1523.             if ($last_refresh_date != '')
  1524.                 $last_refresh_date_obj = new \DateTime($last_refresh_date);
  1525.             else {
  1526.                 $new_cc $em
  1527.                     ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  1528.                     ->findOneBy(
  1529.                         array(
  1530.                             'name' => 'accounting_year_start',
  1531.                         )
  1532.                     );
  1533.                 $last_refresh_date_obj = new \DateTime($new_cc->getData());
  1534.                 $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1535.             }
  1536.             $last_refresh_date_obj->modify('+1 day');
  1537.             $today = new \DateTime();
  1538.             if ($last_refresh_date_obj $today) {
  1539.                 $terminate 1;
  1540.             }
  1541.             $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1542.             //ok now we got the date so get grn item on this date
  1543.             //GRN
  1544.             $query "SELECT grn_item.*, grn.grn_date, grn.document_hash from  grn_item
  1545.               join grn on grn.grn_id=grn_item.grn_id
  1546.             where grn.grn_date ='" $last_refresh_date " 00:00:00' and grn.approved=1";
  1547.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1548.             $queryData $stmt;
  1549.             $grn_ids = [];
  1550.             foreach ($queryData as $item) {
  1551.                 $data[$item['product_id']][] = array(
  1552.                     'date' => $last_refresh_date,
  1553.                     'entity' => array_flip(GeneralConstant::$Entity_list)['Grn'],
  1554.                     'entityId' => $item['grn_id'],
  1555.                     'colorId' => $item['color_id'],
  1556.                     'sizeId' => $item['size_id'],
  1557.                     'entityDocHash' => $item['document_hash'],
  1558.                     'qtyAdd' => $item['qty'],
  1559.                     'qtySub' => 0,
  1560.                     'valueAdd' => ($item['qty'] * $item['price_with_expense']),
  1561.                     'valueSub' => 0,
  1562.                     'price' => $item['price_with_expense'],
  1563.                     'fromWarehouse' => 0,
  1564.                     'toWarehouse' => $item['warehouse_id'],
  1565.                     'fromWarehouseSub' => 0,
  1566. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1567.                     'toWarehouseSub' => $item['warehouse_action_id']
  1568.                 );
  1569.                 if (!in_array($item['grn_id'], $grn_ids))
  1570.                     $grn_ids[] = $item['grn_id'];
  1571.             }
  1572.             //now add grns
  1573.             foreach ($data as $key => $item) {
  1574.                 if (!empty($item)) {
  1575.                     foreach ($item as $entry) {
  1576.                         $transDate = new \DateTime($entry['date']);
  1577.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1578.                             $key,
  1579.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1580.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1581.                             $entry['fromWarehouse'],
  1582.                             $entry['toWarehouse'],
  1583.                             $entry['fromWarehouseSub'],
  1584.                             $entry['toWarehouseSub'],
  1585.                             $transDate,
  1586.                             $entry['qtyAdd'],
  1587.                             $entry['qtySub'],
  1588.                             $entry['valueAdd'],
  1589.                             $entry['valueSub'],
  1590.                             $entry['price'],
  1591.                             $this->getLoggedUserCompanyId($request),
  1592.                             0,
  1593.                             $entry['entity'],
  1594.                             $entry['entityId'],
  1595.                             $entry['entityDocHash'],
  1596.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_SUPPLER
  1597.                         );
  1598.                         if ($last_refresh_date_obj == '') {
  1599.                             $last_refresh_date_obj $transDate;
  1600.                         } else if ($transDate $last_refresh_date_obj) {
  1601.                             $last_refresh_date_obj $transDate;
  1602.                         }
  1603.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1604.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1605.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1606.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1607.                             "",
  1608.                             'inventory_refresh_debug'1); //last er 1 is append
  1609.                     }
  1610.                 }
  1611.             }
  1612.             ///adding grn vouhcer mod here too incase it wasnot in the distributed IG for heads
  1613. //            $grn=$em->getRepository('ApplicationBundle\\Entity\\Grn')->findBy(array(
  1614. //                'grnId'=>$grn_ids,
  1615. //                'modifyVoucherFlag'=>1 //have to add this flag
  1616. //            ));
  1617.             foreach ($grn_ids as $grn_id) {
  1618.                 if ($modifyAccTransaction == 1)
  1619.                     Inventory::ModifyGrnTransactions($em$grn_id1);
  1620.                 else
  1621.                     Inventory::ModifyGrnTransactions($em$grn_id);
  1622.             }
  1623.             //adding voucher ends
  1624.             $inv_head_list_by_wa = [];
  1625.             $inv_head_list = [];
  1626.             $cogs_head 0;
  1627.             $cogs_head 0;
  1628.             $internal_proj 0;
  1629. //            if ($project) {
  1630. //                if ($project->getProjectType() == 2) {
  1631. //                    $cogs_head = $project->getInternalProjectAssetHeadId();
  1632. //                    $internal_proj = 1;
  1633. //                } else {
  1634. //                    $cogs_head_qry = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1635. //                        'name' => 'cogs'
  1636. //                    ));
  1637. //                    $cogs_head = $cogs_head_qry->getData();
  1638. //                }
  1639. //            } else {
  1640.             $cogs_head_qry $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1641.                 'name' => 'cogs'
  1642.             ));
  1643.             $cogs_head $cogs_head_qry->getData();
  1644. //            }
  1645.             $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');
  1646.             foreach ($warehouse_action_list as $wa) {
  1647.                 $inv_head_data $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1648.                         'name' => 'warehouse_action_' $wa['id'])
  1649.                 );
  1650.                 if ($inv_head_data) {
  1651.                     $inv_head_list_by_wa[$wa['id']] = $inv_head_data->getData();
  1652.                     $inv_head_list[] = $inv_head_data->getData();
  1653.                 }
  1654.             }
  1655.             $data = [];
  1656.             //____________STOCK_RECEIVED___________________
  1657.             $docEntity "StockReceivedNote";
  1658.             $docEntityIdField "stockReceivedNoteId";
  1659.             $accTransactionDataByDocId = [];
  1660.             $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
  1661.               join stock_received_note on stock_received_note.stock_received_note_id=stock_received_note_item.stock_received_note_id
  1662.             where stock_received_note.stock_received_note_date ='" $last_refresh_date " 00:00:00' and stock_received_note.approved=1";
  1663.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1664.             $queryData $stmt;
  1665.             $grn_ids = [];
  1666.             foreach ($queryData as $item) {
  1667.                 $data[$item['product_id']][] = array(
  1668.                     'date' => $last_refresh_date,
  1669.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  1670.                     'entityId' => $item['stock_received_note_id'],
  1671.                     'colorId' => $item['color_id'],
  1672.                     'sizeId' => $item['size_id'],
  1673.                     'type' => $item['type'],
  1674.                     'entityDocHash' => $item['document_hash'],
  1675.                     'qtyAdd' => $item['qty'],
  1676.                     'qtySub' => 0,
  1677.                     'valueAdd' => ($item['qty'] * $item['price']),
  1678.                     'valueSub' => 0,
  1679.                     'price' => $item['price'],
  1680.                     'fromWarehouse' => 0,
  1681.                     'toWarehouse' => $item['warehouse_id'],
  1682.                     'fromWarehouseSub' => 0,
  1683. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1684.                     'toWarehouseSub' => $item['warehouse_action_id']
  1685.                 );
  1686. //                if (!in_array($item['grn_id'], $grn_ids))
  1687. //                    $grn_ids[] = $item['grn_id'];
  1688.             }
  1689.             foreach ($data as $key => $item) {
  1690.                 if (!empty($item)) {
  1691.                     foreach ($item as $entry) {
  1692.                         $transDate = new \DateTime($entry['date']);
  1693.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1694.                             $key,
  1695.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1696.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1697.                             $entry['fromWarehouse'],
  1698.                             $entry['toWarehouse'],
  1699.                             $entry['fromWarehouseSub'],
  1700.                             $entry['toWarehouseSub'],
  1701.                             $transDate,
  1702.                             $entry['qtyAdd'],
  1703.                             $entry['qtySub'],
  1704.                             $entry['valueAdd'],
  1705.                             $entry['valueSub'],
  1706.                             $entry['price'],
  1707.                             $this->getLoggedUserCompanyId($request),
  1708.                             0,
  1709.                             $entry['entity'],
  1710.                             $entry['entityId'],
  1711.                             $entry['entityDocHash'],
  1712.                             $entry['type'] == ?
  1713.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_OPENING :
  1714.                                 ($entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_STOCK_IN :
  1715.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT)
  1716.                         );
  1717.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1718.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1719.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1720.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1721.                             "",
  1722.                             'inventory_refresh_debug'1); //last er 1 is append
  1723.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1724.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1725.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  1726.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  1727.                         else
  1728.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  1729.                         if ($last_refresh_date_obj == '') {
  1730.                             $last_refresh_date_obj $transDate;
  1731.                         } else if ($transDate $last_refresh_date_obj) {
  1732.                             $last_refresh_date_obj $transDate;
  1733.                         }
  1734.                     }
  1735.                 }
  1736.             }
  1737.             if ($modifyAccTransaction == 1) {
  1738.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1739.                     $docHere $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  1740.                         $docEntityIdField => $docId,
  1741.                     ));;
  1742.                     if ($docHere) {
  1743.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1744.                         if ($curr_v_ids == null)
  1745.                             $curr_v_ids = [];
  1746.                         $skipVids = [];
  1747.                         $toChangeVid 0;
  1748.                         $voucher null;
  1749.                         foreach ($curr_v_ids as $vid) {
  1750.                             if (in_array($vid$skipVids))
  1751.                                 continue;
  1752.                             $skipVids[] = $vid//to prevent duplicate query
  1753.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  1754.                                 'transactionId' => $vid,
  1755.                             ));;
  1756.                             if ($voucher) {
  1757.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1758.                                     $toChangeVid $vid;
  1759.                                 } else {
  1760.                                     continue;
  1761.                                 }
  1762.                             }
  1763.                         }
  1764.                         if ($toChangeVid == 0) {
  1765.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1766.                                 $em,
  1767.                                 $docHere->getStockReceivedNoteDate()->format('Y-m-d'),
  1768.                                 0,
  1769.                                 AccountsConstant::VOUCHER_JOURNAL,
  1770.                                 'Journal For Stock Received Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  1771.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1772.                                 'JV',
  1773.                                 'GN',
  1774.                                 0,
  1775.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1776.                                 0,
  1777.                                 $docHere->getCreatedLoginId(),
  1778.                                 $docHere->getCompanyId(),
  1779.                                 '',
  1780.                                 0,
  1781.                                 1
  1782.                             );
  1783.                             $em->flush();
  1784.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  1785.                                 'transactionId' => $toChangeVid,
  1786.                             ));;
  1787.                         }
  1788.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  1789.                         $tot_inv_amount 0;
  1790.                         foreach ($transData as $k => $v) {
  1791.                             $tot_inv_amount += ($v);
  1792.                             Accounts::CreateNewTransactionDetails($em,
  1793.                                 '',
  1794.                                 $toChangeVid,
  1795.                                 Generic::CurrToInt($v),
  1796.                                 $k,
  1797.                                 'Inventory Inward For - ' $docHere->getDocumentHash(),
  1798.                                 AccountsConstant::DEBIT,
  1799.                                 0,
  1800.                                 [],
  1801.                                 [],
  1802.                                 $docHere->getCreatedLoginId()
  1803.                             );
  1804.                         }
  1805.                         $stockReceivedType $docHere->getType();
  1806.                         $to_balance_head 0;
  1807.                         if (in_array($stockReceivedType, [23]))
  1808.                             $to_balance_head $docHere->getCreditHeadId();
  1809.                         else {
  1810.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1811.                                     'name' => 'inv_on_transit_head')
  1812.                             );
  1813.                             if ($inv_transit_head)
  1814.                                 $to_balance_head $inv_transit_head->getData();
  1815.                         }
  1816.                         Accounts::CreateNewTransactionDetails($em,
  1817.                             '',
  1818.                             $toChangeVid,
  1819.                             Generic::CurrToInt($tot_inv_amount),
  1820.                             $to_balance_head,
  1821.                             in_array($stockReceivedType, [23]) ? 'Balancing of Stock in Items for -' $docHere->getDocumentHash() : 'In Transit Items for -' $docHere->getDocumentHash(),
  1822.                             AccountsConstant::CREDIT,
  1823.                             0,
  1824.                             [],
  1825.                             [],
  1826.                             $docHere->getCreatedLoginId()
  1827.                         );
  1828.                         if ($voucher)
  1829.                             $voucher->setTransactionAmount($tot_inv_amount);
  1830.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1831.                         if ($curr_v_ids != null)
  1832.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1833.                         else
  1834.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1835.                         $em->flush();
  1836. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  1837.                     }
  1838.                 }
  1839.             }
  1840.             $data = [];
  1841.             $query "SELECT purchase_invoice.* from  purchase_invoice
  1842. where purchase_invoice.purchase_invoice_date ='" $last_refresh_date " 00:00:00' and purchase_invoice.approved=1
  1843.             ";
  1844.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1845.             $queryData $stmt;
  1846.             foreach ($queryData as $pi) {
  1847.                 $transDate = new \DateTime($pi['purchase_invoice_date']);
  1848.                 if ($last_refresh_date_obj == '') {
  1849.                     $last_refresh_date_obj $transDate;
  1850.                 } else if ($transDate $last_refresh_date_obj) {
  1851.                     $last_refresh_date_obj $transDate;
  1852.                 }
  1853.                 Accounts::CalibrateProductPriceWithPi($em$pi['purchase_invoice_id'], 1);
  1854.             }
  1855.             $data = [];
  1856.             $query "SELECT expense_invoice.* from  expense_invoice
  1857. where expense_invoice.expense_invoice_date ='" $last_refresh_date " 00:00:00' and expense_invoice.approved=1 and
  1858.             expense_invoice_type_id=1";
  1859.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1860.             $queryData $stmt;
  1861.             foreach ($queryData as $ei) {
  1862.                 $transDate = new \DateTime($ei['expense_invoice_date']);
  1863.                 if ($last_refresh_date_obj == '') {
  1864.                     $last_refresh_date_obj $transDate;
  1865.                 } else if ($transDate $last_refresh_date_obj) {
  1866.                     $last_refresh_date_obj $transDate;
  1867.                 }
  1868.                 $grn_ids json_decode($ei['grn_id_list'], true);
  1869.                 if ($grn_ids == null)
  1870.                     $grn_ids = [];
  1871. //                if (!empty($grn_ids)) {
  1872. //
  1873. //
  1874. //                        if ($ei->getExpenseInvocationStrategyOnGrn() != 2) {
  1875. //                            $grn = $em->getRepository('ApplicationBundle\\Entity\\Grn')->findBy(array(
  1876. //                                'purchaseOrderId' => $ei->getPurchaseOrderId()
  1877. //                            ));
  1878. //
  1879. //                        }
  1880. //                        else
  1881. //                        {
  1882. //                            $po = $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(array(
  1883. //                                'purchaseOrderId' => $ei['purchase_order_id']
  1884. //                            ));
  1885. //
  1886. //                            if ($po) {
  1887. //                                $po->setExpenseAmount($po->getExpenseAmount() + $ei['invoice_amount']);
  1888. //                            }
  1889. //                            continue; //grn expense will be there anyway
  1890. //                        }
  1891. //
  1892. //
  1893. //
  1894. //                }
  1895.                 Accounts::CalibrateProductPriceWithExpense($em$ei['expense_invoice_id']);
  1896. //                $po = $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(array(
  1897. //                    'purchaseOrderId' => $ei['purchase_order_id']
  1898. //                ));
  1899. //
  1900. //
  1901. //                //first get the total valuation
  1902. //                if ($po) {
  1903. //                    $total_product_value = 0;
  1904. //                    $total_pending_expense = 0;
  1905. //                    $po_item_data = $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(array(
  1906. ////                'productId' => $item->getProductId(),
  1907. //                        'purchaseOrderId' => $ei['purchase_order_id']
  1908. //                    ));
  1909. //
  1910. //
  1911. //                    foreach ($po_item_data as $it) {
  1912. ////                    $product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(array(
  1913. ////                        'id' => $item->getProductId()
  1914. ////                    ));
  1915. //
  1916. //                        $poqty = $it->getReceived();
  1917. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);
  1918. //                        $total_product_value += (1 * $po_price);
  1919. //
  1920. //
  1921. //                    }
  1922. //
  1923. //
  1924. //                    //now we know the total grn price value. lets get the fraction increase
  1925. //                    $total_pending_expense = $ei['invoice_amount'];
  1926. //                    if ($total_product_value != 0)
  1927. //                        $fraction_increase = ($total_pending_expense) / ($total_product_value);
  1928. //                    else
  1929. //                        $fraction_increase = 0;
  1930. //
  1931. //                    foreach ($po_item_data as $it) {
  1932. //                        $item = $it;
  1933. //                        $product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(array(
  1934. //                            'id' => $it->getProductId()
  1935. //                        ));
  1936. //                        if (!$product)
  1937. //                            continue;
  1938. //
  1939. ////                    $items_in_inventory=$em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(array(
  1940. ////                        'productId'=>$item->getProductId()
  1941. ////                    ));
  1942. //
  1943. //                        $poqty = $it->getReceived();
  1944. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);;
  1945. //
  1946. //                        $existing_qty = $product->getQty();;
  1947. //
  1948. //
  1949. //                        $increased_po_price = ($po_price * $fraction_increase);
  1950. //
  1951. //                        //now lets see homuch is the total price
  1952. //                        $new_purchase_price = $product->getPurchasePrice();
  1953. //
  1954. //                        if ($increased_po_price != 0) {
  1955. //                            $last_grn_item = $em->getRepository('ApplicationBundle\\Entity\\GrnItem')->findOneBy(array(
  1956. //                                'purchaseOrderItemId' => $item->getId()
  1957. //                            ));
  1958. //                            if ($last_grn_item) {
  1959. //
  1960. //                                $data[$last_grn_item->getProductId()][] = array(
  1961. //                                    'date' => $last_refresh_date,
  1962. //
  1963. //                                    'entity' => array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  1964. //                                    'entityId' => $ei['expense_invoice_id'],
  1965. //                                    'colorId' => $last_grn_item->getColorId(),
  1966. //                                    'sizeId' => $last_grn_item->getSizeId(),
  1967. //                                    'entityDocHash' => $ei['document_hash'],
  1968. //                                    'qtyAdd' => 0,
  1969. //                                    'qtySub' => 0,
  1970. //                                    'valueAdd' => $increased_po_price,
  1971. ////                                    'valueAdd' => $increased_po_price>=0?$increased_po_price:0,
  1972. ////                    'valueSub' => ($item['qty'] * $item['price']),
  1973. ////                                    'valueSub' => $increased_po_price<0?((-1)*$increased_po_price):0,
  1974. //                                    'valueSub' => 0,
  1975. //                                    'price' => '_UNSET_',
  1976. //                                    'fromWarehouse' => 0,
  1977. //                                    'toWarehouse' => $last_grn_item->getWarehouseId(),
  1978. //                                    'fromWarehouseSub' => 0,
  1979. ////                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1980. //                                    'toWarehouseSub' => $last_grn_item->getWarehouseActionId()
  1981. //                                );
  1982. //
  1983. ////                                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);
  1984. ////
  1985. ////                                $total_item_price = $increased_po_price + ($product->getPurchasePrice() * ($existing_qty));
  1986. ////                                if ($existing_qty != 0)
  1987. ////                                    $new_purchase_price = $total_item_price / $existing_qty;
  1988. //
  1989. //
  1990. //                                $total_pending_expense -= $increased_po_price;
  1991. //                            }
  1992. //                        }
  1993. //                    }
  1994. //
  1995. //
  1996. //
  1997. //
  1998. //
  1999. //
  2000. //                } else {
  2001. //                    continue;
  2002. //                }
  2003.             }
  2004.             $data = [];
  2005.             //____________STOCK_TRANSFER___________________
  2006.             $docEntity "StockTransfer";
  2007.             $docEntityIdField "stockTransferId";
  2008.             $accTransactionDataByDocId = [];
  2009.             $query "SELECT stock_transfer_item.*,  stock_transfer.stock_transfer_date, stock_transfer.document_hash, stock_transfer.transfer_action_type from  stock_transfer_item
  2010.               join stock_transfer on stock_transfer.stock_transfer_id=stock_transfer_item.stock_transfer_id
  2011.             where stock_transfer.stock_transfer_date ='" $last_refresh_date " 00:00:00' and stock_transfer.approved=1";
  2012.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2013.             $queryData $stmt;
  2014.             $grn_ids = [];
  2015.             foreach ($queryData as $item) {
  2016.                 $data[$item['product_id']][] = array(
  2017.                     'date' => $last_refresh_date,
  2018.                     'transfer_action_type' => $item['transfer_action_type'],
  2019.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  2020.                     'entityId' => $item['stock_transfer_id'],
  2021.                     'colorId' => $item['color_id'],
  2022.                     'sizeId' => $item['size_id'],
  2023.                     'entityDocHash' => $item['document_hash'],
  2024.                     'qtyAdd' => $item['transfer_action_type'] == $item['qty'] : 0,
  2025.                     'qtySub' => $item['qty'],
  2026.                     'valueAdd' => 0,
  2027. //                    'valueSub' => ($item['qty'] * $item['price']),
  2028.                     'valueSub' => '_AUTO_',
  2029.                     'price' => $item['price'],
  2030.                     'fromWarehouse' => $item['warehouse_id'],
  2031.                     'toWarehouse' => $item['transfer_action_type'] == $item['to_warehouse_id'] : 0,
  2032.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  2033. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  2034.                     'toWarehouseSub' => $item['transfer_action_type'] == $item['to_warehouse_action_id'] : 0
  2035.                 );
  2036. //                if (!in_array($item['grn_id'], $grn_ids))
  2037. //                    $grn_ids[] = $item['grn_id'];
  2038.             }
  2039.             //now add grns
  2040.             foreach ($data as $key => $item) {
  2041.                 if (!empty($item)) {
  2042.                     foreach ($item as $entry) {
  2043.                         $transDate = new \DateTime($entry['date']);
  2044.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2045.                             $key,
  2046.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2047.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2048.                             $entry['fromWarehouse'],
  2049.                             $entry['toWarehouse'],
  2050.                             $entry['fromWarehouseSub'],
  2051.                             $entry['toWarehouseSub'],
  2052.                             $transDate,
  2053.                             $entry['qtyAdd'],
  2054.                             $entry['qtySub'],
  2055.                             $entry['valueAdd'],
  2056.                             $entry['valueSub'],
  2057.                             $entry['price'],
  2058.                             $this->getLoggedUserCompanyId($request),
  2059.                             0,
  2060.                             $entry['entity'],
  2061.                             $entry['entityId'],
  2062.                             $entry['entityDocHash'],
  2063.                             $entry['transfer_action_type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_INTER_WAREHOUSE GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT
  2064.                         );
  2065.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2066.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2067.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2068.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2069.                             "",
  2070.                             'inventory_refresh_debug'1); //last er 1 is append
  2071.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2072.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  2073.                         if ($entry['transfer_action_type'] == 4) {
  2074.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2075.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2076.                             else
  2077.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2078.                         }
  2079.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2080.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2081.                         else
  2082.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2083.                         if ($last_refresh_date_obj == '') {
  2084.                             $last_refresh_date_obj $transDate;
  2085.                         } else if ($transDate $last_refresh_date_obj) {
  2086.                             $last_refresh_date_obj $transDate;
  2087.                         }
  2088.                     }
  2089.                 }
  2090.             }
  2091.             if ($modifyAccTransaction == 1) {
  2092.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2093.                     $docHere $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  2094.                         $docEntityIdField => $docId,
  2095.                     ));;
  2096.                     if ($docHere) {
  2097.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2098.                         if ($curr_v_ids == null)
  2099.                             $curr_v_ids = [];
  2100.                         $skipVids = [];
  2101.                         $toChangeVid 0;
  2102.                         $voucher null;
  2103.                         foreach ($curr_v_ids as $vid) {
  2104.                             if (in_array($vid$skipVids))
  2105.                                 continue;
  2106.                             $skipVids[] = $vid//to prevent duplicate query
  2107.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2108.                                 'transactionId' => $vid,
  2109.                             ));;
  2110.                             if ($voucher) {
  2111.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2112.                                     $toChangeVid $vid;
  2113.                                 } else {
  2114.                                     continue;
  2115.                                 }
  2116.                             }
  2117.                         }
  2118.                         if ($toChangeVid == 0) {
  2119.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2120.                                 $em,
  2121.                                 $docHere->getStockTransferDate()->format('Y-m-d'),
  2122.                                 0,
  2123.                                 AccountsConstant::VOUCHER_JOURNAL,
  2124.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  2125.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2126.                                 'JV',
  2127.                                 'GN',
  2128.                                 0,
  2129.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2130.                                 0,
  2131.                                 $docHere->getCreatedLoginId(),
  2132.                                 $docHere->getCompanyId(),
  2133.                                 '',
  2134.                                 0,
  2135.                                 1
  2136.                             );
  2137.                             $em->flush();
  2138.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2139.                                 'transactionId' => $toChangeVid,
  2140.                             ));;
  2141.                         }
  2142.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  2143.                         $tot_inv_amount 0;
  2144.                         foreach ($transData as $k => $v) {
  2145.                             $tot_inv_amount += ($v);
  2146.                             Accounts::CreateNewTransactionDetails($em,
  2147.                                 '',
  2148.                                 $toChangeVid,
  2149.                                 Generic::CurrToInt($v),
  2150.                                 $k,
  2151.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2152.                                 $v >= AccountsConstant::DEBIT AccountsConstant::CREDIT,
  2153.                                 0,
  2154.                                 [],
  2155.                                 [],
  2156.                                 $docHere->getCreatedLoginId()
  2157.                             );
  2158.                         }
  2159. //                        $stockReceivedType = $docHere->getType();
  2160.                         $to_balance_head 0;
  2161.                         if ($docHere->getTransferActionType() == 4) {
  2162.                         } else {
  2163.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  2164.                                     'name' => 'inv_on_transit_head')
  2165.                             );
  2166.                             if ($inv_transit_head)
  2167.                                 $to_balance_head $inv_transit_head->getData();
  2168.                         }
  2169.                         if ($to_balance_head != 0) {
  2170.                             Accounts::CreateNewTransactionDetails($em,
  2171.                                 '',
  2172.                                 $toChangeVid,
  2173.                                 Generic::CurrToInt($tot_inv_amount),
  2174.                                 $to_balance_head,
  2175.                                 'In Transit Items for -' $docHere->getDocumentHash(),
  2176.                                 $tot_inv_amount >= AccountsConstant::CREDIT AccountsConstant::DEBIT,
  2177.                                 0,
  2178.                                 [],
  2179.                                 [],
  2180.                                 $docHere->getCreatedLoginId()
  2181.                             );
  2182.                         }
  2183.                         if ($voucher)
  2184.                             $voucher->setTransactionAmount($tot_inv_amount);
  2185.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2186.                         if ($curr_v_ids != null)
  2187.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2188.                         else
  2189.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2190.                         $em->flush();
  2191. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2192.                     }
  2193.                 }
  2194.             }
  2195.             $data = [];
  2196.             //____________IRR___________________
  2197.             $docEntity "ItemReceivedAndReplacement";
  2198.             $docEntityIdField "itemReceivedAndReplacementId";
  2199.             $accTransactionDataByDocId = [];
  2200.             $query "SELECT irr_item.*,  item_received_replacement.irr_date, item_received_replacement.document_hash from  irr_item
  2201.               join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  2202.             where item_received_replacement.irr_date ='" $last_refresh_date " 00:00:00' and item_received_replacement.approved=1";
  2203.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2204.             $queryData $stmt;
  2205.             $irr_add_data = [];
  2206.             $irr_replace_data = [];
  2207.             $irr_dispose_data = [];
  2208.             foreach ($queryData as $item) {
  2209.                 $irr_add_data[$item['received_product_id']][] = array(
  2210.                     'date' => $last_refresh_date,
  2211.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  2212.                     'entityId' => $item['irr_id'],
  2213.                     'colorId' => $item['received_product_color_id'],
  2214.                     'sizeId' => $item['received_product_color_id'],
  2215.                     'entityDocHash' => $item['document_hash'],
  2216.                     'qtyAdd' => $item['received_qty'],
  2217.                     'qtySub' => 0,
  2218.                     'valueAdd' => ($item['received_qty'] * $item['received_unit_purchase_price']),
  2219.                     'valueSub' => 0,
  2220.                     'price' => $item['received_unit_purchase_price'],
  2221.                     'fromWarehouse' => 0,
  2222.                     'toWarehouse' => $item['received_warehouse_id'],
  2223.                     'fromWarehouseSub' => 0,
  2224.                     'toWarehouseSub' => $item['received_warehouse_action_id']
  2225.                 );
  2226.                 $irr_replace_data[$item['replaced_product_id']][] = array(
  2227.                     'date' => $last_refresh_date,
  2228.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  2229.                     'entityId' => $item['irr_id'],
  2230.                     'colorId' => $item['replaced_product_color_id'],
  2231.                     'sizeId' => $item['replaced_product_color_id'],
  2232.                     'entityDocHash' => $item['document_hash'],
  2233.                     'qtyAdd' => 0,
  2234.                     'qtySub' => $item['replaced_qty'],
  2235.                     'valueAdd' => 0,
  2236.                     'valueSub' => ($item['replaced_qty'] * $item['replaced_unit_purchase_price']),
  2237.                     'price' => $item['replaced_unit_purchase_price'],
  2238.                     'fromWarehouse' => $item['replaced_warehouse_id'],
  2239.                     'toWarehouse' => 0,
  2240.                     'fromWarehouseSub' => $item['replaced_warehouse_action_id'],
  2241.                     'toWarehouseSub' => 0
  2242.                 );
  2243.                 $irr_dispose_data[$item['received_product_id']][] = array(
  2244.                     'date' => $last_refresh_date,
  2245.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  2246.                     'entityId' => $item['irr_id'],
  2247.                     'colorId' => $item['received_product_color_id'],
  2248.                     'sizeId' => $item['received_product_size_id'],
  2249.                     'entityDocHash' => $item['document_hash'],
  2250.                     'qtyAdd' => 0,
  2251.                     'qtySub' => $item['dispose_qty'],
  2252.                     'valueAdd' => 0,
  2253.                     'valueSub' => ($item['dispose_qty'] * $item['received_unit_purchase_price']),
  2254.                     'price' => $item['received_unit_purchase_price'],
  2255.                     'fromWarehouse' => $item['received_warehouse_id'],
  2256.                     'toWarehouse' => 0,
  2257.                     'fromWarehouseSub' => $item['received_warehouse_id'],
  2258.                     'toWarehouseSub' => 0
  2259.                 );
  2260.             }
  2261.             //now add irrs
  2262.             foreach ($irr_add_data as $key => $item) {
  2263.                 if (!empty($item)) {
  2264.                     foreach ($item as $entry) {
  2265.                         $transDate = new \DateTime($entry['date']);
  2266.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2267.                             $key,
  2268.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2269.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2270.                             $entry['fromWarehouse'],
  2271.                             $entry['toWarehouse'],
  2272.                             $entry['fromWarehouseSub'],
  2273.                             $entry['toWarehouseSub'],
  2274.                             $transDate,
  2275.                             $entry['qtyAdd'],
  2276.                             $entry['qtySub'],
  2277.                             $entry['valueAdd'],
  2278.                             $entry['valueSub'],
  2279.                             $entry['price'],
  2280.                             $this->getLoggedUserCompanyId($request),
  2281.                             0,
  2282.                             $entry['entity'],
  2283.                             $entry['entityId'],
  2284.                             $entry['entityDocHash'],
  2285.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2286.                         );
  2287.                         if ($modifiedData)
  2288.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2289.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2290.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2291.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2292.                                 "",
  2293.                                 'inventory_refresh_debug'1); //last er 1 is append
  2294.                         if ($last_refresh_date_obj == '') {
  2295.                             $last_refresh_date_obj $transDate;
  2296.                         } else if ($transDate $last_refresh_date_obj) {
  2297.                             $last_refresh_date_obj $transDate;
  2298.                         }
  2299.                     }
  2300.                 }
  2301.             }
  2302.             foreach ($irr_replace_data as $key => $item) {
  2303.                 if (!empty($item)) {
  2304.                     foreach ($item as $entry) {
  2305.                         $transDate = new \DateTime($entry['date']);
  2306.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2307.                             $key,
  2308.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2309.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2310.                             $entry['fromWarehouse'],
  2311.                             $entry['toWarehouse'],
  2312.                             $entry['fromWarehouseSub'],
  2313.                             $entry['toWarehouseSub'],
  2314.                             $transDate,
  2315.                             $entry['qtyAdd'],
  2316.                             $entry['qtySub'],
  2317.                             $entry['valueAdd'],
  2318.                             $entry['valueSub'],
  2319.                             $entry['price'],
  2320.                             $this->getLoggedUserCompanyId($request),
  2321.                             0,
  2322.                             $entry['entity'],
  2323.                             $entry['entityId'],
  2324.                             $entry['entityDocHash']);
  2325.                         if ($modifiedData)
  2326.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2327.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2328.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2329.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2330.                                 "",
  2331.                                 'inventory_refresh_debug'1); //last er 1 is append
  2332.                         if ($last_refresh_date_obj == '') {
  2333.                             $last_refresh_date_obj $transDate;
  2334.                         } else if ($transDate $last_refresh_date_obj) {
  2335.                             $last_refresh_date_obj $transDate;
  2336.                         }
  2337.                     }
  2338.                 }
  2339.             }
  2340.             foreach ($irr_dispose_data as $key => $item) {
  2341.                 if (!empty($item)) {
  2342.                     foreach ($item as $entry) {
  2343.                         $transDate = new \DateTime($entry['date']);
  2344.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2345.                             $key,
  2346.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2347.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2348.                             $entry['fromWarehouse'],
  2349.                             $entry['toWarehouse'],
  2350.                             $entry['fromWarehouseSub'],
  2351.                             $entry['toWarehouseSub'],
  2352.                             $transDate,
  2353.                             $entry['qtyAdd'],
  2354.                             $entry['qtySub'],
  2355.                             $entry['valueAdd'],
  2356.                             $entry['valueSub'],
  2357.                             $entry['price'],
  2358.                             $this->getLoggedUserCompanyId($request),
  2359.                             0,
  2360.                             $entry['entity'],
  2361.                             $entry['entityId'],
  2362.                             $entry['entityDocHash'],
  2363.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2364.                         );
  2365.                         if ($modifiedData)
  2366.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2367.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2368.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2369.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2370.                                 "",
  2371.                                 'inventory_refresh_debug'1); //last er 1 is append
  2372.                         if ($last_refresh_date_obj == '') {
  2373.                             $last_refresh_date_obj $transDate;
  2374.                         } else if ($transDate $last_refresh_date_obj) {
  2375.                             $last_refresh_date_obj $transDate;
  2376.                         }
  2377.                     }
  2378.                 }
  2379.             }
  2380.             $data = [];
  2381.             //____________DELIVERY_RECEIPT___________________
  2382.             $docEntity "DeliveryReceipt";
  2383.             $docEntityIdField "deliveryReceiptId";
  2384.             $accTransactionDataByDocId = [];
  2385.             $query "SELECT delivery_receipt_item.*, delivery_receipt.delivery_receipt_date, delivery_receipt.document_hash, delivery_receipt.skip_inventory_hit from  delivery_receipt_item
  2386.               join delivery_receipt on delivery_receipt.delivery_receipt_id=delivery_receipt_item.delivery_receipt_id
  2387.             where delivery_receipt.delivery_receipt_date ='" $last_refresh_date " 00:00:00' and delivery_receipt.approved=1";
  2388.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2389.             $queryData $stmt;
  2390.             foreach ($queryData as $item) {
  2391.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  2392.                     ->findOneBy(
  2393.                         array(
  2394.                             'id' => $item['product_id']
  2395.                         )
  2396.                     );
  2397.                 $curr_purchase_price $product->getPurchasePrice();
  2398.                 if ($item['skip_inventory_hit'] != 1) {
  2399.                     $data[$item['product_id']][] = array(
  2400.                         'date' => $last_refresh_date,
  2401.                         'entity' => array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  2402.                         'entityId' => $item['delivery_receipt_id'],
  2403.                         'colorId' => $item['color_id'],
  2404.                         'sizeId' => $item['size_id'],
  2405.                         'entityDocHash' => $item['document_hash'],
  2406.                         'qtyAdd' => 0,
  2407.                         'qtySub' => ($item['qty'] * $item['unit_multiplier']),
  2408.                         'valueAdd' => 0,
  2409.                         'valueSub' => '_AUTO_',
  2410.                         'price' => $curr_purchase_price,
  2411.                         'fromWarehouse' => $item['warehouse_id'],
  2412.                         'toWarehouse' => 0,
  2413.                         'fromWarehouseSub' => $item['warehouse_action_id'] != null $item['warehouse_action_id'] : GeneralConstant::WAREHOUSE_ACTION_GOODS,
  2414.                         'toWarehouseSub' => 0
  2415.                     );
  2416.                 }
  2417.                 $get_kids_sql "UPDATE `delivery_receipt_item` SET current_purchase_price='" $curr_purchase_price "' WHERE id=" $item['id'] . ";";
  2418.                 $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2419.             }
  2420.             foreach ($data as $key => $item) {
  2421.                 if (!empty($item)) {
  2422.                     foreach ($item as $entry) {
  2423.                         $transDate = new \DateTime($entry['date']);
  2424.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2425.                             $key,
  2426.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2427.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2428.                             $entry['fromWarehouse'],
  2429.                             $entry['toWarehouse'],
  2430.                             $entry['fromWarehouseSub'],
  2431.                             $entry['toWarehouseSub'],
  2432.                             $transDate,
  2433.                             $entry['qtyAdd'],
  2434.                             $entry['qtySub'],
  2435.                             $entry['valueAdd'],
  2436.                             $entry['valueSub'],
  2437.                             $entry['price'],
  2438.                             $this->getLoggedUserCompanyId($request),
  2439.                             0,
  2440.                             $entry['entity'],
  2441.                             $entry['entityId'],
  2442.                             $entry['entityDocHash'],
  2443.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2444.                         );
  2445.                         if ($modifiedData)
  2446.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2447.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2448.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2449.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2450.                                 "",
  2451.                                 'inventory_refresh_debug'1); //last er 1 is append
  2452.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2453.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  2454.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2455.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2456.                         else
  2457.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2458.                         if ($last_refresh_date_obj == '') {
  2459.                             $last_refresh_date_obj $transDate;
  2460.                         } else if ($transDate $last_refresh_date_obj) {
  2461.                             $last_refresh_date_obj $transDate;
  2462.                         }
  2463.                     }
  2464.                 }
  2465.             }
  2466.             if ($modifyAccTransaction == 1) {
  2467.                 //for now we are suuming there is only receipt without confirmation needed
  2468.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2469.                     $docHereDr $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  2470.                         $docEntityIdField => $docId,
  2471.                     ));;
  2472.                     $so $em->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findOneBy(
  2473.                         array(
  2474.                             'salesOrderId' => $docHereDr->getSalesOrderId()
  2475.                         )
  2476.                     );
  2477.                     $query $em->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
  2478.                         ->createQueryBuilder('p');
  2479.                     $query->where('p.salesOrderId = :soID')
  2480.                         ->setParameter('soID'$docHereDr->getSalesOrderId());
  2481.                     $query->andWhere("p.deliveryReceiptIds LIKE '%" $docId "%' ");
  2482.                     $query->setMaxResults(1);
  2483.                     $results $query->getQuery()->getResult();
  2484.                     $docHere null;
  2485.                     if (!empty($results))
  2486.                         $docHere $results[0];
  2487.                     if ($docHere) {
  2488.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2489.                         if ($curr_v_ids == null)
  2490.                             $curr_v_ids = [];
  2491.                         $skipVids = [];
  2492.                         $toChangeVid 0;
  2493.                         $voucher null;
  2494.                         foreach ($curr_v_ids as $vid) {
  2495.                             if (in_array($vid$skipVids))
  2496.                                 continue;
  2497.                             $skipVids[] = $vid//to prevent duplicate query
  2498.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2499.                                 'transactionId' => $vid,
  2500.                             ));;
  2501.                             if ($voucher) {
  2502.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2503.                                     $toChangeVid $vid;
  2504.                                 } else {
  2505.                                     continue;
  2506.                                 }
  2507.                                 if (strpos($voucher->getDescription(), 'Inventory') !== false) {
  2508. //                                    echo "Word Found!";
  2509.                                     $toChangeVid $vid;
  2510.                                 } else {
  2511.                                     continue;
  2512.                                 }
  2513.                             }
  2514.                         }
  2515.                         if ($toChangeVid == 0) {
  2516.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2517.                                 $em,
  2518.                                 $docHere->getSalesInvoiceDate()->format('Y-m-d'),
  2519.                                 0,
  2520.                                 AccountsConstant::VOUCHER_JOURNAL,
  2521.                                 'Journal For Inventory balance for Sales Invoice ' $docHere->getDocumentHash(),
  2522.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2523.                                 'JV',
  2524.                                 'GN',
  2525.                                 0,
  2526.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2527.                                 0,
  2528.                                 $docHere->getCreatedLoginId(),
  2529.                                 $docHere->getCompanyId(),
  2530.                                 '',
  2531.                                 0,
  2532.                                 1,
  2533.                                 0''$so->getBranchId(),
  2534.                                 AccountsConstant::INVOICE_REVENUE_JOURNAL,
  2535.                                 array_flip(GeneralConstant::$Entity_list)['SalesInvoice'], $docHere->getSalesInvoiceId(), $docHere->getDocumentHash()
  2536.                             );
  2537.                             $em->flush();
  2538.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  2539.                                 'transactionId' => $toChangeVid,
  2540.                             ));;
  2541.                         }
  2542. //                        DeleteDocument::AccTransactions($em, $toChangeVid, 0);
  2543.                         //now remove cogs or inventory related transactions
  2544.                         $voucherDetails $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(array(
  2545.                             'transactionId' => $toChangeVid,
  2546.                         ));;
  2547.                         foreach ($voucherDetails as $vdtls) {
  2548.                             if (in_array($vdtls->getAccountsHeadId(), $inv_head_list)) {
  2549.                                 $em->remove($vdtls);
  2550.                                 $em->flush();
  2551.                             }
  2552.                             if ($cogs_head == $vdtls->getAccountsHeadId()) {
  2553.                                 $em->remove($vdtls);
  2554.                                 $em->flush();
  2555.                             }
  2556.                         }
  2557.                         $tot_inv_amount 0;
  2558.                         foreach ($transData as $k => $v) {
  2559.                             $tot_inv_amount += ($v);
  2560.                             Accounts::CreateNewTransactionDetails($em,
  2561.                                 '',
  2562.                                 $toChangeVid,
  2563.                                 Generic::CurrToInt($v),
  2564.                                 $k,
  2565.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2566.                                 AccountsConstant::DEBIT,
  2567.                                 0,
  2568.                                 [],
  2569.                                 [],
  2570.                                 $docHere->getCreatedLoginId()
  2571.                             );
  2572.                         }
  2573. //                        $stockReceivedType = $docHere->getType();
  2574.                         $to_balance_head 0;
  2575. //                        if ($docHere->getTransferActionType() == 4)
  2576.                         if (1) {
  2577.                         } else {
  2578.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  2579.                                     'name' => 'inv_on_transit_head')
  2580.                             );
  2581.                             if ($inv_transit_head)
  2582.                                 $to_balance_head $inv_transit_head->getData();
  2583.                         }
  2584.                         if ($to_balance_head != 0) {
  2585.                             Accounts::CreateNewTransactionDetails($em,
  2586.                                 '',
  2587.                                 $toChangeVid,
  2588.                                 Generic::CurrToInt($tot_inv_amount),
  2589.                                 $to_balance_head,
  2590.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  2591.                                 AccountsConstant::CREDIT,
  2592.                                 0,
  2593.                                 [],
  2594.                                 [],
  2595.                                 $docHere->getCreatedLoginId()
  2596.                             );
  2597.                         }
  2598.                         if ($voucher)
  2599.                             $voucher->setTransactionAmount($tot_inv_amount);
  2600.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2601.                         if ($curr_v_ids != null)
  2602.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2603.                         else
  2604.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2605.                         $em->flush();
  2606. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2607.                     }
  2608.                 }
  2609.             }
  2610.             $data = [];
  2611.             //____________STOCK_CONSUMPTION___________________
  2612.             $docEntity "StockConsumptionNote";
  2613.             $docEntityIdField "stockConsumptionNoteId";
  2614.             $accTransactionDataByDocId = [];
  2615.             $query "SELECT stock_consumption_note_item.*,  stock_consumption_note.stock_consumption_note_date, stock_consumption_note.document_hash, stock_consumption_note.data
  2616.               from  stock_consumption_note_item
  2617.               join stock_consumption_note on stock_consumption_note.stock_consumption_note_id=stock_consumption_note_item.stock_consumption_note_id
  2618.             where stock_consumption_note.stock_consumption_note_date ='" $last_refresh_date " 00:00:00' and stock_consumption_note.approved=1";
  2619.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2620.             $queryData $stmt;
  2621.             $consumption_data = [];
  2622.             $produced_data = [];
  2623.             $checked_stcm_ids = [];
  2624.             foreach ($queryData as $item) {
  2625. //                $product=$em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  2626. //                    ->findOneBy(
  2627. //                        array(
  2628. //                            'id'=>$item['product_id']
  2629. //                        )
  2630. //                    );
  2631. //
  2632. //                $curr_purchase_price=$product->getPurchasePrice();
  2633.                 if (!in_array($item['stock_consumption_note_id'], $checked_stcm_ids)) {
  2634.                     $conversion_data json_decode($item['data'], true);
  2635.                     if ($conversion_data == null)
  2636.                         $conversion_data = [];
  2637.                     if (isset($conversion_data['conversionData'])) {
  2638.                         if (isset($conversion_data['conversionData']['converted_products'])) {
  2639.                             $curr_spec_data $conversion_data['conversionData'];
  2640.                             foreach ($curr_spec_data['converted_products'] as $pika_key => $val) {
  2641.                                 $consumption_data[$val][] = array(
  2642.                                     'date' => $last_refresh_date,
  2643.                                     'type' => 2,
  2644.                                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2645.                                     'entityId' => $item['stock_consumption_note_id'],
  2646.                                     'colorId' => isset($curr_spec_data['converted_product_colors'][$pika_key]) ? ($curr_spec_data['converted_product_colors'][$pika_key]) : 0,
  2647.                                     'sizeId' => isset($curr_spec_data['converted_product_sizes'][$pika_key]) ? ($curr_spec_data['converted_product_sizes'][$pika_key]) : 0,
  2648.                                     'entityDocHash' => $item['document_hash'],
  2649.                                     'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_units'][$pika_key]) : 0,
  2650.                                     'qtySub' => 0,
  2651.                                     '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,
  2652.                                     'valueSub' => 0,
  2653.                                     'price' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_unit_price'][$pika_key]) : 0,
  2654.                                     'fromWarehouse' => 0,
  2655.                                     'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key]) ? ($curr_spec_data['converted_warehouseId'][$pika_key]) : 0,
  2656.                                     'fromWarehouseSub' => 0,
  2657.                                     'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key]) ? ($curr_spec_data['converted_warehouseActionId'][$pika_key]) : 0
  2658.                                 );
  2659.                             }
  2660.                         }
  2661.                     }
  2662. //                    if(isset($conversion_data['expenseCost'] ))
  2663. //                    if(isset($conversion_data['expenseCost']['expense_heads'] ))
  2664. //                    {
  2665. //                        $curr_spec_data=$conversion_data['expenseCost'];
  2666. //                        foreach($curr_spec_data['expense_heads'] as $pika_key=>$val)
  2667. //                        {
  2668. //
  2669. //                            $consumption_data[$val][] = array(
  2670. //                                'date' => $last_refresh_date,
  2671. //                                'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2672. //                                'entityId' => $item['stock_consumption_note_id'],
  2673. //                                'entityDocHash' => $item['document_hash'],
  2674. //                                'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_units'][$pika_key]):0,
  2675. //                                'qtySub' => 0,
  2676. //                                '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,
  2677. //                                'valueSub' => 0,
  2678. //                                'price' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_unit_price'][$pika_key]):0,
  2679. //                                'fromWarehouse' => 0,
  2680. //                                'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key])?(1*$curr_spec_data['converted_warehouseId'][$pika_key]):0,
  2681. //                                'fromWarehouseSub' => 0,
  2682. //                                'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key])?(1*$curr_spec_data['converted_warehouseActionId'][$pika_key]):0
  2683. //                            );
  2684. //                        }
  2685. //                    }
  2686.                     $checked_stcm_ids[] = $item['stock_consumption_note_id'];
  2687.                 }
  2688.                 $consumption_data[$item['product_id']][] = array(
  2689.                     'date' => $last_refresh_date,
  2690.                     'type' => 1,
  2691.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2692.                     'entityId' => $item['stock_consumption_note_id'],
  2693.                     'colorId' => $item['color_id'],
  2694.                     'sizeId' => $item['size_id'],
  2695.                     'entityDocHash' => $item['document_hash'],
  2696.                     'qtyAdd' => 0,
  2697.                     'qtySub' => ($item['qty'] * 1),
  2698.                     'valueAdd' => 0,
  2699.                     'valueSub' => (($item['qty']) * ($item['price'])),
  2700.                     'price' => $item['price'],
  2701.                     'fromWarehouse' => $item['warehouse_id'],
  2702.                     'toWarehouse' => 0,
  2703.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  2704.                     'toWarehouseSub' => 0
  2705.                 );
  2706. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2707. //                $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  2708. //                
  2709.             }
  2710.             foreach ($consumption_data as $key => $item) {
  2711.                 if (!empty($item)) {
  2712.                     foreach ($item as $entry) {
  2713.                         $transDate = new \DateTime($entry['date']);
  2714.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2715.                             $key,
  2716.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2717.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2718.                             $entry['fromWarehouse'],
  2719.                             $entry['toWarehouse'],
  2720.                             $entry['fromWarehouseSub'],
  2721.                             $entry['toWarehouseSub'],
  2722.                             $transDate,
  2723.                             $entry['qtyAdd'],
  2724.                             $entry['qtySub'],
  2725.                             $entry['valueAdd'],
  2726.                             $entry['valueSub'],
  2727.                             $entry['price'],
  2728.                             $this->getLoggedUserCompanyId($request),
  2729.                             0,
  2730.                             $entry['entity'],
  2731.                             $entry['entityId'],
  2732.                             $entry['entityDocHash'],
  2733.                             $entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION
  2734.                         );
  2735.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2736.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2737.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2738.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2739.                             "",
  2740.                             'inventory_refresh_debug'1); //last er 1 is append
  2741.                         if ($last_refresh_date_obj == '') {
  2742.                             $last_refresh_date_obj $transDate;
  2743.                         } else if ($transDate $last_refresh_date_obj) {
  2744.                             $last_refresh_date_obj $transDate;
  2745.                         }
  2746.                     }
  2747.                 }
  2748.             }
  2749.             $data = [];
  2750.             //____________PRODUCTION___________________
  2751.             $docEntity "Production";
  2752.             $docEntityIdField "productionId";
  2753.             $accTransactionDataByDocId = [];
  2754.             $consumedAmountByProductionId = [];
  2755.             $query "SELECT * from production_process_settings
  2756.             where approved=1 order by production_process_settings_id asc  ";
  2757.             $stmt $em->getConnection()->fetchAllAssociative($query);
  2758.             $processList $stmt;
  2759. //            $processList=[];
  2760.             foreach ($processList as $process) {
  2761.                 $query "SELECT production_entry_item.*,  production.production_date, production.document_hash
  2762.               from  production_entry_item
  2763.               join production on production_entry_item.production_id=production.production_id
  2764.             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  ";
  2765.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  2766.                 $queryData $stmt;
  2767.                 $produced_data = [];
  2768.                 $rejected_data = [];
  2769.                 $consumed_data = [];
  2770.                 foreach ($queryData as $item) {
  2771. //                $product=$em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  2772. //                    ->findOneBy(
  2773. //                        array(
  2774. //                            'id'=>$item['product_id']
  2775. //                        )
  2776. //                    );
  2777. //
  2778. //                $curr_purchase_price=$product->getPurchasePrice();
  2779.                     if ($item['price'] == '')
  2780.                         $item['price'] = 0;
  2781.                     if ($item['price'] < 0)
  2782.                         $item['price'] = 0;
  2783.                     $item['production_nature_id'];
  2784.                     $consumed_data[$item['product_id']][] = array(
  2785.                         'date' => $last_refresh_date,
  2786.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2787.                         'entityId' => $item['production_id'],
  2788.                         'colorId' => $item['color_id'],
  2789.                         'sizeId' => $item['size_id'],
  2790.                         'entityDocHash' => $item['document_hash'],
  2791.                         'qtyAdd' => 0,
  2792.                         'qtySub' => ($item['additional_consumed_qty'] * 1) + ($item['consumed_qty']),
  2793.                         'valueAdd' => 0,
  2794.                         'valueSub' => '_AUTO_',
  2795.                         'price' => $item['price'],
  2796.                         'fromWarehouse' => $item['warehouse_id'],
  2797.                         'toWarehouse' => 0,
  2798.                         'fromWarehouseSub' => $item['consumed_item_action_tag_id'],
  2799.                         'toWarehouseSub' => 0,
  2800.                         'production_nature_id' => $item['production_nature_id'],
  2801.                     );
  2802.                     $produced_data[$item['product_id']][] = array(
  2803.                         'date' => $last_refresh_date,
  2804.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2805.                         'entityId' => $item['production_id'],
  2806.                         'colorId' => $item['color_id'],
  2807.                         'sizeId' => $item['size_id'],
  2808.                         'entityDocHash' => $item['document_hash'],
  2809.                         'qtyAdd' => ($item['accepted_qty'] * 1),
  2810.                         'qtySub' => 0,
  2811.                         'valueAdd' => (($item['accepted_qty'] * 1) * ($item['price'])),
  2812.                         'valueSub' => 0,
  2813.                         'price' => $item['price'],
  2814.                         'fromWarehouse' => 0,
  2815.                         'toWarehouse' => $item['warehouse_id'],
  2816.                         'fromWarehouseSub' => 0,
  2817.                         'toWarehouseSub' => $item['produced_item_action_tag_id'],
  2818.                         'production_nature_id' => $item['production_nature_id'],
  2819.                     );
  2820.                     $rejected_data[$item['product_id']][] = array(
  2821.                         'date' => $last_refresh_date,
  2822.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2823.                         'entityId' => $item['production_id'],
  2824.                         'colorId' => $item['color_id'],
  2825.                         'sizeId' => $item['size_id'],
  2826.                         'entityDocHash' => $item['document_hash'],
  2827.                         'qtyAdd' => ($item['rejected_qty'] * 1),
  2828.                         'qtySub' => 0,
  2829.                         'valueAdd' => (($item['rejected_qty'] * 1) * ($item['price'])),
  2830.                         'valueSub' => 0,
  2831.                         'price' => $item['price'],
  2832.                         'fromWarehouse' => 0,
  2833.                         'toWarehouse' => $item['warehouse_id'],
  2834.                         'fromWarehouseSub' => 0,
  2835.                         'toWarehouseSub' => $item['rejected_item_action_tag_id'],
  2836.                         'production_nature_id' => $item['production_nature_id'],
  2837.                     );
  2838. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2839. //                $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  2840. //                
  2841.                 }
  2842.                 foreach ($consumed_data as $key => $item) {
  2843.                     if (!empty($item)) {
  2844.                         foreach ($item as $entry) {
  2845.                             $transDate = new \DateTime($entry['date']);
  2846.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2847.                                 $key,
  2848.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2849.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2850.                                 $entry['fromWarehouse'],
  2851.                                 $entry['toWarehouse'],
  2852.                                 $entry['fromWarehouseSub'],
  2853.                                 $entry['toWarehouseSub'],
  2854.                                 $transDate,
  2855.                                 $entry['qtyAdd'],
  2856.                                 $entry['qtySub'],
  2857.                                 $entry['valueAdd'],
  2858.                                 $entry['valueSub'],
  2859.                                 $entry['price'],
  2860.                                 $this->getLoggedUserCompanyId($request),
  2861.                                 0,
  2862.                                 $entry['entity'],
  2863.                                 $entry['entityId'],
  2864.                                 $entry['entityDocHash'],
  2865.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION);
  2866.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2867.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2868.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2869.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2870.                                 "",
  2871.                                 'inventory_refresh_debug'1); //last er 1 is append
  2872.                             if (!isset($consumedAmountByProductionId[$entry['entityId']]))
  2873.                                 $consumedAmountByProductionId[$entry['entityId']] = ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2874.                             else
  2875.                                 $consumedAmountByProductionId[$entry['entityId']] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2876.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2877.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  2878.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2879.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2880.                             else
  2881.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2882.                             if ($last_refresh_date_obj == '') {
  2883.                                 $last_refresh_date_obj $transDate;
  2884.                             } else if ($transDate $last_refresh_date_obj) {
  2885.                                 $last_refresh_date_obj $transDate;
  2886.                             }
  2887.                         }
  2888.                     }
  2889.                 }
  2890.                 foreach ($produced_data as $key => $item) {
  2891.                     if (!empty($item)) {
  2892.                         foreach ($item as $entry) {
  2893.                             $transDate = new \DateTime($entry['date']);
  2894.                             $productionNature $entry['production_nature_id'];
  2895.                             if (in_array($productionNature, [12])) {
  2896.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2897.                                     $key,
  2898.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2899.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2900.                                     $entry['fromWarehouse'],
  2901.                                     $entry['toWarehouse'],
  2902.                                     $entry['fromWarehouseSub'],
  2903.                                     $entry['toWarehouseSub'],
  2904.                                     $transDate,
  2905.                                     $entry['qtyAdd'],
  2906.                                     $entry['qtySub'],
  2907. //                                $entry['valueAdd'],
  2908.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2909.                                     $entry['valueSub'],
  2910.                                     $entry['price'],
  2911.                                     $this->getLoggedUserCompanyId($request),
  2912.                                     0,
  2913.                                     $entry['entity'],
  2914.                                     $entry['entityId'],
  2915.                                     $entry['entityDocHash'],
  2916.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2917.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2918.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2919.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2920.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2921.                                     "",
  2922.                                     'inventory_refresh_debug'1); //last er 1 is append
  2923.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2924.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2925.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2926.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2927.                                 else
  2928.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2929. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2930. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2931. //                            else
  2932. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2933.                             } else {
  2934.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2935.                                     $key,
  2936.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2937.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2938.                                     $entry['fromWarehouse'],
  2939.                                     $entry['toWarehouse'],
  2940.                                     $entry['fromWarehouseSub'],
  2941.                                     $entry['toWarehouseSub'],
  2942.                                     $transDate,
  2943.                                     0,
  2944.                                     0,
  2945. //                                $entry['valueAdd'],
  2946.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2947.                                     0,
  2948.                                     $entry['price'],
  2949.                                     $this->getLoggedUserCompanyId($request),
  2950.                                     0,
  2951.                                     $entry['entity'],
  2952.                                     $entry['entityId'],
  2953.                                     $entry['entityDocHash'],
  2954.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2955.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2956.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2957.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2958.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2959.                                     "",
  2960.                                     'inventory_refresh_debug'1); //last er 1 is append
  2961.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2962.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2963.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2964.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2965.                                 else
  2966.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2967. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2968. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2969. //                            else
  2970. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2971.                             }
  2972.                             if ($last_refresh_date_obj == '') {
  2973.                                 $last_refresh_date_obj $transDate;
  2974.                             } else if ($transDate $last_refresh_date_obj) {
  2975.                                 $last_refresh_date_obj $transDate;
  2976.                             }
  2977.                         }
  2978.                     }
  2979.                 }
  2980.                 foreach ($rejected_data as $key => $item) {
  2981.                     if (!empty($item)) {
  2982.                         foreach ($item as $entry) {
  2983.                             $transDate = new \DateTime($entry['date']);
  2984.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2985.                                 $key,
  2986.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2987.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2988.                                 $entry['fromWarehouse'],
  2989.                                 $entry['toWarehouse'],
  2990.                                 $entry['fromWarehouseSub'],
  2991.                                 $entry['toWarehouseSub'],
  2992.                                 $transDate,
  2993.                                 $entry['qtyAdd'],
  2994.                                 $entry['qtySub'],
  2995.                                 $entry['valueAdd'],
  2996.                                 $entry['valueSub'],
  2997.                                 $entry['price'],
  2998.                                 $this->getLoggedUserCompanyId($request),
  2999.                                 0,
  3000.                                 $entry['entity'],
  3001.                                 $entry['entityId'],
  3002.                                 $entry['entityDocHash'],
  3003.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  3004.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  3005.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  3006.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  3007.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  3008.                                 "",
  3009.                                 'inventory_refresh_debug'1); //last er 1 is append
  3010.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  3011.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  3012.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  3013.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = (-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  3014.                             else
  3015.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ((-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  3016.                             if ($last_refresh_date_obj == '') {
  3017.                                 $last_refresh_date_obj $transDate;
  3018.                             } else if ($transDate $last_refresh_date_obj) {
  3019.                                 $last_refresh_date_obj $transDate;
  3020.                             }
  3021.                         }
  3022.                     }
  3023.                 }
  3024.             }
  3025.             if ($modifyAccTransaction == 1) {
  3026.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  3027.                     $docHere $em->getRepository('ApplicationBundle\\Entity\\' $docEntity)->findOneBy(array(
  3028.                         $docEntityIdField => $docId,
  3029.                     ));;
  3030.                     if ($docHere) {
  3031.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  3032.                         if ($curr_v_ids == null)
  3033.                             $curr_v_ids = [];
  3034.                         $skipVids = [];
  3035.                         $toChangeVid 0;
  3036.                         $voucher null;
  3037.                         foreach ($curr_v_ids as $vid) {
  3038.                             if (in_array($vid$skipVids))
  3039.                                 continue;
  3040.                             $skipVids[] = $vid//to prevent duplicate query
  3041.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  3042.                                 'transactionId' => $vid,
  3043.                             ));;
  3044.                             if ($voucher) {
  3045.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  3046.                                     $toChangeVid $vid;
  3047.                                 } else {
  3048.                                     continue;
  3049.                                 }
  3050.                             }
  3051.                         }
  3052.                         if ($toChangeVid == 0) {
  3053.                             $toChangeVid Accounts::CreateNewTransaction(0,
  3054.                                 $em,
  3055.                                 $docHere->getProductionDate()->format('Y-m-d'),
  3056.                                 0,
  3057.                                 AccountsConstant::VOUCHER_JOURNAL,
  3058.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  3059.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  3060.                                 'JV',
  3061.                                 'GN',
  3062.                                 0,
  3063.                                 Accounts::GetVNoHash($em'jv''gn'0),
  3064.                                 0,
  3065.                                 $docHere->getCreatedLoginId(),
  3066.                                 $docHere->getCompanyId(),
  3067.                                 '',
  3068.                                 0,
  3069.                                 1
  3070.                             );
  3071.                             $em->flush();
  3072.                             $voucher $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  3073.                                 'transactionId' => $toChangeVid,
  3074.                             ));;
  3075.                         }
  3076.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  3077.                         $tot_inv_amount 0;
  3078.                         foreach ($transData as $k => $v) {
  3079.                             $tot_inv_amount += ($v);
  3080.                             Accounts::CreateNewTransactionDetails($em,
  3081.                                 '',
  3082.                                 $toChangeVid,
  3083.                                 Generic::CurrToInt($v),
  3084.                                 $k,
  3085.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  3086.                                 AccountsConstant::DEBIT,
  3087.                                 0,
  3088.                                 [],
  3089.                                 [],
  3090.                                 $docHere->getCreatedLoginId()
  3091.                             );
  3092.                         }
  3093. //                        $stockReceivedType = $docHere->getType();
  3094.                         $to_balance_head 0;
  3095. //                        if ($docHere->getTransferActionType() == 4)
  3096.                         if (1) {
  3097.                         } else {
  3098.                             $inv_transit_head $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  3099.                                     'name' => 'inv_on_transit_head')
  3100.                             );
  3101.                             if ($inv_transit_head)
  3102.                                 $to_balance_head $inv_transit_head->getData();
  3103.                         }
  3104.                         if ($to_balance_head != 0) {
  3105.                             Accounts::CreateNewTransactionDetails($em,
  3106.                                 '',
  3107.                                 $toChangeVid,
  3108.                                 Generic::CurrToInt($tot_inv_amount),
  3109.                                 $to_balance_head,
  3110.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  3111.                                 AccountsConstant::CREDIT,
  3112.                                 0,
  3113.                                 [],
  3114.                                 [],
  3115.                                 $docHere->getCreatedLoginId()
  3116.                             );
  3117.                         }
  3118.                         if ($voucher)
  3119.                             $voucher->setTransactionAmount($tot_inv_amount);
  3120.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  3121.                         if ($curr_v_ids != null)
  3122.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  3123.                         else
  3124.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  3125.                         $em->flush();
  3126. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  3127.                     }
  3128.                 }
  3129.             }
  3130.             if ($terminate == 0) {
  3131.                 return new JsonResponse(array(
  3132.                     "success" => true,
  3133.                     "last_refresh_date" => $last_refresh_date,
  3134.                     "inventory_refreshed" => $refreshed_opening
  3135.                 ));
  3136.             } else {
  3137.                 return new JsonResponse(array(
  3138.                     "success" => false,
  3139.                     "last_refresh_date" => $last_refresh_date,
  3140.                     "inventory_refreshed" => $refreshed_opening
  3141.                 ));
  3142.             }
  3143.         }
  3144.         return new JsonResponse(array(
  3145.             "success" => false,
  3146.             "last_refresh_date" => $last_refresh_date,
  3147.             "inventory_refreshed" => $refreshed_opening
  3148.         ));
  3149.         //2 .now make an array with necessary data based on challan and grn for now willl need consumption later
  3150.         //broken into transactions not closing
  3151.         //structure---> $data['productId']=array(
  3152.         //'date'=>'2017-09-02 00:00:00'
  3153.         //'qtyAdd'=>'2'
  3154.         //'qtySub'=>'0'
  3155.         //'valueAdd'=>'2000'
  3156.         //'valueSub'=>'0'
  3157.         //'fromWarehouse'=>'0'
  3158.         //'toWarehouse'=>'0'
  3159.         //'fromWarehouseSub'=>'0'
  3160.         //'toWarehouseSub'=>'0'
  3161.         //)
  3162.         //
  3163.     }
  3164.     public function OpeningItemAction(Request $request)
  3165.     {
  3166.         $em $this->getDoctrine()->getManager();
  3167.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  3168.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  3169.         if ($request->isMethod('POST')) {
  3170.             $pp trim($request->request->get('purchasePrice'));
  3171. //replace comma with space
  3172.             $pp str_replace(","""$pp);
  3173.             if ($request->request->get('productId') != '') {
  3174.                 foreach ($request->request->get('warehouseId') as $key => $value) {
  3175.                     $data = array(
  3176.                         'productId' => $request->request->get('productId'),
  3177.                         'warehouseId' => $request->request->get('warehouseId')[$key],
  3178.                         'warehouseActionId' => $request->request->get('warehouseActionId')[$key],
  3179.                         'purchasePrice' => $pp,
  3180.                         'date' => new \DateTime($request->request->get('date')),
  3181.                         'qty' => $request->request->get('qty')[$key],
  3182.                     );
  3183.                     $transDate = new \DateTime($request->request->get('date'));
  3184.                     $new = new InvItemInOut();
  3185.                     $new->setProductId($request->request->get('productId'));
  3186.                     $new->setWarehouseId($request->request->get('warehouseId')[$key]);
  3187.                     $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  3188.                     $new->setActionTagId($request->request->get('warehouseActionId')[$key]);
  3189.                     $new->setTransactionDate($transDate);
  3190.                     $new->setQty($request->request->get('qty')[$key]);
  3191.                     $new->setPrice($pp);
  3192.                     $new->setAmount($request->request->get('qty')[$key] * $pp);
  3193.                     $new->setEntity(0);// opening =0
  3194.                     $new->setEntityId(0);// opening =0
  3195.                     $new->setDebitCreditHeadId(0);// opening =0
  3196.                     $new->setVoucherIds(null);// opening =0
  3197.                     $em->persist($new);
  3198.                     $em->flush();
  3199. //                    $total_inv_value_in_by_id += $request->request->get('qty')[$key] * $pp;
  3200.                     Inventory::AddOpeningInventoryStock($em$data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3201.                 }
  3202.             }
  3203.         }
  3204.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  3205.             'name' => 'warehouse_action_1'//for now for stock of goods
  3206.         ));
  3207.         return $this->render('@Inventory/pages/input_forms/opening_item_assign.html.twig',
  3208.             array(
  3209.                 'page_title' => "Opening Items",
  3210.                 'inv_head' => $inv_head $inv_head->getData() : '',
  3211.                 'products' => $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\InvProducts')->findBy(array(
  3212.                     'status' => GeneralConstant::ACTIVE//for now for stock of goods
  3213. //                    'opening_locked'=>0
  3214.                 )),
  3215.                 'warehouseList' => Inventory::WarehouseList($em),
  3216.                 'warehouseActionList' => $warehouse_action_list
  3217.             )
  3218.         );
  3219.     }
  3220.     public function CreateProductCategoryAction(Request $request)
  3221.     {
  3222.         if ($request->isMethod('POST')) {
  3223.             $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));
  3224.             if ($cat_data['id'] != '')
  3225.                 return new JsonResponse(array("success" => true'cat_data' => $cat_data));
  3226.         }
  3227.         return new JsonResponse(array("success" => false,));
  3228. //        return $this->redirectToRoute("create_product");
  3229.     }
  3230.     public function CreateProductSubCategoryAction(Request $request)
  3231.     {
  3232.         if ($request->isMethod('POST')) {
  3233.             $spec_data Inventory::CreateSubCategory($this->getDoctrine()->getManager(),
  3234.                 $this->getLoggedUserCompanyId($request), $request->request->get('spec_name'),
  3235.                 $request->request->get('level'0),
  3236.                 $request->request->get('parentId'0),
  3237.                 $request->request->get('itemgroupId'),
  3238.                 $request->request->get('categoryId'),
  3239.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3240.             if ($spec_data['id'] != '')
  3241.                 return new JsonResponse(array("success" => true'spec_data' => $spec_data'level' => $request->request->get('level'0)));
  3242.         }
  3243.         return new JsonResponse(array("success" => false,));
  3244. //        return $this->redirectToRoute("create_product");
  3245.     }
  3246.     public function CreateProductSpecAction(Request $request)
  3247.     {
  3248.         $em $this->getDoctrine()->getManager();
  3249.         if ($request->isMethod('POST')) {
  3250.             //1st add to cnetral server
  3251.             $spec_data=[
  3252.                 'id' => 0,
  3253.                 'global_id' => 0,
  3254.                 'name' => $request->request->get('name'''),
  3255.                 'unit_text' => $request->request->get('unitText'''),
  3256.                 'unique_hash' => $request->request->get('uniqueHash'''),
  3257.                 'markers' => $request->request->get('markers'''),
  3258.                 'tags' => $request->request->get('tags'''),
  3259.             ];
  3260.             $specType $em->getRepository('ApplicationBundle\\Entity\\SpecType')->findOneBy(array(
  3261.                 'uniqueHash' => $request->request->get('uniqueHash'''),
  3262.             ));
  3263.             if ($specType) {
  3264.                 $spec_data['id'] = $specType->getId();
  3265.                 $spec_data['global_id'] = $specType->getGlobalId();
  3266.             }
  3267.             if(!$spec_data['global_id']) {
  3268.                 $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/api/create_product_spec_public';
  3269.                 $curl curl_init();
  3270.                 curl_setopt_array($curl, [
  3271.                     CURLOPT_RETURNTRANSFER => true,
  3272.                     CURLOPT_POST => true,
  3273.                     CURLOPT_URL => $urlToCall,
  3274.                     CURLOPT_CONNECTTIMEOUT => 10,
  3275.                     CURLOPT_SSL_VERIFYPEER => false,
  3276.                     CURLOPT_SSL_VERIFYHOST => false,
  3277.                     CURLOPT_HTTPHEADER => [],
  3278.                     CURLOPT_POSTFIELDS => http_build_query([
  3279.                         'name' => $request->request->get('name'''),
  3280.                         'unitText' => $request->request->get('unitText'''),
  3281.                         'uniqueHash' => $request->request->get('uniqueHash'''),
  3282.                         'markers' => $request->request->get('markers'''),
  3283.                         'tags' => $request->request->get('tags'''),
  3284.                     ])
  3285.                 ]);
  3286.                 $retData curl_exec($curl);
  3287.                 $errData curl_error($curl);
  3288.                 curl_close($curl);
  3289.                 if ($errData) {
  3290.                     return new JsonResponse(['success' => false]);
  3291.                 }
  3292.                 $retData json_decode($retDatatrue);
  3293.                 $spec_data $retData['spec_data'];
  3294.             }
  3295.             $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  3296.             $spec_data Inventory::CreateProductSpecification($em,
  3297.                 $systemType,
  3298.                 $spec_data['name'],
  3299.                 $spec_data['unit_text'],
  3300.                 $spec_data['unique_hash'],
  3301.                 $spec_data['markers'],
  3302.                 $spec_data['tags'],
  3303.                 $spec_data['global_id'],
  3304.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3305.             );
  3306.             if ($spec_data['id'] != '')
  3307.                 return new JsonResponse(array("success" => true'spec_data' => $spec_data));
  3308.         }
  3309.         return new JsonResponse(array("success" => false,));
  3310. //        return $this->redirectToRoute("create_product");
  3311.     }
  3312.     public function CreateProductBrandAction(Request $request)
  3313.     {
  3314.         if ($request->isMethod('POST')) {
  3315.             $data Inventory::CreateBrand($this->getDoctrine()->getManager(),
  3316.                 $this->getLoggedUserCompanyId($request), $request->request->get('brand_name'),
  3317.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3318.             if ($data['id'] != '')
  3319.                 return new JsonResponse(array("success" => true'data' => $data));
  3320.         }
  3321.         return new JsonResponse(array("success" => false,));
  3322. //        return $this->redirectToRoute("create_product");
  3323.     }
  3324.     public function CreateIssueNoteAction(Request $request)
  3325.     {
  3326.         return $this->render('@Inventory/pages/input_forms/issue_note.html.twig',
  3327.             array(
  3328.                 'page_title' => 'Issue Note'
  3329.             )
  3330.         );
  3331.     }
  3332.     public function ProcessDraftDeliveryReceiptAction(Request $request$id 0)
  3333.     {
  3334.         $em $this->getDoctrine()->getManager();
  3335.         $companyId $this->getLoggedUserCompanyId($request);
  3336.         $extId $id;
  3337.         $receiptId $id;
  3338.         $allowed 0;
  3339.         if ($request->isMethod('POST')) {
  3340.             $receiptId $request->request->get('deliveryReceiptId');
  3341.             $QD $this->getDoctrine()
  3342.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3343.                 ->findOneBy(
  3344.                     array(
  3345.                         'deliveryReceiptId' => $receiptId
  3346.                     ),
  3347.                     array()
  3348.                 );
  3349.             $soId $QD->getSalesOrderId();
  3350.             $drData = [];
  3351.             $dr_item_data $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')->findBy(
  3352.                 array(
  3353.                     'deliveryReceiptId' => $receiptId,
  3354.                 )
  3355.             );
  3356.             foreach ($dr_item_data as $dr_item) {
  3357.                 $drData[] = array(
  3358.                     'soItemId' => $dr_item->getSalesorderItemId(),
  3359.                     'qty' => $dr_item->getQty()
  3360.                 );
  3361.             }
  3362. //            $drData=[
  3363. //                ['soItemId'=>9,'qty'=>9],
  3364. //                ['soItemId'=>9,'qty'=>9],
  3365. //                ['soItemId'=>9,'qty'=>9],
  3366. //            ];
  3367.             $toGetSoItemsId = [];
  3368.             $toGetDoItemsId = [];
  3369.             $drDataBySoItemId = [];
  3370.             $drDataByDoItemId = [];
  3371.             $so $em->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findOneBy(array(
  3372.                 'salesOrderId' => $soId   //$id is soId
  3373.             ));
  3374.             if ($so->getDeliveryOrderSkipFlag() == 1) {
  3375.                 foreach ($drData as $pp) {
  3376.                     $toGetSoItemsId[] = $pp['soItemId'];
  3377.                     $drDataBySoItemId[$pp['soItemId']] = $pp;
  3378.                 }
  3379.             } else {
  3380.                 foreach ($drData as $pp) {
  3381.                     $toGetDoItemsId[] = $pp['soItemId'];
  3382.                     $drDataByDoItemId[$pp['soItemId']] = $pp;
  3383.                 }
  3384.                 $do_item_data $em->getRepository('ApplicationBundle\\Entity\\DeliveryOrderItem')->findBy(
  3385.                     array(
  3386.                         'salesorderId' => $id,
  3387.                         'id' => $toGetDoItemsId
  3388.                     )
  3389.                 );
  3390.                 foreach ($do_item_data as $dd) {
  3391.                     $toGetSoItemsId[] = $dd->getSalesorderItemId();
  3392.                     $drDataBySoItemId[$dd->getSalesorderItemId()] = $drDataByDoItemId[$dd->getId()];
  3393.                 }
  3394. //                $do_item_data = $em->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findOneBy(
  3395. //                    array(
  3396. ////                'salesOrderId'=>$post_data->get('soId', null),
  3397. //                        'id' => $post_data->get('do_details_id')[$key]
  3398. //                    )
  3399. //                );
  3400.             }
  3401.             $so_item_data $em->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')->findBy(
  3402.                 array(
  3403.                     'salesOrderId' => $soId,
  3404.                     'id' => $toGetSoItemsId
  3405.                 )
  3406.             );
  3407.             $prev_so_amount $so->getSoAmount();
  3408.             $total_discounted_amount 0;
  3409.             $total_product_amount 0;
  3410.             $total_discount 0;
  3411.             $total_special_discount $so->getSpecialDiscountAmount();
  3412.             $total_special_discount_rate $so->getSpecialDiscountRate();
  3413.             foreach ($so_item_data as $item) {
  3414.                 $qty $drDataBySoItemId[$item->getId()]['qty'];
  3415.                 $price $item->getPrice();
  3416.                 $amount $qty $price;
  3417.                 $discountAmount $amount * ($item->getDiscountRate() / 100);
  3418.                 $discountedAmount $amount $discountAmount;
  3419.                 $total_discounted_amount += $discountedAmount;
  3420.                 $total_discount += $discountAmount;
  3421.                 $total_product_amount += $amount;
  3422.             }
  3423.             $aitRate $so->getAitRate();
  3424.             $vatRate $so->getVatRate();
  3425.             if ($aitRate == '' || $aitRate == null$aitRate 0;
  3426.             if ($vatRate == '' || $vatRate == null$vatRate 0;
  3427. //        $so->setVatRate($post->get('vat_rate', null));
  3428.             $vatAmount $total_discounted_amount * ($vatRate 100);
  3429.             $aitAmount $total_discounted_amount * ($aitRate 100);
  3430.             $total_sales_amount $total_discounted_amount $vatAmount $aitAmount $total_special_discount;
  3431.             //now get client
  3432.             $client $em->getRepository('ApplicationBundle\\Entity\\AccClients')->findOneBy(array(
  3433.                 'clientId' => $so->getClientId(),
  3434.             ));
  3435.             if ($client->getCreditLimitEnabled() != 1) {
  3436.                 $allowed 1;
  3437.             } else {
  3438.                 $creditLimit $client->getCreditLimit();
  3439.                 $due $client->getClientDue();
  3440.                 if ($creditLimit >= ($due $total_sales_amount))
  3441.                     $allowed 1;
  3442.             }
  3443.             //now package data
  3444.             if ($allowed == 0) {
  3445.                 return new JsonResponse(array(
  3446.                     'success' => false,
  3447. //                        'documentHash' => $order->getDocumentHash(),
  3448.                     'documentId' => $receiptId,
  3449.                     'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3450.                     'viewUrl' => '',
  3451.                 ));
  3452.             }
  3453.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  3454.             $dochash $request->request->get('docHash'); //change
  3455.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3456.             $approveRole 1;  //created
  3457.             $approveHash $request->request->get('approvalHash');
  3458.             $receiptId $request->request->get('deliveryReceiptId');
  3459.             $sig DocValidation::isSignatureOk($em$loginId$approveHash);
  3460. //            $this->addFlash(
  3461. //                'success',
  3462. //                'New Transaction Added.'
  3463. //            );
  3464.             $success $sig == false true;
  3465.             if ($success == true) {
  3466.                 $QD $this->getDoctrine()
  3467.                     ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3468.                     ->findOneBy(
  3469.                         array(
  3470.                             'deliveryReceiptId' => $receiptId
  3471.                         ),
  3472.                         array()
  3473.                     );
  3474.                 $draftFlag $QD->getDraftFlag();
  3475.                 if ($draftFlag == 1) {
  3476.                     //now add Approval info
  3477.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3478.                     $approveRole 1;  //created
  3479.                     System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3480.                         $receiptId,
  3481.                         $loginId,
  3482.                         $approveRole,
  3483.                         $request->request->get('approvalHash'));
  3484.                     $options = array(
  3485.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3486.                         'notification_server' => $this->container->getParameter('notification_server'),
  3487.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3488.                         'url' => $this->generateUrl(
  3489.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  3490.                             ['entity_view_route_path_name']
  3491.                         )
  3492.                     );
  3493.                     System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3494.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3495.                         $receiptId,
  3496.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3497.                     );
  3498.                     $QD->setDraftFlag(0);
  3499.                     $em->flush();
  3500.                 }
  3501.                 $url $this->generateUrl(
  3502.                     'view_delivery_receipt'
  3503.                 );
  3504.                 if ($request->request->has('returnJson')) {
  3505. //                    $dr = $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findBy(
  3506. //                        array(
  3507. //                            'salesOrderId' => $orderId, ///material
  3508. //
  3509. //                        )
  3510. //                    );
  3511.                     return new JsonResponse(array(
  3512.                         'success' => true,
  3513. //                        'documentHash' => $order->getDocumentHash(),
  3514.                         'documentId' => $receiptId,
  3515.                         'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3516.                         'viewUrl' => $url "/" $receiptId,
  3517.                     ));
  3518.                 } else {
  3519.                     $this->addFlash(
  3520.                         'success',
  3521.                         'Action Successful'
  3522.                     );
  3523.                     return $this->redirect($url "/" $receiptId);
  3524.                 }
  3525.             }
  3526.         }
  3527.         return new JsonResponse(array(
  3528.             'success' => false,
  3529. //                        'documentHash' => $order->getDocumentHash(),
  3530.             'documentId' => $receiptId,
  3531.             'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3532.             'viewUrl' => '',
  3533.         ));
  3534.     }
  3535.     public function CreateServiceChallanAction(Request $request)
  3536.     {
  3537.         $em $this->getDoctrine()->getManager();
  3538.         if ($request->isMethod('POST')) {
  3539.             $entity_id array_flip(GeneralConstant::$Entity_list)['ServiceChallan']; //change
  3540.             $dochash $request->request->get('docHash'); //change
  3541.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3542.             $approveRole $request->request->get('approvalRole');
  3543.             $approveHash $request->request->get('approvalHash');
  3544.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  3545.                 $loginId$approveRole$approveHash)
  3546.             ) {
  3547.                 $this->addFlash(
  3548.                     'error',
  3549.                     'Sorry Could not insert Data.'
  3550.                 );
  3551.             } else {
  3552.                 $receiptId SalesOrderM::CreateNewServiceChallan($this->getDoctrine()->getManager(), $request->request,
  3553.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  3554.                     $this->getLoggedUserCompanyId($request));
  3555.                 //now add Approval info
  3556.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3557. //                $approveRole = 1;  //created
  3558.                 $options = array(
  3559.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3560.                     'notification_server' => $this->container->getParameter('notification_server'),
  3561.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3562.                     'url' => $this->generateUrl(
  3563.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ServiceChallan']]
  3564.                         ['entity_view_route_path_name']
  3565.                     )
  3566.                 );
  3567.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3568.                     array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3569.                     $receiptId,
  3570.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3571.                 );
  3572.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3573.                     $receiptId,
  3574.                     $loginId,
  3575.                     $approveRole,
  3576.                     $request->request->get('approvalHash'));
  3577.                 $this->addFlash(
  3578.                     'success',
  3579.                     'New Service Challan Created'
  3580.                 );
  3581.                 $url $this->generateUrl(
  3582.                     'view_service_challan'
  3583.                 );
  3584.                 return $this->redirect($url "/" $receiptId);
  3585.             }
  3586.         }
  3587.         return $this->render('@Inventory/pages/input_forms/create_service_challan.html.twig',
  3588.             array(
  3589.                 'page_title' => 'New Service Challan',
  3590.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  3591.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  3592.                 'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  3593.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  3594.                 'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
  3595.                 'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
  3596.                 'deliveryOrders' => SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
  3597.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
  3598.                 'serviceList' => Inventory::ServiceList($em$this->getLoggedUserCompanyId($request))
  3599.             )
  3600.         );
  3601.     }
  3602.     public function GetItemListForDrAction(Request $request)
  3603.     {
  3604.         $em $this->getDoctrine()->getManager();
  3605.         $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3606.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3607.         if ($request->isMethod('POST')) {
  3608.             $em $this->getDoctrine();
  3609.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3610.             );
  3611.             $Content = [];
  3612.             $Transport_data = [];
  3613.             $Lul_data = [];
  3614.             if ($request->request->get('doId') != '')
  3615.                 $find_array['deliveryOrderId'] = $request->request->get('doId');
  3616. //            if($request->request->get('warehouseId')!='')
  3617. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3618.             $QD $this->getDoctrine()
  3619.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryOrderItem')
  3620.                 ->findBy(
  3621.                     $find_array,
  3622.                     array()
  3623.                 );
  3624. //            if($request->request->get('wareHouseId')!='')
  3625.             $DO $this->getDoctrine()
  3626.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryOrder')
  3627.                 ->findOneBy(
  3628.                     $find_array,
  3629.                     array()
  3630.                 );
  3631.             $sendData = array(
  3632. //                'salesType'=>$SO->getSalesType(),
  3633. //                'packageData'=>[],
  3634.                 'productList' => [],
  3635. //                'productListByPackage'=>[],
  3636.             );
  3637.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3638.             $pckg_item_cross_match_data = [];
  3639.             $unitList Inventory::UnitTypeList($em);
  3640.             $colorList Inventory::GetColorList($em);
  3641.             foreach ($QD as $product) {
  3642. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  3643.                 if (($product->getBalance()) <= 0)
  3644.                     continue;
  3645.                 $fdm $product->getProductFdm();
  3646.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3647.                 $find_query = array();
  3648.                 $soItem $this->getDoctrine()
  3649.                     ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  3650.                     ->findOneBy(
  3651.                         array(
  3652.                             'id' => $product->getSalesorderItemId()
  3653.                         )
  3654.                     );
  3655.                 if (!$soItem)
  3656.                     continue;
  3657. //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3658. //                $soBalance = $soItem->getBalance();
  3659.                 $soBalance $soItem->getQty();
  3660. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3661. //                $doBalance = $product->getBalance();
  3662.                 $doBalance $product->getQty();
  3663.                 //now check if any so ir do item id there that is at
  3664.                 //least pending
  3665.                 $approvalPendingDrs $this->getDoctrine()
  3666.                     ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3667.                     ->findBy(
  3668.                         array(
  3669.                             'deliveryOrderId' => $DO->getDeliveryOrderId(),
  3670.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3671.                         )
  3672.                     );
  3673.                 foreach ($approvalPendingDrs as $appPendDr) {
  3674.                     $appPendDrItem $this->getDoctrine()
  3675.                         ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3676.                         ->findOneBy(
  3677.                             array(
  3678.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3679.                                 'salesorderItemId' => $product->getSalesorderItemId()
  3680.                             )
  3681.                         );
  3682.                     if ($appPendDrItem) {
  3683.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3684.                             $soBalance $soBalance $appPendDrItem->getQty();
  3685.                             $doBalance $doBalance $appPendDrItem->getQty();
  3686.                         }
  3687.                     }
  3688.                 }
  3689.                 $colorId $product->getColorId();
  3690.                 $size $product->getSizeId();
  3691. //                $find_query['colorId']=
  3692.                 if ($productData['productId'] != 0) {
  3693.                     $find_query['productId'] = $productData['productId'];
  3694.                     if ($colorId == '' || $colorId == || $colorId == null)
  3695.                         $colorId $productData['defaultColorId'] ?? 0;
  3696.                     if ($size == '' || $size == || $size == null)
  3697.                         $size $productData['defaultSize'] ?? 0;
  3698.                     $find_query['productId'] = $productData['productId'];
  3699.                 } else {
  3700.                     if ($productData['igId'] != 0) {
  3701.                         $find_query['igId'] = $productData['igId'];
  3702.                     }
  3703.                     if ($productData['categoryId'] != 0) {
  3704.                         $find_query['categoryId'] = $productData['categoryId'];
  3705.                     }
  3706.                     if ($productData['subCategoryId'] != 0) {
  3707.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3708.                     }
  3709.                     if ($productData['brandId'] != 0) {
  3710.                         $find_query['brandId'] = $productData['brandId'];
  3711.                     }
  3712.                 }
  3713.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3714.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3715.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3716. //                    $find_query['color'] = $colorId;
  3717.                 } else
  3718.                     $find_query['color'] = $colorId;
  3719.                 if ($size == '' || $size == || $size == null) {
  3720. //                    $find_query['size'] = $size;
  3721.                 } else
  3722.                     $find_query['size'] = 0;
  3723.                 $inventory_by_warehouse_list $this->getDoctrine()
  3724.                     ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  3725.                     ->findBy(
  3726.                         $find_query,
  3727.                         array()
  3728.                     );
  3729.                 $new_pid $productData['productId'];
  3730.                 $p_data = array(
  3731.                     'details_id' => $product->getId(),
  3732. //                        'productId'=>$new_pid,
  3733.                     'productIdList' => [],
  3734.                     'multList' => [],
  3735.                     'drItemIds' => [],
  3736.                     'drItemQty' => [],
  3737.                     'drItemCodeIds' => [],
  3738.                     'drItemCartonIds' => [],
  3739.                     'drItemReturnableFlag' => [],
  3740.                     'drItemReturnDueDate' => [],
  3741.                     'drItemReturnNote' => [],
  3742.                     'drItemReturnStatus' => [],
  3743.                     'colorIds' => [],
  3744.                     'colorNames' => [],
  3745.                     'sizeIds' => [],
  3746.                     'productNameList' => [],
  3747.                     'availableInventoryList' => [],
  3748.                     'warehouseActionId' => [],
  3749.                     'warehouseActionName' => [],
  3750.                     'availableBarcodes' => [],
  3751.                     'availableBarcodesStr' => [],
  3752. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3753. //                        'available_inventory'=>0,
  3754. //                        'package_id'=>$product->getPackageId(),
  3755.                     'qty' => $product->getQty(),
  3756.                     'delivered' => $product->getDelivered(),
  3757. //                    'deliverable' => $product->getDeliverable() - $product->getTransitQty(),
  3758.                     'deliverable' => min($soBalance$doBalance),
  3759. //                    'balance' => $product->getBalance(),
  3760.                     'balance' => min($soBalance$doBalance),
  3761.                     'productNameFdm' => $product->getProductNameFdm(),
  3762.                     'productFdm' => $product->getProductFdm(),
  3763. //                        'delivered'=>$product->getDelivered(),
  3764.                 );
  3765.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  3766.                     if ($inventory_by_warehouse->getQty() <= 0)
  3767.                         continue;
  3768.                     $unitType $product->getUnitTypeId();
  3769.                     $mult_unit 1;
  3770.                     if ($drId != 0) {
  3771.                         $drItem $this->getDoctrine()
  3772.                             ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3773.                             ->findOneBy(
  3774.                                 array(
  3775.                                     'deliveryReceiptId' => $drId,
  3776.                                     'productId' => $inventory_by_warehouse->getProductId(),
  3777.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  3778.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  3779.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  3780.                                 )
  3781.                             );
  3782.                         if ($drItem) {
  3783.                             $returnableMeta SalesOrderM::GetDeliveryReceiptItemReturnableMetaFromOtherdata($drItem->getOtherdata());
  3784.                             $p_data['drItemIds'][] = $drItem->getId();
  3785.                             $p_data['drItemQty'][] = $drItem->getQty();
  3786.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  3787.                             if ($codes == null)
  3788.                                 $codes = [];
  3789.                             $p_data['drItemCodeIds'][] = $codes;
  3790.                             $codes json_decode($drItem->getCartonIds(), true);
  3791.                             if ($codes == null)
  3792.                                 $codes = [];
  3793.                             $p_data['drItemCartonIds'][] = $codes;
  3794.                             $p_data['drItemReturnableFlag'][] = $returnableMeta['temporary_returnable_flag'];
  3795.                             $p_data['drItemReturnDueDate'][] = $returnableMeta['temporary_return_due_date'];
  3796.                             $p_data['drItemReturnNote'][] = $returnableMeta['temporary_return_note'];
  3797.                             $p_data['drItemReturnStatus'][] = $returnableMeta['temporary_return_status'];
  3798.                         } else {
  3799.                             $p_data['drItemIds'][] = 0;
  3800.                             $p_data['drItemQty'][] = 0;
  3801.                             $p_data['drItemCodeIds'][] = 0;
  3802.                             $p_data['drItemCartonIds'][] = 0;
  3803.                             $p_data['drItemReturnableFlag'][] = 0;
  3804.                             $p_data['drItemReturnDueDate'][] = '';
  3805.                             $p_data['drItemReturnNote'][] = '';
  3806.                             $p_data['drItemReturnStatus'][] = '';
  3807.                         }
  3808.                     } else {
  3809.                         $p_data['drItemIds'][] = 0;
  3810.                         $p_data['drItemQty'][] = 0;
  3811.                         $p_data['drItemCodeIds'][] = 0;
  3812.                         $p_data['drItemCartonIds'][] = 0;
  3813.                         $p_data['drItemReturnableFlag'][] = 0;
  3814.                         $p_data['drItemReturnDueDate'][] = '';
  3815.                         $p_data['drItemReturnNote'][] = '';
  3816.                         $p_data['drItemReturnStatus'][] = '';
  3817.                     }
  3818.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  3819.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  3820.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  3821.                         }
  3822.                     };
  3823.                     if ($mult_unit == 0)
  3824.                         $mult_unit 1;
  3825.                     $inv_product_id $inventory_by_warehouse->getProductId();
  3826.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  3827.                     $p_data['multList'][] = $mult_unit;
  3828.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  3829.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  3830.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  3831.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  3832.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  3833. //                        $p_data['availableInventoryList'][]=$inventory_by_warehouse?(($inventory_by_warehouse->getQty())*$mult_unit):0;
  3834.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  3835.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  3836.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  3837.                 }
  3838.                 $sendData['productList'][] = $p_data;
  3839.             }
  3840.             //now package data
  3841.             if ($sendData) {
  3842.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3843.             }
  3844.             return new JsonResponse(array("success" => false));
  3845.         }
  3846.         return new JsonResponse(array("success" => false));
  3847.     }
  3848.     public function GetItemListForDrBySoAction(Request $request)
  3849.     {
  3850.         $em $this->getDoctrine()->getManager();
  3851.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3852.         if ($request->isMethod('POST')) {
  3853.             $em $this->getDoctrine();
  3854.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3855. //                'type'=>1//product only
  3856.             );
  3857.             $find_item_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3858.                 'type' => 1//product only
  3859.             );
  3860.             $Content = [];
  3861.             $Transport_data = [];
  3862.             $Lul_data = [];
  3863.             $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3864.             if ($request->request->get('soId') != '') {
  3865.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3866.                 $find_item_array['salesOrderId'] = $request->request->get('soId');
  3867.             }
  3868. //            if($request->request->get('warehouseId')!='')
  3869. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3870.             $QD $this->getDoctrine()
  3871.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  3872.                 ->findBy(
  3873.                     $find_item_array,
  3874.                     array()
  3875.                 );
  3876. //            if($request->request->get('wareHouseId')!='')
  3877.             $DO $this->getDoctrine()
  3878.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  3879.                 ->findOneBy(
  3880.                     $find_array,
  3881.                     array()
  3882.                 );
  3883.             $sendData = array(
  3884. //                'salesType'=>$SO->getSalesType(),
  3885. //                'packageData'=>[],
  3886.                 'productList' => [],
  3887. //                'productListByPackage'=>[],
  3888.             );
  3889.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3890.             $pckg_item_cross_match_data = [];
  3891.             $unitList Inventory::UnitTypeList($em);
  3892.             $colorList Inventory::GetColorList($em);
  3893.             foreach ($QD as $product) {
  3894.                 if (($product->getBalance() - $product->getTransitQty()) <= 0)
  3895.                     continue;
  3896.                 //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3897. //                $soBalance = $soItem->getBalance();
  3898.                 $soBalance $product->getQty();
  3899. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3900. //                $doBalance = $product->getBalance();
  3901. //                $doBalance = 0;
  3902.                 //now check if any so ir do item id there that is at
  3903.                 //least pending
  3904.                 $approvalPendingDrs $this->getDoctrine()
  3905.                     ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  3906.                     ->findBy(
  3907.                         array(
  3908.                             'salesOrderId' => $DO->getSalesOrderId(),
  3909.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3910.                         )
  3911.                     );
  3912.                 foreach ($approvalPendingDrs as $appPendDr) {
  3913.                     $appPendDrItem $this->getDoctrine()
  3914.                         ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  3915.                         ->findOneBy(
  3916.                             array(
  3917.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3918. //                                'salesorderItemId' => $product->getId(),
  3919.                                 'salesorderItemId' => $product->getId()
  3920.                             )
  3921.                         );
  3922.                     if ($appPendDrItem) {
  3923.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3924.                             $soBalance $soBalance $appPendDrItem->getQty();
  3925.                         }
  3926. //                        $doBalance=$doBalance-$appPendDrItem->getQty();
  3927.                     }
  3928.                 }
  3929.                 $fdm $product->getProductFdm();
  3930.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3931.                 $find_query = array();
  3932.                 $colorId $product->getColorId();
  3933.                 $size $product->getSizeId();
  3934. //                $find_query['colorId']=
  3935.                 if ($productData['productId'] != 0) {
  3936.                     $find_query['productId'] = $productData['productId'];
  3937.                     if ($colorId == '' || $colorId == || $colorId == null)
  3938.                         $colorId $productData['defaultColorId'] ?? 0;
  3939.                     if ($size == '' || $size == || $size == null)
  3940.                         $size $productData['defaultSize'] ?? 0;
  3941.                 } else {
  3942.                     if ($productData['igId'] != 0) {
  3943.                         $find_query['igId'] = $productData['igId'];
  3944.                     }
  3945.                     if ($productData['categoryId'] != 0) {
  3946.                         $find_query['categoryId'] = $productData['categoryId'];
  3947.                     }
  3948.                     if ($productData['subCategoryId'] != 0) {
  3949.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3950.                     }
  3951.                     if ($productData['brandId'] != 0) {
  3952.                         $find_query['brandId'] = $productData['brandId'];
  3953.                     }
  3954.                 }
  3955.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3956.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3957.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3958. //                    $find_query['color'] = $colorId;
  3959.                 } else
  3960.                     $find_query['color'] = $colorId;
  3961.                 if ($size == '' || $size == || $size == null) {
  3962. //                    $find_query['size'] = $size;
  3963.                 } else
  3964.                     $find_query['size'] = 0;
  3965.                 $inventory_by_warehouse_list $this->getDoctrine()
  3966.                     ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  3967.                     ->findBy(
  3968.                         $find_query,
  3969.                         array()
  3970.                     );
  3971.                 $new_pid $productData['productId'];
  3972.                 $unitType $product->getUnitTypeId();
  3973.                 $p_data = array(
  3974.                     'details_id' => $product->getId(),
  3975.                     'unitType' => $unitType,
  3976.                     'productIdList' => [],
  3977.                     'multList' => [],
  3978.                     'drItemIds' => [],
  3979.                     'drItemQty' => [],
  3980.                     'drItemCodeIds' => [],
  3981.                     'drItemCartonIds' => [],
  3982.                     'drItemReturnableFlag' => [],
  3983.                     'drItemReturnDueDate' => [],
  3984.                     'drItemReturnNote' => [],
  3985.                     'drItemReturnStatus' => [],
  3986.                     'colorIds' => [],
  3987.                     'colorNames' => [],
  3988.                     'sizeIds' => [],
  3989.                     'productNameList' => [],
  3990.                     'availableInventoryList' => [],
  3991.                     'warehouseActionId' => [],
  3992.                     'warehouseActionName' => [],
  3993.                     'availableBarcodes' => [],
  3994.                     'availableBarcodesStr' => [],
  3995. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3996. //                        'available_inventory'=>0,
  3997. //                        'package_id'=>$product->getPackageId(),
  3998.                     'qty' => $product->getQty(),
  3999.                     'delivered' => $product->getDelivered(),
  4000. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  4001. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  4002.                     'deliverable' => $soBalance,
  4003. //                    'deliverable' => $product->getBalance(),
  4004.                     'balance' => $soBalance,
  4005. //                    'balance' => $product->getBalance(),
  4006.                     'productNameFdm' => $product->getProductNameFdm(),
  4007.                     'productFdm' => $product->getProductFdm(),
  4008. //                        'delivered'=>$product->getDelivered(),
  4009.                 );
  4010.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  4011.                     if ($inventory_by_warehouse->getQty() <= 0)
  4012.                         continue;
  4013.                     $mult_unit 1;
  4014.                     if ($drId != 0) {
  4015.                         $drItem $this->getDoctrine()
  4016.                             ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  4017.                             ->findOneBy(
  4018.                                 array(
  4019.                                     'deliveryReceiptId' => $drId,
  4020.                                     'productId' => $inventory_by_warehouse->getProductId(),
  4021.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  4022.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  4023.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  4024.                                 )
  4025.                             );
  4026.                         if ($drItem) {
  4027.                             $returnableMeta SalesOrderM::GetDeliveryReceiptItemReturnableMetaFromOtherdata($drItem->getOtherdata());
  4028.                             $p_data['drItemIds'][] = $drItem->getId();
  4029.                             $p_data['drItemQty'][] = $drItem->getQty();
  4030.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  4031.                             if ($codes == null)
  4032.                                 $codes = [];
  4033.                             $p_data['drItemCodeIds'][] = $codes;
  4034.                             $codes json_decode($drItem->getCartonIds(), true);
  4035.                             if ($codes == null)
  4036.                                 $codes = [];
  4037.                             $p_data['drItemCartonIds'][] = $codes;
  4038.                             $p_data['drItemReturnableFlag'][] = $returnableMeta['temporary_returnable_flag'];
  4039.                             $p_data['drItemReturnDueDate'][] = $returnableMeta['temporary_return_due_date'];
  4040.                             $p_data['drItemReturnNote'][] = $returnableMeta['temporary_return_note'];
  4041.                             $p_data['drItemReturnStatus'][] = $returnableMeta['temporary_return_status'];
  4042.                         } else {
  4043.                             $p_data['drItemIds'][] = 0;
  4044.                             $p_data['drItemQty'][] = 0;
  4045.                             $p_data['drItemCodeIds'][] = 0;
  4046.                             $p_data['drItemCartonIds'][] = 0;
  4047.                             $p_data['drItemReturnableFlag'][] = 0;
  4048.                             $p_data['drItemReturnDueDate'][] = '';
  4049.                             $p_data['drItemReturnNote'][] = '';
  4050.                             $p_data['drItemReturnStatus'][] = '';
  4051.                         }
  4052.                     } else {
  4053.                         $p_data['drItemIds'][] = 0;
  4054.                         $p_data['drItemQty'][] = 0;
  4055.                         $p_data['drItemCodeIds'][] = 0;
  4056.                         $p_data['drItemCartonIds'][] = 0;
  4057.                         $p_data['drItemReturnableFlag'][] = 0;
  4058.                         $p_data['drItemReturnDueDate'][] = '';
  4059.                         $p_data['drItemReturnNote'][] = '';
  4060.                         $p_data['drItemReturnStatus'][] = '';
  4061.                     }
  4062.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  4063.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  4064.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  4065.                         }
  4066.                     };
  4067.                     if ($mult_unit == 0)
  4068.                         $mult_unit 1;
  4069.                     $inv_product_id $inventory_by_warehouse->getProductId();
  4070.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  4071.                     $p_data['multList'][] = $mult_unit;
  4072.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  4073.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  4074.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  4075.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  4076.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  4077.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  4078.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  4079.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  4080.                 }
  4081.                 $sendData['productList'][] = $p_data;
  4082.             }
  4083.             //now package data
  4084.             if ($sendData) {
  4085.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4086.             }
  4087.             return new JsonResponse(array("success" => false));
  4088.         }
  4089.         return new JsonResponse(array("success" => false));
  4090.     }
  4091.     public function GetExtraTemporaryReturnableItemsForDrAction(Request $request)
  4092.     {
  4093.         $em $this->getDoctrine()->getManager();
  4094.         $companyId $this->getLoggedUserCompanyId($request);
  4095.         $warehouseActionList Inventory::warehouse_action_list($em$companyId'');
  4096.         $unitList Inventory::UnitTypeList($em);
  4097.         $colorList Inventory::GetColorList($em);
  4098.         if (!$request->isMethod('POST')) {
  4099.             return new JsonResponse(array("success" => false));
  4100.         }
  4101.         $productId $request->request->get('productId'0);
  4102.         $warehouseId $request->request->get('warehouseId'0);
  4103.         $drId $request->request->get('drId'0);
  4104.         if (($productId) == || ($warehouseId) == 0) {
  4105.             return new JsonResponse(array("success" => false));
  4106.         }
  4107.         $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($productId);
  4108.         if (!$product) {
  4109.             return new JsonResponse(array("success" => false));
  4110.         }
  4111.         $productList Inventory::ProductList($em$companyId);
  4112.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(array(
  4113.             'CompanyId' => $companyId,
  4114.             'warehouseId' => $warehouseId,
  4115.             'productId' => $productId,
  4116.         ));
  4117.         $sendData = array(
  4118.             'productList' => [],
  4119.         );
  4120.         foreach ($slotList as $slot) {
  4121.             if ($slot->getQty() <= 0) {
  4122.                 continue;
  4123.             }
  4124.             $multUnit 1;
  4125.             if ($product->getUnitTypeId() != $slot->getUnitTypeId()) {
  4126.                 if (isset($unitList[$slot->getUnitTypeId()]['conversion'][$product->getUnitTypeId()])) {
  4127.                     $multUnit $unitList[$slot->getUnitTypeId()]['conversion'][$product->getUnitTypeId()];
  4128.                 }
  4129.             }
  4130.             if ($multUnit == 0) {
  4131.                 $multUnit 1;
  4132.             }
  4133.             $drItem null;
  4134.             if (($drId) != 0) {
  4135.                 $drItem $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')->findOneBy(array(
  4136.                     'deliveryReceiptId' => $drId,
  4137.                     'salesorderItemId' => [0null''],
  4138.                     'productId' => $slot->getProductId(),
  4139.                     'warehouseActionId' => $slot->getActionTagId(),
  4140.                     'colorId' => $slot->getColor() == ? [0null''] : $slot->getColor(),
  4141.                     'sizeId' => $slot->getSize() == ? [0null''] : $slot->getSize(),
  4142.                 ));
  4143.             }
  4144.             $returnableMeta SalesOrderM::GetDeliveryReceiptItemReturnableMetaFromOtherdata($drItem $drItem->getOtherdata() : []);
  4145.             $availableQty = (($slot->getQty()) / $multUnit);
  4146.             if ($drItem && $availableQty < ($drItem->getQty())) {
  4147.                 $availableQty $drItem->getQty();
  4148.             }
  4149.             $sendData['productList'][] = array(
  4150.                 'details_id' => 0,
  4151.                 'productIdList' => array($slot->getProductId()),
  4152.                 'multList' => array($multUnit),
  4153.                 'drItemIds' => array($drItem $drItem->getId() : 0),
  4154.                 'drItemQty' => array($drItem ? ($drItem->getQty()) : 0),
  4155.                 'drItemCodeIds' => array($drItem ? (json_decode($drItem->getProductByCodeIds(), true) ?: []) : []),
  4156.                 'drItemCartonIds' => array($drItem ? (json_decode($drItem->getCartonIds(), true) ?: []) : []),
  4157.                 'drItemReturnableFlag' => array($drItem $returnableMeta['temporary_returnable_flag'] : 1),
  4158.                 'drItemReturnDueDate' => array($drItem $returnableMeta['temporary_return_due_date'] : ''),
  4159.                 'drItemReturnNote' => array($drItem $returnableMeta['temporary_return_note'] : ''),
  4160.                 'drItemReturnStatus' => array($drItem $returnableMeta['temporary_return_status'] : 'pending'),
  4161.                 'colorIds' => array($slot->getColor() ? $slot->getColor() : 0),
  4162.                 'colorNames' => array($slot->getColor() && isset($colorList[$slot->getColor()]) ? $colorList[$slot->getColor()]['name'] : ''),
  4163.                 'sizeIds' => array($slot->getSize() ? $slot->getSize() : 0),
  4164.                 'productNameList' => array(isset($productList[$slot->getProductId()]) ? $productList[$slot->getProductId()]['name'] : $product->getName()),
  4165.                 'availableInventoryList' => array($availableQty),
  4166.                 'warehouseActionId' => array($slot->getActionTagId()),
  4167.                 'warehouseActionName' => array(isset($warehouseActionList[$slot->getActionTagId()]) ? $warehouseActionList[$slot->getActionTagId()] : ''),
  4168.                 'availableBarcodes' => array([]),
  4169.                 'availableBarcodesStr' => array(''),
  4170.                 'serialEnabled' => array(isset($productList[$slot->getProductId()]) ? $productList[$slot->getProductId()]['has_serial'] : 0),
  4171.                 'qty' => $availableQty,
  4172.                 'delivered' => 0,
  4173.                 'deliverable' => $availableQty,
  4174.                 'balance' => $availableQty,
  4175.                 'productNameFdm' => 'Temporary returnable item',
  4176.                 'productFdm' => $product->getProductFdm(),
  4177.                 'extraTempItemFlag' => 1,
  4178.             );
  4179.         }
  4180.         return new JsonResponse(array("success" => true"content" => $sendData));
  4181.     }
  4182.     public function GetItemListForStockReqBySoAction(Request $request)
  4183.     {
  4184.         $em $this->getDoctrine()->getManager();
  4185.         if ($request->isMethod('POST')) {
  4186.             $em $this->getDoctrine();
  4187.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  4188.             );
  4189.             $Content = [];
  4190.             $Transport_data = [];
  4191.             $Lul_data = [];
  4192.             // NOTE: do NOT pre-filter by serviceId. In the filter-based sales model every sales-order
  4193.             // line carries a serviceId (>0, referencing AccService) with an empty product_fdm, so the
  4194.             // old `serviceId => [0, null]` filter excluded 100% of the items and the Stock Requisition
  4195.             // item list always came back empty. We fetch all lines of the SO and resolve their names below.
  4196.             $sendData = array(
  4197. //                'salesType'=>$SO->getSalesType(),
  4198. //                'packageData'=>[],
  4199.                 'productList' => [],
  4200. //                'productListByPackage'=>[],
  4201.             );
  4202.             if ($request->request->get('soId') != '') {
  4203.                 $find_array['salesOrderId'] = $request->request->get('soId');
  4204. //            if($request->request->get('warehouseId')!='')
  4205. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4206.                 $QD $this->getDoctrine()
  4207.                     ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  4208.                     ->findBy(
  4209.                         $find_array,
  4210.                         array()
  4211.                     );
  4212. //            if($request->request->get('wareHouseId')!='')
  4213. //            $DO = $this->getDoctrine()
  4214. //                ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  4215. //                ->findOneBy(
  4216. //                    $find_array,
  4217. //                    array()
  4218. //                );
  4219.                 $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4220.                 $pckg_item_cross_match_data = [];
  4221.                 $unitList Inventory::UnitTypeList($em);
  4222.                 // Service/filter lines have no productNameFdm yet â€” resolve their name from AccService.
  4223.                 $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  4224.                 foreach ($QD as $product) {
  4225. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  4226. //                    continue;
  4227.                     $fdm $product->getProductFdm();
  4228.                     $serviceId = (int) $product->getServiceId();
  4229.                     $unitType $product->getUnitTypeId();
  4230.                     // Display name: product lines carry a productNameFdm; filter/service-based lines
  4231.                     // (no FDM finalised yet) are named from the AccService they reference.
  4232.                     $nameFdm $product->getProductNameFdm();
  4233.                     if (($nameFdm === null || $nameFdm === '') && $serviceId && isset($serviceList[$serviceId])) {
  4234.                         $nameFdm $serviceList[$serviceId]['name'];
  4235.                         if (!$unitType && isset($serviceList[$serviceId]['unit_type'])) {
  4236.                             $unitType $serviceList[$serviceId]['unit_type'];
  4237.                         }
  4238.                     }
  4239.                     $p_data = array(
  4240.                         'details_id' => $product->getId(),
  4241.                         'serviceId' => $serviceId,
  4242.                         'unitType' => $unitType,
  4243.                         'productIdList' => [],
  4244.                         'multList' => [],
  4245.                         'productNameList' => [],
  4246.                         'availableInventoryList' => [],
  4247.                         'warehouseActionId' => [],
  4248.                         'warehouseActionName' => [],
  4249.                         'availableBarcodes' => [],
  4250.                         'availableBarcodesStr' => [],
  4251. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  4252. //                        'available_inventory'=>0,
  4253. //                        'package_id'=>$product->getPackageId(),
  4254.                         'qty' => $product->getQty(),
  4255.                         'delivered' => $product->getDelivered(),
  4256. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  4257. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  4258.                         'deliverable' => $product->getBalance(),
  4259.                         'balance' => $product->getBalance(),
  4260.                         'productNameFdm' => $nameFdm,
  4261.                         'productFdm' => $product->getProductFdm(),
  4262. //                        'delivered'=>$product->getDelivered(),
  4263.                     );
  4264.                     $sendData['productList'][] = $p_data;
  4265.                 }
  4266.             }
  4267.             //now package data
  4268.             if ($sendData) {
  4269.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4270.             }
  4271.             return new JsonResponse(array("success" => false));
  4272.         }
  4273.         return new JsonResponse(array("success" => false));
  4274.     }
  4275.     public function GetProductPriceAjaxAction(Request $request)
  4276.     {
  4277.         $em $this->getDoctrine()->getManager();
  4278.         $priceData = [];
  4279.         $defaultData = [
  4280.             => [    //currId
  4281.                 => 0       ///customerID=> value
  4282.             ]
  4283.         ];
  4284.         $priceData = [
  4285.             => $defaultData
  4286.         ];
  4287.         if ($request->isMethod('POST')) {
  4288.             $em $this->getDoctrine();
  4289.             $find_query = array();
  4290.             $pid $request->request->get('productId'0);
  4291.             $find_query['productId'] = $pid;
  4292.             $priceData = [
  4293. //                $pid =>$defaultData
  4294.             ];
  4295.             $priceDataQry $em
  4296.                 ->getRepository('ApplicationBundle\\Entity\\ProductMrp')
  4297.                 ->findBy(
  4298.                     $find_query,
  4299.                     array(
  4300.                         'productMrpId' => 'desc'
  4301.                     )
  4302.                 );
  4303.             if (!empty($priceDataQry)) {
  4304.                 foreach ($priceDataQry as $priceDataQ) {
  4305.                     $currId $priceDataQ->getCurrency();
  4306.                     if ($currId == null$currId 0;
  4307.                     if (!isset($priceData[$pid][$currId]))
  4308.                         $priceData[$pid][$currId] = $defaultData;
  4309.                     $priceByCustomerType json_decode($priceDataQ->getPriceByCustomerTypes(), true);
  4310.                     if ($priceByCustomerType == null$priceByCustomerType = [];
  4311.                     foreach ($priceByCustomerType as $ct => $pbct) {
  4312.                         if (!isset($priceData[$pid][$currId][$ct]))
  4313.                             $priceData[$pid][$currId][$ct] = $pbct;
  4314.                     }
  4315.                 }
  4316.             }
  4317.         }
  4318.         //now package data
  4319.         $retData = array(
  4320.             'success' => true,
  4321.             'data' => $priceData
  4322.         );
  4323.         return new JsonResponse($retData);
  4324.     }
  4325.     public function GetBarcodesListForStAction(Request $request)
  4326.     {
  4327.         $em $this->getDoctrine()->getManager();
  4328.         $sendData = [];
  4329.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  4330.         if ($request->isMethod('POST')) {
  4331.             $em $this->getDoctrine();
  4332.             $find_query = array();
  4333.             $find_query['warehouseId'] = $request->request->get('warehouseId');
  4334.             $find_query['actionTagId'] = $request->request->get('warehouseActionId');
  4335.             $find_query['productId'] = $request->request->get('productId');
  4336.             $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  4337.             $inventory_by_warehouse_list $this->getDoctrine()
  4338.                 ->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  4339.                 ->findBy(
  4340.                     $find_query,
  4341.                     array()
  4342.                 );
  4343.             $new_pid $request->request->get('productId');
  4344.             $p_data = array();
  4345.             //now get bacodes if available
  4346. //                    $query = "SELECT product_by_code_id, GROUP_CONCAT(DISTINCT sales_code SEPARATOR ',') sales_code_list_str
  4347. //FROM product_by_code
  4348. //where company_id=" . $this->getLoggedUserCompanyId($request).
  4349. //                        " and product_id=".$inv_product_id.
  4350. //                        " and warehouse_id=".$inventory_by_warehouse->getWarehouseId().
  4351. //                        " and warehouse_action_id=".$inventory_by_warehouse->getActionTagId();
  4352. //                        " GROUP BY product_by_code_id" ;
  4353.             $query "SELECT product_by_code_id, sales_code
  4354. FROM product_by_code
  4355. where company_id = :companyId
  4356.   and product_id = :productId
  4357.   and warehouse_id = :warehouseId
  4358.   and warehouse_action_id = :warehouseActionId";
  4359.             $stmt $em->getConnection()->fetchAllAssociative($query, array(
  4360.                 'companyId' => (int) $this->getLoggedUserCompanyId($request),
  4361.                 'productId' => (int) $request->request->get('productId'),
  4362.                 'warehouseId' => (int) $request->request->get('warehouseId'),
  4363.                 'warehouseActionId' => (int) $request->request->get('warehouseActionId'),
  4364.             ));
  4365.             $results $stmt;
  4366.             $sales_code_list_str '';
  4367.             foreach ($results as $pika => $result) {
  4368.                 if ($pika != 0)
  4369.                     $sales_code_list_str .= ',';
  4370.                 $sales_code_list_str .= str_pad($result['sales_code'], 13'0'STR_PAD_LEFT);
  4371.             }
  4372.             if ($results) {
  4373.                 $p_data['availableBarcodes'] = $sales_code_list_str != '' || $sales_code_list_str != null
  4374.                     explode(','$sales_code_list_str) : [];
  4375.                 $p_data['availableBarcodesStr'] = $sales_code_list_str != '' || $sales_code_list_str != null
  4376.                     $sales_code_list_str "";
  4377. //
  4378.             } else {
  4379.                 $p_data['availableBarcodes'] = [];
  4380.                 $p_data['availableBarcodesStr'] = "";
  4381. //
  4382.             }
  4383.             $sendData $p_data;
  4384.         }
  4385.         //now package data
  4386.         if (!empty($sendData['availableBarcodes'])) {
  4387.             return new JsonResponse(array("success" => true"content" => $sendData));
  4388.         }
  4389.         return new JsonResponse(array("success" => false));
  4390.     }
  4391.     public function GetItemListForSalesReturnAction(Request $request)
  4392.     {
  4393.         if ($request->isMethod('POST')) {
  4394.             $em $this->getDoctrine();
  4395.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  4396.             );
  4397.             $Content = [];
  4398.             $Transport_data = [];
  4399.             $Lul_data = [];
  4400.             if ($request->request->get('drId') != '')
  4401.                 $find_array['deliveryReceiptId'] = $request->request->get('drId');
  4402. //            if($request->request->get('warehouseId')!='')
  4403. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4404.             $QD $this->getDoctrine()
  4405.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  4406.                 ->findBy(
  4407.                     $find_array,
  4408.                     array()
  4409.                 );
  4410. //            if($request->request->get('wareHouseId')!='')
  4411.             $DR $this->getDoctrine()
  4412.                 ->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  4413.                 ->findOneBy(
  4414.                     $find_array,
  4415.                     array()
  4416.                 );
  4417.             $sendData = array(
  4418.                 'productList' => [],
  4419.             );
  4420.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4421.             $pckg_item_cross_match_data = [];
  4422.             $unitList Inventory::UnitTypeList($em);
  4423.             foreach ($QD as $product) {
  4424.                 if (($product->getQty()) <= 0)
  4425.                     continue;
  4426.                 $new_pid $product->getProductId();
  4427.                 $sales_code_range = [];
  4428.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  4429.                     $sales_code_range json_decode($product->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  4430.                 } else {
  4431.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  4432.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getSalesCodeRange());
  4433.                     $sales_code_range json_decode($json_without_bigintstrue);
  4434.                 }
  4435.                 $p_data = array(
  4436.                     'details_id' => $product->getId(),
  4437.                     'dr_id' => $product->getDeliveryReceiptId(),
  4438.                     'productId' => $new_pid,
  4439.                     'product_name' => isset($productList[$new_pid]) ? $productList[$new_pid]['name'] : '',
  4440.                     'qty' => $product->getQty(),
  4441.                     'delivered' => $product->getDelivered(),
  4442.                     'unitTypeId' => $product->getUnitTypeId(),
  4443.                     'deliverable' => $product->getDeliverable(),
  4444.                     'balance' => $product->getBalance(),
  4445.                     'salesCodeRangeStr' => $product->getSalesCodeRange(),
  4446.                     'salesCodeRange' => $sales_code_range,
  4447.                     'sales_codes' => $sales_code_range,
  4448.                     'sales_price' => $product->getPrice(),
  4449.                     'purchase_price' => $product->getCurrentPurchasePrice()
  4450. //                        'delivered'=>$product->getDelivered(),
  4451.                 );
  4452.                 $sendData['productList'][] = $p_data;
  4453.             }
  4454.             //now package data
  4455.             if ($sendData) {
  4456.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4457.             }
  4458.             return new JsonResponse(array("success" => false));
  4459.         }
  4460.         return new JsonResponse(array("success" => false));
  4461.     }
  4462.     public function GetItemListForIrrAction(Request $request)
  4463.     {
  4464.         if ($request->isMethod('POST')) {
  4465.             $em $this->getDoctrine();
  4466.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  4467.             );
  4468.             $Content = [];
  4469.             $Transport_data = [];
  4470.             $Lul_data = [];
  4471.             if ($request->request->get('srId') != '')
  4472.                 $find_array['salesReturnId'] = $request->request->get('srId');
  4473. //            if($request->request->get('warehouseId')!='')
  4474. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4475.             $QD $this->getDoctrine()
  4476.                 ->getRepository('ApplicationBundle\\Entity\\SalesReturnItem')
  4477.                 ->findBy(
  4478.                     $find_array,
  4479.                     array()
  4480.                 );
  4481. //            if($request->request->get('wareHouseId')!='')
  4482.             $sendData = array(
  4483.                 'productList' => [],
  4484.             );
  4485.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4486.             $pckg_item_cross_match_data = [];
  4487.             $unitList Inventory::UnitTypeList($em);
  4488.             foreach ($QD as $product) {
  4489.                 if (($product->getReceivedBalance()) <= && ($product->getReplacedBalance()) <= 0)
  4490.                     continue;
  4491.                 $DR_ITEM null;
  4492.                 $DR_TAGGED_CODES = [];
  4493.                 $DR_TAGGED_CODES_FOR_SELECTIZE = [];
  4494.                 $RESTRICT_RECEIVED_CODES_FLAG 0;
  4495.                 $sales_code_range = [];
  4496.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  4497.                     $sales_code_range json_decode($product->getReceivedCodeRange(), true512JSON_BIGINT_AS_STRING);
  4498.                 } else {
  4499.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  4500.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getReceivedCodeRange());
  4501.                     $sales_code_range json_decode($json_without_bigintstrue);
  4502.                 }
  4503.                 $DR_TAGGED_CODES $sales_code_range;
  4504.                 if (!empty($DR_TAGGED_CODES)) {
  4505.                     $RESTRICT_RECEIVED_CODES_FLAG 1;
  4506.                     foreach ($DR_TAGGED_CODES as $DTC) {
  4507.                         $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  4508.                             'value' => $DTC
  4509.                         );
  4510.                     }
  4511.                 }
  4512. //                if ($product->getTaggedDetailsId() != 0 && $product->getTaggedDetailsId() != null) {
  4513. //
  4514. //                    $DR_ITEM = $this->getDoctrine()
  4515. //                        ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  4516. //                        ->findOneBy(
  4517. //                            array(
  4518. //                                'id' => $product->getTaggedDetailsId()
  4519. //                            ),
  4520. //                            array()
  4521. //                        );
  4522. //                    if ($DR_ITEM) {
  4523. //                        if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  4524. //
  4525. //                            $DR_TAGGED_CODES = json_decode($DR_ITEM->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  4526. //                        } else {
  4527. //
  4528. //                            $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  4529. //                            $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $DR_ITEM->getSalesCodeRange());
  4530. //                            $DR_TAGGED_CODES = json_decode($json_without_bigints, true);
  4531. //                        }
  4532. //
  4533. //                        if ($DR_TAGGED_CODES == null)
  4534. //                            $DR_TAGGED_CODES = [];
  4535. //                        if (!empty($DR_TAGGED_CODES)) {
  4536. //                            $RESTRICT_RECEIVED_CODES_FLAG = 1;
  4537. //                            foreach ($DR_TAGGED_CODES as $DTC) {
  4538. //                                $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  4539. //                                    'value' => $DTC
  4540. //                                );
  4541. //                            }
  4542. //                        }
  4543. //                    }
  4544. //                }
  4545.                 $p_data = array(
  4546.                     'details_id' => $product->getId(),
  4547.                     'receivedDrTaggedCodes' => $DR_TAGGED_CODES,
  4548.                     'receivedDrTaggedCodesStr' => implode(','$DR_TAGGED_CODES),
  4549.                     'receivedDrTaggedCodesForSel' => $DR_TAGGED_CODES_FOR_SELECTIZE,
  4550.                     'receivedRestrictCodesFlag' => $RESTRICT_RECEIVED_CODES_FLAG,
  4551.                     'receivedProductId' => $product->getReceivedProductId(),
  4552.                     'receivedBalance' => $product->getReceivedBalance(),
  4553.                     'receivedUnitSalesPrice' => $product->getReceivedUnitSalesPrice(),
  4554.                     'receivedUnitPurchasePrice' => $product->getReceivedUnitPurchasePrice(),
  4555.                     'receivedProductName' => isset($productList[$product->getReceivedProductId()]) ? $productList[$product->getReceivedProductId()]['name'] : '',
  4556.                     'replacedProductId' => $product->getReplacedProductId(),
  4557.                     'replacedBalance' => $product->getReplacedBalance(),
  4558.                     'replacedUnitSalesPrice' => $product->getReplacedUnitSalesPrice(),
  4559.                     'replacedUnitPurchasePrice' => $product->getReplacedUnitPurchasePrice(),
  4560.                     'replacedProductName' => isset($productList[$product->getReplacedProductId()]) ? $productList[$product->getReplacedProductId()]['name'] : '',
  4561.                     'disposeBalance' => $product->getDisposeBalance(),
  4562.                     'unusedBalance' => $product->getUnusedBalance(),
  4563.                     'disposeTag' => $product->getDisposeTag(),
  4564.                     'unitTypeId' => $product->getUnitTypeId(),
  4565. //                        'delivered'=>$product->getDelivered(),
  4566.                 );
  4567.                 $sendData['productList'][] = $p_data;
  4568.             }
  4569.             //now package data
  4570.             if ($sendData) {
  4571.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4572.             }
  4573.             return new JsonResponse(array("success" => false));
  4574.         }
  4575.         return new JsonResponse(array("success" => false));
  4576.     }
  4577.     public function LabelFormatAction(Request $request$id 0)
  4578.     {
  4579.         $data = array(
  4580.             'formatId' => '',
  4581.             'formatCode' => '',
  4582.             'name' => '',
  4583.             'labelType' => 0,
  4584.             'width' => 60,
  4585.             'pageWidth' => 6,
  4586.             'height' => 39,
  4587.             'pageHeight' => 2,
  4588.             'formatData' => '',
  4589.         );
  4590.         if ($request->isMethod('POST')) {
  4591.             $post $request->request;
  4592.             $exists_already 0;
  4593.             if ($request->request->get('formatId') != '') {
  4594.                 $query_here $this->getDoctrine()
  4595.                     ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  4596.                     ->findOneBy(
  4597.                         array(
  4598.                             'formatId' => $request->request->get('formatId')
  4599.                         )
  4600.                     );
  4601.                 if (!empty($query_here)) {
  4602.                     $exists_already 1;
  4603.                     $new $query_here;
  4604.                 } else
  4605.                     $new = new LabelFormat();
  4606.             } else
  4607.                 $new = new LabelFormat();
  4608.             $new->setName($request->request->get('name'));
  4609.             $new->setLabelType($request->request->get('labelType'));
  4610.             $new->setWidth($request->request->get('width'));
  4611.             $new->setHeight($request->request->get('height'));
  4612.             $new->setFormatCode($request->request->get('formatCode'));
  4613.             $new->setActive(GeneralConstant::ACTIVE);
  4614.             $new->setPageHeight($request->request->get('pageHeight'));
  4615.             $new->setPageWidth($request->request->get('pageWidth'));
  4616.             $new->setFormatData($request->request->get('formatData'));
  4617.             if ($exists_already == 0)
  4618.                 $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4619.             $new->setEditLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4620.             $new->setCompanyId($request->getSession()->get(UserConstants::USER_COMPANY_ID));
  4621.             $em $this->getDoctrine()->getManager();
  4622.             $em->persist($new);
  4623.             $em->flush();
  4624.         }
  4625.         if ($id != 0) {
  4626.             $query_here $this->getDoctrine()
  4627.                 ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  4628.                 ->findOneBy(
  4629.                     array(
  4630.                         'formatId' => $id
  4631.                     )
  4632.                 );
  4633.             if ($query_here)
  4634.                 $data $query_here;
  4635.         } else if ($request->query->has('formatId')) {
  4636.             $query_here $this->getDoctrine()
  4637.                 ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  4638.                 ->findOneBy(
  4639.                     array(
  4640.                         'formatId' => $request->query->get('formatId')
  4641.                     )
  4642.                 );
  4643.             if ($query_here)
  4644.                 $data $query_here;
  4645.         }
  4646.         return $this->render(
  4647.             '@Inventory/pages/input_forms/label_format.html.twig',
  4648.             array(
  4649.                 'page_title' => 'Label Format',
  4650.                 'data' => $data,
  4651.                 'labelTypeList' => LabelConstant::$label_type_list,
  4652.                 'labelFieldsList' => LabelConstant::$label_fields_list,
  4653.                 'formatList' => $this->getDoctrine()
  4654.                     ->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  4655.                     ->findBy(
  4656.                         array( //                            'formatId' => $request->query->get('formatId')
  4657.                         )
  4658.                     )
  4659.                 //                'incomeLedgerHeads'=>Accounts::getChildLedgerHeads($this->getDoctrine()->getManager(),AccountsConstant::INCOME)
  4660.             )
  4661.         );
  4662.     }
  4663.     public function GetServiceListForScAction(Request $request)
  4664.     {
  4665.         if ($request->isMethod('POST')) {
  4666.             $em $this->getDoctrine();
  4667.             $find_array = array(
  4668.                 'type' => 2//service
  4669.             );
  4670.             $Content = [];
  4671.             $Transport_data = [];
  4672.             $Lul_data = [];
  4673.             if ($request->request->get('soId') != '')
  4674.                 $find_array['salesOrderId'] = $request->request->get('soId');
  4675. //            if($request->request->get('warehouseId')!='')
  4676. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4677.             $QD $this->getDoctrine()
  4678.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  4679.                 ->findBy(
  4680.                     $find_array,
  4681.                     array()
  4682.                 );
  4683. //            if($request->request->get('wareHouseId')!='')
  4684.             $SO $this->getDoctrine()
  4685.                 ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  4686.                 ->findOneBy(
  4687.                     array(
  4688.                         'salesOrderId' => $request->request->get('soId')
  4689.                     ),
  4690.                     array()
  4691.                 );
  4692.             $sendData = array(
  4693. //                'salesType'=>$SO->getSalesType(),
  4694. //                'packageData'=>[],
  4695.                 'productList' => [],
  4696. //                'productListByPackage'=>[],
  4697.             );
  4698.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager(), $SO->getCompanyId());
  4699.             $pckg_item_cross_match_data = [];
  4700.             foreach ($QD as $product) {
  4701.                 $p_data = array(
  4702.                     'details_id' => $product->getId(),
  4703.                     'service_id' => $product->getServiceId(),
  4704.                     'service_name' => $serviceList[$product->getServiceId()]['name'],
  4705.                     'available_inventory' => $product->getBalance(),
  4706. //                        'package_id'=>$product->getPackageId(),
  4707.                     'qty' => $product->getQty(),
  4708.                     'delivered' => $product->getDelivered(),
  4709. //                    'deliverable'=>$product->getDeliverable(),
  4710.                     'balance' => $product->getBalance(),
  4711. //                        'delivered'=>$product->getDelivered(),
  4712.                 );
  4713.                 $sendData['serviceList'][] = $p_data;
  4714.             }
  4715.             //now package data
  4716.             if ($sendData) {
  4717.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4718.             }
  4719.             return new JsonResponse(array("success" => false));
  4720.         }
  4721.         return new JsonResponse(array("success" => false));
  4722.     }
  4723.     public function CreateReceivedNoteAction(Request $request)
  4724.     {
  4725.         if ($request->isMethod('POST')) {
  4726.             $em $this->getDoctrine()->getManager();
  4727.             $entity_id array_flip(GeneralConstant::$Entity_list)['Grn']; //change
  4728.             $dochash $request->request->get('docHash'); //change
  4729.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4730.             $approveRole 1;  //created
  4731.             $approveHash $request->request->get('approvalHash');
  4732.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4733.                 $loginId$approveRole$approveHash)
  4734.             ) {
  4735.                 $this->addFlash(
  4736.                     'error',
  4737.                     'Sorry Couldnot insert Data.'
  4738.                 );
  4739.             } else {
  4740.                 $data $request->request;
  4741.                 $grnId Inventory::CreateGrn($this->getDoctrine()->getManager(), $data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4742.                 //now add Approval info
  4743.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4744.                 $approveRole 1;  //created
  4745.                 $options = array(
  4746.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4747.                     'notification_server' => $this->container->getParameter('notification_server'),
  4748.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4749.                     'url' => $this->generateUrl(
  4750.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['Grn']]
  4751.                         ['entity_view_route_path_name']
  4752.                     )
  4753.                 );
  4754.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4755.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  4756.                     $grnId,
  4757.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4758.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['Grn'], $grnId,
  4759.                     $loginId,
  4760.                     $approveRole,
  4761.                     $request->request->get('approvalHash'));
  4762.                 $this->addFlash(
  4763.                     'success',
  4764.                     'New GRN Added.'
  4765.                 );
  4766.                 $url $this->generateUrl(
  4767.                     'view_grn'
  4768.                 );
  4769.                 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),
  4770.                     "Good Received Note : " $dochash " Has Been Created And is Under Processing",
  4771.                     'pos',
  4772.                     System::getPositionIdsByDepartment($em, [GeneralConstant::SALES_DEPARTMENTGeneralConstant::PURCHASE_DEPARTMENTGeneralConstant::ACCOUNTS_DEPARTMENTGeneralConstant::INVENTORY_DEPARTMENT]),
  4773.                     'success',
  4774.                     $url "/" $grnId,
  4775.                     "GRN"
  4776.                 );
  4777.                 return $this->redirect($url "/" $grnId);
  4778.             }
  4779.         }
  4780.         return $this->render('@Inventory/pages/input_forms/received_note.html.twig',
  4781.             array(
  4782.                 'page_title' => 'GRN',
  4783.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  4784.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  4785.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  4786.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  4787.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  4788.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  4789.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  4790.                 'material_inward' => $this->getDoctrine()
  4791.                     ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  4792.                     ->findBy(
  4793.                         array(
  4794.                             'stage' => GeneralConstant::STAGE_PENDING_TAG
  4795.                         )
  4796.                     )
  4797. //                'po'=>Inventory::getPurchaseOrderList
  4798.             )
  4799.         );
  4800.     }
  4801.     public function GetQcListForGrnAction(Request $request)
  4802.     {
  4803.         if ($request->isMethod('POST')) {
  4804.             $find_array = array(
  4805.                 'stage' => GeneralConstant::STAGE_PENDING_TAG
  4806.             );
  4807.             $Content = [];
  4808.             $ContentByProductId = [];
  4809.             $Transport_data = [];
  4810.             $Lul_data = [];
  4811.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4812.             if ($request->request->get('poId') != '')
  4813.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4814.             if ($request->request->get('warehouseId') != '')
  4815.                 $find_array['warehouseId'] = $request->request->get('warehouseId');
  4816.             $QD $this->getDoctrine()
  4817.                 ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  4818.                 ->findBy(
  4819.                     $find_array,
  4820.                     array(
  4821.                         'inwardDate' => 'ASC',
  4822.                         'qcDate' => 'ASC'
  4823.                     )
  4824.                 );
  4825.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4826.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4827.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4828.             $lotNumArray = [];
  4829.             foreach ($QD as $entry) {
  4830. //                $inwardDate=strtotime($entry->getInwardDate());
  4831. //                $qcDate=strtotime($entry->getQcDate());
  4832.                 $inwardDate = ($entry->getInwardDate() instanceof \DateTime) ? $entry->getInwardDate()->format('m/d/Y') : '';
  4833.                 $qcDate = ($entry->getQcDate() instanceof \DateTime) ? $entry->getQcDate()->format('m/d/Y') : '';
  4834.                 if (!in_array($entry->getLotNumber(), $lotNumArray))
  4835.                     $lotNumArray[] = $entry->getLotNumber();
  4836.                 if (isset($ContentByProductId[$entry->getPurchaseOrderItemId()])) {
  4837.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['inwardDateList'][] = $inwardDate;
  4838.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcDateList'][] = $inwardDate;
  4839.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcIdList'][] = $entry->getQcId();
  4840.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['appQtyList'][] = $entry->getApprovedQty();
  4841.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['totQty'] += ($entry->getApprovedQty());
  4842.                 } else {
  4843.                     $ContentByProductId[$entry->getPurchaseOrderItemId()] = array(
  4844.                         'productName' => $productList[$entry->getProductId()]['name'],
  4845.                         'productUnitName' => $unitList[$productList[$entry->getProductId()]['unit_type']]['name'],
  4846.                         'qcHash' => $entry->getDocumentHash(),
  4847.                         'warehouseName' => $warehouse[$entry->getWarehouseId()]['name'],
  4848.                         'inwardDate' => $inwardDate,
  4849.                         'inwardDateList' => [$inwardDate],
  4850.                         'qcDateList' => [$qcDate],
  4851.                         'qcIdList' => [$entry->getQcId()],
  4852.                         'qcDate' => $qcDate,
  4853.                         'poQty' => $entry->getPoQty(),
  4854.                         'poPrevbalance' => $entry->getPoBalance(),
  4855.                         'appQty' => $entry->getApprovedQty(),
  4856.                         'appQtyList' => [$entry->getApprovedQty()],
  4857.                         'totQty' => $entry->getApprovedQty(),
  4858.                         'poBalance' => $entry->getPoBalance() - $entry->getApprovedQty(),
  4859.                         'qcId' => $entry->getQcId(),
  4860.                         'productId' => $entry->getProductId()
  4861.                     );
  4862.                 }
  4863.                 $Expense_Cost[$entry->getQcId()] = json_decode($entry->getExpenseCost());
  4864.                 $Expense_Id[$entry->getQcId()] = json_decode($entry->getExpenseId());
  4865.             }
  4866.             foreach ($ContentByProductId as $c) {
  4867.                 $Content[] = $c;
  4868.             }
  4869.             if ($QD) {
  4870.                 return new JsonResponse(array("success" => true"content" => $Content"lotNumber" => implode(', '$lotNumArray), 'Expense_Cost' => $Expense_Cost'Expense_Id' => $Expense_Id));
  4871.             }
  4872.             return new JsonResponse(array("success" => false));
  4873.         }
  4874.         return new JsonResponse(array("success" => false));
  4875.     }
  4876.     public function GetSrListForIrAction(Request $request)
  4877.     {
  4878.         if ($request->isMethod('POST')) {
  4879.             $find_array = array();
  4880.             $Content = [];
  4881.             if ($request->request->get('srId') != '')
  4882.                 $find_array['stockRequisitionId'] = $request->request->get('srId');
  4883.             $find_array['forceSkipTag'] = [0null];
  4884.             $QD $this->getDoctrine()
  4885.                 ->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')
  4886.                 ->findBy(
  4887.                     $find_array
  4888.                 );
  4889.             $itemList Inventory::ItemGroupList($this->getDoctrine()->getManager());
  4890.             $catgoryList Inventory::ProductCategoryList($this->getDoctrine()->getManager());
  4891.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4892.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4893.             $fdmData = array();
  4894.             $em $this->getDoctrine()->getManager();
  4895.             $matchType 'MAXIMUM';
  4896.             if ($request->request->has('matchType') != '') {
  4897.                 $matchType $request->request->get('matchType');
  4898.             }
  4899.             if ($matchType == 'MINIMUM') {
  4900.                 foreach ($QD as $entry) {
  4901.                     if ($entry->getTagPendingAmount() <= 0)
  4902.                         continue;
  4903.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4904.                     $combined_id $entry->getProductFdm();
  4905.                     if (isset($fdmData[$combined_id])) {
  4906.                         $fdmData[$combined_id]['unit'] += $entry->getTagPendingAmount();
  4907.                         $fdmData[$combined_id]['specific_unit'][] = $entry->getTagPendingAmount();
  4908.                         $fdmData[$combined_id]['detailsIds'][] = $entry->getId();
  4909.                         $fdmData[$combined_id]['docIds'][] = $entry->getStockRequisitionId();
  4910.                     } else {
  4911.                         $fdmData[$combined_id] = array(
  4912.                             'id' => 0,
  4913.                             'alias' => $entry->getNote(),
  4914.                             'unit' => $entry->getTagPendingAmount(),
  4915.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4916.                             'warranty' => 0,
  4917.                             'unitTypeId' => 0,
  4918.                             'unit_price' => 0,
  4919.                             'fdm' => $combined_id,
  4920.                             'extDetailsId' => 0,
  4921.                             'product_name' => $productData['productName'],
  4922.                             'total_price' => 0,
  4923.                             'detailsIds' => [$entry->getId()],
  4924.                             'docIds' => [$entry->getStockRequisitionId()],
  4925.                         );
  4926.                     }
  4927.                 }
  4928.             }
  4929.             if ($matchType == 'MAXIMUM') {
  4930.                 foreach ($QD as $entry) {
  4931.                     if ($entry->getTagPendingAmount() <= 0)
  4932.                         continue;
  4933.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4934.                     $combined_id $entry->getProductFdm();
  4935.                     $assigned 0;
  4936.                     foreach ($fdmData as $key_ind => $rel_val) {
  4937.                         $matchFdm Inventory::MatchFdm($key_ind$combined_id);
  4938.                         if ($matchFdm['hasMatched'] == 1) {
  4939.                             if ($matchFdm['isIdentical'] == 1) {
  4940.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4941.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4942.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4943.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4944.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4945.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4946.                                 $assigned 1;
  4947.                             } elseif ($matchFdm['SecondBelongsToFirst'] == 1) {
  4948.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4949.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4950.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4951.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4952.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4953.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4954.                                 $assigned 1;
  4955.                             } elseif ($matchFdm['FirstBelongsToSecond'] == 1) {
  4956.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4957.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4958.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4959.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4960.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4961.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4962.                                 $fdmData[$combined_id] = $fdmData[$key_ind];
  4963.                                 unset($fdmData[$key_ind]);
  4964.                                 $assigned 1;
  4965.                             }
  4966.                         } else {
  4967.                         }
  4968.                         if ($assigned == 1)
  4969.                             break;
  4970.                     }
  4971.                     if ($assigned == 0) {
  4972.                         $fdmData[$combined_id] = array(
  4973.                             'id' => 0,
  4974.                             'alias' => $entry->getNote(),
  4975.                             'unit' => $entry->getTagPendingAmount(),
  4976.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4977.                             'specific_unit_type_id' => [$entry->getUnitTypeId()],
  4978.                             'warranty' => 0,
  4979.                             'unitTypeId' => $productData['unitTypeId'],
  4980. //                            'unitTypeId' => $productData['unitTypeId'],
  4981.                             'unit_price' => 0,
  4982.                             'fdm' => $combined_id,
  4983.                             'extDetailsId' => 0,
  4984.                             'product_name' => htmlspecialchars($productData['productName']),
  4985.                             'total_price' => 0,
  4986.                             'detailsIds' => [$entry->getId()],
  4987.                             'docIds' => [$entry->getStockRequisitionId()],
  4988.                         );
  4989.                     }
  4990.                     if (isset($fdmData[$combined_id])) {
  4991.                     } else {
  4992.                     }
  4993.                 }
  4994.             }
  4995.             $QD $this->getDoctrine()
  4996.                 ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  4997.                 ->findBy(
  4998.                     array('stockRequisitionId' => $request->request->get('srId'))
  4999.                 );
  5000.             $contentNote "";
  5001.             foreach ($QD as $r) {
  5002.                 $contentNote .= $r->getNote();
  5003.                 $contentNote .= " , ";
  5004.             }
  5005.             foreach ($fdmData as $dt) {
  5006.                 $Content[] = $dt;
  5007.             }
  5008.             if ($Content) {
  5009.                 return new JsonResponse(array("success" => true"content" => $Content"contentNote" => $contentNote));
  5010.             }
  5011.             return new JsonResponse(array("success" => false));
  5012.         }
  5013.         return new JsonResponse(array("success" => false));
  5014.     }
  5015.     public function GetGrnListForEiAction(Request $request)
  5016.     {
  5017.         if ($request->isMethod('POST')) {
  5018.             $find_array = array(
  5019.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  5020.                 'approved' => GeneralConstant::APPROVED,
  5021.                 'invoiceTagged' => 1
  5022.             );
  5023.             $Content = [];
  5024.             $Content_obj = [];
  5025.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  5026.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  5027.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  5028.             if ($request->request->get('poId') != '')
  5029.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  5030.             if ($request->request->get('grnId') != '')
  5031.                 $find_array['grnId'] = $request->request->get('grnId');
  5032.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5033.             $QD_GRN $this->getDoctrine()
  5034.                 ->getRepository('ApplicationBundle\\Entity\\Grn')
  5035.                 ->findBy(
  5036.                     $find_array,
  5037.                     array(
  5038.                         'grnDate' => 'ASC'
  5039.                     )
  5040.                 );
  5041.             $poId 0;
  5042. //
  5043. //            $expense_id=$QD_GRN->getExpenseId()!=''?json_decode($QD_GRN->getExpenseId()):[];
  5044. //                $expense_list=$QD_GRN->getExpenseCost()!=''?json_decode($QD_GRN->getExpenseCost()):[];
  5045. //                $expense_tagged=$QD_GRN->getExpenseTagged()!=''?json_decode($QD_GRN->getExpenseTagged()):[];
  5046.             $partyId $request->request->get('partyId');
  5047.             $bill_details = [];
  5048.             $bill_details_data = [];
  5049.             $bill_details_for_grn = [];
  5050.             $exp_list InventoryConstant::$Expense_list_details;
  5051.             $supp_list Inventory::ProductSupplierList($this->getDoctrine()->getManager());
  5052.             $head_qry $this->getDoctrine()
  5053.                 ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  5054.                 ->findAll();
  5055.             $head_list = [];
  5056.             $head_list_by_advance = [];
  5057.             foreach ($head_qry as $data) {
  5058.                 $head_list[$data->getAccountsHeadId()] = array(
  5059.                     'id' => $data->getAccountsHeadId(),
  5060.                     'name' => $data->getName(),
  5061.                     'advanceTagged' => $data->getAdvanceTagged(),
  5062.                     'advanceOf' => $data->getAdvanceOf(),
  5063.                     'balance' => $data->getCurrentBalance()
  5064.                 );
  5065.                 if ($data->getAdvanceOf() != null && $data->getAdvanceOf() != && $data->getAdvanceOf() != '')
  5066.                     $head_list_by_advance[$data->getAdvanceOf()] = array(
  5067.                         'id' => $data->getAccountsHeadId(),
  5068.                         'name' => $data->getName(),
  5069.                         'advanceTagged' => $data->getAdvanceTagged(),
  5070.                         'advanceOf' => $data->getAdvanceOf(),
  5071.                         'balance' => $data->getCurrentBalance()
  5072.                     );
  5073.             }
  5074.             $exp_def_head = [];
  5075.             foreach ($exp_list as $key => $item) {
  5076.                 $def_settings $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  5077.                     'name' => $item['name'] . '_onsite_head'
  5078.                 ));
  5079.                 if ($def_settings)
  5080.                     $exp_def_head[$item['id']] = $def_settings->getData();
  5081.                 else
  5082.                     $exp_def_head[$item['id']] = '';
  5083.             }
  5084.             $bill_details_by_party = [];
  5085. //            System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($QD_GRN),'debug_data');
  5086. //            System::log_it($this->container->getParameter('kernel.root_dir'),$partyId,'debug_data');
  5087. //            System::log_it($this->container->getParameter('kernel.root_dir'),"\nexp list here".json_encode($exp_list),'debug_data');
  5088. //
  5089.             foreach ($QD_GRN as $key => $value) {
  5090.                 $expense_id $value->getExpenseId() != '' json_decode($value->getExpenseId(), true) : [];
  5091.                 $expense_list $value->getExpenseCost() != '' json_decode($value->getExpenseCost(), true) : [];
  5092.                 $expense_tagged $value->getExpenseTagged() != '' json_decode($value->getExpenseTagged(), true) : [];
  5093. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_id),'debug_data');
  5094. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_list),'debug_data');
  5095.                 foreach ($exp_list as $chabi => $entry) {
  5096. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nChabi ".$chabi,'debug_data');
  5097. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nkeys are ".array_keys($expense_id),'debug_data');
  5098.                     if (array_key_exists($chabi$expense_id)) {
  5099. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nFOUND KEY!! ",'debug_data');
  5100.                         if ($partyId == ''//all
  5101.                         {
  5102.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  5103.                                 $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  5104.                                 $advance_balance 0;
  5105.                                 if ($partyHeadId != 0) {
  5106.                                     $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  5107.                                     $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  5108.                                     $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  5109.                                 }
  5110.                                 $bill_details_by_party[$my_val][] = array(
  5111.                                     'partyId' => $my_val,
  5112.                                     'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  5113.                                     'partyHeadId' => $partyHeadId,
  5114.                                     'expTypeId' => $chabi,
  5115.                                     'expTypeName' => $exp_list[$chabi]['name'],
  5116.                                     'expTypeAlias' => $exp_list[$chabi]['alias'],
  5117.                                     'expAmount' => $expense_list[$chabi][$index],
  5118.                                     'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  5119.                                     'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  5120.                                     'AdvanceBalance' => $advance_balance,
  5121.                                     'grnId' => $value->getGrnId(),
  5122.                                     'grnName' => $value->getDocumentHash(),
  5123.                                 );
  5124.                             }
  5125.                         } else {
  5126.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  5127.                                 if (in_array($my_val$partyId)) {
  5128.                                     $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  5129.                                     $advance_balance 0;
  5130.                                     if ($partyHeadId != 0) {
  5131.                                         $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  5132.                                         $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  5133.                                         $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  5134.                                     }
  5135.                                     $bill_details_by_party[$my_val][] = array(
  5136.                                         'partyId' => $my_val,
  5137.                                         'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  5138.                                         'partyHeadId' => $partyHeadId,
  5139.                                         'expTypeId' => $chabi,
  5140.                                         'expTypeName' => $exp_list[$chabi]['name'],
  5141.                                         'expTypeAlias' => $exp_list[$chabi]['alias'],
  5142.                                         'expAmount' => $expense_list[$chabi][$index],
  5143.                                         'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  5144.                                         'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  5145.                                         'AdvanceBalance' => $advance_balance,
  5146.                                         'grnId' => $value->getGrnId(),
  5147.                                         'grnName' => $value->getDocumentHash(),
  5148.                                     );
  5149.                                 }
  5150.                             }
  5151.                         }
  5152.                     }
  5153.                 }
  5154.             }
  5155. //            $Content_obj=
  5156. //
  5157. //            foreach($Content_obj as $item)
  5158. //            {
  5159. //                $Content[]=$item;
  5160. //
  5161. //            }
  5162.             $list_of_keys array_keys($bill_details_by_party);
  5163.             if ($bill_details_by_party) {
  5164.                 return new JsonResponse(array("success" => true"content" => $bill_details_by_party'index' => $list_of_keys'h_l_b_a' => $head_list_by_advance));
  5165.             }
  5166.             return new JsonResponse(array("success" => false));
  5167.         }
  5168.         return new JsonResponse(array("success" => false));
  5169.     }
  5170.     public function GetServiceListForPiAction(Request $request)
  5171.     {
  5172.         if ($request->isMethod('POST')) {
  5173. //            $find_array=array(
  5174. //                'stage' =>  GeneralConstant::STAGE_PENDING_TAG,
  5175. //                'approved'=>GeneralConstant::APPROVED
  5176. //            );
  5177.             $Content = [];
  5178.             $Content_obj = [];
  5179.             $ContentService = [];
  5180.             $Content_service_obj = [];
  5181. //            $warehouse=Inventory::WarehouseList($this->getDoctrine()->getManager());
  5182. //            $poList=Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  5183. //            $productList=Inventory::ProductList($this->getDoctrine()->getManager());
  5184.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  5185.             if ($request->request->get('poId') != '')
  5186.                 $poId $request->request->get('poId');
  5187.             if ($request->request->get('grnId') != '')
  5188.                 $find_array['grnId'] = $request->request->get('grnId');
  5189.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5190.             //adding service data temporarily
  5191.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(
  5192.                 array('purchaseOrderId' => $poId));
  5193.             $multiply_type $po->getCurrencyMultiply();
  5194.             $multiply_rate $po->getCurrencyMultiplyRate();
  5195.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  5196.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  5197.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5198.                 array('purchaseOrderId' => $poId));
  5199.             foreach ($po_items as $item) {
  5200. //                $po_item_list[$item->getProductId()]=$item;
  5201.                 //temporary service add
  5202.                 if ($item->getType() == 2)
  5203.                     $Content_service_obj[$item->getId()] = array(
  5204.                         'serviceId' => $item->getServiceId(),
  5205.                         'poItemId' => $item->getId(),
  5206.                         'colorId' => 0,
  5207.                         'sizeId' => 0,
  5208.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  5209.                         'qty' => $item->getQty(),
  5210.                         'balance' => $item->getBalance(),
  5211.                         'unit_name' => '',
  5212.                         'unit_price' => $item->getPrice() * $multiplier,
  5213.                         'grn_id' => 0,
  5214.                     );
  5215.                 //temprary service add end
  5216.             }
  5217.             //temporary service data adding done
  5218.             $po_data = [];
  5219.             $po_data = array(
  5220.                 'docHash' => $po->getDocumentHash(),
  5221.                 'docDate' => $po->getPurchaseOrderDate(),
  5222.                 'supplierId' => $po->getSupplierId(),
  5223.                 'supplierName' => $po->getSupplierId(),
  5224.                 'vatRate' => $po->getVatRate(),
  5225.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  5226.                 'aitRate' => $po->getAitRate(),
  5227.                 'aitAmount' => $po->getAitAmount(),
  5228.                 'tdsRate' => $po->getTdsRate(),
  5229.                 'tdsAmount' => $po->getTdsAmount(),
  5230.                 'vdsRate' => $po->getVdsRate(),
  5231.                 'vdsAmount' => $po->getVdsAmount(),
  5232.                 'discountRate' => $po->getDiscountRate(),
  5233.                 'discountAmount' => $po->getVatAmount(),
  5234.             );
  5235.             foreach ($Content_obj as $item) {
  5236.                 $Content[] = $item;
  5237.             }
  5238.             foreach ($Content_service_obj as $item) {
  5239.                 $ContentService[] = $item;
  5240.             }
  5241.             if ($Content || $ContentService) {
  5242.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  5243.             }
  5244.             return new JsonResponse(array("success" => false));
  5245.         }
  5246.         return new JsonResponse(array("success" => false));
  5247.     }
  5248.     public function GetGrnListForPiAction(Request $request)
  5249.     {
  5250.         if ($request->isMethod('POST')) {
  5251.             $find_array = array(
  5252.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  5253.                 'approved' => GeneralConstant::APPROVED
  5254.             );
  5255.             $Content = [];
  5256.             $Content_obj = [];
  5257.             $ContentService = [];
  5258.             $Content_service_obj = [];
  5259.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  5260.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  5261.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  5262.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  5263.             if ($request->request->get('poId') != '')
  5264.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  5265.             if ($request->request->get('grnId') != '')
  5266.                 $find_array['grnId'] = $request->request->get('grnId');
  5267.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5268.             $QD_GRN $this->getDoctrine()
  5269.                 ->getRepository('ApplicationBundle\\Entity\\Grn')
  5270.                 ->findBy(
  5271.                     $find_array,
  5272.                     array(
  5273.                         'grnDate' => 'ASC'
  5274.                     )
  5275.                 );
  5276.             $poId 0;
  5277.             foreach ($QD_GRN as $value) {
  5278.                 $grn_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\GrnItem')->findBy(
  5279.                     array('grnId' => $value->getGrnId()));
  5280.                 $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5281.                     array('purchaseOrderId' => $value->getPurchaseOrderId()));
  5282.                 $poId $value->getPurchaseOrderId();
  5283.                 $po_item_list = [];
  5284.                 foreach ($po_items as $item) {
  5285.                     $po_item_list[$item->getProductId()] = $item;
  5286.                 }
  5287.                 foreach ($grn_items as $entry) {
  5288.                     //adding transaction
  5289. //                    System::log_it($this->container->getParameter('kernel.root_dir'),$entry->getProductId(),'debug_data');
  5290.                     $Content_obj[$entry->getId()] = array(
  5291.                         'productId' => $entry->getProductId(),
  5292.                         'poItemId' => $entry->getPurchaseOrderItemId(),
  5293.                         'productName' => $productList[$entry->getProductId()]['name'],
  5294.                         'colorId' => $entry->getColorId(),
  5295.                         'sizeId' => $entry->getSizeId(),
  5296.                         'qty' => isset($Content_obj[$entry->getId()]) ? $Content_obj[$entry->getId()]['qty'] + $entry->getQty() : $entry->getQty(),
  5297.                         'unit_name' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  5298. //                            'unit_price'=>$po_item_list[$entry->getProductId()]->getPrice(),
  5299.                         'unit_price' => $entry->getPrice(),
  5300.                         'grn_id' => $entry->getId(),
  5301.                     );
  5302.                 }
  5303. //            for
  5304.             }
  5305.             //adding service data temporarily
  5306.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(
  5307.                 array('purchaseOrderId' => $poId));
  5308.             $multiply_type $po->getCurrencyMultiply();
  5309.             $multiply_rate $po->getCurrencyMultiplyRate();
  5310.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  5311.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  5312.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5313.                 array('purchaseOrderId' => $poId));
  5314.             foreach ($po_items as $item) {
  5315. //                $po_item_list[$item->getProductId()]=$item;
  5316.                 //temporary service add
  5317.                 if ($item->getType() == 2)
  5318.                     $Content_service_obj[$item->getId()] = array(
  5319.                         'serviceId' => $item->getServiceId(),
  5320.                         'poItemId' => $item->getId(),
  5321.                         'colorId' => 0,
  5322.                         'sizeId' => 0,
  5323.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  5324.                         'qty' => $item->getQty(),
  5325.                         'balance' => $item->getBalance(),
  5326.                         'unit_name' => '',
  5327.                         'unit_price' => $item->getPrice() * $multiplier,
  5328.                         'grn_id' => 0,
  5329.                     );
  5330.                 //temprary service add end
  5331.             }
  5332.             //temporary service data adding done
  5333.             $po_data = [];
  5334.             $vatAmount $po->getVatAmount();
  5335.             $priceAfterDiscount $po->getSupplierPayableAmount() - $po->getVatAmount();
  5336.             $vatRate = ($vatAmount $priceAfterDiscount) * 100;
  5337.             $po_data = array(
  5338.                 'docHash' => $po->getDocumentHash(),
  5339.                 'docDate' => $po->getPurchaseOrderDate(),
  5340.                 'supplierId' => $po->getSupplierId(),
  5341.                 'supplierName' => $po->getSupplierId(),
  5342.                 'vatRate' => $vatRate,
  5343.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  5344.                 'aitRate' => $po->getAitRate(),
  5345.                 'aitAmount' => $po->getAitAmount(),
  5346.                 'tdsRate' => $po->getTdsRate(),
  5347.                 'tdsAmount' => $po->getTdsAmount(),
  5348.                 'vdsRate' => $po->getVdsRate(),
  5349.                 'vdsAmount' => $po->getVdsAmount(),
  5350.                 'discountRate' => $po->getDiscountRate(),
  5351. //                'discountAmount' => $po->getVatAmount(),
  5352.                 'vatAmount' => $vatAmount,
  5353.                 'discountAmount' => $po->getDiscountAmount(),
  5354.                 'supplierPayableAmount' => $po->getSupplierPayableAmount(),
  5355.                 'priceAfterDiscount' => $priceAfterDiscount
  5356.             );
  5357.             foreach ($Content_obj as $item) {
  5358.                 $Content[] = $item;
  5359.             }
  5360.             foreach ($Content_service_obj as $item) {
  5361.                 $ContentService[] = $item;
  5362.             }
  5363.             if ($Content) {
  5364.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  5365.             }
  5366.             return new JsonResponse(array("success" => false));
  5367.         }
  5368.         return new JsonResponse(array("success" => false));
  5369.     }
  5370.     public function GetPoDetailsForPiAction(Request $request$poId)
  5371.     {
  5372.     }
  5373.     public function GetPoDetailsAction(Request $request$poId)
  5374.     {
  5375.         if ($request->isMethod('POST')) {
  5376.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findBy(
  5377.                 array('purchaseOrderId' => $poId));
  5378.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5379.                 array('purchaseOrderId' => $poId));
  5380.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  5381.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5382.             $spec_type Inventory::SpecTypeList($this->getDoctrine()->getManager());
  5383.             $Content = [];
  5384.             $po_items_list = [];
  5385.             foreach ($po_items as $entry) {
  5386.                 $po_items_list[] = array(
  5387.                     'productId' => $entry->getProductId(),
  5388.                     'productName' => $productList[$entry->getProductId()]['name'],
  5389.                     'price' => $entry->getPrice(),
  5390.                     'unit' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  5391.                     'spec' => $spec_type[$productList[$entry->getProductId()]['spec_type']]['name'],
  5392.                     'received' => $entry->getReceived(),
  5393.                     'qty' => $entry->getQty(),
  5394.                     'balance' => $entry->getBalance()
  5395.                 );
  5396.             }
  5397.             $po_data = [];
  5398.             $po_data = array(
  5399.                 'docHash' => $po->getDocumentHash(),
  5400.                 'docDate' => $po->getPurchaseOrderDate(),
  5401.                 'supplierId' => $po->getSupplierId(),
  5402.                 'supplierName' => $po->getSupplierId(),
  5403.             );
  5404.             if ($po_data) {
  5405.                 return new JsonResponse(array("success" => true"content" => $po_data));
  5406.             }
  5407.             return new JsonResponse(array("success" => false));
  5408.         }
  5409.         return new JsonResponse(array("success" => false));
  5410.     }
  5411.     public function CreateSalesReplacementAction(Request $request)
  5412.     {
  5413.         $em $this->getDoctrine()->getManager();
  5414.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5415.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5416.         if ($request->isMethod('POST')) {
  5417.             $em $this->getDoctrine()->getManager();
  5418.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesReplacement']; //change
  5419.             $dochash $request->request->get('voucherNumber'); //change
  5420.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5421.             $approveRole $request->request->get('approvalRole');
  5422.             $approveHash $request->request->get('approvalHash');
  5423.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5424.                 $loginId$approveRole$approveHash)
  5425.             ) {
  5426.                 $this->addFlash(
  5427.                     'error',
  5428.                     'Sorry Couldnot insert Data.'
  5429.                 );
  5430.             } else {
  5431.                 if ($request->request->has('check_allowed'))
  5432.                     $check_allowed 1;
  5433.                 $StID Inventory::CreateNewSalesReplacement(
  5434.                     $this->getDoctrine()->getManager(),
  5435.                     $request->request,
  5436.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5437.                     $this->getLoggedUserCompanyId($request)
  5438.                 );
  5439.                 //now add Approval info
  5440.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5441.                 $approveRole 1;  //created
  5442.                 $options = array(
  5443.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5444.                     'notification_server' => $this->container->getParameter('notification_server'),
  5445.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5446.                     'url' => $this->generateUrl(
  5447.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesReplacement']]
  5448.                         ['entity_view_route_path_name']
  5449.                     )
  5450.                 );
  5451.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5452.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5453.                     $StID,
  5454.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5455.                 );
  5456.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesReplacement'], $StID,
  5457.                     $loginId,
  5458.                     $approveRole,
  5459.                     $request->request->get('approvalHash'));
  5460.                 $this->addFlash(
  5461.                     'success',
  5462.                     'Stock Transfer Added.'
  5463.                 );
  5464.                 $url $this->generateUrl(
  5465.                     'view_st'
  5466.                 );
  5467.                 return $this->redirect($url "/" $StID);
  5468.             }
  5469.         }
  5470.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  5471.             array(
  5472.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5473.             )
  5474.         );
  5475.         $INVLIST = [];
  5476.         foreach ($slotList as $slot) {
  5477.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5478.         }
  5479.         return $this->render('@Inventory/pages/input_forms/sales_replacement.html.twig',
  5480.             array(
  5481.                 'page_title' => 'Sales Replacement Note',
  5482.                 'warehouseList' => Inventory::WarehouseList($em),
  5483.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5484.                 'warehouseActionList' => $warehouse_action_list,
  5485.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5486.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5487.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5488.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5489.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5490.                 'prefix_list' => array(
  5491.                     [
  5492.                         'id' => 1,
  5493.                         'value' => 'GN',
  5494.                         'text' => 'GN'
  5495.                     ]
  5496.                 ),
  5497.                 'assoc_list' => array(
  5498.                     [
  5499.                         'id' => 1,
  5500.                         'value' => 1,
  5501.                         'text' => 'GN'
  5502.                     ]
  5503.                 ),
  5504.                 'INVLIST' => $INVLIST
  5505.             )
  5506.         );
  5507.     }
  5508.     public function SalesReplacementListAction(Request $request)
  5509.     {
  5510.         $q $this->getDoctrine()
  5511.             ->getRepository('ApplicationBundle\\Entity\\SalesReplacement')
  5512.             ->findBy(
  5513.                 array(
  5514.                     'status' => GeneralConstant::ACTIVE,
  5515.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5516. //                    'approved' =>  GeneralConstant::APPROVED,
  5517.                 )
  5518.             );
  5519.         $stage_list = array(
  5520.             => 'Pending',
  5521.             => 'Pending',
  5522.             => 'Complete',
  5523.             => 'Partial',
  5524.         );
  5525.         $data = [];
  5526.         foreach ($q as $entry) {
  5527.             $data[] = array(
  5528.                 'doc_date' => $entry->getSalesReplacementDate(),
  5529.                 'id' => $entry->getSalesReplacementId(),
  5530.                 'doc_hash' => $entry->getDocumentHash(),
  5531.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5532.                 'stage' => $stage_list[$entry->getStage()]
  5533.             );
  5534.         }
  5535.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5536.             array(
  5537.                 'page_title' => 'Stock Transfer List',
  5538.                 'data' => $data
  5539.             )
  5540.         );
  5541.     }
  5542.     public function ViewSalesReplacementAction(Request $request$id)
  5543.     {
  5544.         $em $this->getDoctrine()->getManager();
  5545.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5546.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  5547.             array(
  5548.                 'page_title' => 'Stock Transfer',
  5549.                 'data' => $dt,
  5550.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5551.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5552.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5553.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5554.                     $id,
  5555.                     $dt['created_by'],
  5556.                     $dt['edited_by'])
  5557.             )
  5558.         );
  5559.     }
  5560.     public function PrintSalesReplacementAction(Request $request$id)
  5561.     {
  5562.         $em $this->getDoctrine()->getManager();
  5563.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5564.         $company_data Company::getCompanyData($em1);
  5565.         $document_mark = array(
  5566.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5567.             'copy' => ''
  5568.         );
  5569.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5570.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5571.                 array(
  5572.                     //full array here
  5573.                     'pdf' => true,
  5574.                     'page_title' => 'Stock Transfer',
  5575.                     'export' => 'pdf,print',
  5576.                     'data' => $dt,
  5577.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5578.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5579.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5580.                         array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5581.                         $id,
  5582.                         $dt['created_by'],
  5583.                         $dt['edited_by']),
  5584.                     'document_mark_image' => $document_mark['original'],
  5585.                     'company_name' => $company_data->getName(),
  5586.                     'company_data' => $company_data,
  5587.                     'company_address' => $company_data->getAddress(),
  5588.                     'company_image' => $company_data->getImage(),
  5589.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5590.                     'red' => 0
  5591.                 )
  5592.             );
  5593.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5594. //                'orientation' => 'landscape',
  5595. //                'enable-javascript' => true,
  5596. //                'javascript-delay' => 1000,
  5597.                 'no-stop-slow-scripts' => false,
  5598.                 'no-background' => false,
  5599.                 'lowquality' => false,
  5600.                 'encoding' => 'utf-8',
  5601. //            'images' => true,
  5602. //            'cookie' => array(),
  5603.                 'dpi' => 300,
  5604.                 'image-dpi' => 300,
  5605. //                'enable-external-links' => true,
  5606. //                'enable-internal-links' => true
  5607.             ));
  5608.             return new Response(
  5609.                 $pdf_response,
  5610.                 200,
  5611.                 array(
  5612.                     'Content-Type' => 'application/pdf',
  5613.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5614.                 )
  5615.             );
  5616.         }
  5617.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5618.             array(
  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.     }
  5639.     public function CreateStockTransferAction(Request $request)
  5640.     {
  5641.         $em $this->getDoctrine()->getManager();
  5642.         $companyId $this->getLoggedUserCompanyId($request);
  5643.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5644.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5645.         if ($request->isMethod('POST')) {
  5646.             $em $this->getDoctrine()->getManager();
  5647.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  5648.             $dochash $request->request->get('docHash'); //change
  5649.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5650.             $approveRole $request->request->get('approvalRole');
  5651.             $approveHash $request->request->get('approvalHash');
  5652.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5653.                 $loginId$approveRole$approveHash)
  5654.             ) {
  5655.                 $this->addFlash(
  5656.                     'error',
  5657.                     'Sorry Couldnot insert Data.'
  5658.                 );
  5659.             } else {
  5660.                 if ($request->request->has('check_allowed'))
  5661.                     $check_allowed 1;
  5662.                 $StID Inventory::CreateNewStockTransfer(
  5663.                     $this->getDoctrine()->getManager(),
  5664.                     $request->request,
  5665.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5666.                     $this->getLoggedUserCompanyId($request)
  5667.                 );
  5668.                 //now add Approval info
  5669.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5670.                 $approveRole 1;  //created
  5671.                 $options = array(
  5672.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5673.                     'notification_server' => $this->container->getParameter('notification_server'),
  5674.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5675.                     'url' => $this->generateUrl(
  5676.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  5677.                         ['entity_view_route_path_name']
  5678.                     )
  5679.                 );
  5680.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5681.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5682.                     $StID,
  5683.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  5684.                 );
  5685.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  5686.                     $loginId,
  5687.                     $approveRole,
  5688.                     $request->request->get('approvalHash'));
  5689.                 $this->addFlash(
  5690.                     'success',
  5691.                     'Stock Transfer Added.'
  5692.                 );
  5693.                 $url $this->generateUrl(
  5694.                     'view_st'
  5695.                 );
  5696.                 return $this->redirect($url "/" $StID);
  5697.             }
  5698.         }
  5699. //        $slotList = $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  5700. //            array(
  5701. //                'CompanyId' => $this->getLoggedUserCompanyId($request),
  5702. //
  5703. //            )
  5704. //        );
  5705.         $INVLIST = [];
  5706. //        foreach ($slotList as $slot) {
  5707. //            $INVLIST[$slot->getWarehouseId() . '_' . $slot->getActionTagId() . '_' . $slot->getproductId()] = $slot->getQty();
  5708. //        }
  5709.         return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  5710.             array(
  5711.                 'page_title' => 'Stock Transfer Note',
  5712.                 'warehouseList' => Inventory::WarehouseList($em),
  5713.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5714.                 'colorList' => Inventory::GetColorList($em),
  5715.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  5716.                 'srList' => [],
  5717.                 'warehouseActionList' => $warehouse_action_list,
  5718.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5719.                 'item_list' => Inventory::ItemGroupList($em),
  5720.                 'item_list_array' => Inventory::ItemGroupListArray($em),
  5721.                 'category_list_array' => Inventory::ProductCategoryListArray($em),
  5722.                 'product_list_array' => Inventory::ProductListDetailedArray($em),
  5723. //                'product_list_array' => [],
  5724.                 'product_list' => Inventory::ProductList($em$companyId),
  5725. //                'product_list' => [],
  5726.                 'prefix_list' => array(
  5727.                     [
  5728.                         'id' => 1,
  5729.                         'value' => 'GN',
  5730.                         'text' => 'GN'
  5731.                     ]
  5732.                 ),
  5733.                 'assoc_list' => array(
  5734.                     [
  5735.                         'id' => 1,
  5736.                         'value' => 1,
  5737.                         'text' => 'GN'
  5738.                     ]
  5739.                 ),
  5740.                 'INVLIST' => $INVLIST
  5741.             )
  5742.         );
  5743.     }
  5744.     public function GetSrItemForTransferAction(Request $request)
  5745.     {
  5746.         $em $this->getDoctrine()->getManager();
  5747.         $search_query = [];
  5748.         $res_data_by_so_item_id = [];
  5749.         $Content = [];
  5750.         $productionProcessSettings = array(
  5751.             'id' => 0
  5752.         );
  5753.         if ($request->query->has('srId'))
  5754.             $search_query['stockRequisitionId'] = $request->query->get('srId');
  5755.         $DT $this->getDoctrine()
  5756.             ->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')
  5757.             ->findBy(
  5758.                 $search_query
  5759.             );
  5760.         $Content = array(
  5761.             'requisitioned_product_item_id' => [],
  5762.             'requisitioned_products' => [],
  5763.             'requisitioned_product_fdm' => [],
  5764.             'requisitioned_product_name' => [],
  5765.             'requisitioned_product_units' => [],
  5766.             'requisitioned_product_unit_type' => [],
  5767.             'requisitioned_product_balance' => [],
  5768.         );
  5769.         foreach ($DT as $dt) {
  5770. //            $data=json_decode($DT->getData(),true);
  5771.             $Content['requisitioned_products'][] = $dt->getProductId();
  5772.             $Content['requisitioned_product_item_id'][] = $dt->getId();
  5773.             $Content['requisitioned_product_fdm'][] = $dt->getProductFdm();
  5774.             $Content['requisitioned_product_name'][] = $dt->getProductNameFdm();
  5775.             $Content['requisitioned_product_units'][] = $dt->getQty();
  5776.             $Content['requisitioned_product_balance'][] = $dt->getAlottmentPendingAmount();
  5777.         }
  5778.         $INVLIST = [];
  5779.         if (!empty($Content)) {
  5780.             return new JsonResponse(array("success" => true"content" => $Content"INVLIST" => $INVLIST));
  5781.         } else {
  5782.             return new JsonResponse(array("success" => false"content" => $Content"INVLIST" => $INVLIST));
  5783.         }
  5784.     }
  5785.     public function StockTransferListAction(Request $request)
  5786.     {
  5787.         $q $this->getDoctrine()
  5788.             ->getRepository('ApplicationBundle\\Entity\\StockTransfer')
  5789.             ->findBy(
  5790.                 array(
  5791.                     'status' => GeneralConstant::ACTIVE,
  5792.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5793. //                    'approved' =>  GeneralConstant::APPROVED,
  5794.                 )
  5795.             );
  5796.         $stage_list = array(
  5797.             => 'Pending',
  5798.             => 'Pending',
  5799.             => 'Complete',
  5800.             => 'Partial',
  5801.         );
  5802.         $data = [];
  5803.         foreach ($q as $entry) {
  5804.             $data[] = array(
  5805.                 'doc_date' => $entry->getStockTransferDate(),
  5806.                 'id' => $entry->getStockTransferId(),
  5807.                 'doc_hash' => $entry->getDocumentHash(),
  5808.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5809.                 'stage' => $stage_list[$entry->getStage()]
  5810.             );
  5811.         }
  5812.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5813.             array(
  5814.                 'page_title' => 'Stock Transfer List',
  5815.                 'data' => $data
  5816.             )
  5817.         );
  5818.     }
  5819.     public function ViewStockTransferAction(Request $request$id)
  5820.     {
  5821.         $em $this->getDoctrine()->getManager();
  5822.         $dt Inventory::GetStockTransferDetails($em$id);
  5823.         return $this->render(
  5824.             '@Inventory/pages/views/view_stock_transfer.html.twig',
  5825.             array(
  5826.                 'page_title' => 'Stock Transfer',
  5827.                 'data' => $dt,
  5828.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5829.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5830.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5831.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5832.                     $id,
  5833.                     $dt['created_by'],
  5834.                     $dt['edited_by'])
  5835.             )
  5836.         );
  5837.     }
  5838.     public function PrintStockTransferAction(Request $request$id)
  5839.     {
  5840.         $em $this->getDoctrine()->getManager();
  5841.         $dt Inventory::GetStockTransferDetails($em$id);
  5842.         $company_data Company::getCompanyData($em1);
  5843.         $document_mark = array(
  5844.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5845.             'copy' => ''
  5846.         );
  5847.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5848.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5849.                 array(
  5850.                     //full array here
  5851.                     'pdf' => true,
  5852.                     'page_title' => 'Stock Transfer',
  5853.                     'export' => 'pdf,print',
  5854.                     'data' => $dt,
  5855.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5856.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5857.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5858.                         array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5859.                         $id,
  5860.                         $dt['created_by'],
  5861.                         $dt['edited_by']),
  5862.                     'document_mark_image' => $document_mark['original'],
  5863.                     'company_name' => $company_data->getName(),
  5864.                     'company_data' => $company_data,
  5865.                     'company_address' => $company_data->getAddress(),
  5866.                     'company_image' => $company_data->getImage(),
  5867.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5868.                     'red' => 0
  5869.                 )
  5870.             );
  5871.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5872. //                'orientation' => 'landscape',
  5873. //                'enable-javascript' => true,
  5874. //                'javascript-delay' => 1000,
  5875.                 'no-stop-slow-scripts' => false,
  5876.                 'no-background' => false,
  5877.                 'lowquality' => false,
  5878.                 'encoding' => 'utf-8',
  5879. //            'images' => true,
  5880. //            'cookie' => array(),
  5881.                 'dpi' => 300,
  5882.                 'image-dpi' => 300,
  5883. //                'enable-external-links' => true,
  5884. //                'enable-internal-links' => true
  5885.             ));
  5886.             return new Response(
  5887.                 $pdf_response,
  5888.                 200,
  5889.                 array(
  5890.                     'Content-Type' => 'application/pdf',
  5891.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5892.                 )
  5893.             );
  5894.         }
  5895.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5896.             array(
  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.     }
  5917.     public function CreateStockConsumptionNoteAction(Request $request)
  5918.     {
  5919.         $em $this->getDoctrine()->getManager();
  5920.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5921.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5922.         if ($request->isMethod('POST')) {
  5923.             $em $this->getDoctrine()->getManager();
  5924.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']; //change
  5925.             $dochash $request->request->get('voucherNumber'); //change
  5926.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5927.             $approveRole $request->request->get('approvalRole');
  5928.             $approveHash $request->request->get('approvalHash');
  5929.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5930.                 $loginId$approveRole$approveHash)
  5931.             ) {
  5932.                 $this->addFlash(
  5933.                     'error',
  5934.                     'Sorry Could not insert Data.'
  5935.                 );
  5936.             } else {
  5937.                 if ($request->request->has('check_allowed'))
  5938.                     $check_allowed 1;
  5939.                 $StID Inventory::CreateNewStockConsumptionNote(
  5940.                     $this->getDoctrine()->getManager(),
  5941.                     $request->request,
  5942.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5943.                     $this->getLoggedUserCompanyId($request)
  5944.                 );
  5945.                 //now add Approval info
  5946.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5947.                 $approveRole 1;  //created
  5948.                 $options = array(
  5949.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5950.                     'notification_server' => $this->container->getParameter('notification_server'),
  5951.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5952.                     'url' => $this->generateUrl(
  5953.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']]
  5954.                         ['entity_view_route_path_name']
  5955.                     )
  5956.                 );
  5957.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5958.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5959.                     $StID,
  5960.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5961.                 );
  5962.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'], $StID,
  5963.                     $loginId,
  5964.                     $approveRole,
  5965.                     $request->request->get('approvalHash'));
  5966.                 $this->addFlash(
  5967.                     'success',
  5968.                     'Stock Consumption Added.'
  5969.                 );
  5970.                 $url $this->generateUrl(
  5971.                     'view_stock_consumption_note'
  5972.                 );
  5973.                 return $this->redirect($url "/" $StID);
  5974.             }
  5975.         }
  5976.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  5977.             array(
  5978.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5979.             )
  5980.         );
  5981.         $INVLIST = [];
  5982.         foreach ($slotList as $slot) {
  5983.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5984.         }
  5985.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  5986.             array(
  5987.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5988.             )
  5989.         );
  5990.         $consumptionTypeList = [];
  5991.         $consumptionTypeListArray = [];
  5992.         foreach ($consumptionTypeQry as $entry) {
  5993.             $p = array(
  5994.                 'name' => $entry->getName(),
  5995.                 'id' => $entry->getConsumptionTypeId(),
  5996.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5997.                 'cost_center_id' => $entry->getCostCenterId(),
  5998.             );
  5999.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  6000.             $consumptionTypeListArray[] = $p;
  6001.         }
  6002.         //add bill list
  6003.         $service_purchase_bill_query $this->getDoctrine()
  6004.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  6005.             ->findBy(
  6006.                 array(
  6007.                     'typeHash' => 'SPB',
  6008.                     'approved' => GeneralConstant::APPROVED
  6009.                 )
  6010.             );
  6011.         $service_purchase_bill_list = [];
  6012.         $service_purchase_bill_list_array = [];
  6013.         $bill = array(
  6014.             'id' => 0,
  6015.             'type' => 'SPB',
  6016.             'name' => 'New Expense',
  6017.             'text' => 'New Expense',
  6018.             'amount' => 0,
  6019.         );
  6020.         $service_purchase_bill_list[0] = $bill;
  6021.         $service_purchase_bill_list_array[] = $bill;
  6022.         foreach ($service_purchase_bill_query as $d) {
  6023.             $bill = array(
  6024.                 'id' => $d->getPurchaseInvoiceId(),
  6025.                 'type' => 'SPB',
  6026.                 'name' => $d->getDocumentHash(),
  6027.                 'text' => $d->getDocumentHash(),
  6028.                 'amount' => $d->getInvoiceAmount(),
  6029.             );
  6030.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  6031.             $service_purchase_bill_list_array[] = $bill;
  6032.         }
  6033.         return $this->render('@Inventory/pages/input_forms/stock_consumption_note.html.twig',
  6034.             array(
  6035.                 'page_title' => 'Stock Consumption Note',
  6036.                 'warehouseList' => Inventory::WarehouseList($em),
  6037.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  6038.                 'consumptionTypeList' => $consumptionTypeList,
  6039.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  6040.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  6041.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6042.                 'warehouseActionList' => $warehouse_action_list,
  6043.                 'warehouseActionListArray' => $warehouse_action_list_array,
  6044.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6045.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6046.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6047.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6048.                 'product_list' => Inventory::ProductListDetailed($this->getDoctrine()->getManager()),
  6049.                 'prefix_list' => array(
  6050.                     [
  6051.                         'id' => 1,
  6052.                         'value' => 'GN',
  6053.                         'text' => 'GN'
  6054.                     ]
  6055.                 ),
  6056.                 'assoc_list' => array(
  6057.                     [
  6058.                         'id' => 1,
  6059.                         'value' => 1,
  6060.                         'text' => 'GN'
  6061.                     ]
  6062.                 ),
  6063.                 'INVLIST' => $INVLIST
  6064.             )
  6065.         );
  6066.     }
  6067.     public function StockConsumptionNoteListAction(Request $request)
  6068.     {
  6069.         $q $this->getDoctrine()
  6070.             ->getRepository('ApplicationBundle\\Entity\\StockConsumptionNote')
  6071.             ->findBy(
  6072.                 array(
  6073.                     'status' => GeneralConstant::ACTIVE,
  6074.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  6075. //                    'approved' =>  GeneralConstant::APPROVED,
  6076.                 )
  6077.             );
  6078.         $stage_list = array(
  6079.             => 'Pending',
  6080.             => 'Pending',
  6081.             => 'Complete',
  6082.             => 'Partial',
  6083.         );
  6084.         $data = [];
  6085.         foreach ($q as $entry) {
  6086.             $data[] = array(
  6087.                 'doc_date' => $entry->getStockConsumptionNoteDate(),
  6088.                 'id' => $entry->getStockConsumptionNoteId(),
  6089.                 'doc_hash' => $entry->getDocumentHash(),
  6090.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  6091.                 'stage' => $stage_list[$entry->getStage()]
  6092.             );
  6093.         }
  6094.         return $this->render('@Inventory/pages/views/stock_consumption_note_list.html.twig',
  6095.             array(
  6096.                 'page_title' => 'Stock Consumption Note List',
  6097.                 'data' => $data
  6098.             )
  6099.         );
  6100.     }
  6101.     public function ViewStockConsumptionNoteAction(Request $request$id)
  6102.     {
  6103.         $em $this->getDoctrine()->getManager();
  6104.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  6105.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  6106.             array(
  6107.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6108.             )
  6109.         );
  6110.         $consumptionTypeList = [];
  6111.         $consumptionTypeListArray = [];
  6112.         foreach ($consumptionTypeQry as $entry) {
  6113.             $p = array(
  6114.                 'name' => $entry->getName(),
  6115.                 'id' => $entry->getConsumptionTypeId(),
  6116.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  6117.                 'cost_center_id' => $entry->getCostCenterId(),
  6118.             );
  6119.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  6120.             $consumptionTypeListArray[] = $p;
  6121.         }
  6122.         //add bill list
  6123.         $service_purchase_bill_query $this->getDoctrine()
  6124.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  6125.             ->findBy(
  6126.                 array(
  6127.                     'typeHash' => 'SPB',
  6128.                     'approved' => GeneralConstant::APPROVED
  6129.                 )
  6130.             );
  6131.         $service_purchase_bill_list = [];
  6132.         $service_purchase_bill_list_array = [];
  6133.         $bill = array(
  6134.             'id' => 0,
  6135.             'type' => 'SPB',
  6136.             'name' => 'New Expense',
  6137.             'text' => 'New Expense',
  6138.             'amount' => 0,
  6139.         );
  6140.         $service_purchase_bill_list[0] = $bill;
  6141.         $service_purchase_bill_list_array[] = $bill;
  6142.         foreach ($service_purchase_bill_query as $d) {
  6143.             $bill = array(
  6144.                 'id' => $d->getPurchaseInvoiceId(),
  6145.                 'type' => 'SPB',
  6146.                 'name' => $d->getDocumentHash(),
  6147.                 'text' => $d->getDocumentHash(),
  6148.                 'amount' => $d->getInvoiceAmount(),
  6149.             );
  6150.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  6151.             $service_purchase_bill_list_array[] = $bill;
  6152.         }
  6153.         return $this->render(
  6154.             '@Inventory/pages/views/view_stock_consumption_note.html.twig',
  6155.             array(
  6156.                 'page_title' => 'Stock Transfer',
  6157.                 'data' => $dt,
  6158.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  6159.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6160.                 'consumptionTypeList' => $consumptionTypeList,
  6161.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  6162.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6163.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6164.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6165.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6166.                     $id,
  6167.                     $dt['created_by'],
  6168.                     $dt['edited_by'])
  6169.             )
  6170.         );
  6171.     }
  6172.     public function PrintStockConsumptionNoteAction(Request $request$id)
  6173.     {
  6174.         $em $this->getDoctrine()->getManager();
  6175.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  6176.         $company_data Company::getCompanyData($em1);
  6177.         $document_mark = array(
  6178.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6179.             'copy' => ''
  6180.         );
  6181.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  6182.             array(
  6183.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6184.             )
  6185.         );
  6186.         $consumptionTypeList = [];
  6187.         $consumptionTypeListArray = [];
  6188.         foreach ($consumptionTypeQry as $entry) {
  6189.             $p = array(
  6190.                 'name' => $entry->getName(),
  6191.                 'id' => $entry->getConsumptionTypeId(),
  6192.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  6193.                 'cost_center_id' => $entry->getCostCenterId(),
  6194.             );
  6195.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  6196.             $consumptionTypeListArray[] = $p;
  6197.         }
  6198.         //add bill list
  6199.         $service_purchase_bill_query $this->getDoctrine()
  6200.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  6201.             ->findBy(
  6202.                 array(
  6203.                     'typeHash' => 'SPB',
  6204.                     'approved' => GeneralConstant::APPROVED
  6205.                 )
  6206.             );
  6207.         $service_purchase_bill_list = [];
  6208.         $service_purchase_bill_list_array = [];
  6209.         $bill = array(
  6210.             'id' => 0,
  6211.             'type' => 'SPB',
  6212.             'name' => 'New Expense',
  6213.             'text' => 'New Expense',
  6214.             'amount' => 0,
  6215.         );
  6216.         $service_purchase_bill_list[0] = $bill;
  6217.         $service_purchase_bill_list_array[] = $bill;
  6218.         foreach ($service_purchase_bill_query as $d) {
  6219.             $bill = array(
  6220.                 'id' => $d->getPurchaseInvoiceId(),
  6221.                 'type' => 'SPB',
  6222.                 'name' => $d->getDocumentHash(),
  6223.                 'text' => $d->getDocumentHash(),
  6224.                 'amount' => $d->getInvoiceAmount(),
  6225.             );
  6226.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  6227.             $service_purchase_bill_list_array[] = $bill;
  6228.         }
  6229.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6230.             $html $this->renderView('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  6231.                 array(
  6232.                     //full array here
  6233.                     'pdf' => true,
  6234.                     'page_title' => 'Stock Consumption',
  6235.                     'export' => 'pdf,print',
  6236.                     'data' => $dt,
  6237.                     'service_purchase_bill_list' => $service_purchase_bill_list,
  6238.                     'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6239.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6240.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6241.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6242.                         array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6243.                         $id,
  6244.                         $dt['created_by'],
  6245.                         $dt['edited_by']),
  6246.                     'document_mark_image' => $document_mark['original'],
  6247.                     'consumptionTypeList' => $consumptionTypeList,
  6248.                     'consumptionTypeListArray' => $consumptionTypeListArray,
  6249.                     'company_name' => $company_data->getName(),
  6250.                     'company_data' => $company_data,
  6251.                     'company_address' => $company_data->getAddress(),
  6252.                     'company_image' => $company_data->getImage(),
  6253.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6254.                     'red' => 0
  6255.                 )
  6256.             );
  6257.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6258. //                'orientation' => 'landscape',
  6259. //                'enable-javascript' => true,
  6260. //                'javascript-delay' => 1000,
  6261.                 'no-stop-slow-scripts' => false,
  6262.                 'no-background' => false,
  6263.                 'lowquality' => false,
  6264.                 'encoding' => 'utf-8',
  6265. //            'images' => true,
  6266. //            'cookie' => array(),
  6267.                 'dpi' => 300,
  6268.                 'image-dpi' => 300,
  6269. //                'enable-external-links' => true,
  6270. //                'enable-internal-links' => true
  6271.             ));
  6272.             return new Response(
  6273.                 $pdf_response,
  6274.                 200,
  6275.                 array(
  6276.                     'Content-Type' => 'application/pdf',
  6277.                     'Content-Disposition' => 'attachment; filename="stock_consumption_note_' $id '.pdf"'
  6278.                 )
  6279.             );
  6280.         }
  6281.         return $this->render('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  6282.             array(
  6283.                 'page_title' => 'Stock Consumption',
  6284.                 'export' => 'pdf,print',
  6285.                 'data' => $dt,
  6286.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  6287.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6288.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6289.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6290.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6291.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6292.                     $id,
  6293.                     $dt['created_by'],
  6294.                     $dt['edited_by']),
  6295.                 'document_mark_image' => $document_mark['original'],
  6296.                 'consumptionTypeList' => $consumptionTypeList,
  6297.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  6298.                 'company_name' => $company_data->getName(),
  6299.                 'company_data' => $company_data,
  6300.                 'company_address' => $company_data->getAddress(),
  6301.                 'company_image' => $company_data->getImage(),
  6302.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6303.                 'red' => 0
  6304.             )
  6305.         );
  6306.     }
  6307.     public function CreateStockReceivedNoteAction(Request $request$id 0)
  6308.     {
  6309.         $em $this->getDoctrine()->getManager();
  6310.         $companyId $this->getLoggedUserCompanyId($request);
  6311.         $extDocData = [];
  6312.         $userId $request->getSession()->get(UserConstants::USER_ID);
  6313.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  6314.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  6315. //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  6316.         $userBranchIdList $request->getSession()->get('branchIdList');
  6317.         if ($userBranchIdList == null$userBranchIdList = [];
  6318.         $userBranchId $request->getSession()->get('branchId');
  6319.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  6320.             $em $this->getDoctrine()->getManager();
  6321.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //change
  6322.             $dochash $request->request->get('docHash'); //change
  6323.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6324.             $approveRole $request->request->get('approvalRole');
  6325.             $approveHash $request->request->get('approvalHash');
  6326.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6327.                 $loginId$approveRole$approveHash$id)
  6328.             ) {
  6329.                 if ($request->request->has('returnJson')) {
  6330.                     return new JsonResponse(array(
  6331.                         'success' => false,
  6332.                         'documentHash' => 0,
  6333.                         'documentId' => 0,
  6334.                         'billIds' => [],
  6335.                         'drIds' => [],
  6336.                         'pmntTransIds' => [],
  6337.                         'viewUrl' => '',
  6338.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  6339.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  6340.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  6341.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  6342.                     ));
  6343.                 } else
  6344.                     $this->addFlash(
  6345.                         'error',
  6346.                         'Sorry Could not insert Data.'
  6347.                     );
  6348.             } else {
  6349.                 if ($request->request->has('check_allowed'))
  6350.                     $check_allowed 1;
  6351.                 try {
  6352.                     $StID Inventory::CreateNewStockReceivedNote(
  6353.                         $this->getDoctrine()->getManager(),
  6354.                         $request->request,
  6355.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6356.                         $this->getLoggedUserCompanyId($request)
  6357.                     );
  6358.                 } catch (\InvalidArgumentException $e) {
  6359.                     if ($request->request->has('returnJson')) {
  6360.                         return new JsonResponse(array(
  6361.                             'success' => false,
  6362.                             'message' => $e->getMessage(),
  6363.                         ));
  6364.                     }
  6365.                     $this->addFlash('error'$e->getMessage());
  6366.                     return $this->redirect($request->getUri());
  6367.                 } catch (\Exception $e) {
  6368.                     if ($request->request->has('returnJson')) {
  6369.                         return new JsonResponse(array(
  6370.                             'success' => false,
  6371.                             'message' => 'Sorry Could not insert Data.',
  6372.                         ));
  6373.                     }
  6374.                     $this->addFlash('error''Sorry Could not insert Data.');
  6375.                     return $this->redirect($request->getUri());
  6376.                 }
  6377.                 //now add Approval info
  6378.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6379.                 $approveRole 1;  //created
  6380.                 $options = array(
  6381.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6382.                     'notification_server' => $this->container->getParameter('notification_server'),
  6383.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6384.                     'url' => $this->generateUrl(
  6385.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  6386.                         ['entity_view_route_path_name']
  6387.                     )
  6388.                 );
  6389.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6390.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6391.                     $StID,
  6392.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6393.                 );
  6394.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  6395.                     $loginId,
  6396.                     $approveRole,
  6397.                     $request->request->get('approvalHash'));
  6398.                 $url $this->generateUrl(
  6399.                     'view_srcv'
  6400.                 );
  6401.                 if ($request->request->has('returnJson')) {
  6402.                     return new JsonResponse(array(
  6403.                         'success' => true,
  6404.                         'documentHash' => $dochash,
  6405.                         'documentId' => $StID,
  6406.                         'viewUrl' => $url "/" $StID,
  6407.                     ));
  6408.                 } else {
  6409.                     $this->addFlash(
  6410.                         'success',
  6411.                         'Stock Received Note Added.'
  6412.                     );
  6413.                     return $this->redirect($url "/" $StID);
  6414.                 }
  6415.             }
  6416.         }
  6417.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  6418.             array(
  6419.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6420.             )
  6421.         );
  6422.         if ($id == 0) {
  6423.         } else {
  6424.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')->findOneBy(
  6425.                 array(
  6426.                     'salesOrderId' => $id///material
  6427.                 )
  6428.             );
  6429.             //now if its not editable, redirect to view
  6430.             if ($extDoc) {
  6431.                 if ($extDoc->getEditFlag() != 1) {
  6432.                     $url $this->generateUrl(
  6433.                         'view_srcv'
  6434.                     );
  6435.                     return $this->redirect($url "/" $id);
  6436.                 } else {
  6437.                     $extDocData $extDoc;
  6438.                     $extDocDataDetails $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findOneBy(
  6439.                         array(
  6440.                             'stockReceivedNoteId' => $id///material
  6441.                         )
  6442.                     );
  6443.                 }
  6444.             } else {
  6445.             }
  6446.         }
  6447.         $INVLIST = [];
  6448.         foreach ($slotList as $slot) {
  6449.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  6450.         }
  6451.         $dataArray = array(
  6452.             'page_title' => 'Stock Received Note',
  6453. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  6454.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  6455.             'users' => Users::getUserListById($em),
  6456.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  6457.             'warehouseList' => Inventory::WarehouseList($em),
  6458.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  6459.             'warehouseActionList' => $warehouse_action_list,
  6460.             'warehouseActionListArray' => $warehouse_action_list_array,
  6461.             'extDocData' => $extDocData,
  6462.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  6463.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6464.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6465.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6466. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6467. //            'product_list' => Inventory::ProductList($em, $companyId),
  6468.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  6469.             'prefix_list' => array(
  6470.                 [
  6471.                     'id' => 1,
  6472.                     'value' => 'GN',
  6473.                     'text' => 'GN'
  6474.                 ]
  6475.             ),
  6476.             'assoc_list' => array(
  6477.                 [
  6478.                     'id' => 1,
  6479.                     'value' => 1,
  6480.                     'text' => 'GN'
  6481.                 ]
  6482.             ),
  6483.             'INVLIST' => $INVLIST,
  6484.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  6485.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  6486.             'userBranchIdList' => $userBranchIdList,
  6487.             'userBranchId' => $userBranchId,
  6488. //            'headList' => Accounts::HeadList($em),
  6489.         );
  6490.         //json
  6491.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  6492.         {
  6493.             $dataArray['success'] = true;
  6494.             return new JsonResponse(
  6495.                 $dataArray
  6496.             );
  6497.         }
  6498.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  6499.             $dataArray
  6500.         );
  6501.     }
  6502.     public function GetItemListForStockReceivedAction(Request $request)
  6503.     {
  6504.         if ($request->isMethod('POST')) {
  6505.             $em $this->getDoctrine();
  6506.             $receiveType 1;//transfer
  6507.             if ($request->request->has('receiveType'))
  6508.                 $receiveType $request->request->get('receiveType');
  6509.             $QD = [];
  6510.             if ($receiveType == 1)
  6511.                 $QD $this->getDoctrine()
  6512.                     ->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  6513.                     ->findBy(
  6514.                         array(
  6515. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  6516.                             'stockTransferId' => $request->request->get('stId')
  6517.                         ),
  6518.                         array()
  6519.                     );
  6520.             if ($receiveType == 2)
  6521.                 $QD $this->getDoctrine()
  6522.                     ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  6523.                     ->findBy(
  6524.                         array(
  6525. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  6526.                             'salesOrderId' => $request->request->get('soId')
  6527.                         ),
  6528.                         array()
  6529.                     );
  6530. //            if($request->request->get('wareHouseId')!='')
  6531. //
  6532. //            $DO=$this->getDoctrine()
  6533. //                ->getRepository('ApplicationBundle\\Entity\\DeliveryOrder')
  6534. //                ->findOneBy(
  6535. //                    $find_array,
  6536. //                    array(
  6537. //
  6538. //                    )
  6539. //                );
  6540.             $sendData = array(
  6541. //                'salesType'=>$SO->getSalesType(),
  6542. //                'packageData'=>[],
  6543.                 'productList' => [],
  6544. //                'productListByPackage'=>[],
  6545.             );
  6546.             $productList Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request));
  6547.             $pckg_item_cross_match_data = [];
  6548.             foreach ($QD as $product) {
  6549. //                $b_code=json_decode($product->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  6550.                 $b_code = [];
  6551.                 $newProductId $product->getProductId();
  6552.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  6553.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6554.                     if ($to_analyze_codes_str != null)
  6555.                         $b_code json_decode($to_analyze_codes_strtrue512JSON_BIGINT_AS_STRING);
  6556.                     else
  6557.                         $b_code = [];
  6558.                 } else {
  6559.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6560.                     if ($to_analyze_codes_str != null) {
  6561.                         $max_int_length strlen((string)PHP_INT_MAX) - 1;
  6562.                         $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$to_analyze_codes_str);
  6563.                         $b_code json_decode($json_without_bigintstrue);
  6564.                     } else {
  6565.                         $b_code = [];
  6566.                     }
  6567.                 }
  6568.                 $b_code_data = [];
  6569.                 foreach ($b_code as $d) {
  6570.                     $b_code_data[] = array(
  6571.                         'id' => $d,
  6572.                         'name' => str_pad($d13'0'STR_PAD_LEFT),
  6573.                     );
  6574.                 }
  6575.                 $p_data = array(
  6576.                     'details_id' => $product->getId(),
  6577.                     'productId' => $product->getProductId(),
  6578.                     'product_name' => isset($productList[$product->getProductId()]) ? $productList[$product->getProductId()]['name'] : 'Unknown Product',
  6579.                     'product_barcodes' => $b_code_data,
  6580. //                    'available_inventory'=>$inventory_by_warehouse?$inventory_by_warehouse->getQty():0,
  6581. //                        'package_id'=>$product->getPackageId(),
  6582.                     'qty' => $receiveType == $product->getQty() : $product->getToBeReceived(),
  6583.                     'unit_price' => $receiveType == $product->getPrice() : $productList[$product->getProductId()]['purchase_price'],
  6584.                     'balance' => $receiveType == $product->getBalance() : ($product->getToBeReceived() - $product->getReceived()),
  6585. //                        'delivered'=>$product->getDelivered(),
  6586.                 );
  6587.                 $sendData['productList'][] = $p_data;
  6588.             }
  6589.             //now package data
  6590.             if ($sendData) {
  6591.                 return new JsonResponse(array("success" => true"content" => $sendData));
  6592.             }
  6593.             return new JsonResponse(array("success" => false));
  6594.         }
  6595.         return new JsonResponse(array("success" => false));
  6596.     }
  6597.     public function StockReceivedNoteListAction(Request $request)
  6598.     {
  6599.         $q $this->getDoctrine()
  6600.             ->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')
  6601.             ->findBy(
  6602.                 array(
  6603.                     'status' => GeneralConstant::ACTIVE,
  6604.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  6605. //                    'approved' =>  GeneralConstant::APPROVED,
  6606.                 )
  6607.             );
  6608.         $stage_list = array(
  6609.             => 'Pending',
  6610.             => 'Pending',
  6611.             => 'Complete',
  6612.             => 'Partial',
  6613.         );
  6614.         $data = [];
  6615.         foreach ($q as $entry) {
  6616.             $data[] = array(
  6617.                 'doc_date' => $entry->getStockReceivedNoteDate(),
  6618.                 'id' => $entry->getStockReceivedNoteId(),
  6619.                 'doc_hash' => $entry->getDocumentHash(),
  6620.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  6621.                 'stage' => $stage_list[$entry->getStage()]
  6622.             );
  6623.         }
  6624.         return $this->render('@Inventory/pages/views/stock_received_note_list.html.twig',
  6625.             array(
  6626.                 'page_title' => 'Stock Received List',
  6627.                 'data' => $data
  6628.             )
  6629.         );
  6630.     }
  6631.     public function ViewStockReceivedNoteAction(Request $request$id)
  6632.     {
  6633.         $em $this->getDoctrine()->getManager();
  6634.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6635.         return $this->render(
  6636.             '@Inventory/pages/views/view_stock_received_note.html.twig',
  6637.             array(
  6638.                 'page_title' => 'Stock Received Note',
  6639.                 'data' => $dt,
  6640.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  6641.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6642.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6643.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6644.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6645.                     $id,
  6646.                     $dt['created_by'],
  6647.                     $dt['edited_by'])
  6648.             )
  6649.         );
  6650.     }
  6651.     public function PrintStockReceivedNoteAction(Request $request$id)
  6652.     {
  6653.         $em $this->getDoctrine()->getManager();
  6654.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6655.         $company_data Company::getCompanyData($em1);
  6656.         $document_mark = array(
  6657.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6658.             'copy' => ''
  6659.         );
  6660.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6661.             $html $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
  6662.                 array(
  6663.                     //full array here
  6664.                     'pdf' => true,
  6665.                     'page_title' => 'Stock Received Note',
  6666.                     'export' => 'pdf,print',
  6667.                     'data' => $dt,
  6668.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6669.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6670.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6671.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6672.                         $id,
  6673.                         $dt['created_by'],
  6674.                         $dt['edited_by']),
  6675.                     'document_mark_image' => $document_mark['original'],
  6676.                     'company_name' => $company_data->getName(),
  6677.                     'company_data' => $company_data,
  6678.                     'company_address' => $company_data->getAddress(),
  6679.                     'company_image' => $company_data->getImage(),
  6680.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6681.                     'red' => 0
  6682.                 )
  6683.             );
  6684.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6685. //                'orientation' => 'landscape',
  6686. //                'enable-javascript' => true,
  6687. //                'javascript-delay' => 1000,
  6688.                 'no-stop-slow-scripts' => false,
  6689.                 'no-background' => false,
  6690.                 'lowquality' => false,
  6691.                 'encoding' => 'utf-8',
  6692. //            'images' => true,
  6693. //            'cookie' => array(),
  6694.                 'dpi' => 300,
  6695.                 'image-dpi' => 300,
  6696. //                'enable-external-links' => true,
  6697. //                'enable-internal-links' => true
  6698.             ));
  6699.             return new Response(
  6700.                 $pdf_response,
  6701.                 200,
  6702.                 array(
  6703.                     'Content-Type' => 'application/pdf',
  6704.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  6705.                 )
  6706.             );
  6707.         }
  6708.         return $this->render('@Inventory/pages/print/print_stock_received_note.html.twig',
  6709.             array(
  6710.                 'page_title' => 'Stock Received Note',
  6711.                 'export' => 'pdf,print',
  6712.                 'data' => $dt,
  6713.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6714.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6715.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6716.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6717.                     $id,
  6718.                     $dt['created_by'],
  6719.                     $dt['edited_by']),
  6720.                 'document_mark_image' => $document_mark['original'],
  6721.                 'company_name' => $company_data->getName(),
  6722.                 'company_data' => $company_data,
  6723.                 'company_address' => $company_data->getAddress(),
  6724.                 'company_image' => $company_data->getImage(),
  6725.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6726.                 'red' => 0
  6727.             )
  6728.         );
  6729.     }
  6730.     public function CreateStoreRequisitionSlipAction(Request $request$id 0)
  6731.     {
  6732.         $em $this->getDoctrine()->getManager();
  6733. //        $id;
  6734.         if ($request->isMethod('POST')) {
  6735.             $em $this->getDoctrine()->getManager();
  6736.             $entity_id array_flip(GeneralConstant::$Entity_list)['StoreRequisition']; //change
  6737.             $dochash $request->request->get('voucherNumber'); //change
  6738.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6739.             $approveRole $request->request->get('approvalRole');
  6740.             $approveHash $request->request->get('approvalHash');
  6741.             $validation Inventory::ValidateStoreRequisitionSlip($request->request);
  6742.             if (!$validation['success']) {
  6743.                 $this->addFlash(
  6744.                     'error',
  6745.                     $validation['error']
  6746.                 );
  6747.             } else if (!DocValidation::isInsertable($em$entity_id$dochash,
  6748.                 $loginId$approveRole$approveHash$id)
  6749.             ) {
  6750.                 $this->addFlash(
  6751.                     'error',
  6752.                     'Sorry, could not insert Data.'
  6753.                 );
  6754.             } else {
  6755.                 if ($request->request->has('check_allowed'))
  6756.                     $check_allowed 1;
  6757.                 $IrID Inventory::CreateNewStoreRequisition($id,
  6758.                     $this->getDoctrine()->getManager(),
  6759.                     $request->request,
  6760.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6761.                     $this->getLoggedUserCompanyId($request)
  6762.                 );
  6763.                 //now add Approval info
  6764.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6765.                 $approveRole $request->request->get('approvalRole');
  6766.                 $options = array(
  6767.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6768.                     'notification_server' => $this->container->getParameter('notification_server'),
  6769.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6770.                     'url' => $this->generateUrl(
  6771.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StoreRequisition']]
  6772.                         ['entity_view_route_path_name']
  6773.                     )
  6774.                 );
  6775.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6776.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  6777.                     $IrID,
  6778.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6779.                 );
  6780.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StoreRequisition'], $IrID,
  6781.                     $loginId,
  6782.                     $approveRole,
  6783.                     $request->request->get('approvalHash'));
  6784.                 $this->addFlash(
  6785.                     'success',
  6786.                     'New Indent Added.'
  6787.                 );
  6788.                 $url $this->generateUrl(
  6789.                     'view_ir'
  6790.                 );
  6791.                 return $this->redirect($url "/" $IrID);
  6792.             }
  6793.         }
  6794.         $extDocData = [];
  6795.         $extDocDetailsData = [];
  6796.         if ($id == 0) {
  6797.         } else {
  6798.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StoreRequisition')->findOneBy(
  6799.                 array(
  6800.                     'storeRequisitionId' => $id///material
  6801.                 )
  6802.             );
  6803.             //now if its not editable, redirect to view
  6804.             if ($extDoc) {
  6805.                 if ($extDoc->getEditFlag() != 1) {
  6806.                     $url $this->generateUrl(
  6807.                         'view_ir'
  6808.                     );
  6809.                     return $this->redirect($url "/" $id);
  6810.                 } else {
  6811.                     $extDocData $extDoc;
  6812.                     $extDocDetailsData $em->getRepository('ApplicationBundle\\Entity\\StoreRequisitionItem')->findBy(
  6813.                         array(
  6814.                             'storeRequisitionId' => $id///material
  6815.                         )
  6816.                     );;
  6817.                 }
  6818.             } else {
  6819.             }
  6820.         }
  6821.         $companyId $this->getLoggedUserCompanyId($request);
  6822.         $productListArray = [];
  6823.         $subCategoryListArray = [];
  6824.         $categoryListArray = [];
  6825.         $igListArray = [];
  6826.         $unitListArray = [];
  6827.         $brandListArray = [];
  6828.         $productList Inventory::ProductList($em$companyId);
  6829.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6830.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6831.         $igList Inventory::ItemGroupList($em$companyId);
  6832.         $unitList Inventory::UnitTypeList($em);
  6833.         $brandList Inventory::GetBrandList($em$companyId);
  6834.         foreach ($productList as $product$productListArray[] = $product;
  6835.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6836.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6837.         foreach ($igList as $product$igListArray[] = $product;
  6838.         foreach ($unitList as $product$unitListArray[] = $product;
  6839.         foreach ($brandList as $product$brandListArray[] = $product;
  6840.         $sr_list = [];
  6841.         $QD $this->getDoctrine()
  6842.             ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  6843.             ->findBy(
  6844.                 array(
  6845.                     'indentTagged' => 0,
  6846.                     'approved' => 1
  6847.                 )
  6848.             );
  6849.         foreach ($QD as $dt) {
  6850.             $sr_list[$dt->getStockRequisitionId()] = array(
  6851.                 'id' => $dt->getStockRequisitionId(),
  6852.                 'name' => $dt->getDocumentHash(),
  6853.                 'text' => $dt->getDocumentHash(),
  6854.             );
  6855.         }
  6856.         return $this->render('@Inventory/pages/input_forms/store_requisition.html.twig',
  6857.             array(
  6858.                 'page_title' => 'Indent Requisition Slip',
  6859.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6860.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6861.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6862.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6863.                 'sr_list' => $sr_list,
  6864.                 'productList' => $productList,
  6865.                 'subCategoryList' => $subCategoryList,
  6866.                 'categoryList' => $categoryList,
  6867.                 'igList' => $igList,
  6868.                 'extId' => $id,
  6869.                 'extDocDetailsData' => $extDocDetailsData,
  6870.                 'extDocData' => $extDocData,
  6871.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6872.                 'unitList' => $unitList,
  6873.                 'brandList' => $brandList,
  6874.                 'brandListArray' => $brandListArray,
  6875.                 'productListArray' => $productListArray,
  6876.                 'subCategoryListArray' => $subCategoryListArray,
  6877.                 'categoryListArray' => $categoryListArray,
  6878.                 'igListArray' => $igListArray,
  6879.                 'unitListArray' => $unitListArray,
  6880.                 'prefix_list' => array(
  6881.                     [
  6882.                         'id' => 1,
  6883.                         'value' => 'GN',
  6884.                         'text' => 'General'
  6885.                     ],
  6886.                     [
  6887.                         'id' => 1,
  6888.                         'value' => 'SD',
  6889.                         'text' => 'For Sales Demand'
  6890.                     ]
  6891.                 ),
  6892.                 'assoc_list' => array(
  6893.                     [
  6894.                         'id' => 1,
  6895.                         'value' => 1,
  6896.                         'text' => 'GN'
  6897.                     ]
  6898.                 )
  6899.             )
  6900.         );
  6901.     }
  6902.     public function CreateStockRequisitionSlipAction(Request $request$id 0)
  6903.     {
  6904.         $em $this->getDoctrine()->getManager();
  6905.         if ($request->isMethod('POST')) {
  6906.             $em $this->getDoctrine()->getManager();
  6907.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockRequisition']; //change
  6908.             $dochash $request->request->get('voucherNumber'); //change
  6909.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6910.             $approveRole $request->request->get('approvalRole');
  6911.             $approveHash $request->request->get('approvalHash');
  6912.             $validation Inventory::ValidateStockRequisitionSlip($request->request);
  6913.             if (!$validation['success']) {
  6914.                 $this->addFlash(
  6915.                     'error',
  6916.                     $validation['error']
  6917.                 );
  6918.             } else if (!DocValidation::isInsertable($em$entity_id$dochash,
  6919.                 $loginId$approveRole$approveHash$id)
  6920.             ) {
  6921.                 $this->addFlash(
  6922.                     'error',
  6923.                     'Sorry, could not insert Data.'
  6924.                 );
  6925.             } else {
  6926.                 if ($request->request->has('check_allowed'))
  6927.                     $check_allowed 1;
  6928.                 $SrID Inventory::CreateNewStockRequisition($id,
  6929.                     $this->getDoctrine()->getManager(),
  6930.                     $request->request,
  6931.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6932.                     $this->getLoggedUserCompanyId($request)
  6933.                 );
  6934.                 //now add Approval info
  6935.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6936.                 $approveRole $request->request->get('approvalRole');
  6937.                 $options = array(
  6938.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6939.                     'notification_server' => $this->container->getParameter('notification_server'),
  6940.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6941.                     'url' => $this->generateUrl(
  6942.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockRequisition']]
  6943.                         ['entity_view_route_path_name']
  6944.                     )
  6945.                 );
  6946.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6947.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  6948.                     $SrID,
  6949.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6950.                 );
  6951.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockRequisition'], $SrID,
  6952.                     $loginId,
  6953.                     $approveRole,
  6954.                     $request->request->get('approvalHash'));
  6955.                 $this->addFlash(
  6956.                     'success',
  6957.                     'New Requisition Added.'
  6958.                 );
  6959.                 $url $this->generateUrl(
  6960.                     'view_sr'
  6961.                 );
  6962. //                return $this->redirect($url . "/" . $SrID);
  6963.             }
  6964.         }
  6965.         $extDocData = [];
  6966.         $extDocDetailsData = [];
  6967.         if ($id == 0) {
  6968.         } else {
  6969.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StockRequisition')->findOneBy(
  6970.                 array(
  6971.                     'stockRequisitionId' => $id///material
  6972.                 )
  6973.             );
  6974.             //now if its not editable, redirect to view
  6975.             if ($extDoc) {
  6976.                 if ($extDoc->getEditFlag() != 1) {
  6977.                     $url $this->generateUrl(
  6978.                         'view_sr'
  6979.                     );
  6980.                     return $this->redirect($url "/" $id);
  6981.                 } else {
  6982.                     $extDocData $extDoc;
  6983.                     $extDocDetailsData $em->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')->findBy(
  6984.                         array(
  6985.                             'stockRequisitionId' => $id///material
  6986.                         )
  6987.                     );;
  6988.                 }
  6989.             } else {
  6990.             }
  6991.         }
  6992.         $companyId $this->getLoggedUserCompanyId($request);
  6993.         $productListArray = [];
  6994.         $subCategoryListArray = [];
  6995.         $categoryListArray = [];
  6996.         $igListArray = [];
  6997.         $unitListArray = [];
  6998.         $brandListArray = [];
  6999.         $productList Inventory::ProductList($em$companyId);
  7000.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  7001.         $categoryList Inventory::ProductCategoryList($em$companyId);
  7002.         $igList Inventory::ItemGroupList($em$companyId);
  7003.         $unitList Inventory::UnitTypeList($em);
  7004.         $brandList Inventory::GetBrandList($em$companyId);
  7005.         foreach ($productList as $product$productListArray[] = $product;
  7006.         foreach ($categoryList as $product$categoryListArray[] = $product;
  7007.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  7008.         foreach ($igList as $product$igListArray[] = $product;
  7009.         foreach ($unitList as $product$unitListArray[] = $product;
  7010.         foreach ($brandList as $product$brandListArray[] = $product;
  7011.         return $this->render('@Inventory/pages/input_forms/stock_requisition_slip.html.twig',
  7012.             array(
  7013.                 'page_title' => 'Stock Requisition Slip',
  7014.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7015.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  7016.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  7017.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  7018.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  7019.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  7020.                 'productList' => $productList,
  7021.                 'extId' => $id,
  7022.                 'extDocDetailsData' => $extDocDetailsData,
  7023.                 'extDocData' => $extDocData,
  7024.                 'subCategoryList' => $subCategoryList,
  7025.                 'categoryList' => $categoryList,
  7026.                 'igList' => $igList,
  7027.                 'unitList' => $unitList,
  7028.                 'brandList' => $brandList,
  7029.                 'brandListArray' => $brandListArray,
  7030.                 'productListArray' => $productListArray,
  7031.                 'subCategoryListArray' => $subCategoryListArray,
  7032.                 'categoryListArray' => $categoryListArray,
  7033.                 'igListArray' => $igListArray,
  7034.                 'unitListArray' => $unitListArray,
  7035.                 'productionBomList' => ProductionM::ProductionBomList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  7036.                 'productionScheduleList' => ProductionM::ProductionScheduleList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  7037.                 'prefix_list' => array(
  7038.                     [
  7039.                         'id' => 1,
  7040.                         'value' => 'GN',
  7041.                         'text' => 'General'
  7042.                     ],
  7043.                     [
  7044.                         'id' => 1,
  7045.                         'value' => 'SD',
  7046.                         'text' => 'For Sales Demand'
  7047.                     ]
  7048.                 ),
  7049.                 'projectList' => $em->getRepository('ApplicationBundle\\Entity\\Project')->findBy(
  7050.                     array(
  7051.                         'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  7052.                     ), array('projectDate' => 'desc')
  7053.                 ),
  7054.                 'salesOrderList' => SalesOrderM::SalesOrderListPendingDelivery($em),
  7055.                 'assoc_list' => array(
  7056.                     [
  7057.                         'id' => 1,
  7058.                         'value' => 'GN',
  7059.                         'text' => 'General'
  7060.                     ]
  7061.                 )
  7062.             )
  7063.         );
  7064.     }
  7065.     public function CreateStockReturnAction(Request $request)
  7066.     {
  7067.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  7068.             array(
  7069.                 'page_title' => 'Stock Return',
  7070. //                'dataList'=>$dta_list
  7071.             )
  7072.         );
  7073.     }
  7074.     public function MaterialInwardAction(Request $request)
  7075.     {
  7076.         $data = [];
  7077.         if ($request->isMethod('POST')) {
  7078.             $errors = [];
  7079.             $poId = (int)$request->request->get('poId');
  7080.             $warehouseId = (int)$request->request->get('warehouseId');
  7081.             $docHash trim((string)$request->request->get('docHash'));
  7082.             $products $request->request->get('products', []);
  7083.             $receivedQty $request->request->get('receivedQty', []);
  7084.             $purchaseOrderItemId $request->request->get('purchaseOrderItemId', []);
  7085.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  7086.             if ($poId <= 0) {
  7087.                 $errors[] = 'Please select a purchase order.';
  7088.             } elseif (!isset($poList[$poId])) {
  7089.                 $errors[] = 'Please select a valid purchase order.';
  7090.             }
  7091.             if ($warehouseId <= 0) {
  7092.                 $errors[] = 'Please select a warehouse.';
  7093.             }
  7094.             if (empty($products) || !is_array($products)) {
  7095.                 $errors[] = 'Please add at least one item.';
  7096.             }
  7097.             $hasPositiveQty false;
  7098.             foreach ((array)$receivedQty as $qty) {
  7099.                 if ($qty === '' || !is_numeric($qty)) {
  7100.                     $errors[] = 'Please enter a valid received quantity.';
  7101.                     break;
  7102.                 }
  7103.                 if ((float)$qty 0) {
  7104.                     $errors[] = 'Received quantity cannot be negative.';
  7105.                     break;
  7106.                 }
  7107.                 if ((float)$qty 0) {
  7108.                     $hasPositiveQty true;
  7109.                 }
  7110.             }
  7111.             if (!$hasPositiveQty) {
  7112.                 $errors[] = 'Please enter received quantity greater than zero for at least one item.';
  7113.             }
  7114.             if ($docHash === '' || stripos($docHash'undefined') !== false || stripos($docHash'document') !== false) {
  7115.                 $errors[] = 'Please generate a valid document number.';
  7116.             }
  7117.             if (empty($errors)) {
  7118.                 //first of all resolve the transport costs
  7119.                 $total_price_value 0;
  7120.                 $data_list $this->getDoctrine()
  7121.                     ->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')
  7122.                     ->findBy(
  7123.                         array(
  7124.                             'purchaseOrderId' => $poId,
  7125.                             'productId' => $products
  7126.                         )
  7127.                     );
  7128.                 $purchase_items = [];
  7129.                 foreach ($data_list as $key => $value) {
  7130.                     $purchase_items[$value->getProductId()] = $value;
  7131.                 }
  7132.                 foreach ($products as $key => $entry) {
  7133.                     if (!isset($purchase_items[$entry])) {
  7134.                         $errors[] = 'Selected product list does not match the chosen purchase order.';
  7135.                         break;
  7136.                     }
  7137.                     $total_price_value $total_price_value + ($receivedQty[$key]) * ($purchase_items[$entry]->getPrice());
  7138.                 }
  7139.                 if (empty($errors)) {
  7140.                     $po_data $poList[$poId];
  7141.                     $supplier_id $po_data['supplier_id'];
  7142.                     $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  7143.                     foreach ($products as $key => $entry) {
  7144.                         if ((float)$receivedQty[$key] > 0) {
  7145.                             Inventory::NewMaterialInward($this->getDoctrine()->getManager(),
  7146.                                 $request->request,
  7147.                                 $key,
  7148.                                 $poId,
  7149.                                 $purchaseOrderItemId,
  7150.                                 $supplier_id,
  7151.                                 $warehouseId,
  7152.                                 $request->request->get('lotNumber'),
  7153.                                 $request->request->get('type_hash'),
  7154.                                 $request->request->get('prefix_hash'),
  7155.                                 $request->request->get('assoc_hash'),
  7156.                                 $request->request->get('number_hash'),
  7157.                                 $docHash,
  7158.                                 $request->request->get('docDate'),
  7159.                                 $purchase_items[$entry],
  7160.                                 $total_price_value,
  7161.                                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7162.                         }
  7163.                     }
  7164.                     $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$warehouseId]['name'];
  7165. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  7166.                     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),
  7167.                         "A stack of material Has Arrived at The " $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  7168.                         'all',
  7169.                         "",
  7170.                         'information',
  7171.                         "",
  7172.                         "Inbound Material"
  7173.                     );
  7174.                 }
  7175.             }
  7176.             foreach ($errors as $error) {
  7177.                 $this->addFlash('error'$error);
  7178.             }
  7179. //                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);
  7180.         }
  7181.         return $this->render('@Inventory/pages/input_forms/material_inward.html.twig',
  7182.             array(
  7183.                 'page_title' => 'Material Inward',
  7184.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  7185.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  7186.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  7187.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  7188.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  7189.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  7190.                 "unitList" => Inventory::UnitTypeList($this->getDoctrine()->getManager())
  7191. //                'po'=>Inventory::getPurchaseOrderList
  7192.             )
  7193.         );
  7194.     }
  7195.     public function QualityControlAction(Request $request)
  7196.     {
  7197.         $checked_qc_list_flag 0;
  7198.         if ($request->query->has('checked_qc_list_flag'))
  7199.             $checked_qc_list_flag $request->query->has('checked_qc_list_flag');
  7200.         if ($request->isMethod('POST')) {
  7201.             $errors = [];
  7202.             $checkedRows $request->request->get('qc_checked', []);
  7203.             $approvedQty $request->request->get('approvedQty', []);
  7204.             if (empty($checkedRows)) {
  7205.                 $errors[] = 'Please select at least one QC item.';
  7206.             }
  7207.             $positiveQtyFound false;
  7208.             foreach ($approvedQty as $qcId => $qty) {
  7209.                 $qtyValue trim((string)$qty);
  7210.                 if ($qtyValue === '' || !is_numeric($qtyValue)) {
  7211.                     $errors[] = 'Approved quantity must be numeric.';
  7212.                     break;
  7213.                 }
  7214.                 if ((float)$qtyValue 0) {
  7215.                     $errors[] = 'Approved quantity cannot be negative.';
  7216.                     break;
  7217.                 }
  7218.                 if ((float)$qtyValue 0) {
  7219.                     $positiveQtyFound true;
  7220.                     if (!in_array($qcId$checkedRows)) {
  7221.                         $errors[] = 'Please check QC before submitting approved rows.';
  7222.                         break;
  7223.                     }
  7224.                 }
  7225.             }
  7226.             if (empty($errors) && !$positiveQtyFound) {
  7227.                 $errors[] = 'Please enter approved quantity greater than zero for at least one QC item.';
  7228.             }
  7229.             if (empty($errors)) {
  7230.                 foreach ($checkedRows as $key => $entry) {
  7231.                     $em $this->getDoctrine()->getManager();
  7232.                     $data $this->getDoctrine()
  7233.                         ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  7234.                         ->findOneBy(
  7235.                             array(
  7236.                                 'qcId' => $entry
  7237.                             )
  7238.                         );
  7239.                     if (!$data) {
  7240.                         $errors[] = 'Invalid QC row selected.';
  7241.                         break;
  7242.                     }
  7243.                     $data->setApprovedQty($approvedQty[$entry]);
  7244.                     $data->setRejectedQty($data->getInwardQty() - $approvedQty[$entry]);
  7245.                     $data->setQcDate(new \DateTime($request->request->get('qcDate')));
  7246.                     $data->setStage(GeneralConstant::STAGE_PENDING_TAG);
  7247.                     $em->flush();
  7248.                     //notification
  7249.                     $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$data->getPurchaseOrderId()];
  7250.                     $supplier_id $po_data['supplier_id'];
  7251.                     $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  7252.                     $product_name Inventory::ProductList($this->getDoctrine()->getManager())[$data->getProductId()]['name'];
  7253.                     $qty $approvedQty[$entry];
  7254.                     $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$data->getWarehouseId()]['name'];
  7255. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  7256.                     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),
  7257.                         $qty " among " $data->getInwardQty() . " units of " $product_name " has passed the Quality Control in " .
  7258.                         $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  7259.                         'all',
  7260.                         "",
  7261.                         'success',
  7262.                         "",
  7263.                         "Quality Control"
  7264.                     );
  7265.                 }
  7266.             }
  7267.             foreach ($errors as $error) {
  7268.                 $this->addFlash('error'$error);
  7269.             }
  7270.         }
  7271.         return $this->render('@Inventory/pages/input_forms/qc.html.twig',
  7272.             array(
  7273.                 'page_title' => 'Quality Control',
  7274.                 'checked_qc_list_flag' => $checked_qc_list_flag,
  7275.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  7276.                 'warehouse_indexed' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7277.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  7278.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  7279.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  7280.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  7281.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7282.                 'material_inward' => $this->getDoctrine()
  7283.                     ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  7284.                     ->findBy(
  7285.                         array(
  7286.                             'stage' => $checked_qc_list_flag == GeneralConstant::STAGE_PENDING GeneralConstant::STAGE_PENDING_TAG
  7287.                         )
  7288.                     )
  7289. //                'po'=>Inventory::getPurchaseOrderList
  7290.             )
  7291.         );
  7292.     }
  7293.     public function InventoryTransactionViewAction(Request $request)
  7294.     {
  7295.         $em $this->getDoctrine()->getManager();
  7296.         $qry_data = array(
  7297.             'warehouseId' => [0],
  7298.             'igId' => [0],
  7299.             'brandId' => [0],
  7300.             'categoryId' => [0],
  7301.             'actionTagId' => [0],
  7302.         );
  7303.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  7304.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  7305.         $data_searched = [];
  7306.         $em $this->getDoctrine()->getManager();
  7307.         $companyId $this->getLoggedUserCompanyId($request);
  7308.         $company_data Company::getCompanyData($em$companyId);
  7309.         $data = [];
  7310.         $print_title "Inventory Report";
  7311.         $document_mark = array(
  7312.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  7313.             'copy' => ''
  7314.         );
  7315.         if ($request->isMethod('POST'))
  7316.             $method 'POST';
  7317.         else
  7318.             $method 'GET';
  7319.         {
  7320.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  7321.                 $request->request$method,
  7322.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7323.                 $companyId);
  7324.             if ($request->query->has('returnJson') || $request->request->has('returnJson')) {
  7325.                 return new JsonResponse(
  7326.                     array(
  7327.                         'success' => true,
  7328. //                    'page_title' => 'Product Details',
  7329. //                    'company_data' => $company_data,
  7330.                         'page_title' => 'Inventory Transactions',
  7331.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7332.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7333.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7334.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7335.                         'data_products' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7336.                         'action_tag' => $warehouse_action_list,
  7337.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7338.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7339.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7340.                         'data_searched' => $data_searched
  7341.                     )
  7342.                 );
  7343.             } else if ($request->request->get('print_data_enabled') == 1) {
  7344.                 $print_sub_title "";
  7345.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  7346.                     array(
  7347.                         'page_title' => 'Inventory Report',
  7348.                         'page_header' => 'Report',
  7349.                         'print_title' => $print_title,
  7350.                         'document_type' => 'Journal voucher',
  7351.                         'document_mark_image' => $document_mark['original'],
  7352.                         'page_header_sub' => 'Add',
  7353.                         'item_data' => [],
  7354.                         'received' => 2,
  7355.                         'return' => 1,
  7356.                         'total_w_vat' => 1,
  7357.                         'total_vat' => 1,
  7358.                         'total_wo_vat' => 1,
  7359.                         'invoice_id' => 'abcd1234',
  7360.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  7361.                         'created_by' => 'created by',
  7362.                         'created_at' => '',
  7363.                         'red' => 0,
  7364.                         'company_name' => $company_data->getName(),
  7365.                         'company_data' => $company_data,
  7366.                         'company_address' => $company_data->getAddress(),
  7367.                         'company_image' => $company_data->getImage(),
  7368.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7369.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7370.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7371.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7372.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7373.                         'action_tag' => $warehouse_action_list,
  7374.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7375.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7376.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7377.                         'data_searched' => $data_searched
  7378.                     )
  7379.                 );
  7380.             }
  7381.         }
  7382.         return $this->render('@Inventory/pages/report/inventory_transaction_view.html.twig',
  7383.             array(
  7384.                 'page_title' => 'Inventory Transactions',
  7385.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7386.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7387.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7388.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7389.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7390.                 'action_tag' => $warehouse_action_list,
  7391.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7392.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7393.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7394.                 'data_searched' => $data_searched
  7395.             )
  7396.         );
  7397.     }
  7398.     public function StockConsumptionViewAction(Request $request)
  7399.     {
  7400.         $em $this->getDoctrine()->getManager();
  7401.         $start_date $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
  7402.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : new \DateTime();
  7403.         $qry_data = array(
  7404.             'warehouseId' => [0],
  7405.             'igId' => [0],
  7406.             'brandId' => [0],
  7407.             'categoryId' => [0],
  7408.             'actionTagId' => [0],
  7409.         );
  7410.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  7411.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  7412.         $data_searched = [];
  7413.         $em $this->getDoctrine()->getManager();
  7414.         $company_data Company::getCompanyData($em1);
  7415.         $data = [];
  7416.         $print_title "Inventory Report";
  7417.         $document_mark = array(
  7418.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  7419.             'copy' => ''
  7420.         );
  7421.         if ($request->isMethod('POST'))
  7422.             $method 'POST';
  7423.         else
  7424.             $method 'GET';
  7425.         $post_data $method == 'POST' $request->request $request->query;
  7426.         $data_searched Inventory::GetStockConsumptionData($this->getDoctrine()->getManager(),
  7427.             $post_data,
  7428.             $method,
  7429.             $start_date,
  7430.             $end_date,
  7431.             $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7432.         if ($post_data->get('print_data_enabled') == 1) {
  7433.             $print_sub_title "";
  7434.             if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  7435.                 $html $this->renderView('@Inventory/pages/print/print_stock_consumption.html.twig',
  7436.                     array(
  7437.                         'pdf' => 'true',
  7438.                         'page_title' => 'Inventory Report',
  7439.                         'page_header' => 'Report',
  7440.                         'print_title' => $print_title,
  7441.                         'document_type' => 'Journal voucher',
  7442.                         'document_mark_image' => $document_mark['original'],
  7443.                         'page_header_sub' => 'Add',
  7444.                         'item_data' => [],
  7445.                         'received' => 2,
  7446.                         'return' => 1,
  7447.                         'total_w_vat' => 1,
  7448.                         'total_vat' => 1,
  7449.                         'total_wo_vat' => 1,
  7450.                         'invoice_id' => 'abcd1234',
  7451.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  7452.                         'created_by' => 'created by',
  7453.                         'created_at' => '',
  7454.                         'red' => 0,
  7455.                         'start_date' => $start_date,
  7456.                         'end_date' => $end_date,
  7457.                         'openFilter' => empty($post_data->keys()) ? 0,
  7458.                         'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  7459.                         'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  7460.                         'company_name' => $company_data->getName(),
  7461.                         'company_data' => $company_data,
  7462.                         'company_address' => $company_data->getAddress(),
  7463.                         'company_image' => $company_data->getImage(),
  7464.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7465.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7466.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7467.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7468.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7469.                         'action_tag' => $warehouse_action_list,
  7470.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7471.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7472.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7473.                         'data_searched' => $data_searched,
  7474.                         'export' => 'all'
  7475.                     )
  7476.                 );
  7477.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  7478.                     'orientation' => count($data_searched['query_columns_filter']) > 'landscape' 'portrait',
  7479.                     'no-stop-slow-scripts' => true,
  7480.                     'no-background' => false,
  7481.                     'lowquality' => false,
  7482.                     'encoding' => 'utf-8',
  7483.                     'dpi' => 300,
  7484.                     'image-dpi' => 300,
  7485.                 ));
  7486.                 return new Response(
  7487.                     $pdf_response,
  7488.                     200,
  7489.                     array(
  7490.                         'Content-Type' => 'application/pdf',
  7491.                         'Content-Disposition' => 'attachment; filename="Stock_Consumption.pdf"'
  7492.                     )
  7493.                 );
  7494.             }
  7495.             return $this->render('@Inventory/pages/print/print_stock_consumption.html.twig',
  7496.                 array(
  7497.                     'page_title' => 'Inventory Report',
  7498.                     'page_header' => 'Report',
  7499.                     'print_title' => $print_title,
  7500.                     'document_type' => 'Journal voucher',
  7501.                     'document_mark_image' => $document_mark['original'],
  7502.                     'page_header_sub' => 'Add',
  7503.                     'item_data' => [],
  7504.                     'received' => 2,
  7505.                     'return' => 1,
  7506.                     'total_w_vat' => 1,
  7507.                     'total_vat' => 1,
  7508.                     'total_wo_vat' => 1,
  7509.                     'invoice_id' => 'abcd1234',
  7510.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  7511.                     'created_by' => 'created by',
  7512.                     'created_at' => '',
  7513.                     'red' => 0,
  7514.                     'start_date' => $start_date,
  7515.                     'end_date' => $end_date,
  7516.                     'openFilter' => empty($post_data->keys()) ? 0,
  7517.                     'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  7518.                     'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  7519.                     'company_name' => $company_data->getName(),
  7520.                     'company_data' => $company_data,
  7521.                     'company_address' => $company_data->getAddress(),
  7522.                     'company_image' => $company_data->getImage(),
  7523.                     'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7524.                     'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7525.                     'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7526.                     'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7527.                     'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7528.                     'action_tag' => $warehouse_action_list,
  7529.                     'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7530.                     'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7531.                     'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7532.                     'data_searched' => $data_searched,
  7533.                     'export' => 'all'
  7534.                 )
  7535.             );
  7536.         }
  7537. //        return new JsonResponse(Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()));
  7538.         return $this->render('@Inventory/pages/report/stock_consumption.html.twig',
  7539.             array(
  7540.                 'page_title' => 'Stock Consumption',
  7541.                 'start_date' => $start_date,
  7542.                 'end_date' => $end_date,
  7543.                 'openFilter' => empty($post_data->keys()) ? 0,
  7544.                 'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  7545.                 'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  7546.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7547.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7548.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7549.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7550.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7551.                 'action_tag' => $warehouse_action_list,
  7552.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7553.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7554.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7555.                 'data_searched' => $data_searched
  7556.             )
  7557.         );
  7558.     }
  7559.     public function ItemViewAction(Request $request)
  7560.     {
  7561.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  7562.             array(
  7563.                 'page_title' => 'Stock Return'
  7564.             )
  7565.         );
  7566.     }
  7567.     public function ProductViewAction(Request $request$id 0)
  7568.     {
  7569.         $em $this->getDoctrine()->getManager();
  7570.         $companyId $this->getLoggedUserCompanyId($request);
  7571.         $company_data Company::getCompanyData($em$companyId);
  7572.         $data = [];
  7573.         $specData = [];
  7574.         $specIds = [];
  7575.         $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  7576.             ->findOneBy(
  7577.                 array(
  7578.                     'id' => $id
  7579.                 )
  7580.             );
  7581.         if ($productData) {
  7582.             $tempSpecData json_decode($productData->getSpecData(), true);
  7583.             if ($tempSpecData == null) {
  7584.                 $tempSpecData = [];
  7585.             }
  7586.             foreach ($tempSpecData as $indSpecData) {
  7587. //                $specId = $indSpecData['id'];
  7588.                 $specData[] = [
  7589.                     'id' => $indSpecData['id'],
  7590.                     'value' => $indSpecData['value']
  7591.                 ];
  7592.                 $specIds[] = $indSpecData['id'];
  7593.             }
  7594.         }
  7595.         $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  7596.             ->findBy(
  7597.                 array(
  7598.                     'productId' => $id
  7599.                 )
  7600.             );
  7601.         $trans_history $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')
  7602.             ->findBy(
  7603.                 array(
  7604.                     'productId' => $id
  7605.                 ), array(
  7606.                     'transactionDate' => 'ASC',
  7607.                     'id' => 'ASC'
  7608.                 )
  7609.             );
  7610. //        $specId = array_keys($specData);
  7611.         $finSpecData = [];
  7612. //        if($productData){
  7613. //            $tempSpec = json_decode($productData->getSpecData(),true);
  7614. //
  7615. //            if($tempSpec == null){
  7616. //                $tempSpecName=[];
  7617. //            }
  7618. //            foreach ($tempSpec as $indSpec)
  7619. //            {
  7620. //                $specIds[]=$indSpec['id'];
  7621. //
  7622. //                $spec = $em->getRepository('ApplicationBundle\\Entity\\SpecType')
  7623. //                    ->findOneBy(
  7624. //                        array(
  7625. //                            'id' => $indSpec['id']
  7626. //                        )
  7627. //                    );
  7628. //
  7629. //                if($spec)
  7630. //                    $indSpec['name']=$spec->getName();
  7631. //                else
  7632. //                    $indSpec['name']='';
  7633. ////                $specId = $indSpecData['id'];
  7634. //
  7635. //                $finSpecData[]=$indSpec;
  7636. //
  7637. //            }
  7638. //        }
  7639.         $specList $em->getRepository('ApplicationBundle\\Entity\\SpecType')
  7640.             ->findBy(
  7641.                 array(
  7642.                     'id' => $specIds
  7643.                 )
  7644.             );
  7645.         $specListById = [];
  7646.         foreach ($specList as $specHere) {
  7647.             $specListById[$specHere->getId()] = $specHere->getName();
  7648.         }
  7649.         foreach ($specData as $specDatum) {
  7650.             $finSpecData[] = [
  7651.                 'id' => $specDatum['id'],
  7652.                 'name' => isset($specListById[$specDatum['id']]) ? $specListById[$specDatum['id']] : '',
  7653.                 'value' => $specDatum['value']
  7654.             ];
  7655.         }
  7656.         $productDataObj = array();
  7657.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  7658.             $getters array_filter(get_class_methods($productData), function ($method) {
  7659.                 return 'get' === substr($method03);
  7660.             });
  7661.             foreach ($getters as $getter) {
  7662.                 if ($getter == 'getGlobalId')
  7663.                     continue;
  7664. //                    if ($getter == 'getId')
  7665. //                        continue;
  7666.                 $Fieldname str_replace('get'''$getter);
  7667.                 $productDataObj[$Fieldname] = $productData->{$getter}(); // `foo!`
  7668.             }
  7669.             if ($request->request->has('genInfoOnly') && $request->request->get('genInfoOnly') == 1) {
  7670.                 $dataArray = array(
  7671.                     'success' => true,
  7672.                     'page_title' => 'Product Details',
  7673.                     'company_data' => $company_data,
  7674.                     'productData' => $productData,
  7675.                     'productDataObj' => $productDataObj,
  7676.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7677.                 );
  7678.             } else {
  7679.                 $dataArray = array(
  7680.                     'success' => true,
  7681.                     'page_title' => 'Product Details',
  7682.                     'company_data' => $company_data,
  7683.                     'productData' => $productData,
  7684.                     'productDataObj' => $productDataObj,
  7685.                     'currInvList' => $currInvList,
  7686.                     'finSpecData' => $finSpecData,
  7687.                     'specList' => $specList,
  7688.                     'trans_history' => $trans_history,
  7689.                     'entityList' => GeneralConstant::$Entity_list_details,
  7690. //                    'productList' => Inventory::ProductList($em, $companyId),
  7691.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7692.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7693.                     'igList' => Inventory::ItemGroupList($em$companyId),
  7694.                     'unitList' => Inventory::UnitTypeList($em),
  7695.                     'brandList' => Inventory::GetBrandList($em$companyId),
  7696.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7697.                     'warehouseList' => Inventory::WarehouseList($em),
  7698.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7699.                 );
  7700.             }
  7701.             return new JsonResponse(
  7702.                 $dataArray
  7703.             );
  7704.         }
  7705.         $dataArray = array(
  7706.             'page_title' => 'Product Details',
  7707.             'company_data' => $company_data,
  7708.             'productData' => $productData,
  7709.             'currInvList' => $currInvList,
  7710.             'specData' => $specData,
  7711. //            'specListById' => $specListById,
  7712.             'finSpecData' => $finSpecData,
  7713.             'trans_history' => $trans_history,
  7714.             'entityList' => GeneralConstant::$Entity_list_details,
  7715. //            'productList' => Inventory::ProductList($em, $companyId),
  7716.             'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7717.             'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7718.             'igList' => Inventory::ItemGroupList($em$companyId),
  7719.             'unitList' => Inventory::UnitTypeList($em),
  7720.             'brandList' => Inventory::GetBrandList($em$companyId),
  7721.             'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7722.             'warehouseList' => Inventory::WarehouseList($em),
  7723.         );
  7724.         return $this->render('@Inventory/pages/views/product_view.html.twig'$dataArray
  7725.         );
  7726.     }
  7727.     public function CheckForProductInWarehouseAction(Request $request$queryStr '')
  7728.     {
  7729.         $em $this->getDoctrine()->getManager();
  7730.         $companyId $this->getLoggedUserCompanyId($request);
  7731.         $data = [
  7732.             'availableQty' => 0,
  7733.             'productByCodesArray' => [],
  7734.             'indRowId' => 0
  7735.         ];
  7736.         $html '';
  7737.         $productByCodeData = [];
  7738.         if ($request->isMethod('POST')) {
  7739.             $warehouseId $request->request->get('warehouseId'0);
  7740.             $warehouseActionId $request->request->get('warehouseActionId'0);
  7741.             $productId $request->request->get('productId'0);
  7742.             $indRowId $request->request->get('indRowId'0);
  7743.             $data['indRowId'] = $indRowId;
  7744.             $inStorage $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  7745.                 ->findBy(
  7746.                     array(
  7747.                         'productId' => $productId,
  7748.                         'warehouseId' => $warehouseId,
  7749.                         'actionTagId' => $warehouseActionId,
  7750.                         'CompanyId' => $companyId,
  7751.                     )
  7752.                 );
  7753.             foreach ($inStorage as $strg) {
  7754.                 $data['availableQty'] += $strg->getQty();
  7755.             }
  7756.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  7757.                 ->findBy(
  7758.                     array(
  7759.                         'productId' => $productId,
  7760.                         'warehouseId' => $warehouseId,
  7761.                         'warehouseActionId' => $warehouseActionId,
  7762.                         'CompanyId' => $companyId,
  7763.                     )
  7764.                 );
  7765.             foreach ($productByCodeData as $pbc) {
  7766.                 $data['productByCodesArray'][] = array(
  7767.                     'id' => $pbc->getProductByCodeId(),
  7768.                     'productId' => $pbc->getProductId(),
  7769.                     'warehouseId' => $pbc->getWarehouseId(),
  7770.                     'warehouseActionId' => $pbc->getWarehouseActionId(),
  7771. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7772.                     'sales_code' => str_pad($pbc->getSalesCode(), 13'0'STR_PAD_LEFT),
  7773. //                'sales_code'=>$d['sales_code'],
  7774.                 );
  7775.             }
  7776.             return new JsonResponse(array(
  7777.                     'success' => true,
  7778.                     'data' => $data,
  7779.                 )
  7780.             );
  7781.         }
  7782.         return new JsonResponse(
  7783.             array(
  7784.                 'success' => false,
  7785.                 'data' => $data,
  7786.             )
  7787.         );
  7788.     }
  7789.     public function ProductByCodeListAjaxAction(Request $request$queryStr '')
  7790.     {
  7791.         $em $this->getDoctrine()->getManager();
  7792.         $companyId $this->getLoggedUserCompanyId($request);
  7793.         $company_data Company::getCompanyData($em$companyId);
  7794.         $data = [];
  7795.         $html '';
  7796.         $productByCodeData = [];
  7797.         if ($request->request->has('query') && $queryStr == '')
  7798.             $queryStr $request->request->get('queryStr');
  7799.         $likeQueryStr '%' $queryStr '%';
  7800.         $get_kids_sql "select product_by_code_id id, product_id, warehouse_id, warehouse_action_id,
  7801.                             sales_code ,
  7802.                             serial_no,
  7803.                             imei1,
  7804.                             imei2,
  7805.                             imei3,
  7806.                             imei4
  7807.                             from product_by_code
  7808.                             where ( CONVERT(sales_code,char)  like :queryStr
  7809.                                     or  CONVERT(serial_no,char)  like :queryStr
  7810.                                     or  CONVERT(imei1,char)  like :queryStr
  7811.                                     or  CONVERT(imei2,char)  like :queryStr
  7812.                                     or  CONVERT(imei3,char)  like :queryStr
  7813.                                     or  CONVERT(imei4,char)  like :queryStr
  7814.                                     ) ";
  7815.         $queryParams = array(
  7816.             'queryStr' => $likeQueryStr,
  7817.             'companyId' => (int) $companyId,
  7818.         );
  7819.         if ($request->query->has('warehouseId')) {
  7820.             $get_kids_sql .= " and warehouse_id = :warehouseId ";
  7821.             $queryParams['warehouseId'] = (int) $request->query->get('warehouseId');
  7822.         }
  7823.         if ($request->query->has('position')) {
  7824.             $get_kids_sql .= " and position = :position ";
  7825.             $queryParams['position'] = (int) $request->query->get('position');
  7826.         }
  7827.         if ($request->query->has('deliveryReceiptId')) {
  7828.             $get_kids_sql .= " and deliveryReceiptId = :deliveryReceiptId ";
  7829.             $queryParams['deliveryReceiptId'] = (int) $request->query->get('deliveryReceiptId');
  7830.         }
  7831.         if ($request->query->has('warehouseActionId')) {
  7832.             $get_kids_sql .= " and warehouse_action_id = :warehouseActionId ";
  7833.             $queryParams['warehouseActionId'] = (int) $request->query->get('warehouseActionId');
  7834.         }
  7835.         if ($request->query->has('productId')) {
  7836.             $get_kids_sql .= " and product_id = :productId ";
  7837.             $queryParams['productId'] = (int) $request->query->get('productId');
  7838.         }
  7839.         $get_kids_sql .= " and company_id = :companyId limit 25";
  7840.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$queryParams);
  7841.         $get_kids $stmt;
  7842.         if (!empty($get_kids)) {
  7843.             foreach ($get_kids as $d) {
  7844.                 $dt = array(
  7845.                     'id' => $d['id'],
  7846.                     'productId' => $d['product_id'],
  7847.                     'warehouseId' => $d['warehouse_id'],
  7848.                     'warehouseActionId' => $d['warehouse_action_id'],
  7849. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7850.                     'sales_code' => str_pad($d['sales_code'], 13'0'STR_PAD_LEFT),
  7851.                     'serial_no' => str_pad($d['serial_no'], 13'0'STR_PAD_LEFT),
  7852.                     'imei1' => str_pad($d['imei1'], 13'0'STR_PAD_LEFT),
  7853.                     'imei2' => str_pad($d['imei2'], 13'0'STR_PAD_LEFT),
  7854.                     'imei3' => str_pad($d['imei3'], 13'0'STR_PAD_LEFT),
  7855.                     'imei4' => str_pad($d['imei4'], 13'0'STR_PAD_LEFT),
  7856. //                'sales_code'=>$d['sales_code'],
  7857.                 );
  7858.                 $data[] = $dt;
  7859.             }
  7860.         }
  7861. //        if($request->query->has('returnJson'))
  7862.         {
  7863.             return new JsonResponse(
  7864.                 array(
  7865.                     'success' => true,
  7866. //                    'page_title' => 'Product Details',
  7867. //                    'company_data' => $company_data,
  7868.                     'data' => $data,
  7869. //                    'exId'=>$id,
  7870. //                'productByCodeData' => $productByCodeData,
  7871. //                'productData' => $productData,
  7872. //                'currInvList' => $currInvList,
  7873. //                'productList' => Inventory::ProductList($em, $companyId),
  7874. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  7875. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  7876. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  7877. //                'unitList' => Inventory::UnitTypeList($em),
  7878. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  7879. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  7880. //                'warehouseList' => Inventory::WarehouseList($em),
  7881.                 )
  7882.             );
  7883.         }
  7884.     }
  7885.     public function selectDataAjaxAction(Request $request$queryStr '',
  7886.                                                  $version 'latest',
  7887.                                                  $identifier '_default_',
  7888.                                                  $apiKey '_ignore_'
  7889.     )
  7890.     {
  7891.         $em $this->getDoctrine()->getManager();
  7892.         $em_goc $this->getDoctrine()->getManager('company_group');
  7893.         $companyId 0;
  7894.         $skipCurrentUserIdRestriction $request->get('skipCurrentUserIdRestriction'0);
  7895.         $dataOnly $request->get('dataOnly'0);
  7896.         $skipCurrentEmployeeIdRestriction $request->get('skipCurrentEmployeeIdRestriction'0);
  7897.         $skipCurrentUserLoginIdRestriction $request->get('skipCurrentUserLoginIdRestriction'0);
  7898.         $currentUserId $request->getSession()->get(UserConstants::USER_ID0);
  7899.         $currentEmployeeId $request->getSession()->get(UserConstants::USER_EMPLOYEE_ID0);
  7900.         $currentUserLoginIds = [];
  7901.         if ($request->request->get('entity_group'0)) {
  7902.             $companyId 0;
  7903.             $em $this->getDoctrine()->getManager('company_group');
  7904.         } else {
  7905.             if ($request->request->get('appId'0) != 0) {
  7906.                 $gocEnabled 0;
  7907.                 if ($this->container->hasParameter('entity_group_enabled'))
  7908.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7909.                 else
  7910.                     $gocEnabled 1;
  7911.                 if ($gocEnabled == 1) {
  7912.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7913.                         $this->getDoctrine()->getManager('company_group'),
  7914.                         $gocEnabled,
  7915.                         $request->request->get('appId'0)
  7916.                     );
  7917.                     if (!empty($dataToConnect)) {
  7918.                         $connector $this->container->get('application_connector');
  7919.                         $connector->resetConnection(
  7920.                             'default',
  7921.                             $dataToConnect['dbName'],
  7922.                             $dataToConnect['dbUser'],
  7923.                             $dataToConnect['dbPass'],
  7924.                             $dataToConnect['dbHost'],
  7925.                             $reset true
  7926.                         );
  7927.                         $em $this->getDoctrine()->getManager();
  7928.                     }
  7929.                 }
  7930.             } else if ($request->getSession()->get(UserConstants::USER_APP_ID) != && $request->getSession()->get(UserConstants::USER_APP_ID) != null) {
  7931.                 $gocEnabled 0;
  7932.                 if ($this->container->hasParameter('entity_group_enabled'))
  7933.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7934.                 else
  7935.                     $gocEnabled 1;
  7936.                 if ($gocEnabled == 1) {
  7937.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7938.                         $this->getDoctrine()->getManager('company_group'),
  7939.                         $gocEnabled,
  7940.                         $request->getSession()->get(UserConstants::USER_APP_ID)
  7941.                     );
  7942.                     if (!empty($dataToConnect)) {
  7943.                         $connector $this->container->get('application_connector');
  7944.                         $connector->resetConnection(
  7945.                             'default',
  7946.                             $dataToConnect['dbName'],
  7947.                             $dataToConnect['dbUser'],
  7948.                             $dataToConnect['dbPass'],
  7949.                             $dataToConnect['dbHost'],
  7950.                             $reset true
  7951.                         );
  7952.                         $em $this->getDoctrine()->getManager();
  7953.                     }
  7954.                 }
  7955.             }
  7956.             $companyId $this->getLoggedUserCompanyId($request);
  7957.         }
  7958.         $configData = [];
  7959.         $isSingleDataset 1;
  7960.         $dataSet $request->request->has('dataset') ? $request->request->get('dataset') : [];
  7961.         if (is_string($dataSet)) $dataSet json_decode($dataSettrue);
  7962.         $valuePairs $request->get('valuePairs', []);
  7963.         if (is_string($valuePairs)) $valuePairs json_decode($valuePairstrue);
  7964.         $allResult = [];
  7965.         $datasetFromConfig = [];
  7966.         if ($identifier != '_default_') {
  7967.             $config_file $this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' $identifier 'Config.json';
  7968.             if (!file_exists($config_file)) {
  7969.             } else {
  7970.                 $fileText file_get_contents($config_file);
  7971.                 //now replace any value pairs
  7972.                 foreach ($valuePairs as $kkeeyy => $vvaalluuee) {
  7973.                     if (is_array($vvaalluuee)) {
  7974.                         if (isset($vvaalluuee['value']) && isset($vvaalluuee['type'])) {
  7975.                             if ($vvaalluuee['type'] == 'array'$fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee['value']), $fileText);
  7976.                             if ($vvaalluuee['type'] == 'value'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7977.                             if ($vvaalluuee['type'] == 'text'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  7978.                         } else {
  7979.                             $fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee), $fileText);
  7980.                         }
  7981.                     } else
  7982.                         $fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee$fileText);
  7983.                 }
  7984.                 $fileText str_ireplace('_query_'$request->get('query'$queryStr), $fileText);
  7985.                 $fileText str_ireplace('_itemLimit_'$request->get('itemLimit''_all_'), $fileText);
  7986.                 $fileText str_ireplace('_offset_'$request->get('offset', ($request->get('itemLimit'10)) * ($request->get('page'1) - 1)), $fileText);
  7987.                 if (!(strpos($fileText'_CURRENT_USER_LOGIN_IDS_') === false) && $skipCurrentUserLoginIdRestriction == 0) {
  7988.                     $userInfo = [];
  7989.                     if ($request->getSession()->get(UserConstants::USER_TYPE0) == UserConstants::USER_TYPE_APPLICANT) {
  7990.                         $userInfo $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityLoginLog')->findBy(
  7991.                             array('userId' => $currentUserId)
  7992.                         );
  7993.                     } else {
  7994.                         $userInfo $em->getRepository('ApplicationBundle\\Entity\\SysLoginLog')->findBy(
  7995.                             array('userId' => $currentUserId)
  7996.                         );
  7997.                     }
  7998.                     foreach ($userInfo as $uLogininfo) {
  7999.                         $currentUserLoginIds[] = $uLogininfo->getLoginId();
  8000.                     }
  8001.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_'json_encode($currentUserLoginIds), $fileText);
  8002.                 } else {
  8003.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_''_EMPTY_'$fileText);
  8004.                 }
  8005.                 if (!(strpos($fileText'_CURRENT_USER_ID_') === false) && $skipCurrentUserIdRestriction == 0) {
  8006.                     $fileText str_ireplace('_CURRENT_USER_ID_'$currentUserId$fileText);
  8007.                 } else {
  8008.                     $fileText str_ireplace('_CURRENT_USER_ID_''_EMPTY_'$fileText);
  8009.                 }
  8010.                 if (!(strpos($fileText'_CURRENT_USER_EMPLOYEE_ID_') === false) && $skipCurrentEmployeeIdRestriction == 0) {
  8011.                     if ((strpos($fileText'skipCurrentEmployeeIdRestriction') === false)) {
  8012.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_'$currentEmployeeId$fileText);
  8013.                     } else {
  8014.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  8015.                     }
  8016.                 } else {
  8017.                     $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  8018.                 }
  8019.                 if ($fileText)
  8020.                     $datasetFromConfig json_decode($fileTexttrue);
  8021.                 $skipCurrentUserIdRestriction = isset($datasetFromConfig['skipCurrentUserIdRestriction']) ? $datasetFromConfig['skipCurrentUserIdRestriction'] : $skipCurrentUserIdRestriction;
  8022.                 $skipCurrentEmployeeIdRestriction = isset($datasetFromConfig['skipCurrentEmployeeIdRestriction']) ? $datasetFromConfig['skipCurrentEmployeeIdRestriction'] : $skipCurrentEmployeeIdRestriction;
  8023.                 $skipCurrentUserLoginIdRestriction = isset($datasetFromConfig['skipCurrentUserLoginIdRestriction']) ? $datasetFromConfig['skipCurrentUserLoginIdRestriction'] : $skipCurrentUserLoginIdRestriction;
  8024.             }
  8025.         }
  8026.         if ($dataSet == null$dataSet = [];
  8027. //        return new JsonResponse(array(
  8028. //            'queryStr'=>$queryStr
  8029. //        ));
  8030.         if (!empty($datasetFromConfig)) {
  8031.             if (isset($datasetFromConfig['tableName'])) {
  8032.                 $isSingleDataset 1;
  8033.                 $dataSet[] = $datasetFromConfig;
  8034.             } else {
  8035.                 if (count($datasetFromConfig) == 1)
  8036.                     $isSingleDataset 1;
  8037.                 $dataSet $datasetFromConfig;
  8038.             }
  8039.         }
  8040.         if (empty($dataSet)) {
  8041.             $isSingleDataset 1;
  8042.             $singleDataSet = array(
  8043.                 "valueField" => $request->request->has('valueField') ? $request->request->get('valueField') : 'id',
  8044.                 "query" => $request->get('query'$queryStr),
  8045.                 "headMarkers" => $request->get('headMarkers'''),
  8046.                 "headMarkersStrictMatch" => $request->get('headMarkersStrictMatch'0),
  8047.                 "itemLimit" => $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25,
  8048.                 "selectorId" => $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_',
  8049.                 "textField" => $request->request->has('textField') ? $request->request->get('textField') : 'name',
  8050.                 "tableName" => $request->request->has('tableName') ? $request->request->get('tableName') : '',
  8051.                 "isMultiple" => $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0,
  8052.                 "orConditions" => $request->request->has('orConditions') ? $request->request->get('orConditions') : [],
  8053.                 "andConditions" => $request->request->has('andConditions') ? $request->request->get('andConditions') : [],
  8054.                 "andOrConditions" => $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [],
  8055.                 "mustConditions" => $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [],
  8056.                 "joinTableData" => $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [],
  8057.                 "selectFieldList" => $request->request->has('selectFieldList') ? $request->request->get('selectFieldList') : ['*'],
  8058.                 "renderTextFormat" => $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '',
  8059.                 "setDataForSingle" => $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0,
  8060.                 "dataId" => $request->request->has('dataId') ? $request->request->get('dataId') : 0,
  8061.                 "lastChildrenOnly" => $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0,
  8062.                 "parentOnly" => $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0,
  8063.                 "parentIdField" => $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id',
  8064.                 "skipDefaultCompanyId" => $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1,
  8065.                 "offset" => $request->request->has('offset') ? $request->request->get('offset') : 0,
  8066.                 "returnTotalMatchedEntriesFlag" => $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0,
  8067.                 "nextOffset" => 0,
  8068.                 "totalMatchedEntries" => 0,
  8069.                 "convertToObject" => $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [],
  8070.                 "convertDateToStringFieldList" => $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [],
  8071.                 "orderByConditions" => $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [],
  8072.                 "convertToUrl" => $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [],
  8073.                 "fullPathList" => $request->request->has('fullPathList') ? $request->request->get('fullPathList') : [],
  8074.                 "ret_data" => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8075.             );
  8076.             $dataSet[] = $singleDataSet;
  8077.         }
  8078. //        $lastResult = [
  8079. //            'identifier' => $identifier,
  8080. //            'dataSet' => $dataSet,
  8081. //        ];
  8082. //        return new JsonResponse($lastResult);
  8083.         $userId $request->getSession()->get(UserConstants::USER_ID);
  8084. //        public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [],$userId=0)
  8085.         foreach ($dataSet as $dsIndex => $dataConfig) {
  8086.             $companyId 0;
  8087.             $queryStringIndividual $queryStr;
  8088.             $data = [];
  8089.             $data_by_id = [];
  8090.             $setValueArray = [];
  8091.             $silentChangeSelectize 0;
  8092.             $setValue 0;
  8093.             $setValueType 0;// 0 for id , 1 for query
  8094.             $selectAll 0;
  8095.             $selectAllFound 0;
  8096.             if (isset($dataConfig['query']))
  8097.                 $queryStringIndividual $dataConfig['query'];
  8098.             if ((strpos($queryStringIndividual'_set_matching_value_') !== false)) {
  8099.                 $selectAllFound 1;
  8100.                 $queryStringIndividual str_ireplace('_set_matching_value_'''$queryStringIndividual);
  8101.             }
  8102.             if ($queryStringIndividual == '_EMPTY_')
  8103.                 $queryStringIndividual '';
  8104.             if ($queryStringIndividual == '_EMPTY_')
  8105.                 $queryStringIndividual '';
  8106.             $queryStringIndividual str_replace('_FSLASH_''/'$queryStringIndividual);
  8107.             if ($queryStringIndividual === '#setValue:') {
  8108.                 $queryStringIndividual '';
  8109.             }
  8110.             if (!(strpos($queryStringIndividual'_silent_change_') === false)) {
  8111.                 $silentChangeSelectize 1;
  8112.                 $queryStringIndividual str_ireplace('_silent_change_'''$queryStringIndividual);
  8113.             }
  8114.             if (!(strpos($queryStringIndividual'#setValue:') === false)) {
  8115.                 $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStringIndividual));
  8116.                 foreach ($setValueArrayBeforeFilter as $svf) {
  8117.                     if ($svf == '_ALL_') {
  8118.                         $selectAll 1;
  8119.                         $setValueArray = [];
  8120.                         continue;
  8121.                     }
  8122.                     if (is_numeric($svf)) {
  8123.                         $setValueArray[] = ($svf 1);
  8124.                         $setValue $svf 1;
  8125.                     }
  8126.                 }
  8127.                 $queryStringIndividual '';
  8128.             }
  8129.             $valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
  8130.             $headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''//Special Field
  8131.             $headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0//Special Field
  8132.             $itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
  8133.             $selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
  8134.             $textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
  8135.             $table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
  8136.             $isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
  8137.             $orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
  8138.             $andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
  8139.             $andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
  8140.             $mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
  8141.             $joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
  8142.             $renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
  8143.             $setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
  8144.             $dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
  8145.             $lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
  8146.             $parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
  8147.             $parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
  8148.             $skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
  8149.             $offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
  8150.             $returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
  8151.             $nextOffset 0;
  8152.             $totalMatchedEntries 0;
  8153.             $convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
  8154.             $convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
  8155.             $orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
  8156.             $convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
  8157.             $fullPathList = isset($dataConfig['fullPathList']) ? $dataConfig['fullPathList'] : [];
  8158.             if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  8159.             if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  8160.             if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  8161.             if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  8162.             if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  8163.             if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  8164.             if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  8165.             if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  8166.             if (is_string($fullPathList)) $fullPathList json_decode($fullPathListtrue);
  8167. //            return new JsonResponse(array(
  8168. //                'dataSet'=>$dataSet,
  8169. //                'dataConfig'=>$dataConfig,
  8170. //                'hi'=>$this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json',
  8171. //                'hiD'=>file_get_contents($this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json')
  8172. //            ));
  8173.             if ($table == '') {
  8174.                 $lastResult = array(
  8175.                     'success' => false,
  8176.                     'currentTs' => (new \Datetime())->format('U'),
  8177.                     'isMultiple' => $isMultiple,
  8178.                     'setValueArray' => $setValueArray,
  8179.                     'setValue' => $setValue,
  8180.                     'data' => $data,
  8181.                     'dataId' => $dataId,
  8182.                     'selectorId' => $selectorId,
  8183.                     'dataById' => $data_by_id,
  8184.                     'selectedId' => 0,
  8185.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8186.                 );
  8187.             } else {
  8188.                 $restrictionData = array(
  8189. //            'table'=>'relevantField in restriction'
  8190.                     'warehouse_action' => 'warehouseActionIds',
  8191.                     'branch' => 'branchIds',
  8192.                     'warehouse' => 'warehouseIds',
  8193.                     'production_process_settings' => 'productionProcessIds',
  8194.                 );
  8195.                 $restrictionIdList = [];
  8196.                 $filterQryForCriteria "select ";
  8197.                 $selectQry "";
  8198. //        $selectQry=" `$table`.* ";
  8199.                 $selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
  8200.                 $selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
  8201.                 if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  8202.                 foreach ($selectFieldList as $selFieldFull) {
  8203.                     if ($selectQry != '')
  8204.                         $selectQry .= ", ";
  8205.                     $selFieldArray explode(' '$selFieldFull);
  8206.                     $selField $selFieldArray[0];
  8207.                     $selFieldAlias $selFieldArray[1] ?? '';
  8208.                     if ($selField == '*')
  8209.                         $selectQry .= " `$table`.$selField ";
  8210.                     else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  8211.                         if ($selectPrefix == '')
  8212.                             $selectQry .= " count(*)  ";
  8213.                         else
  8214.                             $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  8215.                     } else {
  8216.                         if ($selectPrefix == '')
  8217.                             $selectQry .= " `$table`.`$selField`  $selFieldAlias";
  8218.                         else
  8219.                             $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  8220.                     }
  8221.                 }
  8222.                 $joinQry " from $table ";
  8223. //        $filterQryForCriteria = "select * from $table ";
  8224.                 foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  8225. //            $conditionStr.=' 1=1 ';
  8226.                     $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  8227.                     $joinTableAlias $joinTableName '_' $joinIndex;
  8228.                     $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  8229.                     $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  8230.                     $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  8231.                     $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  8232.                     $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  8233.                     $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  8234.                     $joinMustConditions = isset($joinTableDatum['joinMustConditions']) ? $joinTableDatum['joinMustConditions'] : [];
  8235.                     $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  8236.                     $joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
  8237.                     $joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
  8238.                     if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  8239.                     if (is_string($joinMustConditions)) $joinMustConditions json_decode($joinMustConditionstrue);
  8240.                     if (is_string($joinAndOrConditions)) $joinAndOrConditions json_decode($joinAndOrConditionstrue);
  8241.                     if (is_string($joinOrConditions)) $joinOrConditions json_decode($joinOrConditionstrue);
  8242.                     foreach ($selectFieldList as $selFieldFull) {
  8243.                         $selFieldArray explode(' '$selFieldFull);
  8244.                         $selField $selFieldArray[0];
  8245.                         $selFieldAlias $selFieldArray[1] ?? '';
  8246.                         if ($selField == '*')
  8247.                             $selectQry .= ", `$joinTableAlias`.$selField ";
  8248.                         else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  8249.                             if ($selectPrefix == '')
  8250.                                 $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  8251.                             else
  8252.                                 $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  8253.                         } else {
  8254.                             if ($selectPrefix == '')
  8255.                                 $selectQry .= ", `$joinTableAlias`.`$selField`  $selFieldAlias";
  8256.                             else
  8257.                                 $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  8258.                         }
  8259.                     }
  8260.                     $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  8261. //            if($joinTablePrimaryField!='')
  8262. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8263. //            $joinAndString = '';
  8264.                     $joinMustString '';
  8265.                     if ($joinTablePrimaryField != '') {
  8266.                         if (!(strpos($joinTablePrimaryField'.') === false)) {
  8267.                             $joinQry .= "  `$joinTableAlias`.`$joinTableOnField`  $fieldJoinType $joinTablePrimaryField ";
  8268.                         } else
  8269.                             $joinQry .= "  `$joinTableAlias`.`$joinTableOnField`  $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8270.                     }
  8271.                     foreach ($joinMustConditions as $mustCondition) {
  8272. //            $conditionStr.=' 1=1 ';
  8273.                         $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  8274.                         $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  8275.                         $aliasInCondition $table;
  8276.                         if (!(strpos($cfield'.') === false)) {
  8277.                             $fullCfieldArray explode('.'$cfield);
  8278.                             $aliasInCondition $fullCfieldArray[0];
  8279.                             $cfield $fullCfieldArray[1];
  8280.                         }
  8281.                         $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  8282.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8283.                             if ($joinMustString != '')
  8284.                                 $joinMustString .= " and ";
  8285.                             if ($ctype == 'like') {
  8286.                                 $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8287.                                 $wordsBySpaces explode(' '$cvalue);
  8288.                                 foreach ($wordsBySpaces as $word) {
  8289.                                     if ($joinMustString != '')
  8290.                                         $joinMustString .= " and ";
  8291.                                     $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8292.                                 }
  8293.                             } else if ($ctype == 'not like') {
  8294.                                 $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8295.                                 $wordsBySpaces explode(' '$cvalue);
  8296.                                 foreach ($wordsBySpaces as $word) {
  8297.                                     if ($joinMustString != '')
  8298.                                         $joinMustString .= " and ";
  8299.                                     $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8300.                                 }
  8301.                             } else if ($ctype == 'not_in') {
  8302.                                 $joinMustString .= " ( ";
  8303.                                 if (in_array('null'$cvalue)) {
  8304.                                     $joinMustString .= " `$joinTableAlias`.$cfield is not null";
  8305.                                     $cvalue array_diff($cvalue, ['null']);
  8306.                                     if (!empty($cvalue))
  8307.                                         $joinMustString .= " and ";
  8308.                                 }
  8309.                                 if (in_array(''$cvalue)) {
  8310.                                     $joinMustString .= "`$joinTableAlias`.$cfield != '' ";
  8311.                                     $cvalue array_diff($cvalue, ['']);
  8312.                                     if (!empty($cvalue))
  8313.                                         $joinMustString .= " and ";
  8314.                                 }
  8315.                                 $joinMustString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8316.                             } else if ($ctype == 'in') {
  8317.                                 if (in_array('null'$cvalue)) {
  8318.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null";
  8319.                                     $cvalue array_diff($cvalue, ['null']);
  8320.                                     if (!empty($cvalue))
  8321.                                         $joinMustString .= " and ";
  8322.                                 }
  8323.                                 if (in_array(''$cvalue)) {
  8324.                                     $joinMustString .= "`$joinTableAlias`.$cfield = '' ";
  8325.                                     $cvalue array_diff($cvalue, ['']);
  8326.                                     if (!empty($cvalue))
  8327.                                         $joinMustString .= " and ";
  8328.                                 }
  8329.                                 $joinMustString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8330.                             } else if ($ctype == '=') {
  8331. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8332. //                            $fullCfieldArray = explode('.', $cfield);
  8333. //                            $aliasInCondition = $fullCfieldArray[0];
  8334. //                            $cfield = $fullCfieldArray[1];
  8335. //                        }
  8336.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8337.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null ";
  8338.                                 else
  8339.                                     $joinMustString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8340.                             } else if ($ctype == '!=') {
  8341.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8342.                                     $joinMustString .= "`$joinTableAlias`.$cfield is not null ";
  8343.                                 else
  8344.                                     $joinMustString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8345.                             } else {
  8346.                                 if (is_string($cvalue))
  8347.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8348.                                 else
  8349.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8350.                             }
  8351.                         }
  8352.                     }
  8353. //            if ($joinMustString != '') {
  8354. //                if ($conditionStr != '')
  8355. //                    $conditionStr .= (" and (" . $joinMustString . ") ");
  8356. //                else
  8357. //                    $conditionStr .= ("  (" . $joinMustString . ") ");
  8358. //            }
  8359.                     if ($joinMustString != '') {
  8360.                         $joinQry .= (' and ' $joinMustString);
  8361. //                        $joinQry.=' and (';
  8362.                     }
  8363.                     $mustBracketDone 0;
  8364.                     $joinAndString '';
  8365. //                    if ($joinTablePrimaryField != '')
  8366. //                        $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8367.                     foreach ($joinAndConditions as $andCondition) {
  8368. //            $conditionStr.=' 1=1 ';
  8369.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  8370.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  8371.                         $aliasInCondition $table;
  8372.                         if (!(strpos($cfield'.') === false)) {
  8373.                             $fullCfieldArray explode('.'$cfield);
  8374.                             $aliasInCondition $fullCfieldArray[0];
  8375.                             $cfield $fullCfieldArray[1];
  8376.                         }
  8377.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  8378.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8379.                             if ($joinAndString != '')
  8380.                                 $joinAndString .= " and ";
  8381.                             if ($ctype == 'like') {
  8382.                                 $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8383.                                 $wordsBySpaces explode(' '$cvalue);
  8384.                                 foreach ($wordsBySpaces as $word) {
  8385.                                     if ($joinAndString != '')
  8386.                                         $joinAndString .= " and ";
  8387.                                     $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8388.                                 }
  8389.                             } else if ($ctype == 'not like') {
  8390.                                 $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8391.                                 $wordsBySpaces explode(' '$cvalue);
  8392.                                 foreach ($wordsBySpaces as $word) {
  8393.                                     if ($joinAndString != '')
  8394.                                         $joinAndString .= " and ";
  8395.                                     $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8396.                                 }
  8397.                             } else if ($ctype == 'not_in') {
  8398.                                 $joinAndString .= " ( ";
  8399.                                 if (in_array('null'$cvalue)) {
  8400.                                     $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  8401.                                     $cvalue array_diff($cvalue, ['null']);
  8402.                                     if (!empty($cvalue))
  8403.                                         $joinAndString .= " and ";
  8404.                                 }
  8405.                                 if (in_array(''$cvalue)) {
  8406.                                     $joinAndString .= "`$joinTableAlias`.$cfield != '' ";
  8407.                                     $cvalue array_diff($cvalue, ['']);
  8408.                                     if (!empty($cvalue))
  8409.                                         $joinAndString .= " and ";
  8410.                                 }
  8411.                                 $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8412.                             } else if ($ctype == 'in') {
  8413.                                 if (in_array('null'$cvalue)) {
  8414.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null";
  8415.                                     $cvalue array_diff($cvalue, ['null']);
  8416.                                     if (!empty($cvalue))
  8417.                                         $joinAndString .= " and ";
  8418.                                 }
  8419.                                 if (in_array(''$cvalue)) {
  8420.                                     $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  8421.                                     $cvalue array_diff($cvalue, ['']);
  8422.                                     if (!empty($cvalue))
  8423.                                         $joinAndString .= " and ";
  8424.                                 }
  8425.                                 $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8426.                             } else if ($ctype == '=') {
  8427. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8428. //                            $fullCfieldArray = explode('.', $cfield);
  8429. //                            $aliasInCondition = $fullCfieldArray[0];
  8430. //                            $cfield = $fullCfieldArray[1];
  8431. //                        }
  8432.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8433.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  8434.                                 else
  8435.                                     $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8436.                             } else if ($ctype == '!=') {
  8437.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8438.                                     $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  8439.                                 else
  8440.                                     $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8441.                             } else {
  8442.                                 if (is_string($cvalue))
  8443.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8444.                                 else
  8445.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8446.                             }
  8447.                         }
  8448.                     }
  8449. //            if ($joinAndString != '') {
  8450. //                if ($conditionStr != '')
  8451. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  8452. //                else
  8453. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  8454. //            }
  8455.                     if ($joinAndString != '') {
  8456.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  8457.                             $joinQry .= ' and (';
  8458.                             $mustBracketDone 1;
  8459.                         }
  8460.                         if ($joinQry != '')
  8461.                             $joinQry .= (" and (" $joinAndString ") ");
  8462.                         else
  8463.                             $joinQry .= ("  (" $joinAndString ") ");
  8464.                     }
  8465.                     $joinAndOrString "";
  8466.                     foreach ($joinAndOrConditions as $andOrCondition) {
  8467. //            $conditionStr.=' 1=1 ';
  8468.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  8469.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  8470.                         $aliasInCondition $table;
  8471.                         if (!(strpos($cfield'.') === false)) {
  8472.                             $fullCfieldArray explode('.'$cfield);
  8473.                             $aliasInCondition $fullCfieldArray[0];
  8474.                             $cfield $fullCfieldArray[1];
  8475.                         }
  8476.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  8477.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8478.                             if ($joinAndOrString != '')
  8479.                                 $joinAndOrString .= " or ";
  8480.                             if ($ctype == 'like') {
  8481.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8482.                                 $wordsBySpaces explode(' '$cvalue);
  8483.                                 foreach ($wordsBySpaces as $word) {
  8484.                                     if ($joinAndOrString != '')
  8485.                                         $joinAndOrString .= " or ";
  8486.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8487.                                 }
  8488.                             } else if ($ctype == 'not like') {
  8489.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8490.                                 $wordsBySpaces explode(' '$cvalue);
  8491.                                 foreach ($wordsBySpaces as $word) {
  8492.                                     if ($joinAndOrString != '')
  8493.                                         $joinAndOrString .= " or ";
  8494.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8495.                                 }
  8496.                             } else if ($ctype == 'not_in') {
  8497.                                 $joinAndOrString .= " ( ";
  8498.                                 if (in_array('null'$cvalue)) {
  8499.                                     $joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
  8500.                                     $cvalue array_diff($cvalue, ['null']);
  8501.                                     if (!empty($cvalue))
  8502.                                         $joinAndOrString .= " or ";
  8503.                                 }
  8504.                                 if (in_array(''$cvalue)) {
  8505.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != '' ";
  8506.                                     $cvalue array_diff($cvalue, ['']);
  8507.                                     if (!empty($cvalue))
  8508.                                         $joinAndOrString .= " or ";
  8509.                                 }
  8510.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8511.                             } else if ($ctype == 'in') {
  8512.                                 if (in_array('null'$cvalue)) {
  8513.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null";
  8514.                                     $cvalue array_diff($cvalue, ['null']);
  8515.                                     if (!empty($cvalue))
  8516.                                         $joinAndOrString .= " or ";
  8517.                                 }
  8518.                                 if (in_array(''$cvalue)) {
  8519.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  8520.                                     $cvalue array_diff($cvalue, ['']);
  8521.                                     if (!empty($cvalue))
  8522.                                         $joinAndOrString .= " or ";
  8523.                                 }
  8524.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8525.                             } else if ($ctype == '=') {
  8526. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8527. //                            $fullCfieldArray = explode('.', $cfield);
  8528. //                            $aliasInCondition = $fullCfieldArray[0];
  8529. //                            $cfield = $fullCfieldArray[1];
  8530. //                        }
  8531.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8532.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
  8533.                                 else
  8534.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8535.                             } else if ($ctype == '!=') {
  8536.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8537.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
  8538.                                 else
  8539.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8540.                             } else {
  8541.                                 if (is_string($cvalue))
  8542.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8543.                                 else
  8544.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8545.                             }
  8546.                         }
  8547.                     }
  8548. //            if ($joinAndOrString != '')
  8549. //                $joinQry .= $joinAndOrString;
  8550.                     if ($joinAndOrString != '') {
  8551.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  8552.                             $joinQry .= ' and (';
  8553.                             $mustBracketDone 1;
  8554.                         }
  8555.                         if ($joinQry != '')
  8556.                             $joinQry .= (" and (" $joinAndOrString ") ");
  8557.                         else
  8558.                             $joinQry .= ("  (" $joinAndOrString ") ");
  8559.                     }
  8560.                     //pika
  8561.                     $joinOrString "";
  8562.                     foreach ($joinOrConditions as $orCondition) {
  8563. //            $conditionStr.=' 1=1 ';
  8564.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  8565.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  8566.                         $aliasInCondition $table;
  8567.                         if (!(strpos($cfield'.') === false)) {
  8568.                             $fullCfieldArray explode('.'$cfield);
  8569.                             $aliasInCondition $fullCfieldArray[0];
  8570.                             $cfield $fullCfieldArray[1];
  8571.                         }
  8572.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  8573.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8574.                             if ($joinOrString != '' || $joinAndString != '' || $joinMustString != '')
  8575.                                 $joinOrString .= " or ";
  8576.                             if ($ctype == 'like') {
  8577.                                 $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8578.                                 $wordsBySpaces explode(' '$cvalue);
  8579.                                 foreach ($wordsBySpaces as $word) {
  8580.                                     if ($joinOrString != '')
  8581.                                         $joinOrString .= " or ";
  8582.                                     $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8583.                                 }
  8584.                             } else if ($ctype == 'not like') {
  8585.                                 $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8586.                                 $wordsBySpaces explode(' '$cvalue);
  8587.                                 foreach ($wordsBySpaces as $word) {
  8588.                                     if ($joinOrString != '')
  8589.                                         $joinOrString .= " or ";
  8590.                                     $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8591.                                 }
  8592.                             } else if ($ctype == 'not_in') {
  8593.                                 $joinOrString .= " ( ";
  8594.                                 if (in_array('null'$cvalue)) {
  8595.                                     $joinOrString .= " `$joinTableAlias`.$cfield is not null";
  8596.                                     $cvalue array_diff($cvalue, ['null']);
  8597.                                     if (!empty($cvalue))
  8598.                                         $joinOrString .= " or ";
  8599.                                 }
  8600.                                 if (in_array(''$cvalue)) {
  8601.                                     $joinOrString .= "`$joinTableAlias`.$cfield != '' ";
  8602.                                     $cvalue array_diff($cvalue, ['']);
  8603.                                     if (!empty($cvalue))
  8604.                                         $joinOrString .= " or ";
  8605.                                 }
  8606.                                 $joinOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8607.                             } else if ($ctype == 'in') {
  8608.                                 if (in_array('null'$cvalue)) {
  8609.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null";
  8610.                                     $cvalue array_diff($cvalue, ['null']);
  8611.                                     if (!empty($cvalue))
  8612.                                         $joinOrString .= " or ";
  8613.                                 }
  8614.                                 if (in_array(''$cvalue)) {
  8615.                                     $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  8616.                                     $cvalue array_diff($cvalue, ['']);
  8617.                                     if (!empty($cvalue))
  8618.                                         $joinOrString .= " or ";
  8619.                                 }
  8620.                                 $joinOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8621.                             } else if ($ctype == '=') {
  8622. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8623. //                            $fullCfieldArray = explode('.', $cfield);
  8624. //                            $aliasInCondition = $fullCfieldArray[0];
  8625. //                            $cfield = $fullCfieldArray[1];
  8626. //                        }
  8627.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8628.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null ";
  8629.                                 else
  8630.                                     $joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8631.                             } else if ($ctype == '!=') {
  8632.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8633.                                     $joinOrString .= "`$joinTableAlias`.$cfield is not null ";
  8634.                                 else
  8635.                                     $joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8636.                             } else {
  8637.                                 if (is_string($cvalue))
  8638.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8639.                                 else
  8640.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8641.                             }
  8642.                         }
  8643.                     }
  8644. //            if ($joinOrString != '')
  8645. //                $joinQry .= $joinOrString;
  8646.                     if ($joinOrString != '') {
  8647.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  8648.                             $joinQry .= ' and (';
  8649.                             $mustBracketDone 1;
  8650.                         }
  8651.                         if ($joinQry != '')
  8652.                             $joinQry .= (" or (" $joinOrString ") ");
  8653.                         else
  8654.                             $joinQry .= ("  (" $joinOrString ") ");
  8655.                     }
  8656.                     if ($joinMustString != '' && $mustBracketDone == 1) {
  8657.                         $joinQry .= ' ) ';
  8658.                     }
  8659. //
  8660. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8661.                 }
  8662.                 $filterQryForCriteria .= $selectQry;
  8663.                 $filterQryForCriteria .= $joinQry;
  8664.                 if ($skipDefaultCompanyId == && $companyId != && !isset($dataConfig['entity_group']))
  8665.                     $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  8666.                 else
  8667.                     $filterQryForCriteria .= " where 1=1 ";
  8668.                 $conditionStr "";
  8669.                 $aliasInCondition $table;
  8670.                 if ($headMarkers != '' && $table == 'acc_accounts_head') {
  8671.                     $markerList explode(','$headMarkers);
  8672.                     $spMarkerQry "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
  8673.                     $markerPassedHeads = [];
  8674.                     foreach ($markerList as $mrkr) {
  8675.                         $spMarkerQry .= " and marker_hash like '%" $mrkr "%'";
  8676.                     }
  8677.                     $spStmt $em->getConnection()->fetchAllAssociative($spMarkerQry);
  8678.                     $spStmtResults $spStmt;
  8679.                     foreach ($spStmtResults as $ggres) {
  8680.                         $markerPassedHeads[] = $ggres['accounts_head_id'];
  8681.                     }
  8682.                     if (!empty($markerPassedHeads)) {
  8683.                         if ($conditionStr != '')
  8684.                             $conditionStr .= " and (";
  8685.                         else
  8686.                             $conditionStr .= " (";
  8687.                         if ($headMarkersStrictMatch != 1) {
  8688.                             foreach ($markerPassedHeads as $mh) {
  8689.                                 $conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" $mh "/%' or ";
  8690.                             }
  8691.                         }
  8692.                         $conditionStr .= "  `$aliasInCondition`.`accounts_head_id` in (" implode(','$markerPassedHeads) . ") ";
  8693.                         $conditionStr .= " )";
  8694.                     }
  8695.                 }
  8696.                 if (isset($restrictionData[$table])) {
  8697.                     $userRestrictionData Users::getUserApplicationAccessSettings($em$userId)['options'];
  8698.                     if (isset($userRestrictionData[$restrictionData[$table]])) {
  8699.                         $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  8700.                         if ($restrictionIdList == null)
  8701.                             $restrictionIdList = [];
  8702.                     }
  8703.                     if (!empty($restrictionIdList)) {
  8704.                         if ($conditionStr != '')
  8705.                             $conditionStr .= " and ";
  8706.                         $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  8707.                     }
  8708.                 }
  8709. //        $aliasInCondition = $table;
  8710.                 if (!empty($setValueArray) || $selectAll == 1) {
  8711.                     if (!empty($setValueArray)) {
  8712.                         if ($conditionStr != '')
  8713.                             $conditionStr .= " and ";
  8714.                         $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  8715.                     }
  8716.                 } else {
  8717.                     $andString '';
  8718.                     foreach ($andConditions as $andCondition) {
  8719. //            $conditionStr.=' 1=1 ';
  8720.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  8721.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  8722.                         $aliasInCondition $table;
  8723.                         if (!(strpos($cfield'.') === false)) {
  8724.                             $fullCfieldArray explode('.'$cfield);
  8725.                             $aliasInCondition $fullCfieldArray[0];
  8726.                             $cfield $fullCfieldArray[1];
  8727.                         }
  8728.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  8729.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8730.                             if ($andString != '')
  8731.                                 $andString .= " and ";
  8732.                             if ($ctype == 'like') {
  8733.                                 $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8734.                                 $wordsBySpaces explode(' '$cvalue);
  8735.                                 foreach ($wordsBySpaces as $word) {
  8736.                                     if ($andString != '')
  8737.                                         $andString .= " and ";
  8738.                                     $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8739.                                 }
  8740.                             } else if ($ctype == 'not like') {
  8741.                                 $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8742.                                 $wordsBySpaces explode(' '$cvalue);
  8743.                                 foreach ($wordsBySpaces as $word) {
  8744.                                     if ($andString != '')
  8745.                                         $andString .= " and ";
  8746.                                     $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8747.                                 }
  8748.                             } else if ($ctype == 'not_in') {
  8749.                                 $andString .= " ( ";
  8750.                                 if (in_array('null'$cvalue)) {
  8751.                                     $andString .= " `$aliasInCondition`.$cfield is not null";
  8752.                                     $cvalue array_diff($cvalue, ['null']);
  8753.                                     if (!empty($cvalue))
  8754.                                         $andString .= " and ";
  8755.                                 }
  8756.                                 if (in_array(''$cvalue)) {
  8757.                                     $andString .= "`$aliasInCondition`.$cfield != '' ";
  8758.                                     $cvalue array_diff($cvalue, ['']);
  8759.                                     if (!empty($cvalue))
  8760.                                         $andString .= " and ";
  8761.                                 }
  8762.                                 $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8763.                             } else if ($ctype == 'in') {
  8764.                                 if (in_array('null'$cvalue)) {
  8765.                                     $andString .= "`$aliasInCondition`.$cfield is null";
  8766.                                     $cvalue array_diff($cvalue, ['null']);
  8767.                                     if (!empty($cvalue))
  8768.                                         $andString .= " and ";
  8769.                                 }
  8770.                                 if (in_array(''$cvalue)) {
  8771.                                     $andString .= "`$aliasInCondition`.$cfield = '' ";
  8772.                                     $cvalue array_diff($cvalue, ['']);
  8773.                                     if (!empty($cvalue))
  8774.                                         $andString .= " and ";
  8775.                                 }
  8776.                                 $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  8777.                             } else if ($ctype == '=') {
  8778.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8779.                                     $andString .= "`$aliasInCondition`.$cfield is null ";
  8780.                                 else
  8781.                                     if (is_string($cvalue))
  8782.                                         $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8783.                                     else
  8784.                                         $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8785.                             } else if ($ctype == '!=') {
  8786.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8787.                                     $andString .= "`$aliasInCondition`.$cfield is not null ";
  8788.                                 else
  8789.                                     $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8790.                             } else {
  8791.                                 if (is_string($cvalue))
  8792.                                     $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8793.                                 else
  8794.                                     $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8795.                             }
  8796.                         }
  8797.                     }
  8798.                     if ($andString != '') {
  8799.                         if ($conditionStr != '')
  8800.                             $conditionStr .= (" and (" $andString ") ");
  8801.                         else
  8802.                             $conditionStr .= ("  (" $andString ") ");
  8803.                     }
  8804.                     $orString '';
  8805.                     foreach ($orConditions as $orCondition) {
  8806.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  8807.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  8808.                         $aliasInCondition $table;
  8809.                         if (!(strpos($cfield'.') === false)) {
  8810.                             $fullCfieldArray explode('.'$cfield);
  8811.                             $aliasInCondition $fullCfieldArray[0];
  8812.                             $cfield $fullCfieldArray[1];
  8813.                         }
  8814.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  8815.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8816.                             if ($orString != '')
  8817.                                 $orString .= " or ";
  8818.                             if ($ctype == 'like') {
  8819.                                 $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8820.                                 $wordsBySpaces explode(' '$cvalue);
  8821.                                 foreach ($wordsBySpaces as $word) {
  8822.                                     if ($orString != '')
  8823.                                         $orString .= " or ";
  8824.                                     $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8825.                                 }
  8826.                             } else if ($ctype == 'not like') {
  8827.                                 $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8828.                                 $wordsBySpaces explode(' '$cvalue);
  8829.                                 foreach ($wordsBySpaces as $word) {
  8830.                                     if ($orString != '')
  8831.                                         $orString .= " or ";
  8832.                                     $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8833.                                 }
  8834.                             } else if ($ctype == 'not_in') {
  8835.                                 $orString .= " ( ";
  8836.                                 if (in_array('null'$cvalue)) {
  8837.                                     $orString .= " `$aliasInCondition`.$cfield is not null";
  8838.                                     $cvalue array_diff($cvalue, ['null']);
  8839.                                     if (!empty($cvalue))
  8840.                                         $orString .= " or ";
  8841.                                 }
  8842.                                 if (in_array(''$cvalue)) {
  8843.                                     $orString .= "`$aliasInCondition`.$cfield != '' ";
  8844.                                     $cvalue array_diff($cvalue, ['']);
  8845.                                     if (!empty($cvalue))
  8846.                                         $orString .= " or ";
  8847.                                 }
  8848.                                 $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8849.                             } else if ($ctype == 'in') {
  8850.                                 $orString .= " ( ";
  8851.                                 if (in_array('null'$cvalue)) {
  8852.                                     $orString .= " `$aliasInCondition`.$cfield is null";
  8853.                                     $cvalue array_diff($cvalue, ['null']);
  8854.                                     if (!empty($cvalue))
  8855.                                         $orString .= " or ";
  8856.                                 }
  8857.                                 if (in_array(''$cvalue)) {
  8858.                                     $orString .= "`$aliasInCondition`.$cfield = '' ";
  8859.                                     $cvalue array_diff($cvalue, ['']);
  8860.                                     if (!empty($cvalue))
  8861.                                         $orString .= " or ";
  8862.                                 }
  8863.                                 $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8864.                             } else if ($ctype == '=') {
  8865.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8866.                                     $orString .= "`$aliasInCondition`.$cfield is null ";
  8867.                                 else
  8868.                                     if (is_string($cvalue))
  8869.                                         $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8870.                                     else
  8871.                                         $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8872.                             } else if ($ctype == '!=') {
  8873.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8874.                                     $orString .= "`$aliasInCondition`.$cfield is not null ";
  8875.                                 else
  8876.                                     $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8877.                             } else {
  8878.                                 if (is_string($cvalue))
  8879.                                     $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8880.                                 else
  8881.                                     $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8882.                             }
  8883.                         }
  8884.                     }
  8885.                     if ($orString != '') {
  8886.                         if ($conditionStr != '')
  8887.                             $conditionStr .= (" or (" $orString ") ");
  8888.                         else
  8889.                             $conditionStr .= ("  (" $orString ") ");
  8890.                     }
  8891.                     $andOrString '';
  8892.                     foreach ($andOrConditions as $andOrCondition) {
  8893.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  8894.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  8895.                         $aliasInCondition $table;
  8896.                         if (!(strpos($cfield'.') === false)) {
  8897.                             $fullCfieldArray explode('.'$cfield);
  8898.                             $aliasInCondition $fullCfieldArray[0];
  8899.                             $cfield $fullCfieldArray[1];
  8900.                         }
  8901.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  8902.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8903.                             if ($andOrString != '')
  8904.                                 $andOrString .= " or ";
  8905.                             if ($ctype == 'like') {
  8906.                                 $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8907.                                 $wordsBySpaces explode(' '$cvalue);
  8908.                                 foreach ($wordsBySpaces as $word) {
  8909.                                     if ($andOrString != '')
  8910.                                         $andOrString .= " or ";
  8911.                                     $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8912.                                 }
  8913.                             } else if ($ctype == 'not like') {
  8914.                                 $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8915.                                 $wordsBySpaces explode(' '$cvalue);
  8916.                                 foreach ($wordsBySpaces as $word) {
  8917.                                     if ($andOrString != '')
  8918.                                         $andOrString .= " or ";
  8919.                                     $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8920.                                 }
  8921.                             } else if ($ctype == 'in') {
  8922.                                 $andOrString .= " ( ";
  8923.                                 if (in_array('null'$cvalue)) {
  8924.                                     $andOrString .= " `$aliasInCondition`.$cfield is null";
  8925.                                     $cvalue array_diff($cvalue, ['null']);
  8926.                                     if (!empty($cvalue))
  8927.                                         $andOrString .= " or ";
  8928.                                 }
  8929.                                 if (in_array(''$cvalue)) {
  8930.                                     $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  8931.                                     $cvalue array_diff($cvalue, ['']);
  8932.                                     if (!empty($cvalue))
  8933.                                         $andOrString .= " or ";
  8934.                                 }
  8935.                                 if (!empty($cvalue))
  8936.                                     $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8937.                                 else
  8938.                                     $andOrString .= "  ) ";
  8939.                             } else if ($ctype == 'not_in') {
  8940.                                 $andOrString .= " ( ";
  8941.                                 if (in_array('null'$cvalue)) {
  8942.                                     $andOrString .= " `$aliasInCondition`.$cfield is not null";
  8943.                                     $cvalue array_diff($cvalue, ['null']);
  8944.                                     if (!empty($cvalue))
  8945.                                         $andOrString .= " or ";
  8946.                                 }
  8947.                                 if (in_array(''$cvalue)) {
  8948.                                     $andOrString .= "`$aliasInCondition`.$cfield != '' ";
  8949.                                     $cvalue array_diff($cvalue, ['']);
  8950.                                     if (!empty($cvalue))
  8951.                                         $andOrString .= " or ";
  8952.                                 }
  8953.                                 if (!empty($cvalue))
  8954.                                     $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8955.                                 else
  8956.                                     $andOrString .= "  ) ";
  8957.                             } else if ($ctype == '=') {
  8958.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8959.                                     $andOrString .= "`$aliasInCondition`.$cfield is null ";
  8960.                                 else
  8961.                                     if (is_string($cvalue))
  8962.                                         $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8963.                                     else
  8964.                                         $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8965.                             } else if ($ctype == '!=') {
  8966.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8967.                                     $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  8968.                                 else
  8969.                                     $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8970.                             } else {
  8971.                                 if (is_string($cvalue))
  8972.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8973.                                 else
  8974.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8975.                             }
  8976.                         }
  8977.                     }
  8978.                     if ($andOrString != '') {
  8979.                         if ($conditionStr != '')
  8980.                             $conditionStr .= (" and (" $andOrString ") ");
  8981.                         else
  8982.                             $conditionStr .= ("  (" $andOrString ") ");
  8983.                     }
  8984.                 }
  8985.                 $mustStr '';
  8986. ///now must conditions
  8987.                 foreach ($mustConditions as $mustCondition) {
  8988. //            $conditionStr.=' 1=1 ';
  8989.                     $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  8990.                     $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  8991.                     $aliasInCondition $table;
  8992.                     if (!(strpos($cfield'.') === false)) {
  8993.                         $fullCfieldArray explode('.'$cfield);
  8994.                         $aliasInCondition $fullCfieldArray[0];
  8995.                         $cfield $fullCfieldArray[1];
  8996.                     }
  8997.                     $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  8998.                     if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8999.                         if ($mustStr != '')
  9000.                             $mustStr .= " and ";
  9001.                         if ($ctype == 'like') {
  9002.                             $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  9003.                             $wordsBySpaces explode(' '$cvalue);
  9004.                             foreach ($wordsBySpaces as $word) {
  9005.                                 if ($mustStr != '')
  9006.                                     $mustStr .= " or ";
  9007.                                 $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  9008.                             }
  9009.                             $mustStr .= " )";
  9010.                         } else if ($ctype == 'not like') {
  9011.                             $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  9012.                             $wordsBySpaces explode(' '$cvalue);
  9013.                             foreach ($wordsBySpaces as $word) {
  9014.                                 if ($mustStr != '')
  9015.                                     $mustStr .= " and ";
  9016.                                 $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  9017.                             }
  9018.                         } else if ($ctype == 'in') {
  9019.                             $mustStr .= " ( ";
  9020.                             if (in_array('null'$cvalue)) {
  9021.                                 $mustStr .= " `$aliasInCondition`.$cfield is null";
  9022.                                 $cvalue array_diff($cvalue, ['null']);
  9023.                                 if (!empty($cvalue))
  9024.                                     $mustStr .= " or ";
  9025.                             }
  9026.                             if (in_array(''$cvalue)) {
  9027.                                 $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  9028.                                 $cvalue array_diff($cvalue, ['']);
  9029.                                 if (!empty($cvalue))
  9030.                                     $mustStr .= " or ";
  9031.                             }
  9032.                             $formattedValues array_map(function ($val) {
  9033.                                 $val trim($val);
  9034.                                 if (is_numeric($val)) {
  9035.                                     return $val;
  9036.                                 }
  9037.                                 return "'" addslashes($val) . "'";
  9038.                             }, $cvalue);
  9039.                             $mustStr .= "`$aliasInCondition`.$cfield IN (" implode(','$formattedValues) . ") ) ";
  9040. //                            $mustStr .= "`$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ) ";
  9041.                         } else if ($ctype == 'not_in') {
  9042.                             $mustStr .= " ( ";
  9043.                             if (in_array('null'$cvalue)) {
  9044.                                 $mustStr .= " `$aliasInCondition`.$cfield is not null";
  9045.                                 $cvalue array_diff($cvalue, ['null']);
  9046.                                 if (!empty($cvalue))
  9047.                                     $mustStr .= " and ";
  9048.                             }
  9049.                             if (in_array(''$cvalue)) {
  9050.                                 $mustStr .= "`$aliasInCondition`.$cfield != '' ";
  9051.                                 $cvalue array_diff($cvalue, ['']);
  9052.                                 if (!empty($cvalue))
  9053.                                     $mustStr .= " and ";
  9054.                             }
  9055.                             $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  9056.                         } else if ($ctype == '=') {
  9057.                             if ($cvalue == 'null' || $cvalue == 'Null')
  9058.                                 $mustStr .= "`$aliasInCondition`.$cfield is null ";
  9059.                             else
  9060.                                 if (is_string($cvalue))
  9061.                                     $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  9062.                                 else
  9063.                                     $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  9064.                         } else if ($ctype == '!=') {
  9065.                             if ($cvalue == 'null' || $cvalue == 'Null')
  9066.                                 $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  9067.                             else
  9068.                                 $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  9069.                         } else {
  9070.                             if (is_string($cvalue))
  9071.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  9072.                             else
  9073.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  9074.                         }
  9075.                     }
  9076.                 }
  9077.                 if ($mustStr != '') {
  9078.                     if ($conditionStr != '')
  9079.                         $conditionStr .= (" and (" $mustStr ") ");
  9080.                     else
  9081.                         $conditionStr .= ("  (" $mustStr ") ");
  9082.                 }
  9083.                 if ($conditionStr != '')
  9084.                     $filterQryForCriteria .= (" and (" $conditionStr ") ");
  9085.                 if ($lastChildrenOnly == 1) {
  9086.                     if ($filterQryForCriteria != '')
  9087.                         $filterQryForCriteria .= ' and ';
  9088.                     $filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  9089.                 } else if ($parentOnly == 1) {
  9090.                     if ($filterQryForCriteria != '')
  9091.                         $filterQryForCriteria .= ' and ';
  9092.                     $filterQryForCriteria .= "`$table`.`$valueField`  in ( select distinct $parentIdField from  $table)";
  9093.                 }
  9094.                 if (!empty($orderByConditions)) {
  9095.                     $filterQryForCriteria .= "  order by ";
  9096.                     $fone 1;
  9097.                     foreach ($orderByConditions as $orderByCondition) {
  9098.                         if ($fone != 1) {
  9099.                             $filterQryForCriteria .= " , ";
  9100.                         }
  9101.                         if (isset($orderByCondition['valueList'])) {
  9102.                             if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  9103.                             if ($orderByCondition['valueList'] == null)
  9104.                                 $orderByCondition['valueList'] = [];
  9105.                             $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  9106.                         } else
  9107.                             $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  9108.                         $fone 0;
  9109.                     }
  9110.                 }
  9111.                 if ($returnTotalMatchedEntriesFlag == 1) {
  9112. //            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9113. //            
  9114. //            $get_kids = $stmt;
  9115.                 }
  9116.                 if ($filterQryForCriteria != '')
  9117.                     if (!empty($setValueArray) || $selectAll == 1) {
  9118.                     } else {
  9119.                         if ($itemLimit != '_ALL_')
  9120.                             $filterQryForCriteria .= "  limit $offset$itemLimit ";
  9121.                         else
  9122.                             $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  9123.                     }
  9124.                 $get_kids_sql $filterQryForCriteria;
  9125.                 $get_kids_sql str_ireplace('_set_matching_value_'''$get_kids_sql);
  9126.                 // TODO: This generic selector assembles SQL across many request-driven table branches.
  9127.                 // Converting it safely requires untangling the shared builder so each branch can bind
  9128.                 // its own parameters without changing selector behavior in unrelated endpoints.
  9129.                 $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9130.                 $get_kids $stmt;
  9131.                 $selectedId 0;
  9132.                 if ($table == 'warehouse_action') {
  9133.                     if (empty($get_kids)) {
  9134.                         $get_kids_sql_2 "select * from warehouse_action";
  9135.                         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql_2);
  9136.                         $get_kids2 $stmt;
  9137.                         if (empty($get_kids2))
  9138.                             $get_kids GeneralConstant::$warehouse_action_list;
  9139.                     }
  9140.                 }
  9141.                 if (!empty($get_kids)) {
  9142.                     $nextOffset $offset count($get_kids);
  9143.                     $nextOffset++;
  9144.                     foreach ($get_kids as $pa) {
  9145.                         if (!empty($setValueArray) && $selectAll == 0) {
  9146.                             if (!in_array($pa[$valueField], $setValueArray))
  9147.                                 continue;
  9148.                         }
  9149.                         if (!empty($restrictionIdList)) {
  9150.                             if (!in_array($pa[$valueField], $restrictionIdList))
  9151.                                 continue;
  9152.                         }
  9153.                         if ($selectAll == || $selectAllFound==1) {
  9154.                             $setValueArray[] = $pa[$valueField];
  9155.                             $setValue $pa[$valueField];
  9156.                         } else if (count($get_kids) == && $setDataForSingle == 1) {
  9157.                             $setValueArray[] = $pa[$valueField];
  9158.                             $setValue $pa[$valueField];
  9159.                         }
  9160.                         if ($valueField != '')
  9161.                             $pa['value'] = $pa[$valueField];
  9162.                         $renderedText $renderTextFormat;
  9163.                         $compare_array = [];
  9164.                         if ($renderTextFormat != '') {
  9165.                             $renderedText $renderTextFormat;
  9166.                             $compare_arrayFull = [];
  9167.                             $compare_array = [];
  9168.                             $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  9169.                             );
  9170.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  9171.                             if (isset($compare_arrayFull[0]))
  9172.                                 $compare_array $compare_arrayFull[0];
  9173. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  9174.                             foreach ($compare_array as $cmpdt) {
  9175.                                 $tbr str_replace("__"""$cmpdt);
  9176.                                 if ($tbr != '') {
  9177.                                     if (isset($pa[$tbr])) {
  9178.                                         if ($pa[$tbr] == null)
  9179.                                             $renderedText str_replace($cmpdt''$renderedText);
  9180.                                         else
  9181.                                             $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  9182.                                     } else {
  9183.                                         $renderedText str_replace($cmpdt''$renderedText);
  9184.                                     }
  9185.                                 }
  9186.                             }
  9187.                         }
  9188.                         $pa['rendered_text'] = $renderedText;
  9189.                         $pa['text'] = ($textField != '' $pa[$textField] : '');
  9190. //                $pa['compare_array'] = $compare_array;
  9191.                         foreach ($convertToObjectFieldList as $convField) {
  9192.                             if (isset($pa[$convField])) {
  9193.                                 $taA json_decode($pa[$convField], true);
  9194.                                 if ($taA == null$taA = [];
  9195.                                 $pa[$convField] = $taA;
  9196.                             } else {
  9197.                                 $pa[$convField] = [];
  9198.                             }
  9199.                         }
  9200.                         foreach ($convertDateToStringFieldList as $convField) {
  9201.                             if (is_array($convField)) {
  9202.                                 $fld $convField['field'];
  9203.                                 $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  9204.                             } else {
  9205.                                 $fld $convField;
  9206.                                 $frmt 'Y-m-d H:i:s';
  9207.                             }
  9208.                             if (isset($pa[$fld])) {
  9209.                                 $taA = new \DateTime($pa[$fld]);
  9210.                                 $pa[$fld] = $taA->format($frmt);
  9211.                             }
  9212.                         }
  9213.                         foreach ($convertToUrl as $convField) {
  9214. //
  9215. //                            $fld = $convField;
  9216. //
  9217. //
  9218. //                            if (isset($pa[$fld])) {
  9219. //
  9220. //
  9221. //                                $pa[$fld] =
  9222. //                                    $this->generateUrl(
  9223. //                                        'dashboard', [
  9224. //
  9225. //                                    ], UrlGenerator::ABSOLUTE_URL
  9226. //                                    ).'/'.$pa[$fld];
  9227. //
  9228. //                            }
  9229.                         }
  9230.                         foreach ($fullPathList as $pathField) {
  9231.                             $fld $pathField;
  9232.                             if (isset($pa[$fld])) {
  9233.                                 if ($pa[$fld] != '' && $pa[$fld] != null) {
  9234.                                     $pa[$fld] = ($this->generateUrl(
  9235.                                             'dashboard', [
  9236.                                         ], UrlGenerator::ABSOLUTE_URL
  9237.                                         ) . $pa[$fld]);
  9238.                                 }
  9239.                             }
  9240.                         }
  9241.                         $pa['currentTs'] = (new \Datetime())->format('U');
  9242.                         $data[] = $pa;
  9243.                         if ($valueField != '') {
  9244.                             $data_by_id[$pa[$valueField]] = $pa;
  9245.                             $selectedId $pa[$valueField];
  9246.                         }
  9247.                     }
  9248.                 }
  9249.                 if ($dataOnly == 1)
  9250.                     $lastResult = array(
  9251.                         'success' => true,
  9252.                         'data' => $data,
  9253.                         'currentTs' => (new \Datetime())->format('U'),
  9254.                         'restrictionIdList' => $restrictionIdList,
  9255.                         'nextOffset' => $nextOffset,
  9256.                         'totalMatchedEntries' => $totalMatchedEntries,
  9257.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  9258.                     );
  9259.                 else
  9260.                     $lastResult = array(
  9261.                         'success' => true,
  9262.                         'data' => $data,
  9263.                         'tableName' => $table,
  9264.                         'setValue' => $setValue,
  9265.                         'currentTs' => (new \Datetime())->format('U'),
  9266.                         'restrictionIdList' => $restrictionIdList,
  9267.                         'andConditions' => $andConditions,
  9268.                         'selectFieldList' => $selectFieldList,
  9269.                         'queryStr' => $queryStringIndividual,
  9270.                         'isMultiple' => $isMultiple,
  9271.                         'nextOffset' => $nextOffset,
  9272.                         'totalMatchedEntries' => $totalMatchedEntries,
  9273.                         'selectorId' => $selectorId,
  9274.                         'setValueArray' => $setValueArray,
  9275.                         'silentChangeSelectize' => $silentChangeSelectize,
  9276.                         'convertToObjectFieldList' => $convertToObjectFieldList,
  9277.                         'conditionStr' => $conditionStr,
  9278.                         'selectAll' => $selectAll,
  9279. //                    'andStr' => $andString,
  9280. //                    'andOrStr' => $andOrString,
  9281.                         'dataById' => $data_by_id,
  9282.                         'selectedId' => $selectedId,
  9283.                         'dataId' => $dataId,
  9284.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  9285.                     );
  9286.             }
  9287.             $allResult[] = $lastResult;
  9288.         }
  9289.         if ($isSingleDataset == 1)
  9290.             return new JsonResponse($lastResult);
  9291.         else
  9292.             return new JsonResponse($allResult);
  9293.     }
  9294.     public function updatePlanningItemSequenceAction(Request $request$queryStr '')
  9295.     {
  9296.         $em $this->getDoctrine()->getManager();
  9297.         $stmt $em->getConnection()->fetchAllAssociative("select  `id` , parent_id, sequence from planning_item where sequence is null 
  9298.             ORDER BY parent_id ASC, id ASC
  9299.                         ");
  9300.         $query_output $stmt;
  9301.         foreach ($query_output as $dupe) {
  9302.             System::updatePlanningItemSequence($em$dupe["id"]);
  9303.         }
  9304.         System::updatePlanningItemSequence(
  9305.             $em,
  9306.             $request->request->get('planningItemId'0),
  9307.             $request->request->get('assignType''_ASSIGN_')   ///can be _MOVE_UP_ or _MOVE_DOWN_
  9308.         );
  9309. //        if($request->query->has('returnJson'))
  9310.         return new JsonResponse(
  9311.             array(
  9312.                 'success' => true,
  9313.                 'data' => [],
  9314.             )
  9315.         );
  9316.     }
  9317.     public function insertDataAjaxAction(Request $request$queryStr '')
  9318.     {
  9319.         $em $this->getDoctrine()->getManager();
  9320. //        if($request->query->has('big_data_test'))
  9321. //        {
  9322. //            for($t=0;$t<$request->request->get('big_data_test',10000);$t++) {
  9323. //                $em = $this->getDoctrine()->getManager('company_group');
  9324. //                $NOTIFICATION = new EntityNotification();
  9325. //                $NOTIFICATION->setAppId(1);
  9326. //                $NOTIFICATION->setCompanyId(0);
  9327. //                $NOTIFICATION->setCompanyId(0);
  9328. //                $NOTIFICATION->setBody('Test Description'.$t);
  9329. //                $NOTIFICATION->setTitle('Test Title'.$t);
  9330. //                $NOTIFICATION->setExpireTs(0);
  9331. //                $NOTIFICATION->setIsBuddybee(0);
  9332. //                $NOTIFICATION->setType(0);
  9333. //                $em->persist($NOTIFICATION);
  9334. //                $em->flush();
  9335. //            }
  9336. //
  9337. //            return new JsonResponse(
  9338. //                array(
  9339. //                    'success' => true,
  9340. //                    'data' => [],
  9341. //
  9342. //
  9343. //                )
  9344. //            );
  9345. //
  9346. //
  9347. //        }
  9348.         if ($request->request->get('entity_group'0)) {
  9349.             $companyId 0;
  9350.             $em $this->getDoctrine()->getManager('company_group');
  9351.         } else
  9352.             $companyId $this->getLoggedUserCompanyId($request);
  9353.         if ($companyId) {
  9354.             $company_data = [];
  9355. //            $company_data = Company::getCompanyData($em, $companyId);
  9356.         } else {
  9357.             $companyId 0;
  9358.             $company_data = [];
  9359.         }
  9360. //        $theEntity= new EntityNotification();
  9361. //        $entityName = 'EntityNotification';
  9362. //
  9363. //        $className='\\CompanyGroupBundle\\Entity\\'.$entityName;
  9364. //
  9365. //
  9366. //            $theEntity= new $className();
  9367.         $dataToAdd $request->request->has('dataToAdd') ? $request->request->get('dataToAdd') : [];
  9368.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  9369.         if ($dataToAdd == null$dataToAdd = [];
  9370.         $dataToRemove $request->request->has('dataToRemove') ? $request->request->get('dataToRemove') : [];
  9371.         if (is_string($dataToRemove)) $dataToAdd json_decode($dataToRemovetrue);
  9372.         if ($dataToRemove == null$dataToRemove = [];
  9373.         $relData = [];
  9374.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  9375.         $updatedDataList = [];
  9376.         foreach ($dataToAdd as $dataInd => $dat) {
  9377.             $entityName $dat['entityName'];
  9378.             $idField $dat['idField'];
  9379.             $findByField = isset($dat['findByField']) ? $dat['findByField'] : '';
  9380.             $findByValue = isset($dat['findByValue']) ? $dat['findByValue'] : '';
  9381.             $returnRefIndex $dat['returnRefIndex'];
  9382.             $findById $dat['findId'];
  9383.             $dataFields = isset($dat['dataFields']) ? $dat['dataFields'] : [];
  9384.             $noCreation = isset($dat['noCreation']) ? $dat['noCreation'] : 0;
  9385.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  9386.             $preAdditionalSql = isset($dat['preAdditionalSql']) ? $dat['preAdditionalSql'] : '';
  9387.             if ($preAdditionalSql != '') {
  9388. //            if ($entityName == 'PlanningItem') {
  9389. //
  9390. //                $stmt='select disctinct parent_id from planning_item;';
  9391. //                
  9392. //                $get_kids = $stmt;
  9393. //                $p_ids=[];
  9394. //                foreach($get_kids as $g)
  9395. //                {
  9396. //                    $p_ids[]=$g['parent_id'];
  9397. //                }
  9398. //
  9399. //
  9400. //
  9401.                 $stmt $em->getConnection()->executeStatement($preAdditionalSql);
  9402. //
  9403. //
  9404.             }
  9405.             if ($entityName == 'PlanningItem') {
  9406.                 $stmt $em->getConnection()->fetchAllAssociative("select  `id` , parent_id, sequence from planning_item where sequence is null
  9407.             ORDER BY parent_id ASC, id ASC
  9408.                         ");
  9409.                 $query_output $stmt;
  9410.                 foreach ($query_output as $dupe) {
  9411.                     System::updatePlanningItemSequence($em$dupe["id"]);
  9412.                 }
  9413.             }
  9414.             $className = ($request->request->get('entity_group'0) ? '\\CompanyGroupBundle\\Entity\\' '\\ApplicationBundle\\Entity\\') . $entityName;
  9415.             if (
  9416.                 ($findById == || $findById == '_NA_') && $findByField == '' && $noCreation == 0
  9417.             ) {
  9418.                 $theEntity = new $className();
  9419. //                $theEntity= new EntityNotification();
  9420.             } else {
  9421.                 if ($findByField != '') {
  9422.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle\\Entity\\' 'ApplicationBundle\\Entity\\') . $entityName)->findOneBy(
  9423.                         array
  9424.                         (
  9425.                             $findByField => $findByValue,
  9426.                         )
  9427.                     );
  9428.                 } else {
  9429.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle\\Entity\\' 'ApplicationBundle\\Entity\\') . $entityName)->findOneBy(
  9430.                         array
  9431.                         (
  9432.                             $idField => $findById,
  9433.                         )
  9434.                     );
  9435.                 }
  9436.             }
  9437.             if (!$theEntity && $noCreation == 0)
  9438.                 $theEntity = new $className();
  9439.             foreach ($dataFields as $dt) {
  9440.                 $setMethod 'set' ucfirst($dt['field']);
  9441.                 $getMethod 'get' ucfirst($dt['field']);
  9442.                 $type = isset($dt['type']) ? $dt['type'] : '_VALUE_';
  9443.                 $action = isset($dt['action']) ? $dt['action'] : '_REPLACE_';
  9444.                 if (method_exists($theEntity$setMethod)) {
  9445.                     $oldValue $theEntity->{$getMethod}();
  9446.                     $newValue $oldValue;
  9447.                     if ($type == '_VALUE_') {
  9448.                         $newValue $dt['value'];
  9449.                     }
  9450.                     if ($type == '_DECIMAL_') {
  9451.                         $newValue $dt['value'];
  9452.                     }
  9453.                     if ($type == '_DATE_') {
  9454.                         $newValue = new \DateTime($dt['value']);
  9455.                     }
  9456.                     if ($type == '_ARRAY_') {
  9457.                         $oldValue json_decode($oldValue);
  9458.                         if ($oldValue == null$oldValue = [];
  9459.                         if ($action == '_REPLACE_') {
  9460.                             $newValue json_encode($dt['value']);
  9461.                         }
  9462.                         if ($action == '_APPEND_') {
  9463.                             $newValue array_merge($oldValuearray_values(array_diff([$dt['value']], $oldValue)));
  9464.                         }
  9465.                         if ($action == '_MERGE_') {
  9466.                             $newValue array_merge($oldValuearray_values(array_diff($dt['value'], $oldValue)));
  9467.                         }
  9468.                         if ($action == '_EXCLUDE_') {
  9469.                             $newValue array_values(array_diff($oldValue, [$dt['value']]));
  9470.                         }
  9471.                         if ($action == '_EXCLUDE_ARRAY_') {
  9472.                             $newValue array_values(array_diff($oldValue$dt['value']));
  9473.                         }
  9474.                         $newValue json_encode($newValue);
  9475.                     }
  9476.                     $theEntity->{$setMethod}($newValue); // `foo!`
  9477. //                    $theEntity->setCompletionPercentage(78); // `foo!`
  9478.                 }
  9479.             }
  9480.             if ($additionalSql != '') {
  9481. //            if ($entityName == 'PlanningItem') {
  9482. //
  9483. //                $stmt='select disctinct parent_id from planning_item;';
  9484. //                
  9485. //                $get_kids = $stmt;
  9486. //                $p_ids=[];
  9487. //                foreach($get_kids as $g)
  9488. //                {
  9489. //                    $p_ids[]=$g['parent_id'];
  9490. //                }
  9491. //
  9492. //
  9493. //
  9494.                 $stmt $em->getConnection()->fetchAllAssociative($additionalSql);
  9495. //
  9496. //
  9497.             }
  9498.             if (($findById == || $findById == '_NA_') && $noCreation == 0) {
  9499.                 $em->persist($theEntity);
  9500.                 $em->flush();
  9501.                 $getMethod 'get' ucfirst($idField);
  9502.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  9503.             } else if ($theEntity) {
  9504.                 $em->flush();
  9505.                 $getMethod 'get' ucfirst($idField);
  9506.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  9507.             }
  9508.             if ($entityName == 'PlanningItem') {
  9509.                 $stmt $em->getConnection()->fetchAllAssociative('select distinct parent_id from planning_item;');
  9510.                 $get_kids $stmt;
  9511.                 $p_ids = [];
  9512.                 foreach ($get_kids as $g) {
  9513.                     $p_ids[] = $g['parent_id'];
  9514.                 }
  9515.                 // Only real parent ids: strip NULL / 0 (top-level marker) so the IN list never has a
  9516.                 // stray/leading comma. Run as TWO separate statements â€” executeStatement is single-statement.
  9517.                 $p_ids array_values(array_unique(array_filter(array_map('intval'$p_ids))));
  9518.                 if (!empty($p_ids)) {
  9519.                     $idList implode(','$p_ids);
  9520.                     $em->getConnection()->executeStatement('UPDATE planning_item d SET d.`has_child` = 0 WHERE d.id NOT IN (' $idList ')');
  9521.                     $em->getConnection()->executeStatement('UPDATE planning_item d SET d.`has_child` = 1 WHERE d.id IN (' $idList ')');
  9522.                 } else {
  9523.                     // no parents recorded â†’ nothing has children
  9524.                     $em->getConnection()->executeStatement('UPDATE planning_item d SET d.`has_child` = 0');
  9525.                 }
  9526.                 $updatedData System::updatePlanningItemSequence($em$theEntity->getId());
  9527.                 $theEntity $updatedData['primaryOne'];
  9528.                 $theEntityUpdated $theEntity;
  9529.                 if ($theEntityUpdated->getEntryType() == 4)///cashflow
  9530.                 {
  9531.                     MiscActions::AddCashFlowProjection($em0, [
  9532.                         'planningItemId' => $theEntityUpdated->getId(),
  9533.                         'fundRequisitionId' => 0,
  9534.                         'concernedPersonId' => 0,
  9535.                         'type' => 1//exp
  9536.                         'subType' => 1//1== khoroch hobe 2: ashbe
  9537.                         'cashFlowType' => 1//2== RCV /in  1: Payment/out
  9538.                         'creationType' => 1//auto
  9539.                         'amountType' => 1//fund
  9540.                         'cashFlowAmount' => 0,
  9541.                         'expAstAmount' => 0,
  9542.                         'accumulatedCashFlowAmount' => 0,
  9543.                         'accumulatedCashFlowBalance' => 0,
  9544.                         'accumulatedExpAstAmount' => 0,
  9545.                         'relevantExpAstHeadId' => 0,
  9546.                         'balancingHeadId' => 0,
  9547.                         'cashFlowHeadId' => 0,
  9548.                         'cashFlowHeadType' => 1,
  9549.                         'relevantProductIds' => [],
  9550.                         'reminderDateTs' => 0,
  9551.                         'cashFlowDateTs' => 0,
  9552.                         'expAstRealizationDateTs' => 0,
  9553.                     ]);
  9554.                 }
  9555.             } else if ($entityName == 'TaskLog') {
  9556.                 $session $request->getSession();
  9557.                 if ($theEntity) {
  9558.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  9559.                     $currTime = new \DateTime();
  9560.                     $options = array(
  9561.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  9562.                         'notification_server' => $this->container->getParameter('notification_server'),
  9563.                     );
  9564.                     $positionsArray = [
  9565.                         array(
  9566.                             'employeeId' => $empId,
  9567.                             'userId' => $session->get(UserConstants::USER_ID0),
  9568.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  9569.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  9570.                             'lat' => 23.8623834,
  9571.                             'lng' => 90.3979294,
  9572.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING,
  9573. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  9574.                         )
  9575.                     ];
  9576.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  9577.                     if ($positionsArray == null$positionsArray = [];
  9578.                     $dataByAttId = [];
  9579.                     $workPlaceType '_UNSET_';
  9580.                     foreach ($positionsArray as $findex => $d) {
  9581.                         $sysUserId 0;
  9582.                         $userId 0;
  9583.                         $empId 0;
  9584.                         $dtTs 0;
  9585.                         $timeZoneStr '+0000';
  9586.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  9587.                         if (isset($d['userId'])) $userId $d['userId'];
  9588.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  9589.                         if (isset($d['tsMilSec'])) {
  9590.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  9591.                         }
  9592.                         if ($dtTs == 0) {
  9593.                             $currTsTime = new \DateTime();
  9594.                             $dtTs $currTsTime->format('U');
  9595.                         } else {
  9596.                             $currTsTime = new \DateTime('@' $dtTs);
  9597.                         }
  9598.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  9599.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  9600.                         $EmployeeAttendance $this->getDoctrine()
  9601.                             ->getRepository(EmployeeAttendance::class)
  9602.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  9603.                         if (!$EmployeeAttendance) {
  9604.                             $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9605.                             $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9606.                             $EmployeeAttendance = new EmployeeAttendance;
  9607.                         } else {
  9608.                             if ($EmployeeAttendance->getCurrentLocation() == 'out') {
  9609.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9610.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9611.                             } else {
  9612.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  9613.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  9614.                             }
  9615.                         }
  9616.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  9617.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  9618.                             $workPlaceType '_STATIC_';
  9619.                         }
  9620.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  9621.                             $dataByAttId[$attendanceInfo->getId()] = array(
  9622.                                 'attendanceInfo' => $attendanceInfo,
  9623.                                 'empId' => $empId,
  9624.                                 'lat' => 0,
  9625.                                 'lng' => 0,
  9626.                                 'address' => 0,
  9627.                                 'sysUserId' => $sysUserId,
  9628.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  9629.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  9630.                                 'positionArray' => []
  9631.                             );
  9632.                         $posData = array(
  9633.                             'ts' => $dtTs,
  9634.                             'lat' => $d['lat'],
  9635.                             'lng' => $d['lng'],
  9636.                             'marker' => $d['markerId'],
  9637.                             'src' => 2,
  9638.                         );
  9639.                         $posDataArray = array(
  9640.                             $dtTs,
  9641.                             $d['lat'],
  9642.                             $d['lng'],
  9643.                             $d['markerId'],
  9644.                             2
  9645.                         );
  9646.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  9647.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  9648.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  9649.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  9650.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  9651.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  9652.                         if (isset($d['address']))
  9653.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  9654. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  9655.                     }
  9656.                     $response = array(
  9657.                         'success' => true,
  9658.                     );
  9659.                     foreach ($dataByAttId as $attInfoId => $d) {
  9660.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  9661.                             $d['empId'],
  9662.                             $d['sysUserId'],
  9663.                             $d['companyId'],
  9664.                             $d['appId'],
  9665.                             $request,
  9666.                             $d['attendanceInfo'],
  9667.                             $options,
  9668.                             $d['positionArray'],
  9669.                             $d['lat'],
  9670.                             $d['lng'],
  9671.                             $d['address'],
  9672.                             $d['markerId']
  9673.                         );
  9674.                     }
  9675.                     $session->set(UserConstants::USER_CURRENT_TASK_ID$theEntity->getId());
  9676.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$theEntity->getPlanningItemId());
  9677.                 } else {
  9678.                     $session->set(UserConstants::USER_CURRENT_TASK_ID0);
  9679.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID0);
  9680.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  9681.                     $currTime = new \DateTime();
  9682.                     $options = array(
  9683.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  9684.                         'notification_server' => $this->container->getParameter('notification_server'),
  9685.                     );
  9686.                     $positionsArray = [
  9687.                         array(
  9688.                             'employeeId' => $empId,
  9689.                             'userId' => $session->get(UserConstants::USER_ID0),
  9690.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  9691.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  9692.                             'lat' => 23.8623834,
  9693.                             'lng' => 90.3979294,
  9694.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT,
  9695. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  9696.                         )
  9697.                     ];
  9698.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  9699.                     if ($positionsArray == null$positionsArray = [];
  9700.                     $dataByAttId = [];
  9701.                     $workPlaceType '_UNSET_';
  9702.                     foreach ($positionsArray as $findex => $d) {
  9703.                         $sysUserId 0;
  9704.                         $userId 0;
  9705.                         $empId 0;
  9706.                         $dtTs 0;
  9707.                         $timeZoneStr '+0000';
  9708.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  9709.                         if (isset($d['userId'])) $userId $d['userId'];
  9710.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  9711.                         if (isset($d['tsMilSec'])) {
  9712.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  9713.                         }
  9714.                         if ($dtTs == 0) {
  9715.                             $currTsTime = new \DateTime();
  9716.                             $dtTs $currTsTime->format('U');
  9717.                         } else {
  9718.                             $currTsTime = new \DateTime('@' $dtTs);
  9719.                         }
  9720.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  9721.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  9722.                         $EmployeeAttendance $this->getDoctrine()
  9723.                             ->getRepository(EmployeeAttendance::class)
  9724.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  9725.                         if (!$EmployeeAttendance) {
  9726.                             continue;
  9727.                         } else {
  9728.                         }
  9729.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  9730.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT) {
  9731.                             $workPlaceType '_STATIC_';
  9732.                         }
  9733.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  9734.                             $dataByAttId[$attendanceInfo->getId()] = array(
  9735.                                 'attendanceInfo' => $attendanceInfo,
  9736.                                 'empId' => $empId,
  9737.                                 'lat' => 0,
  9738.                                 'lng' => 0,
  9739.                                 'address' => 0,
  9740.                                 'sysUserId' => $sysUserId,
  9741.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  9742.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  9743.                                 'positionArray' => []
  9744.                             );
  9745.                         $posData = array(
  9746.                             'ts' => $dtTs,
  9747.                             'lat' => $d['lat'],
  9748.                             'lng' => $d['lng'],
  9749.                             'marker' => $d['markerId'],
  9750.                             'src' => 2,
  9751.                         );
  9752.                         $posDataArray = array(
  9753.                             $dtTs,
  9754.                             $d['lat'],
  9755.                             $d['lng'],
  9756.                             $d['markerId'],
  9757.                             2
  9758.                         );
  9759.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  9760.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  9761.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  9762.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  9763.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  9764.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  9765.                         if (isset($d['address']))
  9766.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  9767. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  9768.                     }
  9769.                     $response = array(
  9770.                         'success' => true,
  9771.                     );
  9772.                     foreach ($dataByAttId as $attInfoId => $d) {
  9773.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  9774.                             $d['empId'],
  9775.                             $d['sysUserId'],
  9776.                             $d['companyId'],
  9777.                             $d['appId'],
  9778.                             $request,
  9779.                             $d['attendanceInfo'],
  9780.                             $options,
  9781.                             $d['positionArray'],
  9782.                             $d['lat'],
  9783.                             $d['lng'],
  9784.                             $d['address'],
  9785.                             $d['markerId']
  9786.                         );
  9787.                     }
  9788.                 }
  9789.                 $theEntityUpdated $theEntity;
  9790.             } else
  9791.                 $theEntityUpdated $theEntity;
  9792. //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  9793.             $getters = [];
  9794.             if ($theEntityUpdated)
  9795.                 $getters array_filter(get_class_methods($theEntityUpdated), function ($method) {
  9796.                     return 'get' === substr($method03);
  9797.                 });
  9798.             $updatedData = [];
  9799.             foreach ($getters as $getter) {
  9800.                 $indForThis str_replace('get'''$getter);
  9801.                 $indForThis lcfirst($indForThis);
  9802.                 $updatedData[$indForThis] = $theEntityUpdated->{$getter}();
  9803.             }
  9804.             $updatedDataList[$dataInd] = $updatedData;
  9805.         }
  9806.         foreach ($dataToRemove as $dataInd => $dat) {
  9807.             $entityName $dat['entityName'];
  9808.             $idField $dat['idField'];
  9809.             $findById $dat['findId'];
  9810.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  9811.             $theEntityList $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle\\Entity\\' 'ApplicationBundle\\Entity\\') . $entityName)->findBy(
  9812.                 array
  9813.                 (
  9814.                     $idField => $findById,
  9815.                 )
  9816.             );
  9817.             foreach ($theEntityList as $dt) {
  9818.                 $em->remove($dt);
  9819.                 $em->flush();
  9820.             }
  9821.             if ($additionalSql != '') {
  9822. //            if ($entityName == 'PlanningItem') {
  9823. //
  9824. //                $stmt='select disctinct parent_id from planning_item;';
  9825. //                
  9826. //                $get_kids = $stmt;
  9827. //                $p_ids=[];
  9828. //                foreach($get_kids as $g)
  9829. //                {
  9830. //                    $p_ids[]=$g['parent_id'];
  9831. //                }
  9832. //
  9833. //
  9834. //
  9835.                 $stmt $em->getConnection()->fetchAllAssociative($additionalSql);
  9836. //
  9837. //
  9838.             }
  9839.             $updatedDataList[$dataInd] = [];
  9840.         }
  9841. //        if ($table == '') {
  9842. //            return new JsonResponse(
  9843. //                array(
  9844. //                    'success' => false,
  9845. ////                    'page_title' => 'Product Details',
  9846. ////                    'company_data' => $company_data,
  9847. //                    'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9848. //
  9849. //                )
  9850. //            );
  9851. //        }
  9852. //        if($request->query->has('returnJson'))
  9853.         return new JsonResponse(
  9854.             array(
  9855.                 'success' => true,
  9856.                 'data' => $relData,
  9857.                 'updatedDataList' => $updatedDataList,
  9858.             )
  9859.         );
  9860.     }
  9861.     public function GetAvailableQtyAction(Request $request$id 0)
  9862.     {
  9863.         $em $this->getDoctrine()->getManager();
  9864.         $productId $request->request->has('productId') ? $request->request->get('productId') : 0;
  9865.         $colorId $request->request->has('colorId') ? $request->request->get('colorId') : 0;
  9866.         $dataId $request->request->has('dataId') ? $request->request->get('dataId') : 0;
  9867.         $allowedWarehouseIds $request->request->has('warehouseId') ? [$request->request->get('warehouseId')] : [];
  9868.         $allowedWarehouseActionIds $request->request->has('warehouseActionId') ? [$request->request->get('warehouseActionId')] : [];
  9869.         $qty Inventory::getSellableProductQty($em$productId$allowedWarehouseIds$allowedWarehouseActionIds$colorId);
  9870.         return new JsonResponse(array("success" => true,
  9871.             "qty" => $qty,
  9872.             "dataId" => $dataId,
  9873.         ));
  9874.     }
  9875.     public
  9876.     function ProductListSelectAjaxAction(Request $request$queryStr '')
  9877.     {
  9878.         $em $this->getDoctrine()->getManager();
  9879.         $companyId $this->getLoggedUserCompanyId($request);
  9880.         $company_data Company::getCompanyData($em$companyId);
  9881.         $data = [];
  9882.         $data_by_id = [];
  9883.         $html '';
  9884.         $productByCodeData = [];
  9885.         if ($queryStr == '_EMPTY_')
  9886.             $queryStr '';
  9887.         if ($request->request->has('query') && $queryStr == '')
  9888.             $queryStr $request->request->get('queryStr');
  9889.         if ($queryStr == '_EMPTY_')
  9890.             $queryStr '';
  9891. //        $queryStr=urldecode($queryStr);
  9892.         $queryStr str_replace('_FSLASH_''/'$queryStr);
  9893.         $filterQryForCriteria "select * from inv_products where 1=1 ";
  9894.         $filterParams = array();
  9895.         if ($request->request->has('sellableOnly') && $request->request->get('sellableOnly') != 0)
  9896.             $filterQryForCriteria .= " and sellable=1";
  9897.         if ($request->request->has('categorizationValues') && $request->request->get('categorizationValues') != '') {
  9898.             foreach ($request->request->get('categorizationValues') as $level => $value) {
  9899.                 if ($value != '' && $value != 0) {
  9900.                     $searchParam GeneralConstant::$fdmSubCatMarkers[$level] . $value '_';
  9901.                     $paramName 'categorizationValue' $level;
  9902.                     $filterQryForCriteria .= " and product_fdm like :" $paramName " ";
  9903.                     $filterParams[$paramName] = '%' $searchParam '%';
  9904.                 }
  9905.             }
  9906.         }
  9907.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9908.             $filterQryForCriteria .= " and sub_category_id = :subCategoryId";
  9909.         else if ($request->request->has('categoryId') && $request->request->get('categoryId') != '')
  9910.             $filterQryForCriteria .= " and category_id = :categoryId";
  9911.         else if ($request->request->has('igId') && $request->request->get('igId') != '')
  9912.             $filterQryForCriteria .= " and ig_id = :igId";
  9913.         if ($request->request->has('brandId') && $request->request->get('brandId') != '')
  9914.             $filterQryForCriteria .= " and brand_company = :brandId";
  9915.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9916.             $filterParams['subCategoryId'] = (int) $request->request->get('subCategoryId');
  9917.         else if ($request->request->has('categoryId') && $request->request->get('categoryId') != '')
  9918.             $filterParams['categoryId'] = (int) $request->request->get('categoryId');
  9919.         else if ($request->request->has('igId') && $request->request->get('igId') != '')
  9920.             $filterParams['igId'] = (int) $request->request->get('igId');
  9921.         if ($request->request->has('brandId') && $request->request->get('brandId') != '')
  9922.             $filterParams['brandId'] = (int) $request->request->get('brandId');
  9923.         if ($request->request->has('restrictedBrandIds') && $request->request->get('restrictedBrandIds') != []) {
  9924.             $restrictedBrandIds $this->normalizeSqlIntList($request->request->get('restrictedBrandIds'));
  9925.             if (!empty($restrictedBrandIds)) {
  9926.                 $filterQryForCriteria .= " and brand_company in (" $this->buildNamedInClause($restrictedBrandIds'restrictedBrandId'$filterParams) . ")";
  9927.             }
  9928.         }
  9929.         if ($request->request->has('productIds')) {
  9930.             $productIds $this->normalizeSqlIntList($request->request->get('productIds'));
  9931.             if (!empty($productIds)) {
  9932.                 $filterQryForCriteria .= " and id in (" $this->buildNamedInClause($productIds'productId'$filterParams) . ") ";
  9933.             }
  9934.         } else if ($request->request->has('productCode')) {
  9935.             $filterQryForCriteria .= " and product_code like :productCode ";
  9936.             $filterParams['productCode'] = '%' $request->request->get('productCode') . '%';
  9937.         } else if ($queryStr != '') {
  9938.             $filterQryForCriteria .= " and  (product_code like :queryProductCode or `name` like :queryName or model_no like :queryModelNo) ";
  9939.             $filterParams['queryProductCode'] = '%' $queryStr '%';
  9940.             $filterParams['queryName'] = '%' $queryStr '%';
  9941.             $filterParams['queryModelNo'] = '%' $queryStr '%';
  9942.         }
  9943.         if ($filterQryForCriteria != '')
  9944.             $filterQryForCriteria .= "  limit 25";
  9945.         $get_kids_sql $filterQryForCriteria;
  9946. //        if ($request->request->has('productIds'))
  9947. //
  9948. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9949. //        else if ($request->request->has('productCode'))
  9950. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9951. //        else if ($filterQryForCriteria!='')
  9952. //            $get_kids_sql = $filterQryForCriteria;
  9953. //
  9954. //        else
  9955. //               $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";
  9956.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  9957.         $get_kids $stmt;
  9958.         $productId 0;
  9959.         if (!empty($get_kids)) {
  9960.             foreach ($get_kids as $product) {
  9961.                 $pa = array();
  9962.                 $pa['id'] = $product['id'];
  9963.                 $pa['name'] = $product['name'];
  9964.                 $pa['id_name'] = $product['id'] . '. ' $product['name'];
  9965.                 $pa['id_mn'] = $product['id'] . '. ' $product['model_no'];;
  9966.                 $pa['id_name_mn'] = $product['id'] . '. ' $product['name'] . ' ( ' $product['model_no'] . ' )';
  9967.                 $pa['globalId'] = $product['global_id'];
  9968.                 $pa['classSuffix'] = $product['class_suffix'];
  9969.                 $pa['productFdm'] = $product['product_fdm'];
  9970.                 $pa['modelNo'] = $product['model_no'];
  9971.                 $pa['partId'] = $product['part_id'];
  9972.                 $pa['hsCode'] = $product['hs_code'];
  9973.                 $pa['productCode'] = $product['product_code'];
  9974.                 $pa['text'] = $product['name'];
  9975.                 $pa['value'] = $product['id'];
  9976.                 $pa['tac'] = $product['tac'];
  9977.                 $pa['igId'] = $product['ig_id'];
  9978.                 $pa['categoryId'] = $product['category_id'];
  9979.                 $pa['subCategoryId'] = $product['sub_category_id'];
  9980.                 $pa['brandCompany'] = $product['brand_company'];
  9981.                 $pa['sales_price'] = $product['curr_sales_price'];
  9982.                 $pa['purchase_price'] = $product['curr_purchase_price'];
  9983.                 $pa['unit_type'] = $product['unit_type_id'];
  9984.                 $pa['single_weight'] = $product['single_weight'];
  9985.                 $pa['single_weight_variance_type'] = $product['single_weight_variance_type'];
  9986.                 $pa['single_weight_variance_value'] = $product['single_weight_variance_value'];
  9987.                 $pa['weight'] = $product['weight'];
  9988.                 $pa['weight_variance_type'] = $product['weight_variance_type'];
  9989.                 $pa['weight_variance_value'] = $product['weight_variance_value'];
  9990.                 $pa['carton_capacity_count'] = $product['carton_capacity_count'];
  9991.                 $pa['type'] = $product['type'];
  9992.                 $pa['qty'] = $product['qty'];
  9993. //                $pa['alias'] = '';
  9994.                 $pa['alias'] = $product['alias'];
  9995.                 $pa['note'] = $product['note'];
  9996.                 $pa['defaultTaxConfigId'] = $product['default_tax_config_id'] == null $product['default_tax_config_id'];
  9997.                 $pa['defaultPurchaseTaxConfigId'] = $product['default_purchase_tax_config_id'] == null $product['default_purchase_tax_config_id'];
  9998.                 $tax_config_ids json_decode($product['tax_config_ids'], true);
  9999.                 if ($tax_config_ids == null)
  10000.                     $tax_config_ids = [];
  10001.                 $pa['taxConfigIds'] = $tax_config_ids;
  10002.                 $purchase_tax_config_ids json_decode($product['purchase_tax_config_ids'], true);
  10003.                 if ($purchase_tax_config_ids == null)
  10004.                     $purchase_tax_config_ids = [];
  10005.                 $pa['purchaseTaxConfigIds'] = $tax_config_ids;
  10006.                 $inco_terms json_decode($product['inco_terms'], true);
  10007.                 if ($inco_terms == null)
  10008.                     $inco_terms = [];
  10009.                 $pa['incoTerms'] = $inco_terms;
  10010.                 $pa['defaultIncoTerm'] = $product['default_inco_term'] == null $product['default_inco_term'];
  10011.                 $pa['has_serial'] = $product['has_serial'];
  10012.                 $pa['expiry_days'] = $product['expiry_days'];
  10013.                 $pa['image'] = $product['default_image'];
  10014.                 $pa['sales_warranty'] = $product['sales_warranty_months'];;
  10015.                 $pa['defaultColorId'] = $product['default_color_id'];;
  10016.                 $allowedColorIds json_decode($product['colors'], true);
  10017.                 if ($allowedColorIds == null$allowedColorIds = [];
  10018.                 if (!in_array($product['default_color_id'], $allowedColorIds))
  10019.                     $allowedColorIds[] = $product['default_color_id'];
  10020.                 $pa['allowedColorIds'] = $allowedColorIds;;
  10021.                 $data[] = $pa;
  10022.                 $data_by_id[$product['id']] = $pa;
  10023.                 $productId $product['id'];
  10024.             }
  10025.         }
  10026. //        if($request->query->has('returnJson'))
  10027.         {
  10028.             return new JsonResponse(
  10029.                 array(
  10030.                     'success' => true,
  10031. //                    'page_title' => 'Product Details',
  10032. //                    'company_data' => $company_data,
  10033.                     'data' => $data,
  10034.                     'dataById' => $data_by_id,
  10035.                     'productId' => $productId,
  10036.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10037. //                    'exId'=>$id,
  10038. //                'productByCodeData' => $productByCodeData,
  10039. //                'productData' => $productData,
  10040. //                'currInvList' => $currInvList,
  10041. //                'productList' => Inventory::ProductList($em, $companyId),
  10042. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10043. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10044. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10045. //                'unitList' => Inventory::UnitTypeList($em),
  10046. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10047. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10048. //                'warehouseList' => Inventory::WarehouseList($em),
  10049.                 )
  10050.             );
  10051.         }
  10052.     }
  10053.     public function SearchByPopulateQueryAction(Request $request$queryStr '')
  10054.     {
  10055.         $em $this->getDoctrine()->getManager();
  10056.         $companyId $this->getLoggedUserCompanyId($request);
  10057.         $company_data Company::getCompanyData($em$companyId);
  10058.         $data = [];
  10059.         //1st search in products
  10060.         foreach ($request->request->get('queryData', []) as $item) {
  10061.             $dt = array(
  10062.                 'dataId' => $item['dataId'] ?? 0,
  10063.                 'id' => 0,
  10064.                 'fdm' => '',
  10065.             );
  10066.             $qryStrForSearch $item['value'] ?? '';
  10067.             $qryArray explode(','$qryStrForSearch);
  10068.             $checkFields = ['name'];
  10069.             list($qryForSearch$queryParams) = $this->buildTokenizedLikeSearchFragment($checkFields$qryArray'or''populateQueryGroup');
  10070.             //selct item group
  10071.             $igId 0;
  10072.             $catId 0;
  10073.             $parId 0;
  10074.             $brandId 0;
  10075.             $fdmSearchQry = [];
  10076.             $result $em->getConnection()->fetchAllAssociative("select * from inv_item_group where 1=0   " $qryForSearch " limit 1"$queryParams);
  10077.             if (!empty($result)) {
  10078.                 $dt['fdm'] .= ('I' $result[0]['id'] . '_');
  10079.                 $fdmSearchQry[] = ('I' $result[0]['id'] . '_');
  10080.                 $igId $result[0]['id'];
  10081.             }
  10082.             list($qryForSearch$queryParams) = $this->buildTokenizedLikeSearchFragment($checkFields$qryArray'and''populateScopedQueryGroup');
  10083.             //then category
  10084.             $result $em->getConnection()->fetchAllAssociative(
  10085.                 "select * from inv_product_categories where ig_id = :igId " $qryForSearch " limit 1",
  10086.                 array_merge(array('igId' => (int) $igId), $queryParams)
  10087.             );
  10088.             if (!empty($result)) {
  10089.                 $dt['fdm'] .= ('C' $result[0]['id'] . '_');
  10090.                 $fdmSearchQry[] = ('C' $result[0]['id'] . '_');
  10091.                 $catId $result[0]['id'];
  10092.             }
  10093.             //then sub category
  10094.             foreach (GeneralConstant::$fdmSubCatMarkers as $ind => $marker) {
  10095.                 $result $em->getConnection()->fetchAllAssociative(
  10096.                     "select * from inv_product_sub_categories where ig_id = :igId and category_id = :catId and parent_id = :parId " $qryForSearch " limit 1",
  10097.                     array_merge(array(
  10098.                         'igId' => (int) $igId,
  10099.                         'catId' => (int) $catId,
  10100.                         'parId' => (int) $parId,
  10101.                     ), $queryParams)
  10102.                 );
  10103.                 if (!empty($result)) {
  10104.                     $dt['fdm'] .= ($marker $result[0]['id'] . '_');
  10105.                     $fdmSearchQry[] = ($marker $result[0]['id'] . '_');
  10106.                     $parId $result[0]['id'];
  10107.                 }
  10108.             }
  10109.             $result $em->getConnection()->fetchAllAssociative("select * from brand_company where 1=1   " $qryForSearch " limit 1"$queryParams);
  10110.             if (!empty($result)) {
  10111.                 $dt['fdm'] .= ('B' $result[0]['id'] . '_');
  10112.                 $fdmSearchQry[] = ('B' $result[0]['id'] . '_');
  10113.                 $brandId $result[0]['id'];
  10114.             }
  10115.             list($qryForSearch$fdmSearchParams) = $this->buildConjunctiveLikeFragment('product_fdm'$fdmSearchQry'populateFdm');
  10116.             $result $em->getConnection()->fetchAllAssociative("select * from inv_products where 1=1   " $qryForSearch " limit 1"$fdmSearchParams);
  10117.             if (!empty($result)) {
  10118.                 $dt['id'] .= $result[0]['id'];
  10119.             }
  10120.             $data[] = $dt;
  10121.         }
  10122.         return new JsonResponse(
  10123.             array(
  10124.                 'success' => !empty($data) ? true false,
  10125.                 'data' => $data
  10126.             )
  10127.         );
  10128.     }
  10129.     public function addProductByGeneralDataAction(Request $request$queryStr '')
  10130.     {
  10131.         $em $this->getDoctrine()->getManager();
  10132.         $companyId $this->getLoggedUserCompanyId($request);
  10133.         $company_data Company::getCompanyData($em$companyId);
  10134.         $data = [];
  10135.         //1st search in products
  10136.         foreach ($request->request->get('dataList', []) as $item) {
  10137. //            $item=Inventory::GetImmutableKeysForProductSyncFromCentralToLocal();
  10138.             //add each part and if not exists, add it
  10139.             $currProductInfo = array(
  10140.                 'dataId' => $item['dataId'] ?? 0,
  10141.                 'id' => 0,
  10142.                 'igId' => 0,
  10143.                 'categoryId' => 0,
  10144.                 'subCategoryIds' => [
  10145.                     => 0,
  10146.                 ],
  10147.                 'fdm' => '',
  10148.             );
  10149.             //iten group
  10150.             if (isset($item['ItemGroup'])) {
  10151.                 $result $em->getConnection()->fetchAllAssociative(
  10152.                     "select * from inv_item_group where id = :itemGroupId or name like :itemGroupName limit 1",
  10153.                     array(
  10154.                         'itemGroupId' => (int) ($item['ItemGroup']['Id'] ?? 0),
  10155.                         'itemGroupName' => (string) ($item['ItemGroup']['Name'] ?? 0),
  10156.                     )
  10157.                 );
  10158.                 if (!empty($result)) {
  10159.                     $currProductInfo['igId'] = $result[0]['id'];
  10160.                 } else {
  10161.                     Inventory::CreateItemGroup($em1);
  10162.                 }
  10163.             }
  10164.             $dt = array(
  10165.                 'dataId' => $item['dataId'] ?? 0,
  10166.                 'id' => 0,
  10167.                 'fdm' => '',
  10168.             );
  10169.             $qryStrForSearch $item['value'] ?? '';
  10170.             $qryArray explode(','$qryStrForSearch);
  10171.             $checkFields = ['name'];
  10172.             list($qryForSearch$queryParams) = $this->buildFlatLikeSearchFragment($checkFields$qryArray'and''generalDataQuery');
  10173.             //selct item group
  10174.             $igId 0;
  10175.             $catId 0;
  10176.             $parId 0;
  10177.             $brandId 0;
  10178.             $fdmSearchQry = [];
  10179.             $result $em->getConnection()->fetchAllAssociative("select * from inv_item_group where 1=1 " $qryForSearch " limit 1"$queryParams);
  10180.             if (!empty($result)) {
  10181.                 $dt['fdm'] .= ('I' $result[0]['id'] . '_');
  10182.                 $fdmSearchQry[] = ('I' $result[0]['id'] . '_');
  10183.                 $igId $result[0]['id'];
  10184.             }
  10185.             //then category
  10186.             $result $em->getConnection()->fetchAllAssociative(
  10187.                 "select * from inv_product_categories where ig_id = :igId " $qryForSearch " limit 1",
  10188.                 array_merge(array('igId' => (int) $igId), $queryParams)
  10189.             );
  10190.             if (!empty($result)) {
  10191.                 $dt['fdm'] .= ('C' $result[0]['id'] . '_');
  10192.                 $fdmSearchQry[] = ('C' $result[0]['id'] . '_');
  10193.                 $catId $result[0]['id'];
  10194.             }
  10195.             //then sub category
  10196.             foreach (GeneralConstant::$fdmSubCatMarkers as $ind => $marker) {
  10197.                 $result $em->getConnection()->fetchAllAssociative(
  10198.                     "select * from inv_product_sub_categories where ig_id = :igId and category_id = :catId and parent_id = :parId " $qryForSearch " limit 1",
  10199.                     array_merge(array(
  10200.                         'igId' => (int) $igId,
  10201.                         'catId' => (int) $catId,
  10202.                         'parId' => (int) $parId,
  10203.                     ), $queryParams)
  10204.                 );
  10205.                 if (!empty($result)) {
  10206.                     $dt['fdm'] .= ($marker $result[0]['id'] . '_');
  10207.                     $fdmSearchQry[] = ($marker $result[0]['id'] . '_');
  10208.                     $parId $result[0]['id'];
  10209.                 }
  10210.             }
  10211.             $result $em->getConnection()->fetchAllAssociative("select * from brand_company where 1=1 " $qryForSearch " limit 1"$queryParams);
  10212.             if (!empty($result)) {
  10213.                 $dt['fdm'] .= ('B' $result[0]['id'] . '_');
  10214.                 $fdmSearchQry[] = ('B' $result[0]['id'] . '_');
  10215.                 $brandId $result[0]['id'];
  10216.             }
  10217.             list($qryForSearch$fdmSearchParams) = $this->buildConjunctiveLikeFragment('product_fdm'$fdmSearchQry'generalDataFdm');
  10218.             $result $em->getConnection()->fetchAllAssociative("select * from inv_products where 1=1 " $qryForSearch " limit 1"$fdmSearchParams);
  10219.             if (!empty($result)) {
  10220.                 $dt['id'] .= $result[0]['id'];
  10221.             }
  10222.             $data[] = $dt;
  10223.         }
  10224.         return new JsonResponse(
  10225.             array(
  10226.                 'success' => empty($data) ? true false,
  10227.                 'data' => $data
  10228.             )
  10229.         );
  10230.     }
  10231.     public function labelFormatSelectAjaxAction(Request $request$queryStr '')
  10232.     {
  10233.         $em $this->getDoctrine()->getManager();
  10234.         $companyId $this->getLoggedUserCompanyId($request);
  10235.         $company_data Company::getCompanyData($em$companyId);
  10236.         $data = [];
  10237.         $data_by_id = [];
  10238.         $html '';
  10239.         $productByCodeData = [];
  10240.         if ($queryStr == '_EMPTY_')
  10241.             $queryStr '';
  10242.         if ($request->request->has('query') && $queryStr == '')
  10243.             $queryStr $request->request->get('queryStr');
  10244.         if ($queryStr == '_EMPTY_')
  10245.             $queryStr '';
  10246.         $filterQryForCriteria "select * from label_format where company_id = :companyId ";
  10247.         $filterParams = array(
  10248.             'companyId' => (int) $companyId,
  10249.         );
  10250.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  10251.             $filterQryForCriteria .= " and label_type = :dataType";
  10252.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  10253.             $filterQryForCriteria .= " and format_id = :formatId";
  10254.         else if ($queryStr != '') {
  10255.             $filterQryForCriteria .= " and (`name` like :labelNameQuery or `format_code` like :labelCodeQuery) ";
  10256.             $filterParams['labelNameQuery'] = '%' $queryStr '%';
  10257.             $filterParams['labelCodeQuery'] = '%' $queryStr '%';
  10258.         }
  10259.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  10260.             $filterParams['dataType'] = (int) $request->request->get('dataType');
  10261.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  10262.             $filterParams['formatId'] = (int) $request->request->get('formatId');
  10263.         if ($filterQryForCriteria != '')
  10264.             $filterQryForCriteria .= "  limit 25";
  10265.         $get_kids_sql $filterQryForCriteria;
  10266. //        if ($request->request->has('productIds'))
  10267. //
  10268. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  10269. //        else if ($request->request->has('productCode'))
  10270. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  10271. //        else if ($filterQryForCriteria!='')
  10272. //            $get_kids_sql = $filterQryForCriteria;
  10273. //
  10274. //        else
  10275. //               $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";
  10276.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  10277.         $get_kids $stmt;
  10278.         $productId 0;
  10279.         if (!empty($get_kids)) {
  10280.             foreach ($get_kids as $product) {
  10281.                 $pa = array();
  10282.                 $pa['id'] = $product['format_id'];
  10283.                 $pa['name'] = $product['name'];
  10284.                 $pa['format_code'] = $product['format_code'] . '. ' $product['name'];
  10285.                 $pa['id_code_name'] = $product['format_id'] . '. ' $product['format_code'] . ' - ' $product['name'] . ' ';
  10286.                 $pa['text'] = $product['name'];
  10287.                 $pa['value'] = $product['format_id'];
  10288.                 $data[] = $pa;
  10289.                 $data_by_id[$product['format_id']] = $pa;
  10290.                 $productId $product['format_id'];
  10291.             }
  10292.         }
  10293. //        if($request->query->has('returnJson'))
  10294.         {
  10295.             return new JsonResponse(
  10296.                 array(
  10297.                     'success' => true,
  10298. //                    'page_title' => 'Product Details',
  10299. //                    'company_data' => $company_data,
  10300.                     'data' => $data,
  10301.                     'dataById' => $data_by_id,
  10302.                     'productId' => $productId,
  10303.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10304. //                    'exId'=>$id,
  10305. //                'productByCodeData' => $productByCodeData,
  10306. //                'productData' => $productData,
  10307. //                'currInvList' => $currInvList,
  10308. //                'productList' => Inventory::ProductList($em, $companyId),
  10309. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10310. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10311. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10312. //                'unitList' => Inventory::UnitTypeList($em),
  10313. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10314. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10315. //                'warehouseList' => Inventory::WarehouseList($em),
  10316.                 )
  10317.             );
  10318.         }
  10319.     }
  10320.     public function CategoryListSelectAjaxAction(Request $request$queryStr '')
  10321.     {
  10322.         $em $this->getDoctrine()->getManager();
  10323.         $companyId $this->getLoggedUserCompanyId($request);
  10324.         $company_data Company::getCompanyData($em$companyId);
  10325.         $data = [];
  10326.         $data_by_id = [];
  10327.         $html '';
  10328.         $productByCodeData = [];
  10329.         if ($queryStr == '_EMPTY_')
  10330.             $queryStr '';
  10331.         if ($request->request->has('query') && $queryStr == '')
  10332.             $queryStr $request->request->get('queryStr');
  10333.         if ($queryStr == '_EMPTY_')
  10334.             $queryStr '';
  10335.         $filterQryForCriteria "select * from inv_product_categories where company_id = :companyId ";
  10336.         $filterParams = array(
  10337.             'companyId' => (int) $companyId,
  10338.             'categoryNameQuery' => '%' $queryStr '%',
  10339.         );
  10340.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10341.             $filterQryForCriteria .= " and ig_id = :igId";
  10342.         $filterQryForCriteria .= " and (`name` like :categoryNameQuery) ";
  10343.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10344.             $filterParams['igId'] = (int) $request->request->get('igId');
  10345.         if ($filterQryForCriteria != '')
  10346.             $filterQryForCriteria .= "  limit 25";
  10347.         $get_kids_sql $filterQryForCriteria;
  10348. //        if ($request->request->has('productIds'))
  10349. //
  10350. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  10351. //        else if ($request->request->has('productCode'))
  10352. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  10353. //        else if ($filterQryForCriteria!='')
  10354. //            $get_kids_sql = $filterQryForCriteria;
  10355. //
  10356. //        else
  10357. //               $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";
  10358.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  10359.         $get_kids $stmt;
  10360.         $productId 0;
  10361.         if (!empty($get_kids)) {
  10362.             foreach ($get_kids as $product) {
  10363.                 $pa = array();
  10364.                 $pa['id'] = $product['id'];
  10365.                 $pa['name'] = $product['name'];
  10366.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  10367.                 $pa['globalId'] = $product['global_id'];
  10368.                 $pa['text'] = $product['name'];
  10369.                 $pa['value'] = $product['id'];
  10370.                 $pa['igId'] = $product['ig_id'];
  10371. //                $pa['categoryId'] = $product['category_id'];
  10372. //                $pa['subCategoryId'] = $product['sub_category_id'];
  10373.                 $data[] = $pa;
  10374.                 $data_by_id[$product['id']] = $pa;
  10375.                 $productId $product['id'];
  10376.             }
  10377.         }
  10378. //        if($request->query->has('returnJson'))
  10379.         {
  10380.             return new JsonResponse(
  10381.                 array(
  10382.                     'success' => true,
  10383. //                    'page_title' => 'Product Details',
  10384. //                    'company_data' => $company_data,
  10385.                     'data' => $data,
  10386.                     'dataById' => $data_by_id,
  10387.                     'productId' => $productId,
  10388.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10389. //                    'exId'=>$id,
  10390. //                'productByCodeData' => $productByCodeData,
  10391. //                'productData' => $productData,
  10392. //                'currInvList' => $currInvList,
  10393. //                'productList' => Inventory::ProductList($em, $companyId),
  10394. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10395. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10396. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10397. //                'unitList' => Inventory::UnitTypeList($em),
  10398. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10399. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10400. //                'warehouseList' => Inventory::WarehouseList($em),
  10401.                 )
  10402.             );
  10403.         }
  10404.     }
  10405.     public function SubCategoryListSelectAjaxAction(Request $request$queryStr '')
  10406.     {
  10407.         $em $this->getDoctrine()->getManager();
  10408.         $companyId $this->getLoggedUserCompanyId($request);
  10409.         $company_data Company::getCompanyData($em$companyId);
  10410.         $data = [];
  10411.         $data_by_id = [];
  10412.         $html '';
  10413.         $productByCodeData = [];
  10414.         if ($queryStr == '_EMPTY_')
  10415.             $queryStr '';
  10416.         if ($request->request->has('query') && $queryStr == '')
  10417.             $queryStr $request->request->get('queryStr');
  10418.         if ($queryStr == '_EMPTY_')
  10419.             $queryStr '';
  10420.         $filterQryForCriteria "select * from inv_product_sub_categories where company_id = :companyId ";
  10421.         $filterParams = array(
  10422.             'companyId' => (int) $companyId,
  10423.             'subCategoryNameQuery' => '%' $queryStr '%',
  10424.         );
  10425.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  10426.             $filterQryForCriteria .= " and sub_category_id = :subCategoryId";
  10427.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  10428.             $filterQryForCriteria .= " and category_id = :categoryId";
  10429.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10430.             $filterQryForCriteria .= " and ig_id = :igId";
  10431.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  10432.             if ($request->request->get('parentId') != 0)
  10433.                 $filterQryForCriteria .= " and parent_id = :parentId";
  10434.             else
  10435.                 $filterQryForCriteria .= " and ( parent_id =0 or parent_id is null ) ";
  10436.         if ($request->request->has('level') && $request->request->get('level') != '')
  10437.             if ($request->request->get('level') != 0)
  10438.                 $filterQryForCriteria .= " and level = :level";
  10439.             else
  10440.                 $filterQryForCriteria .= " and ( level =0 or level is null) ";
  10441.         $filterQryForCriteria .= " and (`name` like :subCategoryNameQuery) ";
  10442.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  10443.             $filterParams['subCategoryId'] = (int) $request->request->get('subCategoryId');
  10444.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  10445.             $filterParams['categoryId'] = (int) $request->request->get('categoryId');
  10446.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10447.             $filterParams['igId'] = (int) $request->request->get('igId');
  10448.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  10449.             if ($request->request->get('parentId') != 0)
  10450.                 $filterParams['parentId'] = (int) $request->request->get('parentId');
  10451.         if ($request->request->has('level') && $request->request->get('level') != '')
  10452.             if ($request->request->get('level') != 0)
  10453.                 $filterParams['level'] = (int) $request->request->get('level');
  10454.         if ($filterQryForCriteria != '')
  10455.             $filterQryForCriteria .= "  limit 25";
  10456.         $get_kids_sql $filterQryForCriteria;
  10457. //        if ($request->request->has('productIds'))
  10458. //
  10459. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  10460. //        else if ($request->request->has('productCode'))
  10461. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  10462. //        else if ($filterQryForCriteria!='')
  10463. //            $get_kids_sql = $filterQryForCriteria;
  10464. //
  10465. //        else
  10466. //               $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";
  10467.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  10468.         $get_kids $stmt;
  10469.         $productId 0;
  10470.         if (!empty($get_kids)) {
  10471.             foreach ($get_kids as $product) {
  10472.                 $pa = array();
  10473.                 $pa['id'] = $product['id'];
  10474.                 $pa['name'] = $product['name'];
  10475.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  10476.                 $pa['globalId'] = $product['global_id'];
  10477.                 $pa['parentId'] = $product['parent_id'];
  10478.                 $pa['text'] = $product['name'];
  10479.                 $pa['value'] = $product['id'];
  10480.                 $pa['igId'] = $product['ig_id'];
  10481.                 $pa['categoryId'] = $product['category_id'];
  10482. //                $pa['subCategoryId'] = $product['sub_category_id'];
  10483.                 $data[] = $pa;
  10484.                 $data_by_id[$product['id']] = $pa;
  10485.                 $productId $product['id'];
  10486.             }
  10487.         }
  10488. //        if($request->query->has('returnJson'))
  10489.         {
  10490.             return new JsonResponse(
  10491.                 array(
  10492.                     'success' => true,
  10493. //                    'page_title' => 'Product Details',
  10494. //                    'company_data' => $company_data,
  10495.                     'data' => $data,
  10496.                     'dataById' => $data_by_id,
  10497.                     'productId' => $productId,
  10498.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10499. //                    'exId'=>$id,
  10500. //                'productByCodeData' => $productByCodeData,
  10501. //                'productData' => $productData,
  10502. //                'currInvList' => $currInvList,
  10503. //                'productList' => Inventory::ProductList($em, $companyId),
  10504. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10505. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10506. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10507. //                'unitList' => Inventory::UnitTypeList($em),
  10508. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10509. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10510. //                'warehouseList' => Inventory::WarehouseList($em),
  10511.                 )
  10512.             );
  10513.         }
  10514.     }
  10515.     public
  10516.     function ProductByCodeViewAction(Request $request$id 0)
  10517.     {
  10518.         $em $this->getDoctrine()->getManager();
  10519.         $companyId $this->getLoggedUserCompanyId($request);
  10520.         $company_data Company::getCompanyData($em$companyId);
  10521.         $data = [];
  10522.         $html '';
  10523.         $productByCodeData = [];
  10524.         if ($id != 0) {
  10525.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10526.                 ->findOneBy(
  10527.                     array(
  10528.                         'productByCodeId' => $id
  10529.                     )
  10530.                 );
  10531.         } else {
  10532.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10533.                 ->findOneBy(
  10534.                     array(
  10535. //                        'productByCodeId' => $id,
  10536.                         'CompanyId' => $companyId
  10537.                     ), array(
  10538.                         'productByCodeId' => 'DESC'
  10539.                     )
  10540.                 );
  10541.             if ($productByCodeData)
  10542.                 $id $productByCodeData->getProductByCodeId();
  10543.         }
  10544.         if ($id != 0) {
  10545.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  10546.                 ->findOneBy(
  10547.                     array(
  10548.                         'id' => $productByCodeData->getProductId()
  10549.                     )
  10550.                 );
  10551.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  10552.                 ->findBy(
  10553.                     array(
  10554.                         'productId' => $id
  10555.                     )
  10556.                 );
  10557.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  10558.                 array(
  10559.                     'page_title' => 'Product Details',
  10560.                     'company_data' => $company_data,
  10561.                     'productByCodeData' => $productByCodeData,
  10562.                     'productData' => $productData,
  10563.                     'currInvList' => $currInvList,
  10564.                     'exId' => $id,
  10565.                     'clientList' => Client::GetExistingClientList($em$companyId),
  10566.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  10567.                     'productList' => Inventory::ProductList($em$companyId),
  10568.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10569.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10570.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10571.                     'unitList' => Inventory::UnitTypeList($em),
  10572.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10573.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10574.                     'warehouseList' => Inventory::WarehouseList($em),
  10575.                 )
  10576.             );
  10577.         } else {
  10578.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  10579.                 array(
  10580.                     'exId' => $id,
  10581.                 )
  10582.             );
  10583.         }
  10584.         if ($request->query->has('returnJson')) {
  10585.             return new JsonResponse(
  10586.                 array(
  10587.                     'success' => true,
  10588.                     'page_title' => 'Product Details',
  10589.                     'company_data' => $company_data,
  10590.                     'renderedHtml' => $html,
  10591.                     'exId' => $id,
  10592. //                'productByCodeData' => $productByCodeData,
  10593. //                'productData' => $productData,
  10594. //                'currInvList' => $currInvList,
  10595. //                'productList' => Inventory::ProductList($em, $companyId),
  10596. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10597. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10598. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10599. //                'unitList' => Inventory::UnitTypeList($em),
  10600. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10601. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10602. //                'warehouseList' => Inventory::WarehouseList($em),
  10603.                 )
  10604.             );
  10605.         } else {
  10606. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10607. //                ->findBy(
  10608. //                    array(
  10609. ////                        'productByCodeId' => $id,
  10610. //                    'CompanyId'=>$companyId
  10611. //                    )
  10612. //                );
  10613.             $productByCodeList = []; //called by ajax
  10614.             return $this->render('@Inventory/pages/views/product_by_code_view.html.twig',
  10615.                 array(
  10616.                     'page_title' => 'Product Details',
  10617.                     'company_data' => $company_data,
  10618.                     'renderedHtml' => $html,
  10619.                     'exId' => $id,
  10620.                     'productByCodeList' => $productByCodeList,
  10621. //                'productByCodeData' => $productByCodeData,
  10622. //                'productData' => $productData,
  10623. //                'currInvList' => $currInvList,
  10624. //                'productList' => Inventory::ProductList($em, $companyId),
  10625. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10626. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10627. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10628. //                'unitList' => Inventory::UnitTypeList($em),
  10629. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10630. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10631. //                'warehouseList' => Inventory::WarehouseList($em),
  10632.                 )
  10633.             );
  10634.         }
  10635.     }
  10636.     public
  10637.     function ConsumptionSettingsAction(Request $request$id)
  10638.     {
  10639.         $cc_id '';
  10640.         $cc_name '';
  10641.         $em $this->getDoctrine()->getManager();
  10642.         $companyId $this->getLoggedUserCompanyId($request);
  10643.         $consumptionTypeId 0;
  10644.         if ($request->isMethod('POST')) {
  10645.             $new_cc = [];
  10646.             if ($request->request->get('consumptionTypeId') != '' && $request->request->get('consumptionTypeId') != 0) {
  10647.                 $em $this->getDoctrine()->getManager();
  10648.                 $new_cc $this->getDoctrine()
  10649.                     ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  10650.                     ->findOneBy(
  10651.                         array(
  10652.                             'consumptionTypeId' => $request->request->get('consumptionTypeId'),
  10653.                         )
  10654.                     );
  10655.                 $new_cc->setName($request->request->get('name'));
  10656.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  10657.                 $new_cc->setCompanyId($companyId);
  10658.                 $em->flush();
  10659.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  10660.                 $this->addFlash(
  10661.                     'success',
  10662.                     'Consumption Information Updated'
  10663.                 );
  10664.             } else {
  10665.                 $new_cc = new ConsumptionType();
  10666.                 $new_cc->setName($request->request->get('name'));
  10667.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  10668.                 $new_cc->setCompanyId($companyId);
  10669.                 $em->persist($new_cc);
  10670.                 $em->flush();
  10671.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  10672.                 $em->flush();
  10673.                 $this->addFlash(
  10674.                     'success',
  10675.                     'New Consumption Type Added'
  10676.                 );
  10677.             }
  10678.         }
  10679.         $extData = [];
  10680.         if ($id != 0) {
  10681.             $extData $this->getDoctrine()
  10682.                 ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  10683.                 ->findOneBy(
  10684.                     array(
  10685.                         'consumptionTypeId' => $id
  10686.                     )
  10687.                 );
  10688. //            $cc_data_list = [];
  10689. //            foreach ($cc_data as $value) {
  10690. //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  10691. //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  10692. //
  10693. //                if ($value->getSupplierCategoryId() == $id) {
  10694. //                    $cc_id = $value->getSupplierCategoryId();
  10695. //                    $cc_name = $value->getName();
  10696. //                }
  10697. //            }
  10698.         }
  10699.         return $this->render('@Inventory/pages/input_forms/consumption_settings.html.twig',
  10700.             array(
  10701.                 'page_title' => 'Consumption Settings',
  10702.                 'consumptionTypeList' => $this->getDoctrine()
  10703.                     ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  10704.                     ->findBy(
  10705.                         array(
  10706.                             'CompanyId' => $companyId
  10707.                         )
  10708.                     ),
  10709.                 'extData' => $extData,
  10710.                 'headList' => Accounts::getParentLedgerHeads($em),
  10711. //                'countryList'=>SalesOrderM::Co
  10712.             )
  10713.         );
  10714.     }
  10715.     public
  10716.     function ProductByCodeCheckAssignPrintAction(Request $request$id 0)
  10717.     {
  10718.         $em $this->getDoctrine()->getManager();
  10719.         $companyId $this->getLoggedUserCompanyId($request);
  10720.         $company_data Company::getCompanyData($em$companyId);
  10721.         $data = [];
  10722.         $html '';
  10723.         $productByCodeData = [];
  10724.         $productDataWeightPackageGm '';
  10725.         $productDataWeightVarianceValue 0;
  10726.         $productDataWeightVarianceType 0;
  10727.         $productByCodeDataObj = [];
  10728.         $dr_id 0;//for dr_id
  10729.         $skipRenderData 0;
  10730.         if ($request->query->has('skipRenderData'))
  10731.             $skipRenderData $request->query->get('skipRenderData');
  10732.         if ($id != 0) {
  10733.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10734.                 ->findOneBy(
  10735.                     array(
  10736.                         'productByCodeId' => $id
  10737.                     )
  10738.                 );
  10739.         } else {
  10740.             if ($request->query->has('scanCode')) {
  10741.                 $query $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10742.                     ->createQueryBuilder('p');
  10743.                 if ($request->query->has('assigned')) {
  10744.                     $query->where('p.assigned > :av')
  10745.                         ->setParameter('av'$request->query->get('assigned'));
  10746.                 } else
  10747.                     $query->where("1=0");
  10748.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  10749.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  10750.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  10751.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  10752.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  10753.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  10754.                 $query->setMaxResults(1);
  10755.                 $results $query->getQuery()->getResult();
  10756.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  10757.             } else
  10758.                 $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10759.                     ->findOneBy(
  10760.                         array(
  10761. //                        'productByCodeId' => $id,
  10762.                             'CompanyId' => $companyId
  10763.                         ), array(
  10764.                             'productByCodeId' => 'DESC'
  10765.                         )
  10766.                     );
  10767.             if ($productByCodeData)
  10768.                 $id $productByCodeData->getProductByCodeId();
  10769.         }
  10770.         if ($id != 0) {
  10771.             $productByCodeDataObj = array(
  10772.                 'salesCode' => $productByCodeData->getSalesCode(),
  10773.                 'sales_code' => $productByCodeData->getSalesCode(),
  10774.                 'sn' => $productByCodeData->getSerialNo(),
  10775.                 'serialNo' => $productByCodeData->getSerialNo(),
  10776.                 'imei1' => $productByCodeData->getImei1(),
  10777.                 'imei2' => $productByCodeData->getImei2(),
  10778.                 'soId' => $productByCodeData->getSalesOrderId(),
  10779.                 'poId' => $productByCodeData->getPurchaseOrderId(),
  10780.                 'irrId' => $productByCodeData->getIrrId(),
  10781.                 'productId' => $productByCodeData->getProductId(),
  10782.                 'productByCodeId' => $productByCodeData->getProductByCodeId(),
  10783.                 'warehouseId' => $productByCodeData->getWarehouseId(),
  10784.                 'warehouseActionId' => $productByCodeData->getWarehouseActionId(),
  10785.                 'stId' => $productByCodeData->getStockTransferId(),
  10786.                 'srId' => $productByCodeData->getStockReceivedNoteId(),
  10787.                 'scmpId' => $productByCodeData->getStockConsumptionNoteId(),
  10788.                 'clientId' => $productByCodeData->getClientId(),
  10789.                 'supplierId' => $productByCodeData->getSupplierId(),
  10790.                 'drId' => $productByCodeData->getDeliveryReceiptId(),
  10791.                 'consumerName' => $productByCodeData->getConsumerName(),
  10792.                 'drItemData' => [],
  10793. //                'salesCodes' => $productByCodeData->getDeliveryReceiptId(),
  10794.             );
  10795.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  10796.                 ->findOneBy(
  10797.                     array(
  10798.                         'id' => $productByCodeData->getProductId()
  10799.                     )
  10800.                 );
  10801.             if ($productByCodeData->getProductionId() != null) {
  10802.                 $productionDataHere $em->getRepository('ApplicationBundle\\Entity\\Production')
  10803.                     ->findOneBy(
  10804.                         array(
  10805.                             'productionId' => $productByCodeData->getProductionId()
  10806.                         )
  10807.                     );
  10808.                 if ($productionDataHere) {
  10809.                     $productDataWeightPackageGm $productionDataHere->getPackageWeight();
  10810.                     $productDataWeightVarianceValue $productionDataHere->getPackageWeightVarianceValue();
  10811.                     $productDataWeightVarianceType $productionDataHere->getPackageWeightVarianceType();
  10812.                 }
  10813.             } else {
  10814.                 if ($productData) {
  10815.                     $productDataWeightPackageGm $productData->getWeight();
  10816.                     $productDataWeightVarianceValue $productData->getWeightVarianceValue();
  10817.                     $productDataWeightVarianceType $productData->getWeightVarianceType();
  10818.                 }
  10819.             }
  10820.             if ($productData) {
  10821.                 $productByCodeDataObj['unitTypeId'] = $productData->getUnitTypeId();
  10822.                 $productByCodeDataObj['purchasePrice'] = $productData->getPurchasePrice();
  10823.                 $productByCodeDataObj['productFdm'] = $productData->getProductFdm();
  10824.                 $productByCodeDataObj['productName'] = $productData->getName();
  10825.                 if ($request->request->has('forSalesReturn') || $request->query->has('forSalesReturn')) {
  10826.                     $QD $this->getDoctrine()
  10827.                         ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  10828.                         ->findOneBy(
  10829.                             array(
  10830.                                 'deliveryReceiptId' => $productByCodeData->getDeliveryReceiptId(),
  10831.                                 'productId' => $productByCodeData->getProductId(),
  10832.                             )
  10833.                         );
  10834. //            if($request->request->get('wareHouseId')!='')
  10835.                     if ($QD) {
  10836.                         $new_pid $QD->getProductId();
  10837.                         $sales_code_range = [];
  10838.                         if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  10839.                             $sales_code_range json_decode($QD->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  10840.                         } else {
  10841.                             $max_int_length strlen((string)PHP_INT_MAX) - 1;
  10842.                             $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$QD->getSalesCodeRange());
  10843.                             $sales_code_range json_decode($json_without_bigintstrue);
  10844.                         }
  10845.                         $p_data = array(
  10846.                             'details_id' => $QD->getId(),
  10847.                             'productId' => $new_pid,
  10848.                             'dr_id' => $productByCodeData->getDeliveryReceiptId(),
  10849.                             'product_name' => $productData->getName(),
  10850.                             'qty' => $QD->getQty(),
  10851.                             'delivered' => $QD->getDelivered(),
  10852.                             'unitTypeId' => $QD->getUnitTypeId(),
  10853.                             'deliverable' => $QD->getDeliverable(),
  10854.                             'balance' => $QD->getBalance(),
  10855.                             'salesCodeRangeStr' => $QD->getSalesCodeRange(),
  10856.                             'salesCodeRange' => $sales_code_range,
  10857.                             'sales_codes' => $sales_code_range,
  10858.                             'sales_price' => $QD->getPrice(),
  10859.                             'purchase_price' => $QD->getCurrentPurchasePrice()
  10860. //                        'delivered'=>$product->getDelivered(),
  10861.                         );
  10862.                         $productByCodeDataObj['drItemData'][] = $p_data;
  10863.                     }
  10864.                 }
  10865.             }
  10866.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  10867.                 ->findBy(
  10868.                     array(
  10869.                         'productId' => $id
  10870.                     )
  10871.                 );
  10872.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  10873.                 array(
  10874.                     'page_title' => 'Details',
  10875.                     'company_data' => $company_data,
  10876.                     'productByCodeData' => $productByCodeData,
  10877.                     'productByCodeDataObj' => $productByCodeDataObj,
  10878.                     'productData' => $productData,
  10879.                     'currInvList' => $currInvList,
  10880.                     'productDataWeightPackageGm' => $productDataWeightPackageGm,
  10881.                     'productDataWeightVarianceValue' => $productDataWeightVarianceValue,
  10882.                     'productDataWeightVarianceType' => $productDataWeightVarianceType,
  10883.                     'exId' => $id,
  10884.                     'clientList' => Client::GetExistingClientList($em$companyId),
  10885.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  10886.                     'productList' => Inventory::ProductList($em$companyId),
  10887.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10888.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10889.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10890.                     'unitList' => Inventory::UnitTypeList($em),
  10891.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10892.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10893.                     'warehouseList' => Inventory::WarehouseList($em),
  10894.                 )
  10895.             ));
  10896.         } else {
  10897.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  10898.                 array(
  10899.                     'exId' => $id,
  10900.                 )
  10901.             ));
  10902.         }
  10903.         if ($request->query->has('returnJson')) {
  10904.             return new JsonResponse(
  10905.                 array(
  10906.                     'success' => true,
  10907.                     'page_title' => 'Product Details',
  10908.                     'company_data' => $company_data,
  10909.                     'renderedHtml' => $html,
  10910.                     'exId' => $id,
  10911.                     'productByCodeDataObj' => $productByCodeDataObj,
  10912. //                'productData' => $productData,
  10913. //                'currInvList' => $currInvList,
  10914. //                'productList' => Inventory::ProductList($em, $companyId),
  10915. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10916. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10917. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10918. //                'unitList' => Inventory::UnitTypeList($em),
  10919. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10920. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10921. //                'warehouseList' => Inventory::WarehouseList($em),
  10922.                 )
  10923.             );
  10924.         } else {
  10925. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10926. //                ->findBy(
  10927. //                    array(
  10928. ////                        'productByCodeId' => $id,
  10929. //                    'CompanyId'=>$companyId
  10930. //                    )
  10931. //                );
  10932.             $productByCodeList = []; //called by ajax
  10933.             return $this->render('@Inventory/pages/views/product_by_code_assign_check_print.html.twig',
  10934.                 array(
  10935.                     'page_title' => 'Serial Manager',
  10936.                     'company_data' => $company_data,
  10937.                     'renderedHtml' => $html,
  10938.                     'exId' => $id,
  10939.                     'productByCodeList' => $productByCodeList,
  10940.                     'productByCodeDataObj' => $productByCodeDataObj,
  10941. //                'productByCodeData' => $productByCodeData,
  10942. //                'productData' => $productData,
  10943. //                'currInvList' => $currInvList,
  10944. //                'productList' => Inventory::ProductList($em, $companyId),
  10945. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10946. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10947. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10948. //                'unitList' => Inventory::UnitTypeList($em),
  10949. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10950. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10951. //                'warehouseList' => Inventory::WarehouseList($em),
  10952.                 )
  10953.             );
  10954.         }
  10955.     }
  10956.     public
  10957.     function TestProductByCodeCheckAssignPrintAction(Request $request$id 0)
  10958.     {
  10959.         $em $this->getDoctrine()->getManager();
  10960.         $companyId $this->getLoggedUserCompanyId($request);
  10961.         $company_data Company::getCompanyData($em$companyId);
  10962.         $data = [];
  10963.         $html '';
  10964.         $productByCodeData = [];
  10965.         $productByCodeDataObj = [];
  10966.         if ($id != 0) {
  10967.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10968.                 ->findOneBy(
  10969.                     array(
  10970.                         'productByCodeId' => $id
  10971.                     )
  10972.                 );
  10973.         } else {
  10974.             if ($request->query->has('scanCode')) {
  10975.                 $query $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10976.                     ->createQueryBuilder('p');
  10977.                 if ($request->query->has('assigned')) {
  10978.                     $query->where('p.assigned > :av')
  10979.                         ->setParameter('av'$request->query->get('assigned'));
  10980.                 } else
  10981.                     $query->where("1=0");
  10982.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  10983.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  10984.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  10985.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  10986.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  10987.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  10988.                 $query->setMaxResults(1);
  10989.                 $results $query->getQuery()->getResult();
  10990.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  10991.             } else
  10992.                 $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10993.                     ->findOneBy(
  10994.                         array(
  10995. //                        'productByCodeId' => $id,
  10996.                             'CompanyId' => $companyId
  10997.                         ), array(
  10998.                             'productByCodeId' => 'DESC'
  10999.                         )
  11000.                     );
  11001.             if ($productByCodeData)
  11002.                 $id $productByCodeData->getProductByCodeId();
  11003.         }
  11004.         if ($id != 0) {
  11005.             $productByCodeDataObj = array(
  11006.                 'sn' => $productByCodeData->getSalesCode(),
  11007.                 'imei1' => $productByCodeData->getImei1(),
  11008.                 'imei2' => $productByCodeData->getImei2(),
  11009.                 'colorId' => $productByCodeData->getColorId(),
  11010.             );
  11011.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  11012.                 ->findOneBy(
  11013.                     array(
  11014.                         'id' => $productByCodeData->getProductId()
  11015.                     )
  11016.                 );
  11017.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  11018.                 ->findBy(
  11019.                     array(
  11020.                         'productId' => $id
  11021.                     )
  11022.                 );
  11023.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  11024.                 array(
  11025.                     'page_title' => 'Details',
  11026.                     'company_data' => $company_data,
  11027.                     'productByCodeData' => $productByCodeData,
  11028.                     'productData' => $productData,
  11029.                     'currInvList' => $currInvList,
  11030.                     'exId' => $id,
  11031.                     'clientList' => Client::GetExistingClientList($em$companyId),
  11032.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  11033.                     'productList' => Inventory::ProductList($em$companyId),
  11034.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  11035.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  11036.                     'igList' => Inventory::ItemGroupList($em$companyId),
  11037.                     'unitList' => Inventory::UnitTypeList($em),
  11038.                     'brandList' => Inventory::GetBrandList($em$companyId),
  11039.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  11040.                     'warehouseList' => Inventory::WarehouseList($em),
  11041.                 )
  11042.             );
  11043.         } else {
  11044.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  11045.                 array(
  11046.                     'exId' => $id,
  11047.                 )
  11048.             );
  11049.         }
  11050.         if ($request->query->has('returnJson')) {
  11051.             return new JsonResponse(
  11052.                 array(
  11053.                     'success' => true,
  11054.                     'page_title' => 'Product Details',
  11055.                     'company_data' => $company_data,
  11056.                     'renderedHtml' => $html,
  11057.                     'exId' => $id,
  11058.                     'productByCodeDataObj' => $productByCodeDataObj,
  11059. //                'productData' => $productData,
  11060. //                'currInvList' => $currInvList,
  11061. //                'productList' => Inventory::ProductList($em, $companyId),
  11062. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11063. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11064. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11065. //                'unitList' => Inventory::UnitTypeList($em),
  11066. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11067. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11068. //                'warehouseList' => Inventory::WarehouseList($em),
  11069.                 )
  11070.             );
  11071.         } else {
  11072. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11073. //                ->findBy(
  11074. //                    array(
  11075. ////                        'productByCodeId' => $id,
  11076. //                    'CompanyId'=>$companyId
  11077. //                    )
  11078. //                );
  11079.             $productByCodeList = []; //called by ajax
  11080.             return $this->render('@Inventory/pages/views/test_product_by_code_assign_check_print.html.twig',
  11081.                 array(
  11082.                     'page_title' => ' Test Serial Manager',
  11083.                     'company_data' => $company_data,
  11084.                     'renderedHtml' => $html,
  11085.                     'exId' => $id,
  11086.                     'productByCodeList' => $productByCodeList,
  11087.                     'productByCodeDataObj' => $productByCodeDataObj,
  11088. //                'productByCodeData' => $productByCodeData,
  11089. //                'productData' => $productData,
  11090. //                'currInvList' => $currInvList,
  11091. //                'productList' => Inventory::ProductList($em, $companyId),
  11092. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11093. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11094. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11095. //                'unitList' => Inventory::UnitTypeList($em),
  11096. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11097. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11098. //                'warehouseList' => Inventory::WarehouseList($em),
  11099.                 )
  11100.             );
  11101.         }
  11102.     }
  11103.     public function DeleteProductAction(Request $request$id '')
  11104.     {
  11105.         $em $this->getDoctrine()->getManager();
  11106.         $idListArray = [];
  11107.         if ($request->isMethod('POST')) {
  11108.             if ($id == 0)
  11109.                 $id $request->request->get('productId');
  11110.             //now check the product closing , if nothing then we cna remove it
  11111.             $query_here $this->getDoctrine()
  11112.                 ->getRepository('ApplicationBundle\\Entity\\InvClosingBalance')
  11113.                 ->findBy(
  11114.                     array(
  11115.                         'productId' => $request->request->get('productId')
  11116.                     )
  11117.                 );
  11118.             if (!empty($query_here)) {
  11119.                 return new JsonResponse(
  11120.                     array(
  11121.                         'success' => false,
  11122.                     )
  11123.                 );
  11124.             } else {
  11125.                 $qry $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')->findBy(array(
  11126.                     'productId' => $id
  11127.                 ));
  11128.                 foreach ($qry as $det) {
  11129.                     //remove any barcoded products
  11130.                     $em->remove($det);
  11131.                     $em->flush();
  11132.                 }
  11133.                 $qry $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findBy(array(
  11134.                     'id' => $id
  11135.                 ));
  11136.                 foreach ($qry as $det) {
  11137.                     //remove any barcoded products
  11138.                     $em->remove($det);
  11139.                     $em->flush();
  11140.                 }
  11141.                 $qry $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')->findBy(array(
  11142.                     'productId' => $id
  11143.                 ));
  11144.                 foreach ($qry as $det) {
  11145.                     //remove any barcoded products
  11146.                     $em->remove($det);
  11147.                     $em->flush();
  11148.                 }
  11149.                 return new JsonResponse(
  11150.                     array(
  11151.                         'success' => true,
  11152.                     )
  11153.                 );
  11154.             }
  11155.         }
  11156.         return new JsonResponse(
  11157.             array(
  11158.                 'success' => false,
  11159.             )
  11160.         );
  11161.     }
  11162.     public
  11163.     function RegisterProductAction(Request $request$idListStr '')
  11164.     {
  11165.         $em $this->getDoctrine()->getManager();
  11166.         $companyId $this->getLoggedUserCompanyId($request);
  11167.         $company_data Company::getCompanyData($em$companyId);
  11168.         $session $request->getSession();
  11169. //        System::setSessionForUser($session );
  11170.         $idListArray = [];
  11171.         if ($idListStr != '')
  11172.             $idListArray explode(','$idListStr);
  11173.         $data = [];
  11174. //        if ($request->isMethod('POST')) {
  11175. //            $post = $request->request;
  11176. //            if ($request->request->get('formatId') != '') {
  11177. //                $query_here = $this->getDoctrine()
  11178. //                    ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  11179. //                    ->findOneBy(
  11180. //                        array(
  11181. //                            'formatId' => $request->request->get('formatId')
  11182. //                        )
  11183. //                    );
  11184. //                if (!empty($query_here))
  11185. //                    $new = $query_here;
  11186. //            } else
  11187. //                $new = new CheckFormat();
  11188. //            $new->setName($request->request->get('name'));
  11189. //            $new->setWidth($request->request->get('width'));
  11190. //            $new->setHeight($request->request->get('height'));
  11191. //            $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
  11192. //            $new->setCheckPayToTop($request->request->get('checkPayToTop'));
  11193. //            $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
  11194. //            $new->setCheckAmountTop($request->request->get('checkAmountTop'));
  11195. //            $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
  11196. //            $new->setCheckAiWTop($request->request->get('checkAiWTop'));
  11197. //            $new->setCheckDateLeft($request->request->get('checkDateLeft'));
  11198. //            $new->setCheckDateTop($request->request->get('checkDateTop'));
  11199. //            $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
  11200. //            $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
  11201. //            $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
  11202. //            $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
  11203. //            $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
  11204. //            $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
  11205. //            $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
  11206. //            $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
  11207. //            $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
  11208. //            $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
  11209. //            $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 1 : 0);
  11210. //            $new->setCheckImage($request->request->get('checkImage'));
  11211. //
  11212. //            $em = $this->getDoctrine()->getManager();
  11213. //            $em->persist($new);
  11214. //            $em->flush();
  11215. //
  11216. //        }
  11217. //        if (!empty($idListArray)) {
  11218. //            $query_here = $this->getDoctrine()
  11219. //                ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11220. //                ->findBy(
  11221. //                    array(
  11222. //                        'productByCodeId' => $idListArray
  11223. //                    )
  11224. //                );
  11225. //            if (!empty($query_here))
  11226. //                $data = $query_here;
  11227. //
  11228. //        }
  11229. //        else if ($request->query->has('formatId')) {
  11230. //            $query_here = $this->getDoctrine()
  11231. //                ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  11232. //                ->findOneBy(
  11233. //                    array(
  11234. //                        'formatId' => $request->query->get('formatId')
  11235. //                    )
  11236. //                );
  11237. //            if (!empty($query_here))
  11238. //                $data = $query_here;
  11239. //        }
  11240.         $data = [];
  11241.         $html '';
  11242.         $productByCodeData = [];
  11243.         if ($request->query->has('returnJson')) {
  11244.             return new JsonResponse(
  11245.                 array(
  11246.                     'success' => true,
  11247.                     'page_title' => 'Product Details',
  11248.                     'company_data' => $company_data,
  11249.                     'renderedHtml' => $html,
  11250.                     'data' => $data,
  11251.                     'idListArray' => $idListArray,
  11252. //                    'exId'=>$id,
  11253. //                'productByCodeData' => $productByCodeData,
  11254. //                'productData' => $productData,
  11255. //                'currInvList' => $currInvList,
  11256. //                'productList' => Inventory::ProductList($em, $companyId),
  11257. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11258. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11259. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11260. //                'unitList' => Inventory::UnitTypeList($em),
  11261. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11262. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11263. //                'warehouseList' => Inventory::WarehouseList($em),
  11264.                 )
  11265.             );
  11266.         } else {
  11267.             return $this->render('@Inventory/pages/input_forms/register_product.html.twig',
  11268.                 array(
  11269.                     'page_title' => 'Register Product',
  11270.                     'company_data' => $company_data,
  11271.                     'renderedHtml' => $html,
  11272. //                    'exIdList'=>$i,
  11273.                     'idListArray' => $idListArray,
  11274.                     'data' => $data,
  11275.                     'productByCodeList' => [],
  11276.                     'productByCodeData' => [],
  11277.                     'productList' => Inventory::ProductList($em$companyId),
  11278.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  11279.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  11280.                     'igList' => Inventory::ItemGroupList($em$companyId),
  11281.                     'unitList' => Inventory::UnitTypeList($em),
  11282.                     'brandList' => Inventory::GetBrandList($em$companyId),
  11283.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  11284.                     'warehouseList' => Inventory::WarehouseList($em),
  11285.                 )
  11286.             );
  11287.         }
  11288.     }
  11289.     public
  11290.     function BrandViewAction(Request $request)
  11291.     {
  11292.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  11293.             array(
  11294.                 'page_title' => 'Stock Return'
  11295.             )
  11296.         );
  11297.     }
  11298.     public
  11299.     function PrintTableDataAction(Request $request)
  11300.     {
  11301.         $em $this->getDoctrine()->getManager();
  11302.         $company_data Company::getCompanyData($em1);
  11303.         $data = [];
  11304.         $print_title "test";
  11305.         $document_mark = array(
  11306.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11307.             'copy' => ''
  11308.         );
  11309.         $mis_data = [];
  11310.         $p 1;
  11311.         return $this->render('@Inventory/pages/print/print_table_data.html.twig',
  11312.             array(
  11313.                 'page_title' => 'Data Report',
  11314.                 'data' => $data,
  11315.                 'page_header' => 'Report',
  11316.                 'print_title' => $print_title,
  11317.                 'document_type' => 'Journal voucher',
  11318.                 'document_mark_image' => $document_mark['original'],
  11319.                 'page_header_sub' => 'Add',
  11320. //                'type_list'=>$type_list,
  11321.                 'mis_data' => $mis_data,
  11322.                 'item_data' => [],
  11323.                 'received' => 2,
  11324.                 'return' => 1,
  11325.                 'total_w_vat' => 1,
  11326.                 'total_vat' => 1,
  11327.                 'total_wo_vat' => 1,
  11328.                 'invoice_id' => 'abcd1234',
  11329.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11330.                 'created_by' => 'created by',
  11331.                 'created_at' => '',
  11332.                 'red' => 0,
  11333.                 'company_name' => $company_data->getName(),
  11334.                 'company_data' => $company_data,
  11335.                 'company_address' => $company_data->getAddress(),
  11336.                 'company_image' => $company_data->getImage(),
  11337.                 'p' => $p
  11338.             )
  11339.         );
  11340.     }
  11341.     public
  11342.     function ReplacementReportAction(Request $request)
  11343.     {
  11344.         $qry_data = array(
  11345.             'warehouseId' => [0],
  11346.             'igId' => [0],
  11347.             'brandId' => [0],
  11348.             'categoryId' => [0],
  11349.             'actionTagId' => [0],
  11350.         );
  11351.         $em $this->getDoctrine()->getManager();
  11352.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  11353.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  11354.         $data_searched = [];
  11355.         $companyId $this->getLoggedUserCompanyId($request);
  11356.         $company_data Company::getCompanyData($em$companyId);
  11357.         $data = [];
  11358.         $print_title "Inventory Report";
  11359.         $document_mark = array(
  11360.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11361.             'copy' => ''
  11362.         );
  11363.         $post_data $request->request;
  11364.         $start_date $post_data->has('start_date') ? $post_data->get('start_date') : '';
  11365.         $end_date $post_data->has('end_date') ? $post_data->get('end_date') : '';
  11366.         if ($request->isMethod('POST'))
  11367.             $method 'POST';
  11368.         else
  11369.             $method 'GET';
  11370.         {
  11371. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  11372.             $data_searched Inventory::GetReplacementReportData($this->getDoctrine()->getManager(),
  11373.                 $request->request$method,
  11374.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  11375.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  11376.                 return new JsonResponse(
  11377.                     array(
  11378.                         'page_title' => 'Inventory ',
  11379.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11380.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11381.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11382.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11383.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11384.                         'action_tag' => $warehouse_action_list,
  11385.                         'start_date' => $start_date,
  11386.                         'end_date' => $end_date,
  11387.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11388.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11389.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11390.                         'data_searched' => $data_searched,
  11391.                         'success' => empty($data_searched['query_result']) ? false true
  11392.                     )
  11393.                 );
  11394.             }
  11395.             if ($request->request->get('print_data_enabled') == 1) {
  11396.                 $print_sub_title "";
  11397.                 return $this->render('@Inventory/pages/print/print_replacement_report.html.twig',
  11398.                     array(
  11399.                         'page_title' => 'Replacement Report',
  11400.                         'page_header' => 'Report',
  11401.                         'print_title' => $print_title,
  11402.                         'document_type' => 'Journal voucher',
  11403.                         'document_mark_image' => $document_mark['original'],
  11404.                         'page_header_sub' => 'Add',
  11405.                         'item_data' => [],
  11406.                         'received' => 2,
  11407.                         'return' => 1,
  11408.                         'total_w_vat' => 1,
  11409.                         'total_vat' => 1,
  11410.                         'total_wo_vat' => 1,
  11411.                         'invoice_id' => 'abcd1234',
  11412.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  11413.                         'created_by' => 'created by',
  11414.                         'created_at' => '',
  11415.                         'red' => 0,
  11416.                         'company_name' => $company_data->getName(),
  11417.                         'company_data' => $company_data,
  11418.                         'company_address' => $company_data->getAddress(),
  11419.                         'company_image' => $company_data->getImage(),
  11420.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11421.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11422.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11423.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11424.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11425.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11426.                         'action_tag' => $warehouse_action_list,
  11427.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11428.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11429.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11430.                         'start_date' => $start_date,
  11431.                         'end_date' => $end_date,
  11432.                         'data_searched' => $data_searched
  11433.                     )
  11434.                 );
  11435.             }
  11436.         }
  11437.         return $this->render('@Inventory/pages/report/replacement_report.html.twig',
  11438.             array(
  11439.                 'page_title' => 'Replacement Report',
  11440.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11441.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11442.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11443.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11444.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11445. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11446.                 'action_tag' => $warehouse_action_list,
  11447.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11448.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11449.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11450.                 'start_date' => $start_date,
  11451.                 'end_date' => $end_date,
  11452.                 'data_searched' => $data_searched,
  11453.                 'success' => empty($data_searched['query_result']) ? false true
  11454.             )
  11455.         );
  11456.     }
  11457.     public
  11458.     function InventoryViewAction(Request $request)
  11459.     {
  11460.         $qry_data = array(
  11461.             'warehouseId' => [0],
  11462.             'igId' => [0],
  11463.             'brandId' => [0],
  11464.             'categoryId' => [0],
  11465.             'actionTagId' => [0],
  11466.         );
  11467.         $em $this->getDoctrine()->getManager();
  11468.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  11469.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  11470.         $data_searched = [];
  11471.         $companyId $this->getLoggedUserCompanyId($request);
  11472.         $company_data Company::getCompanyData($em$companyId);
  11473.         $data = [];
  11474.         $print_title "Inventory Report";
  11475.         $document_mark = array(
  11476.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11477.             'copy' => ''
  11478.         );
  11479.         if ($request->isMethod('POST'))
  11480.             $method 'POST';
  11481.         else
  11482.             $method 'GET';
  11483.         {
  11484. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  11485.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  11486.                 $request->request$method,
  11487.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  11488.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  11489.                 return new JsonResponse(
  11490.                     array(
  11491.                         'page_title' => 'Inventory ',
  11492.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11493.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11494.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11495.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11496.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11497.                         'action_tag' => $warehouse_action_list,
  11498.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11499.                         'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  11500.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11501.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11502.                         'data_searched' => $data_searched,
  11503.                         'success' => empty($data_searched['query_result']) ? false true
  11504.                     )
  11505.                 );
  11506.             }
  11507.             if ($request->request->get('print_data_enabled') == 1) {
  11508.                 $print_sub_title "";
  11509.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  11510.                     array(
  11511.                         'page_title' => 'Inventory Report',
  11512.                         'page_header' => 'Report',
  11513.                         'print_title' => $print_title,
  11514.                         'document_type' => 'Journal voucher',
  11515.                         'document_mark_image' => $document_mark['original'],
  11516.                         'page_header_sub' => 'Add',
  11517.                         'item_data' => [],
  11518.                         'received' => 2,
  11519.                         'return' => 1,
  11520.                         'total_w_vat' => 1,
  11521.                         'total_vat' => 1,
  11522.                         'total_wo_vat' => 1,
  11523.                         'invoice_id' => 'abcd1234',
  11524.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  11525.                         'created_by' => 'created by',
  11526.                         'created_at' => '',
  11527.                         'red' => 0,
  11528.                         'company_name' => $company_data->getName(),
  11529.                         'company_data' => $company_data,
  11530.                         'company_address' => $company_data->getAddress(),
  11531.                         'company_image' => $company_data->getImage(),
  11532.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11533.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11534.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11535.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11536.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11537.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11538.                         'action_tag' => $warehouse_action_list,
  11539.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11540.                         'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  11541.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11542.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11543.                         'data_searched' => $data_searched
  11544.                     )
  11545.                 );
  11546.             }
  11547.         }
  11548.         return $this->render('@Inventory/pages/report/inventory_view.html.twig',
  11549.             array(
  11550.                 'page_title' => 'Inventory',
  11551.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11552.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11553.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11554.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11555.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11556. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11557.                 'action_tag' => $warehouse_action_list,
  11558.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11559.                 'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  11560.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11561.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11562.                 'data_searched' => $data_searched
  11563.             )
  11564.         );
  11565.     }
  11566.     public
  11567.     function GrnListAction(Request $request)
  11568.     {
  11569.         $q $this->getDoctrine()
  11570.             ->getRepository('ApplicationBundle\\Entity\\Grn')
  11571.             ->findBy(
  11572.                 array(
  11573.                     'status' => GeneralConstant::ACTIVE,
  11574. //                    'approved' =>  GeneralConstant::APPROVED,
  11575.                 )
  11576.             );
  11577.         $stage_list = array(
  11578.             => 'Pending',
  11579.             => 'Pending',
  11580.             => 'Complete',
  11581.             => 'Partial',
  11582.         );
  11583.         $data = [];
  11584.         foreach ($q as $entry) {
  11585.             $data[] = array(
  11586.                 'doc_date' => $entry->getGrnDate(),
  11587.                 'id' => $entry->getGrnId(),
  11588.                 'doc_hash' => $entry->getDocumentHash(),
  11589.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  11590.                 'stage' => $stage_list[$entry->getStage()]
  11591.             );
  11592.         }
  11593.         return $this->render('@Inventory/pages/views/grn_list.html.twig',
  11594.             array(
  11595.                 'page_title' => 'Grn List',
  11596.                 'data' => $data
  11597.             )
  11598.         );
  11599.     }
  11600.     public
  11601.     function ViewGrnAction(Request $request$id)
  11602.     {
  11603.         $em $this->getDoctrine()->getManager();
  11604.         $dt Inventory::GetGrnDetails($em$id);
  11605.         return $this->render(
  11606.             '@Inventory/pages/views/view_grn.html.twig',
  11607.             array(
  11608.                 'page_title' => 'View',
  11609.                 'data' => $dt,
  11610.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  11611.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11612.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11613.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11614.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  11615.                     $id,
  11616.                     $dt['created_by'],
  11617.                     $dt['edited_by'])
  11618.             )
  11619.         );
  11620.     }
  11621.     public
  11622.     function PrintGrnAction(Request $request$id)
  11623.     {
  11624.         $em $this->getDoctrine()->getManager();
  11625.         $dt Inventory::GetGrnDetails($em$id);
  11626.         $company_data Company::getCompanyData($em1);
  11627.         $document_mark = array(
  11628.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11629.             'copy' => ''
  11630.         );
  11631.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11632.             $html $this->renderView('@Inventory/pages/print/print_received_note.html.twig',
  11633.                 array(
  11634.                     //full array here
  11635.                     'pdf' => true,
  11636.                     'page_title' => 'Grn',
  11637.                     'export' => 'pdf,print',
  11638.                     'data' => $dt,
  11639.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11640.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11641.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11642.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  11643.                         $id,
  11644.                         $dt['created_by'],
  11645.                         $dt['edited_by']),
  11646.                     'document_mark_image' => $document_mark['original'],
  11647.                     'company_name' => $company_data->getName(),
  11648.                     'company_data' => $company_data,
  11649.                     'company_address' => $company_data->getAddress(),
  11650.                     'company_image' => $company_data->getImage(),
  11651.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11652.                     'red' => 0
  11653.                 )
  11654.             );
  11655.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11656. //                'orientation' => 'landscape',
  11657. //                'enable-javascript' => true,
  11658. //                'javascript-delay' => 1000,
  11659.                 'no-stop-slow-scripts' => false,
  11660.                 'no-background' => false,
  11661.                 'lowquality' => false,
  11662.                 'encoding' => 'utf-8',
  11663. //            'images' => true,
  11664. //            'cookie' => array(),
  11665.                 'dpi' => 300,
  11666.                 'image-dpi' => 300,
  11667. //                'enable-external-links' => true,
  11668. //                'enable-internal-links' => true
  11669.             ));
  11670.             return new Response(
  11671.                 $pdf_response,
  11672.                 200,
  11673.                 array(
  11674.                     'Content-Type' => 'application/pdf',
  11675.                     'Content-Disposition' => 'attachment; filename="grn.pdf"'
  11676.                 )
  11677.             );
  11678.         }
  11679.         return $this->render('@Inventory/pages/print/print_received_note.html.twig',
  11680.             array(
  11681.                 'page_title' => 'Grn',
  11682.                 'export' => 'pdf,print',
  11683.                 'data' => $dt,
  11684.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11685.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11686.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11687.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  11688.                     $id,
  11689.                     $dt['created_by'],
  11690.                     $dt['edited_by']),
  11691.                 'document_mark_image' => $document_mark['original'],
  11692.                 'company_name' => $company_data->getName(),
  11693.                 'company_data' => $company_data,
  11694.                 'company_address' => $company_data->getAddress(),
  11695.                 'company_image' => $company_data->getImage(),
  11696.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11697.                 'red' => 0
  11698.             )
  11699.         );
  11700.     }
  11701.     public
  11702.     function PrintGrnBarcodeAction(Request $request$id)
  11703.     {
  11704.         $em $this->getDoctrine()->getManager();
  11705.         $dt Inventory::GetGrnDetails($em$id);
  11706.         $company_data Company::getCompanyData($em1);
  11707.         $repeatCount 1;
  11708.         if ($request->query->has('repeatCount'))
  11709.             $repeatCount $request->query->get('repeatCount');
  11710.         $document_mark = array(
  11711.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11712.             'copy' => ''
  11713.         );
  11714.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11715.             $html $this->renderView('@Inventory/pages/print/print_grn_barcodes.html.twig',
  11716.                 array(
  11717.                     //full array here
  11718.                     'pdf' => true,
  11719.                     'page_title' => 'Grn Barcodes',
  11720.                     'export' => 'print',
  11721.                     'data' => $dt,
  11722.                     'repeatCount' => $repeatCount,
  11723.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11724.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11725.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11726.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  11727.                         $id,
  11728.                         $dt['created_by'],
  11729.                         $dt['edited_by']),
  11730.                     'document_mark_image' => $document_mark['original'],
  11731.                     'company_name' => $company_data->getName(),
  11732.                     'company_data' => $company_data,
  11733.                     'company_address' => $company_data->getAddress(),
  11734.                     'company_image' => $company_data->getImage(),
  11735.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11736.                     'red' => 0
  11737.                 )
  11738.             );
  11739.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11740. //                'orientation' => 'landscape',
  11741.                 'enable-javascript' => true,
  11742. //                'javascript-delay' => 1000,
  11743.                 'no-stop-slow-scripts' => false,
  11744.                 'no-background' => false,
  11745.                 'lowquality' => false,
  11746.                 'encoding' => 'utf-8',
  11747. //            'images' => true,
  11748. //            'cookie' => array(),
  11749.                 'dpi' => 300,
  11750.                 'image-dpi' => 300,
  11751. //                'enable-external-links' => true,
  11752. //                'enable-internal-links' => true
  11753.             ));
  11754.             return new Response(
  11755.                 $pdf_response,
  11756.                 200,
  11757.                 array(
  11758.                     'Content-Type' => 'application/pdf',
  11759.                     'Content-Disposition' => 'attachment; filename="grn_barcodes.pdf"'
  11760.                 )
  11761.             );
  11762.         }
  11763.         return $this->render('@Inventory/pages/print/print_grn_barcodes.html.twig',
  11764.             array(
  11765.                 'page_title' => 'Grn barcodes',
  11766. //                'export'=>'pdf,print',
  11767.                 'data' => $dt,
  11768.                 'repeatCount' => $repeatCount,
  11769.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11770.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11771.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11772.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  11773.                     $id,
  11774.                     $dt['created_by'],
  11775.                     $dt['edited_by']),
  11776.                 'document_mark_image' => $document_mark['original'],
  11777.                 'company_name' => $company_data->getName(),
  11778.                 'company_data' => $company_data,
  11779.                 'company_address' => $company_data->getAddress(),
  11780.                 'company_image' => $company_data->getImage(),
  11781.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11782.                 'red' => 0
  11783.             )
  11784.         );
  11785.     }
  11786.     public function GenerateBarcodeAction(Request $request$type$id$item_id)
  11787.     {
  11788.         $em $this->getDoctrine()->getManager();
  11789.         $repeatCount 1;
  11790.         $spec_item_id 0;
  11791.         $skip_ids = [];
  11792.         $clearUnnecessaryOnly 0;
  11793.         if ($request->query->has('skipIds'))
  11794.             $skip_ids $request->query->get('skipIds');
  11795.         if ($request->query->has('clearUnnecessaryOnly'))
  11796.             $clearUnnecessaryOnly $request->query->get('clearUnnecessaryOnly');
  11797.         if ($type == 'srcv') {
  11798.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')->findOneBy(
  11799.                 array(
  11800.                     'stockReceivedNoteId' => $id
  11801.                 )
  11802.             );
  11803.             if ($item_id == '_single_') {
  11804.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findBy(
  11805.                     array(
  11806.                         'stockReceivedNoteId' => $id,
  11807. //                        'id' => $item_id
  11808.                     )
  11809.                 );
  11810.             } else {
  11811.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findBy(
  11812.                     array(
  11813.                         'stockReceivedNoteId' => $id,
  11814.                         'id' => $item_id
  11815.                     )
  11816.                 );
  11817.             }
  11818.             $inv_acc_data = [
  11819.                 'fa_amount' => 0,
  11820.                 'tg_amount' => 0,
  11821.             ];
  11822.             $inv_acc_data_by_head = [
  11823.             ];
  11824.             $new_non_delivered_sales_code_range = [];
  11825.             foreach ($doc_item_data as $entry) {
  11826.                 //adding transaction
  11827.                 $sales_code_range_ser = [];
  11828.                 if (in_array($entry->getId(), $skip_ids))
  11829.                     continue;
  11830.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  11831.                     ->findOneBy(
  11832.                         array(
  11833.                             'id' => $entry->getProductId()
  11834.                         )
  11835.                     );
  11836.                 $stitem $em->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  11837.                     ->findOneBy(
  11838.                         array(
  11839.                             'id' => $entry->getStockTransferItemId(),
  11840.                             'productId' => $entry->getProductId()
  11841.                         )
  11842.                     );
  11843.                 if ($product) {
  11844.                     if ($product->getHasSerial() == 1) {
  11845.                         //clear if exists
  11846.                         if ($clearUnnecessaryOnly == 1) {
  11847.                             $get_kids_sql "DELETE FROM product_by_code
  11848.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  11849. //                $get_kids_sql .=' ORDER BY name ASC';
  11850.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  11851.                             $em->flush();
  11852.                         } else {
  11853.                             $get_kids_sql "DELETE FROM product_by_code
  11854.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  11855. //                $get_kids_sql .=' ORDER BY name ASC';
  11856.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  11857.                             $em->flush();
  11858.                         }
  11859. //                        $check_here = $stmt;
  11860.                         //now addng product by code
  11861.                         $sales_code_range = [];
  11862.                         if ($doc_data->getType() == || $doc_data->getType() == 4) {
  11863. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  11864. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  11865.                             $product_action_tag_id $entry->getWarehouseActionId();
  11866.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getQty(),
  11867.                                 $doc_data->getStockReceivedNoteDate(), $entry->getWarrantyMon(), 0$doc_data->getCompanyId(), $entry->getWarehouseId(),
  11868.                                 $entry->getWarehouseActionId(), $entry->getPurchaseCodeRange(), nullnullnullnull$doc_data->getStockReceivedNoteId()
  11869.                             );
  11870.                             $sales_code_range $barcodeData['sales_code_range'];
  11871.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  11872.                             $em->flush();
  11873.                         }
  11874. //                        else {
  11875. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11876. //
  11877. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11878. //                            } else {
  11879. //
  11880. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11881. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  11882. //                                $sales_code_range = json_decode($json_without_bigints, true);
  11883. //                            }
  11884. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11885. //
  11886. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11887. //                            } else {
  11888. //
  11889. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11890. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  11891. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  11892. //                            }
  11893. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  11894. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  11895. //                            $new_non_delivered_sales_code_range = [];
  11896. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  11897. //                                if (!(in_array($ndsc, $sales_code_range)))
  11898. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  11899. //                            }
  11900. //                            if ($sales_code_range != null) {
  11901. //                                foreach ($sales_code_range as $ind => $dt) {
  11902. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11903. //                                        ->findOneBy(
  11904. //                                            array(
  11905. //                                                'salesCode' => [$dt],
  11906. //                                                'productId' => $entry->getProductId()
  11907. //                                            )
  11908. //                                        );
  11909. //
  11910. //                                    if ($np) {
  11911. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  11912. //                                        $np->setProductId($entry->getProductId());
  11913. //                                        $np->setWarehouseId($entry->getWarehouseId());
  11914. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  11915. //                                        $np->setPosition(1);//in warehouse
  11916. //                                        $np->setStockReceivedNoteId($id);
  11917. //
  11918. //
  11919. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  11920. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  11921. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  11922. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  11923. //                                            'direction' => 'in',
  11924. //                                            'warehouseId' => $entry->getWarehouseId(),
  11925. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  11926. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  11927. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  11928. //                                        );
  11929. //                                        $np->setTransactionHistory(json_encode(
  11930. //                                            $trans_history
  11931. //                                        ));
  11932. //
  11933. //
  11934. //                                        $em->persist($np);
  11935. //                                        $em->flush();
  11936. //                                    }
  11937. //                                }
  11938. //                            }
  11939. //                        }
  11940.                     }
  11941.                 }
  11942.                 //adding transaction
  11943.                 if ($stitem) {
  11944.                     $stitem->setNonDeliveredSalesCodeRange(json_encode($new_non_delivered_sales_code_range));
  11945.                 }
  11946.                 $spec_item_id $entry->getId();
  11947.                 if ($item_id == '_single_') {
  11948.                     break;
  11949.                 }
  11950.             }
  11951.         }
  11952.         if ($type == 'irr') {
  11953.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacement')->findOneBy(
  11954.                 array(
  11955.                     'itemReceivedAndReplacementId' => $id
  11956.                 )
  11957.             );
  11958.             if ($item_id == '_single_') {
  11959.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacementItem')->findBy(
  11960.                     array(
  11961.                         'itemReceivedAndReplacementId' => $id,
  11962. //                        'id' => $item_id
  11963.                     )
  11964.                 );
  11965.             } else {
  11966.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacementItem')->findBy(
  11967.                     array(
  11968.                         'itemReceivedAndReplacementId' => $id,
  11969.                         'id' => $item_id
  11970.                     )
  11971.                 );
  11972.             }
  11973.             $inv_acc_data = [
  11974.                 'fa_amount' => 0,
  11975.                 'tg_amount' => 0,
  11976.             ];
  11977.             $inv_acc_data_by_head = [
  11978.             ];
  11979.             $new_non_delivered_sales_code_range = [];
  11980.             foreach ($doc_item_data as $entry) {
  11981.                 //adding transaction
  11982.                 $sales_code_range_ser = [];
  11983.                 if (in_array($entry->getId(), $skip_ids))
  11984.                     continue;
  11985.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  11986.                     ->findOneBy(
  11987.                         array(
  11988.                             'id' => $entry->getReceivedProductId()
  11989.                         )
  11990.                     );
  11991.                 if ($product) {
  11992.                     if ($product->getHasSerial() == 1) {
  11993.                         //clear if exists
  11994. //                        if($clearUnnecessaryOnly==1) {
  11995. //                            $get_kids_sql = "DELETE FROM product_by_code
  11996. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  11997. ////                $get_kids_sql .=' ORDER BY name ASC';
  11998. //
  11999. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12000. //                            
  12001. //                            $em->flush();
  12002. //                        }
  12003. //                        else{
  12004. //                            $get_kids_sql = "DELETE FROM product_by_code
  12005. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12006. ////                $get_kids_sql .=' ORDER BY name ASC';
  12007. //
  12008. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12009. //                            
  12010. //                            $em->flush();
  12011. //                        }
  12012. //                        $check_here = $stmt;
  12013.                         //now addng product by code
  12014.                         $sales_code_range = [];
  12015.                         if ($entry->getReceivedQty() > 0) {
  12016. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  12017. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  12018. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  12019.                             $barcodeData Inventory::GenerateBarcode($em$entry->getReceivedProductId(), $entry->getReceivedQty(),
  12020.                                 $doc_data->getItemReceivedAndReplacementDate(), 00$doc_data->getCompanyId(), $entry->getReceivedWarehouseId(),
  12021.                                 $entry->getReceivedWarehouseActionId(), nullnullnullnullnullnullnullnull$doc_data->getItemReceivedAndReplacementId()
  12022.                             );
  12023.                             $sales_code_range $barcodeData['sales_code_range'];
  12024.                             $entry->setReceivedCodeRange(json_encode($sales_code_range));
  12025.                             $em->flush();
  12026.                         }
  12027. //                        else {
  12028. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12029. //
  12030. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12031. //                            } else {
  12032. //
  12033. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12034. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  12035. //                                $sales_code_range = json_decode($json_without_bigints, true);
  12036. //                            }
  12037. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12038. //
  12039. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12040. //                            } else {
  12041. //
  12042. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12043. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  12044. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  12045. //                            }
  12046. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  12047. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  12048. //                            $new_non_delivered_sales_code_range = [];
  12049. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  12050. //                                if (!(in_array($ndsc, $sales_code_range)))
  12051. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  12052. //                            }
  12053. //                            if ($sales_code_range != null) {
  12054. //                                foreach ($sales_code_range as $ind => $dt) {
  12055. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12056. //                                        ->findOneBy(
  12057. //                                            array(
  12058. //                                                'salesCode' => [$dt],
  12059. //                                                'productId' => $entry->getProductId()
  12060. //                                            )
  12061. //                                        );
  12062. //
  12063. //                                    if ($np) {
  12064. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  12065. //                                        $np->setProductId($entry->getProductId());
  12066. //                                        $np->setWarehouseId($entry->getWarehouseId());
  12067. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  12068. //                                        $np->setPosition(1);//in warehouse
  12069. //                                        $np->setStockReceivedNoteId($id);
  12070. //
  12071. //
  12072. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  12073. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  12074. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  12075. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  12076. //                                            'direction' => 'in',
  12077. //                                            'warehouseId' => $entry->getWarehouseId(),
  12078. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  12079. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  12080. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  12081. //                                        );
  12082. //                                        $np->setTransactionHistory(json_encode(
  12083. //                                            $trans_history
  12084. //                                        ));
  12085. //
  12086. //
  12087. //                                        $em->persist($np);
  12088. //                                        $em->flush();
  12089. //                                    }
  12090. //                                }
  12091. //                            }
  12092. //                        }
  12093.                     }
  12094.                 }
  12095.                 //adding transaction
  12096.                 $spec_item_id $entry->getId();
  12097.                 if ($item_id == '_single_') {
  12098.                     break;
  12099.                 }
  12100.             }
  12101.         }
  12102.         if ($type == 'prdcn') {
  12103.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\Production')->findOneBy(
  12104.                 array(
  12105.                     'productionId' => $id
  12106.                 )
  12107.             );
  12108.             if ($item_id == '_single_') {
  12109.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findBy(
  12110.                     array(
  12111.                         'productionId' => $id,
  12112. //                        'id' => $item_id
  12113.                     )
  12114.                 );
  12115.             } else {
  12116.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findBy(
  12117.                     array(
  12118.                         'productionId' => $id,
  12119.                         'id' => $item_id
  12120.                     )
  12121.                 );
  12122.             }
  12123.             $inv_acc_data = [
  12124.                 'fa_amount' => 0,
  12125.                 'tg_amount' => 0,
  12126.             ];
  12127.             $inv_acc_data_by_head = [
  12128.             ];
  12129.             $new_non_delivered_sales_code_range = [];
  12130.             foreach ($doc_item_data as $entry) {
  12131.                 //adding transaction
  12132.                 $sales_code_range_ser = [];
  12133.                 if (in_array($entry->getId(), $skip_ids))
  12134.                     continue;
  12135.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12136.                     ->findOneBy(
  12137.                         array(
  12138.                             'id' => $entry->getProductId()
  12139.                         )
  12140.                     );
  12141.                 if ($product) {
  12142.                     if ($product->getHasSerial() == 1) {
  12143.                         //clear if exists
  12144. //                        if($clearUnnecessaryOnly==1) {
  12145. //                            $get_kids_sql = "DELETE FROM product_by_code
  12146. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12147. ////                $get_kids_sql .=' ORDER BY name ASC';
  12148. //
  12149. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12150. //                            
  12151. //                            $em->flush();
  12152. //                        }
  12153. //                        else{
  12154. //                            $get_kids_sql = "DELETE FROM product_by_code
  12155. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12156. ////                $get_kids_sql .=' ORDER BY name ASC';
  12157. //
  12158. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12159. //                            
  12160. //                            $em->flush();
  12161. //                        }
  12162. //                        $check_here = $stmt;
  12163.                         //now addng product by code
  12164.                         $sales_code_range = [];
  12165.                         if ($entry->getProducedQty() > 0) {
  12166. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  12167. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  12168. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  12169.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getProducedQty(),
  12170.                                 $doc_data->getProductionDate(), 00$doc_data->getCompanyId(), $entry->getWarehouseId(),
  12171.                                 $entry->getProducedItemActionTagId(), nullnullnullnullnullnullnull$doc_data->getProductionId(), null
  12172.                             );
  12173.                             $sales_code_range $barcodeData['sales_code_range'];
  12174.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  12175.                             $em->flush();
  12176.                         }
  12177. //                        else {
  12178. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12179. //
  12180. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12181. //                            } else {
  12182. //
  12183. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12184. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  12185. //                                $sales_code_range = json_decode($json_without_bigints, true);
  12186. //                            }
  12187. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12188. //
  12189. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12190. //                            } else {
  12191. //
  12192. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12193. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  12194. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  12195. //                            }
  12196. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  12197. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  12198. //                            $new_non_delivered_sales_code_range = [];
  12199. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  12200. //                                if (!(in_array($ndsc, $sales_code_range)))
  12201. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  12202. //                            }
  12203. //                            if ($sales_code_range != null) {
  12204. //                                foreach ($sales_code_range as $ind => $dt) {
  12205. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12206. //                                        ->findOneBy(
  12207. //                                            array(
  12208. //                                                'salesCode' => [$dt],
  12209. //                                                'productId' => $entry->getProductId()
  12210. //                                            )
  12211. //                                        );
  12212. //
  12213. //                                    if ($np) {
  12214. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  12215. //                                        $np->setProductId($entry->getProductId());
  12216. //                                        $np->setWarehouseId($entry->getWarehouseId());
  12217. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  12218. //                                        $np->setPosition(1);//in warehouse
  12219. //                                        $np->setStockReceivedNoteId($id);
  12220. //
  12221. //
  12222. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  12223. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  12224. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  12225. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  12226. //                                            'direction' => 'in',
  12227. //                                            'warehouseId' => $entry->getWarehouseId(),
  12228. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  12229. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  12230. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  12231. //                                        );
  12232. //                                        $np->setTransactionHistory(json_encode(
  12233. //                                            $trans_history
  12234. //                                        ));
  12235. //
  12236. //
  12237. //                                        $em->persist($np);
  12238. //                                        $em->flush();
  12239. //                                    }
  12240. //                                }
  12241. //                            }
  12242. //                        }
  12243.                     }
  12244.                 }
  12245.                 //adding transaction
  12246.                 $spec_item_id $entry->getId();
  12247.                 if ($item_id == '_single_') {
  12248.                     break;
  12249.                 }
  12250.             }
  12251.         }
  12252.         return new JsonResponse(array(
  12253.             'success' => $spec_item_id != true false,
  12254.             'skipIds' => [],
  12255.             'spec_item_id' => $spec_item_id
  12256.         ));
  12257. //        return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12258. //            array(
  12259. //                'page_title' => 'Srcv barcodes',
  12260. ////                'export'=>'pdf,print',
  12261. //                'data' => $dt,
  12262. //                'repeatCount' => $repeatCount,
  12263. //                'item_id' => $item_id,
  12264. //                'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12265. //                    $id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12266. //                'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12267. //                    array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12268. //                    $id,
  12269. //                    $dt['created_by'],
  12270. //                    $dt['edited_by']),
  12271. //                'document_mark_image' => $document_mark['original'],
  12272. //                                    'company_name' => $company_data->getName(),
  12273. //                    'company_data'=>$company_data,
  12274. //                'company_address' => $company_data->getAddress(),
  12275. //                'company_image' => $company_data->getImage(),
  12276. //                'invoice_footer' => $company_data->getInvoiceFooter(),
  12277. //                'red' => 0
  12278. //
  12279. //            )
  12280. //        );
  12281.     }
  12282.     public
  12283.     function PrintLabelAction(Request $request$id)
  12284.     {
  12285.         $em $this->getDoctrine()->getManager();
  12286. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12287.         $repeatCount 1;
  12288.         $assignProductId '';
  12289.         $productByCodeIds = [];
  12290.         $print_selection_type 1;
  12291.         $print_selection_string 1;
  12292.         $assignLabelFormatId 0;
  12293.         $assignColorId 0;
  12294.         $assignProductionScheduleId 0;
  12295.         $warehouseId '';
  12296.         $warehouseActionId '';
  12297.         $toAssignPosition '';
  12298.         $printFlag $request->request->has('printFlag') ? $request->request->get('printFlag') : 1;
  12299.         $returnJson $request->request->has('returnJson') ? $request->request->get('returnJson') : 0;
  12300.         if ($returnJson == 1)
  12301.             $printFlag 0;
  12302.         $companyId $this->getLoggedUserCompanyId($request);
  12303.         if ($request->query->has('repeatCount'))
  12304.             $repeatCount $request->query->get('repeatCount');
  12305.         if ($request->request->has('print_selection_type'))
  12306.             $print_selection_type $request->request->get('print_selection_type');
  12307.         if ($request->request->has('print_selection_string'))
  12308.             $print_selection_string $request->request->get('print_selection_string');
  12309.         if ($request->request->has('productByCodeIds'))
  12310.             $productByCodeIds json_decode($request->request->get('productByCodeIds'), true);
  12311.         if ($request->request->has('formatId'))
  12312.             $assignLabelFormatId $request->request->get('formatId');
  12313.         if ($printFlag == 0) {
  12314.             if ($request->request->has('productSelector'))
  12315.                 $assignProductId $request->request->get('productSelector');
  12316.             if ($request->request->has('colorId'))
  12317.                 $assignColorId $request->request->get('colorId');
  12318.             if ($request->request->has('productionScheduleId'))
  12319.                 $assignProductionScheduleId $request->request->get('productionScheduleId');
  12320.             if ($request->request->has('warehouseId'))
  12321.                 $warehouseId $request->request->get('warehouseId');
  12322.             if ($request->request->has('warehouseActionId'))
  12323.                 $warehouseActionId $request->request->get('warehouseActionId');
  12324.             if ($request->request->has('position'))
  12325.                 $toAssignPosition $request->request->get('position');
  12326.             if ($assignColorId == '')
  12327.                 $assignColorId 0;
  12328.         }
  12329.         if ($productByCodeIds == null)
  12330.             $productByCodeIds = [];
  12331.         $productByCodeData = [];
  12332.         $productList = [];
  12333.         $productIds = [];
  12334.         if ($print_selection_type == 2) {
  12335.             //range
  12336.             $productByCodeIds Inventory::getIdsFromIdSelectionStr($print_selection_string);
  12337.         }
  12338.         $labelData = [
  12339.             'formatId' => 0
  12340.         ];
  12341.         $formatId 0;
  12342.         if (!empty($productByCodeIds)) {
  12343.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12344.                 ->findBy(
  12345.                     array(
  12346.                         'productByCodeId' => $productByCodeIds
  12347.                     )
  12348.                 );
  12349.             foreach ($productByCodeData as $d) {
  12350.                 if ($d->getStage() < 10$d->setStage(11);
  12351.                 if ($assignProductId != '') {
  12352.                     $d->setProductId($assignProductId);
  12353.                 }
  12354.                 if ($assignColorId != 0) {
  12355.                     $d->setColorId($assignColorId);
  12356.                 } else {
  12357.                     $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12358.                         ->findOneBy(
  12359.                             array(
  12360.                                 'id' => $assignProductId
  12361.                             )
  12362.                         );
  12363.                     if ($productData) {
  12364.                         $d->setColorId($productData->getDefaultColorId());
  12365.                     }
  12366.                 }
  12367.                 if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  12368.                     $d->setDefaultLabelFormatId($assignLabelFormatId);
  12369.                     $d->setDeviceLabelFormatId($assignLabelFormatId);
  12370.                 }
  12371.                 $toAssignPosition != '' $d->setPosition($toAssignPosition) : '';
  12372.                 $warehouseId != '' $d->setWarehouseId($warehouseId) : '';
  12373.                 $warehouseActionId != '' $d->setWarehouseActionId($warehouseActionId) : '';
  12374.                 if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  12375.                     $d->setProductionScheduleId($assignProductionScheduleId);
  12376.                     $productionSchedule $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  12377.                         ->findOneBy(
  12378.                             array(
  12379.                                 'productionScheduleId' => $assignProductionScheduleId
  12380.                             )
  12381.                         );
  12382.                     if ($productionSchedule) {
  12383.                         if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  12384.                             //becuase it will assigned at previous lines
  12385.                         } else {
  12386.                             $d->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  12387.                             $d->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  12388.                         }
  12389.                         $d->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  12390.                         $d->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  12391.                     }
  12392.                 }
  12393.                 $em->flush();
  12394.                 if ($d->getProductId() != '' || $d->getProductId() != null)
  12395.                     $productIds[] = $d->getProductId();
  12396.                 $formatId $d->getDeviceLabelFormatId();
  12397.             }
  12398.         }
  12399.         $labelFormatHere $em->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  12400.             ->findOneBy(
  12401.                 array(
  12402.                     'formatId' => $formatId,
  12403. //                        'CompanyId' => $companyId
  12404.                 )
  12405.             );
  12406.         if ($labelFormatHere) {
  12407.             $formatData json_decode($labelFormatHere->getFormatData(), true);
  12408.             if ($formatData == null$formatData = [];
  12409.             $labelData = array(
  12410.                 'id' => $labelFormatHere->getFormatId(),
  12411.                 'formatId' => $labelFormatHere->getFormatId(),
  12412.                 'labelType' => $labelFormatHere->getLabelType(),
  12413.                 'name' => $labelFormatHere->getName(),
  12414.                 'width' => $labelFormatHere->getWidth(),
  12415.                 'pageWidth' => $labelFormatHere->getPageWidth(),
  12416.                 'height' => $labelFormatHere->getheight(),
  12417.                 'pageHeight' => $labelFormatHere->getPageHeight(),
  12418.                 'formatData' => $formatData,
  12419.             );
  12420.         }
  12421.         $productList Inventory::ProductList($em$this->getLoggedUserCompanyId($request), 10''$productIds);
  12422.         $company_data Company::getCompanyData($em1);
  12423.         $document_mark = array(
  12424.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12425.             'copy' => ''
  12426.         );
  12427.         $dt $productByCodeData;
  12428.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12429.             $html $this->renderView('@Inventory/pages/print/print_label.html.twig',
  12430.                 array(
  12431.                     //full array here
  12432.                     'pdf' => true,
  12433.                     'page_title' => 'Device Labels',
  12434.                     'export' => 'print',
  12435.                     'repeatCount' => $repeatCount,
  12436.                     'labelData' => $labelData,
  12437.                     'brandList' => Inventory::GetBrandList($em$companyId),
  12438. //                    'item_id' => $item_id,
  12439.                     'data' => $dt,
  12440.                     'productList' => $productList,
  12441.                     'approval_data' => [],
  12442.                     'document_log' => [],
  12443.                     'document_mark_image' => $document_mark['original'],
  12444.                     'company_name' => $company_data->getName(),
  12445.                     'company_data' => $company_data,
  12446.                     'company_address' => $company_data->getAddress(),
  12447.                     'company_image' => $company_data->getImage(),
  12448.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12449.                     'red' => 0
  12450.                 )
  12451.             );
  12452.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12453. //                'orientation' => 'landscape',
  12454.                 'enable-javascript' => true,
  12455. //                'javascript-delay' => 1000,
  12456.                 'no-stop-slow-scripts' => false,
  12457.                 'no-background' => false,
  12458.                 'lowquality' => false,
  12459.                 'encoding' => 'utf-8',
  12460. //            'images' => true,
  12461. //            'cookie' => array(),
  12462.                 'dpi' => 300,
  12463.                 'image-dpi' => 300,
  12464. //                'enable-external-links' => true,
  12465. //                'enable-internal-links' => true
  12466.             ));
  12467.             return new Response(
  12468.                 $pdf_response,
  12469.                 200,
  12470.                 array(
  12471.                     'Content-Type' => 'application/pdf',
  12472.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  12473.                 )
  12474.             );
  12475.         }
  12476.         $url $this->generateUrl(
  12477.             'print_label'
  12478.         );
  12479.         if ($returnJson == && $printFlag == 0) {
  12480. //                    $dr = $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findBy(
  12481. //                        array(
  12482. //                            'salesOrderId' => $orderId, ///material
  12483. //
  12484. //                        )
  12485. //                    );
  12486.             return new JsonResponse(array(
  12487.                 'success' => true,
  12488. //                        'documentHash' => $order->getDocumentHash(),
  12489. //                'documentId' => $receiptId,
  12490. //                'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
  12491. //
  12492. //                'viewUrl' => $url . "/" . $receiptId,
  12493.             ));
  12494.         } else return $this->render('@Inventory/pages/print/print_label.html.twig',
  12495.             array(
  12496.                 'page_title' => 'Product Labels',
  12497. //                'export'=>'pdf,print',
  12498.                 'data' => $dt,
  12499.                 'productList' => $productList,
  12500.                 'repeatCount' => $repeatCount,
  12501. //                'item_id' => $item_id,
  12502.                 'labelData' => $labelData,
  12503.                 'brandList' => Inventory::GetBrandList($em$companyId),
  12504.                 'approval_data' => [],
  12505.                 'document_log' => [],
  12506.                 'document_mark_image' => $document_mark['original'],
  12507.                 'company_name' => $company_data->getName(),
  12508.                 'company_data' => $company_data,
  12509.                 'company_address' => $company_data->getAddress(),
  12510.                 'company_image' => $company_data->getImage(),
  12511.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12512.                 'red' => 0
  12513.             )
  12514.         );
  12515.     }
  12516.     public
  12517.     function PrintCartonLabelAction(Request $request$id)
  12518.     {
  12519.         $em $this->getDoctrine()->getManager();
  12520. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12521.         $repeatCount 1;
  12522.         $assignProductId '';
  12523.         $productByCodeIds = [];
  12524.         $cartonId 0;
  12525.         if ($id != 0)
  12526.             $cartonId $id;
  12527.         $colorText '';
  12528.         $weightText '';
  12529.         if ($request->query->has('repeatCount'))
  12530.             $repeatCount $request->query->get('repeatCount');
  12531.         if ($request->request->has('printCartonId'))
  12532.             $cartonId $request->request->get('printCartonId');
  12533.         if ($request->request->has('printCartonColorText'))
  12534.             $colorText $request->request->get('printCartonColorText');
  12535.         if ($request->request->has('printCartonWeightText'))
  12536.             $weightText $request->request->get('printCartonWeightText');
  12537.         $labelData = [
  12538.             'formatId' => 0
  12539.         ];
  12540.         if ($productByCodeIds == null)
  12541.             $productByCodeIds = [];
  12542.         $productByCodeData = [];
  12543.         $cartonData = [];
  12544.         $product = [];
  12545.         if ($cartonId != 0) {
  12546.             $cartonData $em->getRepository('ApplicationBundle\\Entity\\Carton')
  12547.                 ->findOneBy(
  12548.                     array(
  12549.                         'id' => $cartonId
  12550.                     )
  12551.                 );
  12552.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12553.                 ->findBy(
  12554.                     array(
  12555.                         'cartonId' => $cartonId
  12556.                     )
  12557.                 );
  12558. //            if(!empty($productByCodeData))
  12559. //                $product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12560. //                ->findOneBy(
  12561. //                    array(
  12562. //                        'id' => $productByCodeData[0]->getProductId()
  12563. //                    )
  12564. //                );
  12565. //            else
  12566.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12567.                 ->findOneBy(
  12568.                     array(
  12569.                         'id' => $cartonData->getProductId()
  12570.                     )
  12571.                 );
  12572.             $formatId $cartonData->getCartonLabelFormatId();
  12573.             $labelFormatHere $em->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  12574.                 ->findOneBy(
  12575.                     array(
  12576.                         'formatId' => $formatId,
  12577. //                        'CompanyId' => $companyId
  12578.                     )
  12579.                 );
  12580.             if ($labelFormatHere) {
  12581.                 $formatData json_decode($labelFormatHere->getFormatData(), true);
  12582.                 if ($formatData == null$formatData = [];
  12583.                 $labelData = array(
  12584.                     'id' => $labelFormatHere->getFormatId(),
  12585.                     'formatId' => $labelFormatHere->getFormatId(),
  12586.                     'labelType' => $labelFormatHere->getLabelType(),
  12587.                     'name' => $labelFormatHere->getName(),
  12588.                     'width' => $labelFormatHere->getWidth(),
  12589.                     'pageWidth' => $labelFormatHere->getPageWidth(),
  12590.                     'height' => $labelFormatHere->getheight(),
  12591.                     'pageHeight' => $labelFormatHere->getPageHeight(),
  12592.                     'formatData' => $formatData,
  12593.                 );
  12594.             }
  12595.         }
  12596.         $company_data Company::getCompanyData($em1);
  12597.         $document_mark = array(
  12598.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12599.             'copy' => ''
  12600.         );
  12601.         $dt $productByCodeData;
  12602.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12603.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  12604.                 array(
  12605.                     //full array here
  12606.                     'pdf' => true,
  12607.                     'page_title' => 'Carton Labels',
  12608.                     'export' => 'print',
  12609.                     'labelData' => $labelData,
  12610.                     'repeatCount' => $repeatCount,
  12611. //                    'item_id' => $item_id,
  12612.                     'data' => $dt,
  12613.                     'cartonData' => $cartonData,
  12614.                     'product' => $product,
  12615.                     'colorText' => $colorText,
  12616.                     'weightText' => $weightText,
  12617.                     'approval_data' => [],
  12618.                     'document_log' => [],
  12619.                     'document_mark_image' => $document_mark['original'],
  12620.                     'company_name' => $company_data->getName(),
  12621.                     'company_data' => $company_data,
  12622.                     'company_address' => $company_data->getAddress(),
  12623.                     'company_image' => $company_data->getImage(),
  12624.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12625.                     'red' => 0
  12626.                 )
  12627.             );
  12628.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12629. //                'orientation' => 'landscape',
  12630.                 'enable-javascript' => true,
  12631. //                'javascript-delay' => 1000,
  12632.                 'no-stop-slow-scripts' => false,
  12633.                 'no-background' => false,
  12634.                 'lowquality' => false,
  12635.                 'encoding' => 'utf-8',
  12636. //            'images' => true,
  12637. //            'cookie' => array(),
  12638.                 'dpi' => 300,
  12639.                 'image-dpi' => 300,
  12640. //                'enable-external-links' => true,
  12641. //                'enable-internal-links' => true
  12642.             ));
  12643.             return new Response(
  12644.                 $pdf_response,
  12645.                 200,
  12646.                 array(
  12647.                     'Content-Type' => 'application/pdf',
  12648.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  12649.                 )
  12650.             );
  12651.         }
  12652.         if ($request->query->has('previewOnly')) {
  12653.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  12654.                 array(
  12655.                     'page_title' => 'Carton Labels',
  12656. //                'export'=>'pdf,print',
  12657.                     'data' => $dt,
  12658.                     'skip_parameters' => 1,
  12659.                     'labelData' => $labelData,
  12660.                     'cartonData' => $cartonData,
  12661.                     'product' => $product,
  12662.                     'colorText' => $colorText,
  12663.                     'weightText' => $weightText,
  12664.                     'repeatCount' => $repeatCount,
  12665. //                'item_id' => $item_id,
  12666.                     'approval_data' => [],
  12667.                     'document_log' => [],
  12668.                     'document_mark_image' => $document_mark['original'],
  12669.                     'company_name' => $company_data->getName(),
  12670.                     'company_data' => $company_data,
  12671.                     'company_address' => $company_data->getAddress(),
  12672.                     'company_image' => $company_data->getImage(),
  12673.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12674.                     'red' => 0
  12675.                 )
  12676.             );
  12677.             if ($request->query->has('returnJson')) {
  12678.                 return new JsonResponse(
  12679.                     array(
  12680.                         'success' => true,
  12681.                         'page_title' => 'Product Details',
  12682.                         'company_data' => $company_data,
  12683.                         'renderedHtml' => $html,
  12684. //                'productData' => $productData,
  12685. //                'currInvList' => $currInvList,
  12686. //                'productList' => Inventory::ProductList($em, $companyId),
  12687. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  12688. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  12689. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  12690. //                'unitList' => Inventory::UnitTypeList($em),
  12691. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  12692. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  12693. //                'warehouseList' => Inventory::WarehouseList($em),
  12694.                     )
  12695.                 );
  12696.             }
  12697.         }
  12698.         return $this->render('@Inventory/pages/print/print_carton_label.html.twig',
  12699.             array(
  12700.                 'page_title' => 'Carton Labels',
  12701. //                'export'=>'pdf,print',
  12702.                 'data' => $dt,
  12703.                 'cartonData' => $cartonData,
  12704.                 'product' => $product,
  12705. //                'productByCodeData' => $productByCodeData,
  12706.                 'colorText' => $colorText,
  12707.                 'weightText' => $weightText,
  12708.                 'repeatCount' => $repeatCount,
  12709.                 'labelData' => $labelData,
  12710. //                'item_id' => $item_id,
  12711.                 'approval_data' => [],
  12712.                 'document_log' => [],
  12713.                 'document_mark_image' => $document_mark['original'],
  12714.                 'company_name' => $company_data->getName(),
  12715.                 'company_data' => $company_data,
  12716.                 'company_address' => $company_data->getAddress(),
  12717.                 'company_image' => $company_data->getImage(),
  12718.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12719.                 'red' => 0
  12720.             )
  12721.         );
  12722.     }
  12723.     public function AssignInfoToProductByCodeAction(Request $request$id)
  12724.     {
  12725.         $em $this->getDoctrine()->getManager();
  12726.         $companyId $this->getLoggedUserCompanyId($request);
  12727. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12728.         $cartonId '';
  12729.         $passStatus 5;
  12730.         $assignProductId '';
  12731.         $assignProductionId '';
  12732.         $assignProductionScheduleId '';
  12733.         $gbWeightGm '';
  12734.         $dvWeightGm '';
  12735.         $cartonWeightGm '';
  12736.         if ($request->request->has('cartonId'))
  12737.             $cartonId $request->request->get('cartonId');
  12738.         if ($request->request->has('passStatus'))
  12739.             $passStatus $request->request->get('passStatus');
  12740.         if ($request->request->has('productByCodeId'))
  12741.             $id $request->request->get('productByCodeId');
  12742.         if ($request->request->has('productId'))
  12743.             $assignProductId $request->request->get('productId');
  12744.         if ($request->request->has('productionId'))
  12745.             $assignProductionId $request->request->get('productionId');
  12746.         if ($request->request->has('productionScheduleId'))
  12747.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  12748.         if ($request->request->has('gbWeightGm'))
  12749.             $gbWeightGm $request->request->get('gbWeightGm');
  12750.         if ($request->request->has('dvWeightGm'))
  12751.             $dvWeightGm $request->request->get('dvWeightGm');
  12752.         if ($request->request->has('cartonWeightGm'))
  12753.             $cartonWeightGm $request->request->get('cartonWeightGm');
  12754.         $cartonAssignedAlready 0;
  12755.         $otherData = array(
  12756.             'currentCartonBalance' => 0,
  12757.             'currentCartonCapacity' => 0,
  12758.             'currentCartonAssigned' => 0,
  12759.             'currentCartonFull' => 0,
  12760.         );
  12761.         if ($id != && $id != '') {
  12762.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12763.                 ->findOneBy(
  12764.                     array(
  12765.                         'productByCodeId' => $id
  12766.                     )
  12767.                 );
  12768.             if ($assignProductId != ''$productByCodeData->setProductId($assignProductId);
  12769.             if ($productByCodeData->getCartonId() != '' || $productByCodeData->getCartonId() != null)
  12770.                 $cartonAssignedAlready 1;
  12771.             else if ($cartonId != ''$productByCodeData->setCartonId($cartonId);
  12772.             if ($dvWeightGm != ''$productByCodeData->setSingleWeightGm($dvWeightGm);
  12773.             if ($gbWeightGm != '') {
  12774.                 $productByCodeData->setPackagedWeightGm($gbWeightGm);
  12775.             }
  12776.             $colorText '_NA_';
  12777.             if ($passStatus != 5$productByCodeData->setStage($passStatus);
  12778.             $productByCodeData->setCompanyId($companyId);
  12779.             if ($assignProductionId != '') {
  12780.                 $productByCodeData->setProductionId($assignProductionId);
  12781.                 $productionData $em->getRepository('ApplicationBundle\\Entity\\Production')
  12782.                     ->findOneBy(
  12783.                         array(
  12784.                             'productionId' => $assignProductionId
  12785.                         )
  12786.                     );
  12787.                 if ($assignProductId != '' && $assignProductId != null && $assignProductId != 0)
  12788.                     $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  12789.                         array(
  12790.                             'productionId' => $assignProductionId,
  12791.                             'productId' => $assignProductId,
  12792.                             'type' => 1,
  12793.                         )
  12794.                     );
  12795.                 else
  12796.                     $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  12797.                         array(
  12798.                             'productionId' => $assignProductionId,
  12799. //                            'productId' => $assignProductId,
  12800.                             'type' => 1,
  12801.                         )
  12802.                     );
  12803.                 $assignProductionScheduleId $productionData->getProductionScheduleId();
  12804.                 if ($productionItemData) {
  12805.                     $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  12806.                     $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  12807.                     $productByCodeData->setPosition(1);//in inventory
  12808.                     $productByCodeData->setSerialAssigned(1);
  12809.                     $productByCodeData->setColorId($productionItemData->getColorId());
  12810.                     $productByCodeData->setColorText($productionItemData->getColorText());
  12811.                     $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  12812.                     $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  12813.                     if ($passStatus == 1)//passed
  12814.                     {
  12815. //                    $transDate = new \DateTime();
  12816. //                    Inventory::addItemToInventoryCompact($em,
  12817. //                        $productionItemData->getProductId(),
  12818. //                        $productionItemData->getWarehouseId(),
  12819. //                        $productionItemData->getWarehouseId(),
  12820. //                        $productionData->getProducedItemActionTagId(),
  12821. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  12822. //                        $transDate,
  12823. //                        1,
  12824. //                        1,
  12825. //                        $entry['valueAdd'],
  12826. //                        $entry['valueSub'],
  12827. //                        $entry['price'],
  12828. //                        $this->getLoggedUserCompanyId($request),
  12829. //                        0,
  12830. //                        $entry['entity'],
  12831. //                        $entry['entityId'],
  12832. //                        $entry['entityDocHash']
  12833. //                    );
  12834.                     }
  12835.                     $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  12836.                     if ($transHistory == null)
  12837.                         $transHistory = [];
  12838.                     $transHistory[] = array(
  12839.                         'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  12840.                         'direction' => 'in',
  12841.                         'warehouseId' => $productionItemData->getWarehouseId(),
  12842.                         'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  12843.                         'fromWarehouseId' => 0,
  12844.                         'fromWarehouseActionId' => //stock of goods
  12845.                     );
  12846.                     $productByCodeData->setTransactionHistory(json_encode($transHistory));
  12847.                 }
  12848.             }
  12849.             if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  12850.                 $productByCodeData->setProductionScheduleId($assignProductionScheduleId);
  12851.                 $productionSchedule $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  12852.                     ->findOneBy(
  12853.                         array(
  12854.                             'productionScheduleId' => $assignProductionScheduleId
  12855.                         )
  12856.                     );
  12857.                 if ($productionSchedule) {
  12858.                     $productByCodeData->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  12859.                     $productByCodeData->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  12860.                     $productByCodeData->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  12861.                     $productByCodeData->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  12862.                     if ($productByCodeData->getProductionId() == null || $productByCodeData->getProductionId() == '' || $productByCodeData->getProductionId() == 0) {
  12863.                         $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  12864.                             array(
  12865.                                 'productionScheduleId' => $assignProductionScheduleId,
  12866.                                 'productId' => $productionSchedule->getProducedProductId(),
  12867.                                 'type' => 1,
  12868.                             )
  12869.                         );
  12870. //                        $assignProductionScheduleId=$productionData->getProductionScheduleId();
  12871.                         if ($productionItemData) {
  12872.                             $productByCodeData->setProductionId($productionItemData->getProductionId());
  12873.                             $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  12874.                             $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  12875.                             $productByCodeData->setPosition(1);//in inventory
  12876.                             $productByCodeData->setSerialAssigned(1);
  12877.                             $productByCodeData->setColorId($productionItemData->getColorId());
  12878.                             $productByCodeData->setColorText($productionItemData->getColorText());
  12879.                             $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  12880.                             $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  12881.                             if ($passStatus == 1)//passed
  12882.                             {
  12883. //                    $transDate = new \DateTime();
  12884. //                    Inventory::addItemToInventoryCompact($em,
  12885. //                        $productionItemData->getProductId(),
  12886. //                        $productionItemData->getWarehouseId(),
  12887. //                        $productionItemData->getWarehouseId(),
  12888. //                        $productionData->getProducedItemActionTagId(),
  12889. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  12890. //                        $transDate,
  12891. //                        1,
  12892. //                        1,
  12893. //                        $entry['valueAdd'],
  12894. //                        $entry['valueSub'],
  12895. //                        $entry['price'],
  12896. //                        $this->getLoggedUserCompanyId($request),
  12897. //                        0,
  12898. //                        $entry['entity'],
  12899. //                        $entry['entityId'],
  12900. //                        $entry['entityDocHash']
  12901. //                    );
  12902.                             }
  12903.                             $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  12904.                             if ($transHistory == null)
  12905.                                 $transHistory = [];
  12906.                             $transHistory[] = array(
  12907.                                 'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  12908.                                 'direction' => 'in',
  12909.                                 'warehouseId' => $productionItemData->getWarehouseId(),
  12910.                                 'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  12911.                                 'fromWarehouseId' => 0,
  12912.                                 'fromWarehouseActionId' => //stock of goods
  12913.                             );
  12914.                             $productByCodeData->setTransactionHistory(json_encode($transHistory));
  12915.                         }
  12916.                     }
  12917.                 }
  12918.             }
  12919. //                $productByCodeData->setPurchaseWarrantyLastDate($new_pwld);
  12920.             $em->flush();
  12921.             //now adding carton
  12922.         }
  12923.         if ($cartonId != '') {
  12924.             $carton $em->getRepository('ApplicationBundle\\Entity\\Carton')
  12925.                 ->findOneBy(
  12926.                     array(
  12927.                         'id' => $cartonId
  12928.                     )
  12929.                 );
  12930.             if ($cartonWeightGm != ''$carton->setCartonWeightGm($cartonWeightGm);
  12931.             $otherData['currentCartonCapacity'] = $carton->getCartonCapacityCount();
  12932.             if ($cartonAssignedAlready == 0)
  12933.                 $carton->setCartonAssignedCount(($carton->getCartonAssignedCount()) + 1);
  12934.             $otherData['currentCartonAssigned'] = $carton->getCartonAssignedCount();
  12935.             $otherData['currentCartonBalance'] = $otherData['currentCartonCapacity'] - $otherData['currentCartonAssigned'];
  12936.             if ($otherData['currentCartonAssigned'] >= $otherData['currentCartonCapacity'])
  12937.                 $otherData['currentCartonFull'] = 1;
  12938.             $em->flush();
  12939.         }
  12940.         if ($cartonId != '') {
  12941. //                    if($cartonAssignedAlready==1)
  12942. //                    {
  12943.             $productByCodeDataListForThisCarton $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12944.                 ->findBy(
  12945.                     array(
  12946.                         'cartonId' => $cartonId
  12947.                     )
  12948.                 );
  12949.             $carton $em->getRepository('ApplicationBundle\\Entity\\Carton')
  12950.                 ->findOneBy(
  12951.                     array(
  12952.                         'id' => $cartonId
  12953.                     )
  12954.                 );
  12955.             $total_carton_predicted_weight 0;
  12956.             $colorTextList = [];
  12957.             $cartonProductByCodeIds = [];
  12958.             foreach ($productByCodeDataListForThisCarton as $pikamaster) {
  12959.                 if (!in_array($pikamaster->getProductByCodeId(), $cartonProductByCodeIds))
  12960.                     $cartonProductByCodeIds[] = $pikamaster->getProductByCodeId();
  12961.                 if (!in_array($pikamaster->getColorText(), $colorTextList) && $pikamaster->getColorText() != null)
  12962.                     $colorTextList[] = $pikamaster->getColorText();
  12963.                 $total_carton_predicted_weight += ($pikamaster->getPackagedWeightGm());
  12964.                 if ($passStatus != 5)
  12965.                     if ($pikamaster->getStage() < $passStatus)
  12966.                         $pikamaster->setStage($passStatus);
  12967.             }
  12968.             if ($carton)
  12969.                 $carton->setCartonCalculatedWeightGm($total_carton_predicted_weight);
  12970.             if ($passStatus != 5)
  12971.                 $carton->setStage($passStatus);
  12972.             $carton->setColors(implode(','$colorTextList));
  12973.             $carton->setCartonProductByCodeIds(json_encode($cartonProductByCodeIds));
  12974.             $em->flush();
  12975.         }
  12976.         return new JsonResponse(array(
  12977.             'success' => true,
  12978.             'otherData' => $otherData,
  12979.         ));
  12980.     }
  12981.     public function RefreshCartonListAction(Request $request$id)
  12982.     {
  12983.         $em $this->getDoctrine()->getManager();
  12984. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12985.         $cartonListArray = [];
  12986.         $cartonList = [];
  12987.         $assignableCartonList = [];
  12988.         $assignableCartonListArray = [];
  12989.         $assignable 0;
  12990.         $cartonId '';
  12991.         $passStatus 5;
  12992.         $assignProductId '';
  12993.         $assignProductionId '';
  12994.         $assignProductionScheduleId '';
  12995.         if ($request->request->has('productionId'))
  12996.             $assignProductionId $request->request->get('productionId');
  12997.         if ($request->request->has('productionScheduleId'))
  12998.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  12999.         if ($request->request->has('assignable'))
  13000.             $assignable $request->request->get('assignable');
  13001.         $cartonAssignedAlready 0;
  13002.         $otherData = array(
  13003.             'currentCartonBalance' => 0,
  13004.             'currentCartonCapacity' => 0,
  13005.             'currentCartonAssigned' => 0,
  13006.             'currentCartonFull' => 0,
  13007.         );
  13008.         //1st get all cartons for this production id
  13009.         $cartonList $em->getRepository('ApplicationBundle\\Entity\\Carton')
  13010.             ->findBy(
  13011.                 array(
  13012. //                    'productionId' => $assignProductionId,
  13013.                     'productionScheduleId' => $assignProductionScheduleId
  13014.                 )
  13015.             );
  13016.         $foundAssignable 0;
  13017.         $setId 0;
  13018.         $lastdmySer '';
  13019.         foreach ($cartonList as $carton) {
  13020.             $cartonData = array(
  13021.                 'id' => $carton->getId(),
  13022.                 'name' => $carton->getCartonNumber(),
  13023.                 'colors' => $carton->getColors(),
  13024.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  13025.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  13026.             );
  13027.             $cartonListArray[] = $cartonData;
  13028.             $cartonList[$cartonData['id']] = $cartonData;
  13029.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  13030.                 $foundAssignable 1;
  13031.                 $setId $cartonData['id'];
  13032.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  13033.                 $assignableCartonListArray[] = $cartonData;
  13034.             }
  13035.         }
  13036.         if ($assignable == && $foundAssignable == 0) {
  13037. //            $productionData = $em->getRepository('ApplicationBundle\\Entity\\Production')
  13038. //                ->findOneBy(
  13039. //                    array(
  13040. //                        'productionId' => $assignProductionId
  13041. //                    )
  13042. //                );
  13043.             $productionScheduleData $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  13044.                 ->findOneBy(
  13045.                     array(
  13046.                         'productionScheduleId' => $assignProductionScheduleId
  13047.                     )
  13048.                 );
  13049.             $productId 0;
  13050.             $product = [];
  13051.             $productModel '';
  13052.             if ($productionScheduleData)
  13053.                 $productId $productionScheduleData->getProducedProductId();
  13054. //            $productionItem = $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')
  13055. //                ->findOneBy(
  13056. //                    array(
  13057. //                        'productionId' => $assignProductionId,
  13058. //                        'type' => 1
  13059. //                    )
  13060. //                );
  13061.             if ($productId != 0) {
  13062. //                    $productId = $productionItem->getProductId();
  13063.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  13064.                     ->findOneBy(
  13065.                         array(
  13066.                             'id' => $productId,
  13067.                         )
  13068.                     );
  13069.                 $productModel $product->getModelNo();
  13070.             }
  13071.             $carton = new Carton();
  13072.             $carton_capacity $productionScheduleData->getCartonCapacity();
  13073.             $carton->setProductId($productId);
  13074.             $carton->setProductionId($assignProductionId);
  13075.             $carton->setProductionScheduleId($assignProductionScheduleId);
  13076.             if ($productionScheduleData) {
  13077.                 $carton->setCartonLabelFormatId($productionScheduleData->getCartonLabelFormatId());
  13078.             }
  13079.             $carton->setCartonCapacityCount($carton_capacity == null $carton_capacity);
  13080.             $carton->setCartonAssignedCount(0);
  13081.             $carton->setCompanyId($this->getLoggedUserCompanyId($request));
  13082.             $today = new \DateTime();
  13083.             $dmy $productModel '-' . ($today->format('m')) . '-' . ($today->format('Y')) . '-' $productionScheduleData->getBatchNumber();
  13084.             $ser 0;
  13085.             $carton->setCartonNumberDmy($dmy);
  13086.             $carton->setCartonNumberLastSer(* (($today->format('h')) . '' . ($today->format('i'))));
  13087.             $carton->setCartonNumber($dmy '-' . ($today->format('h')) . '' . ($today->format('i')));
  13088.             $em->persist($carton);
  13089.             $em->flush();
  13090.             $cartonData = array(
  13091.                 'id' => $carton->getId(),
  13092.                 'name' => $carton->getCartonNumber(),
  13093.                 'colors' => $carton->getColors(),
  13094.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  13095.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  13096.             );
  13097.             $cartonListArray[] = $cartonData;
  13098.             $cartonList[$cartonData['id']] = $cartonData;
  13099.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  13100.                 $foundAssignable 1;
  13101.                 $setId $cartonData['id'];
  13102.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  13103.                 $assignableCartonListArray[] = $cartonData;
  13104.             }
  13105.         }
  13106.         return new JsonResponse(array(
  13107.             'success' => true,
  13108.             'cartonList' => $cartonList,
  13109.             'cartonListArray' => $cartonListArray,
  13110.             'assignableCartonList' => $assignableCartonList,
  13111.             'assignableCartonListArray' => $assignableCartonListArray,
  13112.             'setId' => $setId,
  13113.         ));
  13114.     }
  13115.     public
  13116.     function PrintDrBarcodeAction(Request $request$id$item_id)
  13117.     {
  13118.         $em $this->getDoctrine()->getManager();
  13119.         $dt Inventory::GetDrDetails($em$id$item_id);
  13120.         $repeatCount 1;
  13121.         if ($request->query->has('repeatCount'))
  13122.             $repeatCount $request->query->get('repeatCount');
  13123.         $company_data Company::getCompanyData($em1);
  13124.         $document_mark = array(
  13125.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13126.             'copy' => ''
  13127.         );
  13128.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13129.             $html $this->renderView('@Inventory/pages/print/print_dr_barcodes.html.twig',
  13130.                 array(
  13131.                     //full array here
  13132.                     'pdf' => true,
  13133.                     'page_title' => 'Challan Barcodes',
  13134.                     'export' => 'print',
  13135.                     'repeatCount' => $repeatCount,
  13136.                     'item_id' => $item_id,
  13137.                     'data' => $dt,
  13138.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13139.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13140.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13141.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  13142.                         $id,
  13143.                         $dt['created_by'],
  13144.                         $dt['edited_by']),
  13145.                     'document_mark_image' => $document_mark['original'],
  13146.                     'company_name' => $company_data->getName(),
  13147.                     'company_data' => $company_data,
  13148.                     'company_address' => $company_data->getAddress(),
  13149.                     'company_image' => $company_data->getImage(),
  13150.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13151.                     'red' => 0
  13152.                 )
  13153.             );
  13154.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13155. //                'orientation' => 'landscape',
  13156.                 'enable-javascript' => true,
  13157. //                'javascript-delay' => 1000,
  13158.                 'no-stop-slow-scripts' => false,
  13159.                 'no-background' => false,
  13160.                 'lowquality' => false,
  13161.                 'encoding' => 'utf-8',
  13162. //            'images' => true,
  13163. //            'cookie' => array(),
  13164.                 'dpi' => 300,
  13165.                 'image-dpi' => 300,
  13166. //                'enable-external-links' => true,
  13167. //                'enable-internal-links' => true
  13168.             ));
  13169.             return new Response(
  13170.                 $pdf_response,
  13171.                 200,
  13172.                 array(
  13173.                     'Content-Type' => 'application/pdf',
  13174.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  13175.                 )
  13176.             );
  13177.         }
  13178.         return $this->render('@Inventory/pages/print/print_dr_barcodes.html.twig',
  13179.             array(
  13180.                 'page_title' => 'Challan barcodes',
  13181. //                'export'=>'pdf,print',
  13182.                 'data' => $dt,
  13183.                 'repeatCount' => $repeatCount,
  13184.                 'item_id' => $item_id,
  13185.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13186.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13187.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13188.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  13189.                     $id,
  13190.                     $dt['created_by'],
  13191.                     $dt['edited_by']),
  13192.                 'document_mark_image' => $document_mark['original'],
  13193.                 'company_name' => $company_data->getName(),
  13194.                 'company_data' => $company_data,
  13195.                 'company_address' => $company_data->getAddress(),
  13196.                 'company_image' => $company_data->getImage(),
  13197.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13198.                 'red' => 0
  13199.             )
  13200.         );
  13201.     }
  13202.     public
  13203.     function PrintIrrBarcodeAction(Request $request$id$item_id)
  13204.     {
  13205.         $em $this->getDoctrine()->getManager();
  13206.         $dt Inventory::GetIrrDetails($em$id$item_id);
  13207.         $repeatCount 1;
  13208.         if ($request->query->has('repeatCount'))
  13209.             $repeatCount $request->query->get('repeatCount');
  13210.         $company_data Company::getCompanyData($em1);
  13211.         $document_mark = array(
  13212.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13213.             'copy' => ''
  13214.         );
  13215.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13216.             $html $this->renderView('@Inventory/pages/print/print_irr_barcodes.html.twig',
  13217.                 array(
  13218.                     //full array here
  13219.                     'pdf' => true,
  13220.                     'page_title' => 'Sales Return Barcodes',
  13221.                     'export' => 'print',
  13222.                     'repeatCount' => $repeatCount,
  13223.                     'item_id' => $item_id,
  13224.                     'data' => $dt,
  13225.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13226.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13227.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13228.                         array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13229.                         $id,
  13230.                         $dt['created_by'],
  13231.                         $dt['edited_by']),
  13232.                     'document_mark_image' => $document_mark['original'],
  13233.                     'company_name' => $company_data->getName(),
  13234.                     'company_data' => $company_data,
  13235.                     'company_address' => $company_data->getAddress(),
  13236.                     'company_image' => $company_data->getImage(),
  13237.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13238.                     'red' => 0
  13239.                 )
  13240.             );
  13241.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13242. //                'orientation' => 'landscape',
  13243.                 'enable-javascript' => true,
  13244. //                'javascript-delay' => 1000,
  13245.                 'no-stop-slow-scripts' => false,
  13246.                 'no-background' => false,
  13247.                 'lowquality' => false,
  13248.                 'encoding' => 'utf-8',
  13249. //            'images' => true,
  13250. //            'cookie' => array(),
  13251.                 'dpi' => 300,
  13252.                 'image-dpi' => 300,
  13253. //                'enable-external-links' => true,
  13254. //                'enable-internal-links' => true
  13255.             ));
  13256.             return new Response(
  13257.                 $pdf_response,
  13258.                 200,
  13259.                 array(
  13260.                     'Content-Type' => 'application/pdf',
  13261.                     'Content-Disposition' => 'attachment; filename="irr_barcodes.pdf"'
  13262.                 )
  13263.             );
  13264.         }
  13265.         return $this->render('@Inventory/pages/print/print_irr_barcodes.html.twig',
  13266.             array(
  13267.                 'page_title' => 'Sales Return barcodes',
  13268. //                'export'=>'pdf,print',
  13269.                 'data' => $dt,
  13270.                 'repeatCount' => $repeatCount,
  13271.                 'item_id' => $item_id,
  13272.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13273.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13274.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13275.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13276.                     $id,
  13277.                     $dt['created_by'],
  13278.                     $dt['edited_by']),
  13279.                 'document_mark_image' => $document_mark['original'],
  13280.                 'company_name' => $company_data->getName(),
  13281.                 'company_data' => $company_data,
  13282.                 'company_address' => $company_data->getAddress(),
  13283.                 'company_image' => $company_data->getImage(),
  13284.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13285.                 'red' => 0
  13286.             )
  13287.         );
  13288.     }
  13289.     public
  13290.     function PrintSrcvBarcodeAction(Request $request$id$item_id)
  13291.     {
  13292.         $em $this->getDoctrine()->getManager();
  13293.         $dt Inventory::GetSrcvDetails($em$id$item_id);
  13294.         $repeatCount 1;
  13295.         if ($request->query->has('repeatCount'))
  13296.             $repeatCount $request->query->get('repeatCount');
  13297.         $company_data Company::getCompanyData($em1);
  13298.         $document_mark = array(
  13299.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13300.             'copy' => ''
  13301.         );
  13302.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13303.             $html $this->renderView('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  13304.                 array(
  13305.                     //full array here
  13306.                     'pdf' => true,
  13307.                     'page_title' => 'Grn Barcodes',
  13308.                     'export' => 'print',
  13309.                     'repeatCount' => $repeatCount,
  13310.                     'item_id' => $item_id,
  13311.                     'data' => $dt,
  13312.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13313.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13314.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13315.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13316.                         $id,
  13317.                         $dt['created_by'],
  13318.                         $dt['edited_by']),
  13319.                     'document_mark_image' => $document_mark['original'],
  13320.                     'company_name' => $company_data->getName(),
  13321.                     'company_data' => $company_data,
  13322.                     'company_address' => $company_data->getAddress(),
  13323.                     'company_image' => $company_data->getImage(),
  13324.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13325.                     'red' => 0
  13326.                 )
  13327.             );
  13328.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13329. //                'orientation' => 'landscape',
  13330.                 'enable-javascript' => true,
  13331. //                'javascript-delay' => 1000,
  13332.                 'no-stop-slow-scripts' => false,
  13333.                 'no-background' => false,
  13334.                 'lowquality' => false,
  13335.                 'encoding' => 'utf-8',
  13336. //            'images' => true,
  13337. //            'cookie' => array(),
  13338.                 'dpi' => 300,
  13339.                 'image-dpi' => 300,
  13340. //                'enable-external-links' => true,
  13341. //                'enable-internal-links' => true
  13342.             ));
  13343.             return new Response(
  13344.                 $pdf_response,
  13345.                 200,
  13346.                 array(
  13347.                     'Content-Type' => 'application/pdf',
  13348.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  13349.                 )
  13350.             );
  13351.         }
  13352.         return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  13353.             array(
  13354.                 'page_title' => 'Srcv barcodes',
  13355. //                'export'=>'pdf,print',
  13356.                 'data' => $dt,
  13357.                 'repeatCount' => $repeatCount,
  13358.                 'item_id' => $item_id,
  13359.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13360.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13361.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13362.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13363.                     $id,
  13364.                     $dt['created_by'],
  13365.                     $dt['edited_by']),
  13366.                 'document_mark_image' => $document_mark['original'],
  13367.                 'company_name' => $company_data->getName(),
  13368.                 'company_data' => $company_data,
  13369.                 'company_address' => $company_data->getAddress(),
  13370.                 'company_image' => $company_data->getImage(),
  13371.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13372.                 'red' => 0
  13373.             )
  13374.         );
  13375.     }
  13376. //product by code
  13377.     public function ImeiListExcelUploadAction(Request $request)
  13378.     {
  13379.         $lastIndex $request->request->get('lastIndex'0);
  13380.         if ($request->isMethod('POST')) {
  13381.             $post $request->request;
  13382.             if ($request->request->has('chunkData')) {
  13383.                 //now getting the relevant checks
  13384.                 $check_list = [];
  13385.                 $csv_data $request->request->get('chunkData', []);
  13386.                 $em $this->getDoctrine()->getManager();
  13387.                 foreach ($csv_data as $ind => $data_row) {
  13388. //                    if ($ind == 1)
  13389. //                        continue;
  13390.                     $np $this->getDoctrine()
  13391.                         ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  13392.                         ->findOneBy(
  13393.                             array(
  13394.                                 'salesCode' => isset($data_row[4]) ? $data_row[4] : 0,
  13395. //                    'approved' =>  GeneralConstant::APPROVED,
  13396.                             )
  13397.                         );
  13398.                     if (!$np)
  13399.                         $np = new ProductByCode();
  13400. //                    $np = new ProductByCode();
  13401.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  13402.                     if (isset($data_row[1])) $np->setProductId($data_row[1]);
  13403.                     if (isset($data_row[0])) $np->setLcNumber($data_row[0]);
  13404.                     if (isset($data_row[2])) $np->setCartonNumber($data_row[2]);
  13405.                     if (isset($data_row[3])) $np->setSerialNo($data_row[3]);
  13406.                     $np->setSerialAssigned(isset($data_row[10]) ? $data_row[10] : 0);
  13407.                     if (isset($data_row[4])) $np->setImei1($data_row[4]);
  13408.                     if (isset($data_row[5])) $np->setImei2($data_row[5]);
  13409.                     if (isset($data_row[6])) $np->setImei3($data_row[6]);
  13410.                     if (isset($data_row[7])) $np->setImei4($data_row[7]);
  13411.                     if (isset($data_row[8])) $np->setBtMac($data_row[8]);
  13412.                     if (isset($data_row[9])) $np->setWlanMac($data_row[9]);
  13413.                     $np->setWarehouseId(isset($data_row[11]) ? $data_row[11] : 0);
  13414.                     $np->setWarehouseActionId(isset($data_row[12]) ? $data_row[12] : 0);
  13415.                     $np->setPosition(isset($data_row[13]) ? $data_row[13] : 0);//in inventory
  13416.                     $np->setPurchaseOrderId(0);
  13417.                     $np->setGrnId(0);
  13418.                     $np->setStage(0);
  13419.                     if (isset($data_row[3])) $np->setSalesCodeRange(json_encode([$data_row[3]]));
  13420. //                $np->setSalesCode($data_row[3]);
  13421.                     if (isset($data_row[4])) $np->setSalesCode($data_row[4]); //IMEI
  13422.                     $np->setSalesCodeSer(0);
  13423.                     $np->setSalesCodeDmy('');
  13424.                     $np->setPurchaseCodeRange("");
  13425.                     $np->setPurchaseReceiptDate(null);
  13426.                     $np->setLastInDate(null);
  13427.                     $np->setStatus(GeneralConstant::ACTIVE);
  13428.                     $np->setTransactionHistory(json_encode([
  13429.                         ]
  13430.                     ));
  13431.                     $np->setPurchaseWarrantyLastDate(null);
  13432.                     $em->persist($np);
  13433.                     $em->flush();
  13434.                 }
  13435.                 return new JsonResponse(array(
  13436.                     "success" => true,
  13437.                     "lastIndex" => $lastIndex,
  13438.                     "file_path" => '',
  13439.                     "csv_data" => $csv_data,
  13440.                     //                "debug_data"=>System::encryptSignature($r)
  13441.                 ));
  13442.             } else {
  13443.                 $path "";
  13444.                 $file_path "";
  13445.                 //            var_dump($request->files);
  13446.                 //        var_dump($request->getFile());
  13447.                 foreach ($request->files as $uploadedFile) {
  13448.                     //            if($uploadedFile->getImage())
  13449.                     //                var_dump($uploadedFile->getFile());
  13450.                     //                var_dump($uploadedFile);
  13451.                     if ($uploadedFile != null) {
  13452.                         $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  13453.                         $path $fileName;
  13454.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  13455.                         if (!file_exists($upl_dir)) {
  13456.                             mkdir($upl_dir0777true);
  13457.                         }
  13458.                         $file $uploadedFile->move($upl_dir$path);
  13459.                     }
  13460.                 }
  13461.                 //        print_r($file);
  13462.                 if ($path != "")
  13463.                     $file_path 'uploads/FileUploads/' $path;
  13464.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  13465.                 //
  13466.                 //            $img_file = file_get_contents($g_path);
  13467.                 //            $r=base64_encode($img_file);
  13468.                 $row 1;
  13469.                 $csv_data = [];
  13470.                 if (($handle fopen($g_path"r")) !== FALSE) {
  13471.                     while (($data fgetcsv($handle1000",")) !== FALSE) {
  13472.                         $num count($data);
  13473.                         $csv_data[$row] = $data;
  13474.                         //                    echo "<p> $num fields in line $row: <br /></p>\n";
  13475.                         $row++;
  13476.                         //                    for ($c=0; $c < $num; $c++) {
  13477.                         //                        echo $data[$c] . "<br />\n";
  13478.                         //                    }
  13479.                     }
  13480.                     fclose($handle);
  13481.                 }
  13482.                 //now getting the relevant checks
  13483.                 $check_list = [];
  13484.                 $em $this->getDoctrine()->getManager();
  13485.                 foreach ($csv_data as $ind => $data_row) {
  13486.                     if ($ind == 1)
  13487.                         continue;
  13488.                     $np = new ProductByCode();
  13489.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  13490.                     $np->setProductId($data_row[1]);
  13491.                     $np->setLcNumber($data_row[0]);
  13492.                     $np->setCartonNumber($data_row[2]);
  13493.                     $np->setSerialNo($data_row[3]);
  13494.                     $np->setSerialAssigned(0);
  13495.                     $np->setImei1($data_row[4]);
  13496.                     $np->setImei2($data_row[5]);
  13497.                     $np->setImei3($data_row[6]);
  13498.                     $np->setImei4($data_row[7]);
  13499.                     $np->setBtMac($data_row[8]);
  13500.                     $np->setWlanMac($data_row[9]);
  13501.                     $np->setWarehouseId(0);
  13502.                     $np->setWarehouseActionId(0);
  13503.                     $np->setPosition(0);//in inventory
  13504.                     $np->setPurchaseOrderId(0);
  13505.                     $np->setGrnId(0);
  13506.                     $np->setStage(0);
  13507.                     $np->setSalesCodeRange(json_encode([$data_row[3]]));
  13508. //                $np->setSalesCode($data_row[3]);
  13509.                     $np->setSalesCode($data_row[4]); //IMEI
  13510.                     $np->setSalesCodeSer(0);
  13511.                     $np->setSalesCodeDmy('');
  13512.                     $np->setPurchaseCodeRange("");
  13513.                     $np->setPurchaseReceiptDate(null);
  13514.                     $np->setLastInDate(null);
  13515.                     $np->setStatus(GeneralConstant::ACTIVE);
  13516.                     $np->setTransactionHistory(json_encode([
  13517.                         ]
  13518.                     ));
  13519.                     $np->setPurchaseWarrantyLastDate(null);
  13520.                     $em->persist($np);
  13521.                     $em->flush();
  13522.                 }
  13523.                 return new JsonResponse(array(
  13524.                     "success" => true,
  13525.                     "lastIndex" => $lastIndex,
  13526.                     "file_path" => $file_path,
  13527.                     "csv_data" => $csv_data,
  13528.                     //                "debug_data"=>System::encryptSignature($r)
  13529.                 ));
  13530.             }
  13531.         }
  13532.         return new JsonResponse(array(
  13533.             "success" => false,
  13534.             "file_path" => '',
  13535.             "csv_data" => [],
  13536.             "lastIndex" => $lastIndex,
  13537.         ));
  13538.     }
  13539.     public
  13540.     function ProductByCodeListAction(Request $request)
  13541.     {
  13542.         $em $this->getDoctrine()->getManager();
  13543.         $companyId $this->getLoggedUserCompanyId($request);
  13544.         $listData Inventory::GetProductListForProductByCodeListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  13545.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  13546.             if ($request->query->has('dataTableQry')) {
  13547.                 return new JsonResponse(
  13548.                     $listData
  13549.                 );
  13550.             }
  13551.         }
  13552.         $q = [];
  13553. //        $q = $this->getDoctrine()
  13554. //            ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  13555. //            ->findBy(
  13556. //                array(
  13557. //                    'status' => GeneralConstant::ACTIVE,
  13558. ////                    'approved' =>  GeneralConstant::APPROVED,
  13559. //                )
  13560. //
  13561. //            );
  13562.         //temp start
  13563. //        foreach($q as $np) {
  13564. //            if($np->getPosition()==1) {   /// only starting ones or in warehouse ones
  13565. //                $temp_obj = json_decode($np->getTransactionHistory());
  13566. //                if ($temp_obj != null) {
  13567. //                    $transHistory = [];
  13568. //                    $transHistory[] = $temp_obj;
  13569. //                    $np->setTransactionHistory(json_encode($transHistory));
  13570. //                }
  13571. //            }
  13572. //            $em->flush();
  13573. //        }
  13574.         ///temp end
  13575.         $stage_list = array(
  13576.             => 'Pending',
  13577.             => 'Pending',
  13578.             => 'Complete',
  13579.             => 'Partial',
  13580.         );
  13581.         $data = [];
  13582. //        foreach($q as $entry)
  13583. //        {
  13584. //            $data[]=array(
  13585. //                'doc_date'=>$entry->getStockRequisitionDate(),
  13586. //                'id'=>$entry->getStockRequisitionId(),
  13587. //                'doc_hash'=>$entry->getDocumentHash(),
  13588. //                'approval_status'=>GeneralConstant::$approvalStatus[$entry->getApproved()],
  13589. //                'stage'=>$stage_list[$entry->getStage()]
  13590. //
  13591. //            );
  13592. //        }
  13593.         return $this->render('@Inventory/pages/views/product_by_code_list.html.twig',
  13594.             array(
  13595.                 'page_title' => 'Product List',
  13596.                 'data' => $q,
  13597. //                'listData' => $listData,
  13598.                 'products' => Inventory::ProductList($em),
  13599.                 'warehouseList' => Inventory::WarehouseList($em)
  13600.             )
  13601.         );
  13602.     }
  13603. //SR
  13604.     public
  13605.     function SrListAction(Request $request)
  13606.     {
  13607.         $q $this->getDoctrine()
  13608.             ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  13609.             ->findBy(
  13610.                 array(
  13611.                     'status' => GeneralConstant::ACTIVE,
  13612. //                    'approved' =>  GeneralConstant::APPROVED,
  13613.                 )
  13614.                 ,
  13615.                 array(
  13616.                     'stockRequisitionDate' => 'DESC'
  13617.                 )
  13618.             );
  13619.         $stage_list = array(
  13620.             => 'Pending',
  13621.             => 'Pending',
  13622.             => 'Complete',
  13623.             => 'Partial',
  13624.         );
  13625.         $data = [];
  13626.         foreach ($q as $entry) {
  13627.             $data[] = array(
  13628.                 'doc_date' => $entry->getStockRequisitionDate(),
  13629.                 'id' => $entry->getStockRequisitionId(),
  13630.                 'doc_hash' => $entry->getDocumentHash(),
  13631.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13632.                 'stage' => $stage_list[$entry->getStage()],
  13633.                 'indentTagged' => $entry->getIndentTagged(),
  13634.                 'srIds' => $entry->getSrIds(),
  13635.                 'irIds' => $entry->getIrIds(),
  13636.                 'prIds' => $entry->getPrIds(),
  13637.                 'poIds' => $entry->getPoIds(),
  13638.             );
  13639.         }
  13640.         return $this->render('@Inventory/pages/views/sr_list.html.twig',
  13641.             array(
  13642.                 'page_title' => 'Stock Requisition List',
  13643.                 'data' => $data
  13644.             )
  13645.         );
  13646.     }
  13647.     public
  13648.     function ViewSrAction(Request $request$id)
  13649.     {
  13650.         $em $this->getDoctrine()->getManager();
  13651.         $dt Inventory::GetSrDetails($em$id);
  13652.         return $this->render(
  13653.             '@Inventory/pages/views/view_stock_requisition.html.twig',
  13654.             array(
  13655.                 'page_title' => 'Stock requisition',
  13656.                 'data' => $dt,
  13657.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13658.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13659.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13660.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13661.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13662.                     $id,
  13663.                     $dt['created_by'],
  13664.                     $dt['edited_by'])
  13665.             )
  13666.         );
  13667.     }
  13668.     public
  13669.     function PrintSrAction(Request $request$id)
  13670.     {
  13671.         $em $this->getDoctrine()->getManager();
  13672.         $dt Inventory::GetSrDetails($em$id);
  13673.         $company_data Company::getCompanyData($em1);
  13674.         $document_mark = array(
  13675.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13676.             'copy' => ''
  13677.         );
  13678.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13679.             $html $this->renderView('@Inventory/pages/print/print_sr.html.twig',
  13680.                 array(
  13681.                     //full array here
  13682.                     'pdf' => true,
  13683.                     'page_title' => 'Stock Requisition',
  13684.                     'export' => 'pdf,print',
  13685.                     'data' => $dt,
  13686.                     'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13687.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13688.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13689.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13690.                         array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13691.                         $id,
  13692.                         $dt['created_by'],
  13693.                         $dt['edited_by']),
  13694.                     'document_mark_image' => $document_mark['original'],
  13695.                     'company_name' => $company_data->getName(),
  13696.                     'company_data' => $company_data,
  13697.                     'company_address' => $company_data->getAddress(),
  13698.                     'company_image' => $company_data->getImage(),
  13699.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13700.                     'red' => 0
  13701.                 )
  13702.             );
  13703.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13704.                 //     'orientation' => 'landscape',
  13705.                 //     'enable-javascript' => true,
  13706.                 //     'javascript-delay' => 1000,
  13707.                 'no-stop-slow-scripts' => false,
  13708.                 'no-background' => false,
  13709.                 'lowquality' => false,
  13710.                 'encoding' => 'utf-8',
  13711.                 //    'images' => true,
  13712.                 //    'cookie' => array(),
  13713.                 'dpi' => 300,
  13714.                 'image-dpi' => 300,
  13715.                 //    'enable-external-links' => true,
  13716.                 //    'enable-internal-links' => true
  13717.             ));
  13718.             return new Response(
  13719.                 $pdf_response,
  13720.                 200,
  13721.                 array(
  13722.                     'Content-Type' => 'application/pdf',
  13723.                     'Content-Disposition' => 'attachment; filename="stock_requisition_' $id '.pdf"'
  13724.                 )
  13725.             );
  13726.         }
  13727.         return $this->render('@Inventory/pages/print/print_sr.html.twig',
  13728.             array(
  13729.                 'page_title' => 'Stock Requisition',
  13730.                 'export' => 'pdf,print',
  13731.                 'data' => $dt,
  13732.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13733.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13734.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13735.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13736.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13737.                     $id,
  13738.                     $dt['created_by'],
  13739.                     $dt['edited_by']),
  13740.                 'document_mark_image' => $document_mark['original'],
  13741.                 'company_name' => $company_data->getName(),
  13742.                 'company_data' => $company_data,
  13743.                 'company_address' => $company_data->getAddress(),
  13744.                 'company_image' => $company_data->getImage(),
  13745.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13746.                 'red' => 0
  13747.             )
  13748.         );
  13749.     }
  13750. //IR
  13751.     public
  13752.     function IrListAction(Request $request)
  13753.     {
  13754.         $q $this->getDoctrine()
  13755.             ->getRepository('ApplicationBundle\\Entity\\StoreRequisition')
  13756.             ->findBy(
  13757.                 array(
  13758.                     'status' => GeneralConstant::ACTIVE,
  13759. //                    'approved' =>  GeneralConstant::APPROVED,
  13760.                 ),
  13761.                 array(
  13762.                     'storeRequisitionDate' => 'DESC'
  13763.                 )
  13764.             );
  13765.         $stage_list = array(
  13766.             => 'Pending',
  13767.             => 'Pending',
  13768.             => 'Complete',
  13769.             => 'Partial',
  13770.         );
  13771.         $data = [];
  13772.         foreach ($q as $entry) {
  13773.             $data[] = array(
  13774.                 'doc_date' => $entry->getStoreRequisitionDate(),
  13775.                 'id' => $entry->getStoreRequisitionId(),
  13776.                 'doc_hash' => $entry->getDocumentHash(),
  13777.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13778.                 'stage' => $stage_list[$entry->getStage()],
  13779.                 'prTagged' => $entry->getIndentTagged(),
  13780.                 'srIds' => $entry->getSrIds(),
  13781.                 'irIds' => $entry->getIrIds(),
  13782.                 'prIds' => $entry->getPrIds(),
  13783.                 'poIds' => $entry->getPoIds(),
  13784.             );
  13785.         }
  13786.         return $this->render('@Inventory/pages/views/ir_list.html.twig',
  13787.             array(
  13788.                 'page_title' => 'Indent Requisition List',
  13789.                 'data' => $data
  13790.             )
  13791.         );
  13792.     }
  13793.     public
  13794.     function ViewIrAction(Request $request$id)
  13795.     {
  13796.         $em $this->getDoctrine()->getManager();
  13797.         $dt Inventory::GetIrDetails($em$id);
  13798.         return $this->render(
  13799.             '@Inventory/pages/views/view_indent_requisition.html.twig',
  13800.             array(
  13801.                 'page_title' => 'Indent',
  13802.                 'data' => $dt,
  13803.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13804.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13805.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13806.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13807.                     $id,
  13808.                     $dt['created_by'],
  13809.                     $dt['edited_by'])
  13810.             )
  13811.         );
  13812.     }
  13813.     public
  13814.     function PrintIrAction(Request $request$id)
  13815.     {
  13816.         $em $this->getDoctrine()->getManager();
  13817.         $dt Inventory::GetIrDetails($em$id);
  13818.         $company_data Company::getCompanyData($em1);
  13819.         $document_mark = array(
  13820.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13821.             'copy' => ''
  13822.         );
  13823.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13824.             $html $this->renderView('@Inventory/pages/print/print_ir.html.twig',
  13825.                 array(
  13826.                     //full array here
  13827.                     'pdf' => true,
  13828.                     'page_title' => 'Indent Requisition',
  13829.                     'export' => 'pdf,print',
  13830.                     'data' => $dt,
  13831.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13832.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13833.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13834.                         array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13835.                         $id,
  13836.                         $dt['created_by'],
  13837.                         $dt['edited_by']),
  13838.                     'document_mark_image' => $document_mark['original'],
  13839.                     'company_name' => $company_data->getName(),
  13840.                     'company_data' => $company_data,
  13841.                     'company_address' => $company_data->getAddress(),
  13842.                     'company_image' => $company_data->getImage(),
  13843.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13844.                     'red' => 0
  13845.                 )
  13846.             );
  13847.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13848. //                'orientation' => 'landscape',
  13849. //                'enable-javascript' => true,
  13850. //                'javascript-delay' => 1000,
  13851.                 'no-stop-slow-scripts' => false,
  13852.                 'no-background' => false,
  13853.                 'lowquality' => false,
  13854.                 'encoding' => 'utf-8',
  13855. //            'images' => true,
  13856. //            'cookie' => array(),
  13857.                 'dpi' => 300,
  13858.                 'image-dpi' => 300,
  13859. //                'enable-external-links' => true,
  13860. //                'enable-internal-links' => true
  13861.             ));
  13862.             return new Response(
  13863.                 $pdf_response,
  13864.                 200,
  13865.                 array(
  13866.                     'Content-Type' => 'application/pdf',
  13867.                     'Content-Disposition' => 'attachment; filename="indent_' $id '.pdf"'
  13868.                 )
  13869.             );
  13870.         }
  13871.         return $this->render('@Inventory/pages/print/print_ir.html.twig',
  13872.             array(
  13873.                 'page_title' => 'Indent Requisition',
  13874.                 'export' => 'pdf,print',
  13875.                 'data' => $dt,
  13876.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13877.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13878.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13879.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13880.                     $id,
  13881.                     $dt['created_by'],
  13882.                     $dt['edited_by']),
  13883.                 'document_mark_image' => $document_mark['original'],
  13884.                 'company_name' => $company_data->getName(),
  13885.                 'company_data' => $company_data,
  13886.                 'company_address' => $company_data->getAddress(),
  13887.                 'company_image' => $company_data->getImage(),
  13888.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13889.                 'red' => 0
  13890.             )
  13891.         );
  13892.     }
  13893. //PR
  13894.     public
  13895.     function PrListAction(Request $request)
  13896.     {
  13897.         $q $this->getDoctrine()
  13898.             ->getRepository('ApplicationBundle\\Entity\\PurchaseRequisition')
  13899.             ->findBy(
  13900.                 array(
  13901.                     'status' => GeneralConstant::ACTIVE,
  13902. //                    'approved' =>  GeneralConstant::APPROVED,
  13903.                 ),
  13904.                 array(
  13905.                     'purchaseRequisitionDate' => 'DESC'
  13906.                 )
  13907.             );
  13908.         $stage_list = array(
  13909.             => 'Pending',
  13910.             => 'Pending',
  13911.             => 'Complete',
  13912.             => 'Partial',
  13913.         );
  13914.         $data = [];
  13915.         foreach ($q as $entry) {
  13916.             $data[] = array(
  13917.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  13918.                 'id' => $entry->getPurchaseRequisitionId(),
  13919.                 'doc_hash' => $entry->getDocumentHash(),
  13920.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13921.                 'acquisition_status' => $entry->getAcquisitionStatus(),
  13922.                 'acquisition_start_date' => $entry->getAcquisitionStartDate(),
  13923.                 'acquisition_end_date' => $entry->getAcquisitionEndDate(),
  13924.                 'acquisition_method' => $entry->getquotationAcquisitionMethod(),
  13925.                 'poTagged' => $entry->getPoTagged(),
  13926.                 'typeHash' => $entry->getTypehash(),
  13927.                 'srIds' => $entry->getSrIds(),
  13928.                 'irIds' => $entry->getIrIds(),
  13929.                 'prIds' => $entry->getPrIds(),
  13930.                 'poIds' => $entry->getPoIds(),
  13931.             );
  13932.         }
  13933.         return $this->render('@Inventory/pages/views/pr_list.html.twig',
  13934.             array(
  13935.                 'page_title' => 'Purchase Requisition List',
  13936.                 'data' => $data
  13937.             )
  13938.         );
  13939.     }
  13940.     public
  13941.     function ServiceRequisitionListAction(Request $request)
  13942.     {
  13943.         $q $this->getDoctrine()
  13944.             ->getRepository('ApplicationBundle\\Entity\\PurchaseRequisition')
  13945.             ->findBy(
  13946.                 array(
  13947.                     'status' => GeneralConstant::ACTIVE,
  13948. //                    'approved' =>  GeneralConstant::APPROVED,
  13949.                 ),
  13950.                 array(
  13951.                     'purchaseRequisitionDate' => 'DESC'
  13952.                 )
  13953.             );
  13954.         $stage_list = array(
  13955.             => 'Pending',
  13956.             => 'Pending',
  13957.             => 'Complete',
  13958.             => 'Partial',
  13959.         );
  13960.         $data = [];
  13961.         foreach ($q as $entry) {
  13962.             $data[] = array(
  13963.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  13964.                 'id' => $entry->getPurchaseRequisitionId(),
  13965.                 'doc_hash' => $entry->getDocumentHash(),
  13966.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13967.                 'poTagged' => $entry->getPoTagged(),
  13968.                 'typeHash' => $entry->getTypehash(),
  13969.                 'srIds' => $entry->getSrIds(),
  13970.                 'irIds' => $entry->getIrIds(),
  13971.                 'prIds' => $entry->getPrIds(),
  13972.                 'poIds' => $entry->getPoIds(),
  13973.             );
  13974.         }
  13975.         return $this->render('@Inventory/pages/views/service_requisition_list.html.twig',
  13976.             array(
  13977.                 'page_title' => 'Service Requisition List',
  13978.                 'data' => $data
  13979.             )
  13980.         );
  13981.     }
  13982.     public
  13983.     function ViewPrAction(Request $request$id)
  13984.     {
  13985.         $em $this->getDoctrine()->getManager();
  13986.         $dt Inventory::GetPrDetails($em$id);
  13987.         $companyId $this->getLoggedUserCompanyId($request);
  13988.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  13989.             array(
  13990.                 'page_title' => 'Purchase Requisition',
  13991.                 'data' => $dt,
  13992.                 'branchList' => Client::BranchList($em$companyId),
  13993.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  13994.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13995.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13996.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13997.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  13998.                     $id,
  13999.                     $dt['created_by'],
  14000.                     $dt['edited_by'])
  14001.             )
  14002.         );
  14003.     }
  14004.     public
  14005.     function ViewServiceRequisitionAction(Request $request$id)
  14006.     {
  14007.         $em $this->getDoctrine()->getManager();
  14008.         $dt Inventory::GetPrDetails($em$id);
  14009.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  14010.             array(
  14011.                 'page_title' => 'Service Requisition',
  14012.                 'data' => $dt,
  14013.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14014.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14015.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14016.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14017.                     $id,
  14018.                     $dt['created_by'],
  14019.                     $dt['edited_by'])
  14020.             )
  14021.         );
  14022.     }
  14023.     public
  14024.     function PrintPrAction(Request $request$id)
  14025.     {
  14026.         $em $this->getDoctrine()->getManager();
  14027.         $dt Inventory::GetPrDetails($em$id);
  14028.         $companyId $this->getLoggedUserCompanyId($request);
  14029.         $company_data Company::getCompanyData($em$companyId);
  14030.         $document_mark = array(
  14031.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  14032.             'copy' => ''
  14033.         );
  14034.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  14035.             $html $this->renderView('@Inventory/pages/print/print_pr.html.twig',
  14036.                 array(
  14037.                     //full array here
  14038.                     'pdf' => true,
  14039.                     'page_title' => 'Purchase Requisition',
  14040.                     'export' => 'pdf,print',
  14041.                     'data' => $dt,
  14042.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14043.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14044.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14045.                         array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14046.                         $id,
  14047.                         $dt['created_by'],
  14048.                         $dt['edited_by']),
  14049.                     'document_mark_image' => $document_mark['original'],
  14050.                     'branchList' => Client::BranchList($em$companyId),
  14051.                     'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  14052.                     'company_name' => $company_data->getName(),
  14053.                     'company_data' => $company_data,
  14054.                     'company_address' => $company_data->getAddress(),
  14055.                     'company_image' => $company_data->getImage(),
  14056.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  14057.                     'red' => 0
  14058.                 )
  14059.             );
  14060.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  14061. //                'orientation' => 'landscape',
  14062. //                'enable-javascript' => true,
  14063. //                'javascript-delay' => 1000,
  14064.                 'no-stop-slow-scripts' => false,
  14065.                 'no-background' => false,
  14066.                 'lowquality' => false,
  14067.                 'encoding' => 'utf-8',
  14068. //            'images' => true,
  14069. //            'cookie' => array(),
  14070.                 'dpi' => 300,
  14071.                 'image-dpi' => 300,
  14072. //                'enable-external-links' => true,
  14073. //                'enable-internal-links' => true
  14074.             ));
  14075.             return new Response(
  14076.                 $pdf_response,
  14077.                 200,
  14078.                 array(
  14079.                     'Content-Type' => 'application/pdf',
  14080.                     'Content-Disposition' => 'attachment; filename="purchase_requisition_' $id '.pdf"'
  14081.                 )
  14082.             );
  14083.         }
  14084.         return $this->render('@Inventory/pages/print/print_pr.html.twig',
  14085.             array(
  14086.                 'page_title' => 'Purchase Requisition',
  14087.                 'export' => 'pdf,print',
  14088.                 'data' => $dt,
  14089.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14090.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14091.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14092.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14093.                     $id,
  14094.                     $dt['created_by'],
  14095.                     $dt['edited_by']),
  14096.                 'document_mark_image' => $document_mark['original'],
  14097.                 'company_name' => $company_data->getName(),
  14098.                 'company_data' => $company_data,
  14099.                 'branchList' => Client::BranchList($em$companyId),
  14100.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  14101.                 'company_address' => $company_data->getAddress(),
  14102.                 'company_image' => $company_data->getImage(),
  14103.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  14104.                 'red' => 0
  14105.             )
  14106.         );
  14107.     }
  14108.     public
  14109.     function CreateSecondaryDeliveryReceiptAction(Request $request)
  14110.     {
  14111.         $em $this->getDoctrine()->getManager();
  14112.         $companyId $this->getLoggedUserCompanyId($request);
  14113.         $userBranchIdList $request->getSession()->get('branchIdList');
  14114.         if ($userBranchIdList == null$userBranchIdList = [];
  14115.         $userBranchId $request->getSession()->get('branchId');
  14116.         if ($request->isMethod('POST')) {
  14117.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  14118.             $dochash $request->request->get('docHash'); //change
  14119.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14120.             $approveRole 1;  //created
  14121.             $approveHash $request->request->get('approvalHash');
  14122.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  14123.                 $loginId$approveRole$approveHash)
  14124.             ) {
  14125.                 $this->addFlash(
  14126.                     'error',
  14127.                     'Sorry Couldnot insert Data.'
  14128.                 );
  14129.             } else {
  14130.                 $receiptId SalesOrderM::CreateNewSecondaryDeliveryReceipt($this->getDoctrine()->getManager(), $request->request,
  14131.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  14132.                     $this->getLoggedUserCompanyId($request));
  14133.                 //now add Approval info
  14134.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14135.                 $approveRole 1;  //created
  14136.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  14137.                     $receiptId,
  14138.                     $loginId,
  14139.                     $approveRole,
  14140.                     $request->request->get('approvalHash'));
  14141.                 $options = array(
  14142.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  14143.                     'notification_server' => $this->container->getParameter('notification_server'),
  14144.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  14145.                     'url' => $this->generateUrl(
  14146.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  14147.                         ['entity_view_route_path_name']
  14148.                     )
  14149.                 );
  14150.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  14151.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  14152.                     $receiptId,
  14153.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  14154.                 );
  14155.                 $this->addFlash(
  14156.                     'success',
  14157.                     'New Delivery Receipt Created'
  14158.                 );
  14159.                 $url $this->generateUrl(
  14160.                     'view_delivery_receipt'
  14161.                 );
  14162.                 return $this->redirect($url "/" $receiptId);
  14163.             }
  14164.         }
  14165.         $debugData = [];
  14166. //        $dr_data=$em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findOneBy(
  14167. //            array(
  14168. //                'deliveryReceiptId'=>$dr_id
  14169. //            )
  14170. //        );
  14171.         $new_swld = new \DateTime('2017-07-09');
  14172. //        if ($entry->getWarranty() > 0)
  14173. //            $new_swld->modify('+' . $entry->getWarranty() . ' month');
  14174.         $debugData[] = $new_swld->format('Y-m-d');
  14175.         $debugData[] = $new_swld;
  14176. //        $debugData[]=$dr_data->getDeliveryReceiptDate();
  14177.         $debugData[] = '+' '1' ' month';
  14178.         $branchList Client::BranchList($em$companyId, [], $userBranchIdList);
  14179.         $warehouseIds = [];
  14180.         foreach ($branchList as $br) {
  14181.             $warehouseIds[] = $br['warehouseId'];
  14182.         }
  14183.         return $this->render('@Inventory/pages/input_forms/secondaryDeliveryReceipt.html.twig',
  14184.             array(
  14185.                 'page_title' => 'New Delivery Receipt',
  14186.                 'ExistingClients' => Accounts::getClientLedgerHeads($em),
  14187.                 'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($em),
  14188.                 'ClientList' => SalesOrderM::GetSecondaryClientList($em),
  14189.                 'warehouse' => Inventory::WarehouseList($em$companyId$warehouseIds),
  14190.                 'salesOrders' => SalesOrderM::SecondarySalesOrderListPendingDelivery($em$warehouseIds),
  14191.                 'salesOrdersArray' => SalesOrderM::SecondarySalesOrderListPendingDeliveryArray($em$warehouseIds),
  14192.                 'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
  14193.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
  14194.                 'debugData' => $debugData,
  14195.             )
  14196.         );
  14197.     }
  14198.     public function AddUnitTypeAction(Request $request$id 0)
  14199.     {
  14200.         $em $this->getDoctrine()->getManager();
  14201.         $unitType $id != $em->getRepository(UnitType::class)->find($id) : null;
  14202.         if ($request->isMethod('POST')) {
  14203.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14204.             Inventory::CreateUnitType($em$id$request->request$loginId);
  14205.             $this->addFlash(
  14206.                 'success',
  14207.                 $id != 'Unit Type Updated' 'Unit Type Added'
  14208.             );
  14209.             $unitType $id != $em->getRepository(UnitType::class)->find($id) : null;
  14210.         }
  14211.         $unitTypeDetails $em->getRepository(UnitType::class)->findBy(array(), array('name' => 'ASC'));
  14212.         $existingConversionMap = [];
  14213.         if ($unitType && $unitType->getConversion() != '') {
  14214.             $existingConversionMap json_decode($unitType->getConversion(), true);
  14215.             if ($existingConversionMap == null) {
  14216.                 $existingConversionMap = [];
  14217.             }
  14218.         }
  14219.         return $this->render('@Inventory/pages/input_forms/addUnitType.html.twig',
  14220.             array(
  14221.                 'page_title' => $id != 'Edit Unit Type' 'Add Unit Type',
  14222.                 'ex_id' => $id,
  14223.                 'ex_det' => $unitType,
  14224.                 'existingConversionMap' => $existingConversionMap,
  14225.                 'unitTypeDetails' => $unitTypeDetails,
  14226.                 'unitTypeRecords' => $unitTypeDetails
  14227.             )
  14228.         );
  14229.     }
  14230.     public function AddCurrencyAction(Request $request$id 0)
  14231.     {
  14232.         $em $this->getDoctrine()->getManager();
  14233.         $currency $id != $em->getRepository(Currencies::class)->find($id) : null;
  14234.         if ($request->isMethod('POST')) {
  14235.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14236.             Inventory::CreateCurrency($em$id$request->request$loginId);
  14237.             $this->addFlash(
  14238.                 'success',
  14239.                 $id != 'Currency Updated' 'Currency Added'
  14240.             );
  14241.             $currency $id != $em->getRepository(Currencies::class)->find($id) : null;
  14242.         }
  14243.         $currencyDetails $em->getRepository(Currencies::class)->findBy(array(), array('code' => 'ASC'));
  14244.         $existingConversionMap = [];
  14245.         if ($currency && $currency->getConversionData() != '') {
  14246.             $existingConversionMap json_decode($currency->getConversionData(), true);
  14247.             if ($existingConversionMap == null) {
  14248.                 $existingConversionMap = [];
  14249.             }
  14250.         }
  14251.         return $this->render('@Inventory/pages/input_forms/addCurrency.html.twig',
  14252.             array(
  14253.                 'page_title' => $id != 'Edit Currency' 'Add Currency',
  14254.                 'ex_id' => $id,
  14255.                 'ex_det' => $currency,
  14256.                 'existingConversionMap' => $existingConversionMap,
  14257.                 'currencyDetails' => $currencyDetails,
  14258.                 'currencyRecords' => $currencyDetails
  14259.             )
  14260.         );
  14261.     }
  14262.     public
  14263.     function SubcategoryListAction()
  14264.     {
  14265.         return $this->render('@Inventory/pages/input_forms/subCategoryList.html.twig',
  14266.             array(
  14267.                 'page_title' => 'Sub Category List',
  14268.             )
  14269.         );
  14270.     }
  14271. //    public function getInventoryProductList(Request $request)
  14272. //    {
  14273. //        $em = $this->getDoctrine()->getManager();
  14274. //
  14275. //        $page = (int) $request->query->get('page', 1);     // Default page = 1
  14276. //        $limit = (int) $request->query->get('limit', 10);   // Default limit = 10
  14277. //        $offset = ($page - 1) * $limit;
  14278. //
  14279. //        // First, get the total count of products
  14280. //        $totalQuery = $em->createQueryBuilder()
  14281. //            ->select('COUNT(i.id)')
  14282. //            ->from('ApplicationBundle:InventoryStorage', 'i')
  14283. //            ->where('i.qty > :minQty')
  14284. //            ->setParameter('minQty', 0)
  14285. //            ->getQuery();
  14286. //
  14287. //        $totalRecords = (int) $totalQuery->getSingleScalarResult();
  14288. //        $totalPages = $limit > 0 ? (int) ceil($totalRecords / $limit) : 1;
  14289. //
  14290. //        // Then, get the paginated data
  14291. //        $qb = $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->createQueryBuilder('i')
  14292. //            ->select([
  14293. //                'i.productId AS productId',
  14294. //                'COALESCE(ig.name, \'\') AS itemGroupName',
  14295. //                'COALESCE(w.name, \'\') AS wareHouseName',
  14296. //                'i.qty AS quantity',
  14297. //                'COALESCE(b.name, \'\') AS brandName',
  14298. //                'COALESCE(u.name, \'\') AS UnitName',
  14299. //                'COALESCE(c.name, \'\') AS color',
  14300. //                'COALESCE(s.name, \'\') AS size',
  14301. //                'COALESCE(i.salesPrice, 0) AS salesPrice',
  14302. //                'COALESCE(p.name, \'\') AS productName'
  14303. //            ])
  14304. //            ->leftJoin('ApplicationBundle:InvProducts', 'p', 'WITH', 'i.productId = p.id')
  14305. //            ->leftJoin('ApplicationBundle:InvItemGroup', 'ig', 'WITH', 'i.igId = ig.id')
  14306. //            ->leftJoin('ApplicationBundle:Warehouse', 'w', 'WITH', 'i.warehouseId = w.id')
  14307. //            ->leftJoin('ApplicationBundle:BrandCompany', 'b', 'WITH', 'i.brandId = b.id')
  14308. //            ->leftJoin('ApplicationBundle:UnitType', 'u', 'WITH', 'i.unitTypeId = u.id')
  14309. //            ->leftJoin('ApplicationBundle:Colors', 'c', 'WITH', 'i.color = c.id')
  14310. //            ->leftJoin('ApplicationBundle:ProductSizes', 's', 'WITH', 'i.size = s.id')
  14311. //            ->where('i.qty > :minQty')
  14312. //            ->setParameter('minQty', 0)
  14313. //            ->setFirstResult($offset)
  14314. //            ->setMaxResults($limit);
  14315. //
  14316. //        $inventoryData = $qb->getQuery()->getResult();
  14317. //
  14318. //        return $this->json([
  14319. //            'page' => $page,
  14320. //            'limit' => $limit,
  14321. //            'totalRecords' => $totalRecords,
  14322. //            'totalPages' => $totalPages,
  14323. //            'data' => $inventoryData,
  14324. //        ]);
  14325. //    }
  14326.     public function getInventoryProductList(Request $request)
  14327.     {
  14328.         $em $this->getDoctrine()->getManager();
  14329.         $page = (int)$request->query->get('page'1);
  14330.         $limit = (int)$request->query->get('limit'10);
  14331.         $offset = ($page 1) * $limit;
  14332.         $totalQuery $em->createQueryBuilder()
  14333.             ->select('COUNT(i.id)')
  14334.             ->from('ApplicationBundle:InventoryStorage''i')
  14335.             ->where('i.qty > :minQty')
  14336.             ->setParameter('minQty'0)
  14337.             ->getQuery();
  14338.         $totalRecords = (int)$totalQuery->getSingleScalarResult();
  14339.         $totalPages $limit ? (int)ceil($totalRecords $limit) : 1;
  14340.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14341.         $qb $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->createQueryBuilder('i')
  14342.             ->select([
  14343.                 'i.productId AS productId',
  14344.                 'COALESCE(ig.name, \'\') AS itemGroupName',
  14345.                 'COALESCE(w.name, \'\') AS wareHouseName',
  14346.                 'COALESCE(wa.name, \'\') AS subWareHouseName',
  14347.                 'i.qty AS quantity',
  14348.                 'i.qty AS lastSold',
  14349.                 'i.qty AS lastPurchase',
  14350.                 'COALESCE(b.name, \'\') AS brandName',
  14351.                 'COALESCE(u.name, \'\') AS UnitName',
  14352.                 'COALESCE(c.name, \'\') AS color',
  14353.                 'COALESCE(s.name, \'\') AS size',
  14354.                 'COALESCE(i.purchasePrice, 0) AS purchasePrice',
  14355.                 'COALESCE(i.salesPrice, 0) AS salesPrice',
  14356.                 'COALESCE(p.name, \'\') AS productName',
  14357.                 'COALESCE(p.productCode, \'\') AS productCode',
  14358.                 "CASE 
  14359.                 WHEN p.images IS NOT NULL AND p.images <> '' 
  14360.                 THEN p.images 
  14361.                 ELSE '$defaultImage
  14362.             END AS image"
  14363.             ])
  14364.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  14365.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''i.igId = ig.id')
  14366.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''i.warehouseId = w.id')
  14367.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''i.actionTagId = wa.id')
  14368.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''i.brandId = b.id')
  14369.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''i.unitTypeId = u.id')
  14370.             ->leftJoin('ApplicationBundle:Colors''c''WITH''i.color = c.id')
  14371.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''i.size = s.id')
  14372.             ->where('i.qty > :minQty')
  14373.             ->setParameter('minQty'0)
  14374.             ->setFirstResult($offset)
  14375.             ->setMaxResults($limit);
  14376.         $inventoryData $qb->getQuery()->getResult();
  14377.         return $this->json([
  14378.             'page' => $page,
  14379.             'limit' => $limit,
  14380.             'totalRecords' => $totalRecords,
  14381.             'totalPages' => $totalPages,
  14382.             'data' => $inventoryData,
  14383.         ]);
  14384.     }
  14385.     public function CreateStockTransferForAppAction(Request $request)
  14386.     {
  14387.         $em $this->getDoctrine()->getManager();
  14388.         $companyId $this->getLoggedUserCompanyId($request);
  14389.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  14390.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  14391.         if ($request->isMethod('POST')) {
  14392.             $em $this->getDoctrine()->getManager();
  14393.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  14394.             $dochash $request->request->get('docHash'); //change
  14395.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14396.             $approveRole $request->request->get('approvalRole');
  14397.             $approveHash $request->request->get('approvalHash');
  14398.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  14399.                 $loginId$approveRole$approveHash)
  14400.             ) {
  14401.                 $this->addFlash(
  14402.                     'error',
  14403.                     'Sorry Couldnot insert Data.'
  14404.                 );
  14405.             } else {
  14406.                 if ($request->request->has('check_allowed'))
  14407.                     $check_allowed 1;
  14408.                 $StID Inventory::CreateNewStockTransferForAPP(
  14409.                     $this->getDoctrine()->getManager(),
  14410.                     $request->request,
  14411.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  14412.                     $this->getLoggedUserCompanyId($request)
  14413.                 );
  14414.                 //now add Approval info
  14415.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14416.                 $approveRole 1;  //created
  14417.                 $options = array(
  14418.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  14419.                     'notification_server' => $this->container->getParameter('notification_server'),
  14420.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  14421.                     'url' => $this->generateUrl(
  14422.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  14423.                         ['entity_view_route_path_name']
  14424.                     )
  14425.                 );
  14426.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  14427.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  14428.                     $StID,
  14429.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  14430.                 );
  14431.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  14432.                     $loginId,
  14433.                     $approveRole,
  14434.                     $request->request->get('approvalHash'));
  14435.                 $this->addFlash(
  14436.                     'success',
  14437.                     'Stock Transfer Added.'
  14438.                 );
  14439.                 $url $this->generateUrl(
  14440.                     'view_st'
  14441.                 );
  14442. //                return $this->redirect($url . "/" . $StID);
  14443.                 return $this->json(['success' => true]);
  14444.             }
  14445.         }
  14446.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  14447.             array(
  14448.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  14449.             )
  14450.         );
  14451.         $INVLIST = [];
  14452.         foreach ($slotList as $slot) {
  14453.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  14454.         }
  14455.         return $this->json(['success' => true]);
  14456. //       return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  14457. //           array(
  14458. //         'page_title' => 'Stock Transfer Note',
  14459. //               'warehouseList' => Inventory::WarehouseList($em),
  14460. //        'warehouseListArray' => Inventory::WarehouseListArray($em),
  14461. //               'colorList' => Inventory::GetColorList($em),
  14462. //               'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  14463. //                'srList' => [],
  14464. //               'warehouseActionList' => $warehouse_action_list,
  14465. //                'warehouseActionListArray' => $warehouse_action_list_array,
  14466. //                'item_list' => Inventory::ItemGroupList($em),
  14467. //                'item_list_array' => Inventory::ItemGroupListArray($em),
  14468. //               'category_list_array' => Inventory::ProductCategoryListArray($em),
  14469. //              'product_list_array' => Inventory::ProductListDetailedArray($em),
  14470. ////               'product_list_array' => [],
  14471. //               'product_list' => Inventory::ProductList($em, $companyId),
  14472. ////                'product_list' => [],
  14473. //               'prefix_list' => array(
  14474. //                   [
  14475. //                       'id' => 1,
  14476. //                       'value' => 'GN',
  14477. //                        'text' => 'GN'
  14478. //
  14479. //                   ]
  14480. //              ),
  14481. //              'assoc_list' => array(
  14482. //                  [
  14483. //                       'id' => 1,
  14484. //                        'value' => 1,
  14485. //                        'text' => 'GN'
  14486. //
  14487. //                  ]
  14488. //               ),
  14489. //              'INVLIST' => $INVLIST
  14490. //           )
  14491. //      );
  14492.     }
  14493.     public function getWarehouseList(Request $request)
  14494.     {
  14495.         $em $this->getDoctrine()->getManager();
  14496.         $warehouses $em->getRepository('ApplicationBundle\\Entity\\Warehouse')
  14497.             ->createQueryBuilder('w')
  14498.             ->select('w.id''w.name')
  14499.             ->orderBy('w.name''ASC')
  14500.             ->getQuery()
  14501.             ->getResult();
  14502.         return $this->json($warehouses);
  14503.     }
  14504.     public function getSubWarehouseList(Request $request)
  14505.     {
  14506.         $em $this->getDoctrine()->getManager();
  14507.         $warehouses $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')
  14508.             ->createQueryBuilder('w')
  14509.             ->select('w.id''w.name')
  14510. //            ->orderBy('w.name', 'ASC')
  14511.             ->getQuery()
  14512.             ->getResult();
  14513.         return $this->json($warehouses);
  14514.     }
  14515.     public function getStockReceiveList(Request $request)
  14516.     {
  14517.         $list GeneralConstant::$stockReceiveType;
  14518.         return $this->json($list);
  14519.     }
  14520.     public function getOrderListByStockReceiveId(Request $request)
  14521.     {
  14522.         $em $this->getDoctrine()->getManager();
  14523.         $typeName $request->request->get('type');
  14524.         $typeId $request->request->get('id');
  14525.         $document null;
  14526.         if ($typeName == 'From Stock Transfer' || $typeId == 1) {
  14527.             $document $em->getRepository('ApplicationBundle\\Entity\\StockTransfer')->createQueryBuilder('s')->select('s.stockTransferId''s.documentHash')->where('s.approved !=1')->getQuery()->getResult();
  14528.         } else if ($typeName == 'For Stock In' || $typeId == 3) {
  14529.             $document $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->createQueryBuilder('a')->select('a.accountsHeadId''a.name')->getQuery()->getResult();
  14530.         } else if ($typeName == 'For Opening Entity' || $typeId == 4) {
  14531.             $document $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')
  14532.                 ->createQueryBuilder('w')
  14533.                 ->select('w.id''w.name')
  14534.                 ->getQuery()
  14535.                 ->getResult();
  14536.         }
  14537.         return $this->json($document);
  14538.     }
  14539.     public function GetProductFromInvStorage(Request $request)
  14540.     {
  14541.         $em $this->getDoctrine()->getManager();
  14542.         $searchTerm trim($request->get('name'));
  14543.         // Fetch all or filtered products
  14544.         if ($searchTerm) {
  14545.             $products $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  14546.                 ->createQueryBuilder('p')
  14547.                 ->where('p.name LIKE :term')
  14548.                 ->setParameter('term''%' $searchTerm '%')
  14549.                 ->getQuery()
  14550.                 ->getResult();
  14551.         } else {
  14552.             $products $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findAll();
  14553.         }
  14554.         $response = [];
  14555.         foreach ($products as $product) {
  14556.             // All InventoryStorage entries for the product
  14557.             $invStorageItems $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy([
  14558.                 'productId' => $product->getId()
  14559.             ]);
  14560.             $inventoryList = [];
  14561.             foreach ($invStorageItems as $item) {
  14562.                 $warehouse $em->getRepository('ApplicationBundle\\Entity\\Warehouse')->find($item->getWarehouseId());
  14563.                 $subWarehouse $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')->find($item->getActionTagId());
  14564.                 $inventoryList[] = [
  14565.                     'warehouse_id' => $item->getWarehouseId(),
  14566.                     'warehouse_name' => $warehouse $warehouse->getName() : '',
  14567.                     'sub_warehouse_id' => $item->getActionTagId(),
  14568.                     'sub_warehouse_name' => $subWarehouse $subWarehouse->getName() : '',
  14569.                     'quantity' => $item->getQty(),
  14570.                     'lastSold' => $item->getNonInvoicedQty(),
  14571.                     'lastPurchase' => $item->getPhysicalQty(),
  14572.                     'purchasePrice' => $item->getPurchasePrice(),
  14573.                     'salesPrice' => $item->getSalesPrice(),
  14574.                     'brandName' => $item->getBrandId(),
  14575.                     'unitName' => 'pcs'// Optional: Resolve via Unit table
  14576.                 ];
  14577.             }
  14578.             $response[] = [
  14579.                 'productId' => $product->getId(),
  14580.                 'itemGroupName' => $product->getIgId(),
  14581.                 'productName' => $product->getName(),
  14582.                 'productCode' => $product->getProductCode(),
  14583.                 'color' => $product->getColors(),
  14584.                 'size' => $product->getSizes(),
  14585.                 'image' => $product->getDefaultImage(),
  14586.                 'inventory' => $inventoryList
  14587.             ];
  14588.         }
  14589.         return new JsonResponse($response);
  14590.     }
  14591.     public function getProductByDocumentId(Request $request)
  14592.     {
  14593.         $em $this->getDoctrine()->getManager();
  14594.         $documentId $request->request->get('documentId');
  14595.         $accountsHeadId $request->request->get('accountsHeadId');
  14596.         if ($documentId) {
  14597.             $productIdRows $em->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  14598.                 ->createQueryBuilder('s')
  14599.                 ->select('s.productId')
  14600.                 ->where('s.stockTransferId = :documentId')
  14601.                 ->setParameter('documentId'$documentId)
  14602.                 ->getQuery()
  14603.                 ->getResult();
  14604.             $fromWarehouseRow $em->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  14605.                 ->createQueryBuilder('s')
  14606.                 ->select('s.warehouseId''s.toWarehouseId''s.warehouseActionId''s.toWarehouseActionId''s.qty''s.price')
  14607.                 ->where('s.stockTransferId = :documentId')
  14608.                 ->setParameter('documentId'$documentId)
  14609.                 ->setMaxResults(1)
  14610.                 ->getQuery()
  14611.                 ->getOneOrNullResult();
  14612.             $productIds array_map(function ($row) {
  14613.                 return $row['productId'];
  14614.             }, $productIdRows);
  14615.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findBy([
  14616.                 'id' => $productIds
  14617.             ]);
  14618.             $productData array_map(function ($p) {
  14619.                 return [
  14620.                     'id' => $p->getId(),
  14621.                     'name' => $p->getName(),
  14622.                     'modelNo' => $p->getModelNo(),
  14623.                     'sku' => $p->getSkuCode(),
  14624.                     'productCode' => $p->getProductCode(),
  14625.                     'purchasePrice' => $p->getPurchasePrice(),
  14626.                     'salesPrice' => $p->getSalesPrice(),
  14627.                     'purchasePriceWoExpense' => $p->getPurchasePriceWoExpense(),
  14628.                     'qty' => $p->getQty(),
  14629.                     'nonInvoicedQty' => $p->getNonInvoicedQty(),
  14630.                     'nonSalesInvoicedQty' => $p->getNonSalesInvoicedQty(),
  14631.                     'unitTypeId' => $p->getUnitTypeId(),
  14632.                     'dimension' => $p->getDimension(),
  14633.                     'dimensionUnitTypeId' => $p->getDimensionUnitTypeId(),
  14634.                     'weight' => $p->getWeight(),
  14635.                     'categoryId' => $p->getCategoryId(),
  14636.                     'subCategoryId' => $p->getSubCategoryId(),
  14637.                     'brandCompany' => $p->getBrandCompany(),
  14638.                     'warehouseId' => $p->getWarehouseId(),
  14639.                     'reorderLevel' => $p->getReorderLevel(),
  14640.                     'defaultImage' => $p->getDefaultImage(),
  14641.                     'status' => $p->getStatus()
  14642.                 ];
  14643.             }, $product);
  14644.             return $this->json([
  14645.                 'warehouseId' => $fromWarehouseRow['warehouseId'],
  14646.                 'toWarehouseId' => $fromWarehouseRow['toWarehouseId'],
  14647.                 'warehouseActionId' => $fromWarehouseRow['warehouseActionId'],
  14648.                 'toWarehouseActionId' => $fromWarehouseRow['toWarehouseActionId'],
  14649.                 'quantity' => $fromWarehouseRow['qty'],
  14650.                 'price' => $fromWarehouseRow['price'],
  14651.                 'products' => $productData
  14652.             ]);
  14653.         } else if ($accountsHeadId) {
  14654.             $products $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findAll();
  14655.             $productData array_map(function ($p) {
  14656.                 return [
  14657.                     'id' => $p->getId(),
  14658.                     'name' => $p->getName(),
  14659.                     'modelNo' => $p->getModelNo(),
  14660.                     'sku' => $p->getSkuCode(),
  14661.                     'productCode' => $p->getProductCode(),
  14662.                     'purchasePrice' => $p->getPurchasePrice(),
  14663.                     'salesPrice' => $p->getSalesPrice(),
  14664.                     'purchasePriceWoExpense' => $p->getPurchasePriceWoExpense(),
  14665.                     'qty' => $p->getQty(),
  14666.                     'nonInvoicedQty' => $p->getNonInvoicedQty(),
  14667.                     'nonSalesInvoicedQty' => $p->getNonSalesInvoicedQty(),
  14668.                     'unitTypeId' => $p->getUnitTypeId(),
  14669.                     'dimension' => $p->getDimension(),
  14670.                     'dimensionUnitTypeId' => $p->getDimensionUnitTypeId(),
  14671.                     'weight' => $p->getWeight(),
  14672.                     'categoryId' => $p->getCategoryId(),
  14673.                     'subCategoryId' => $p->getSubCategoryId(),
  14674.                     'brandCompany' => $p->getBrandCompany(),
  14675.                     'warehouseId' => $p->getWarehouseId(),
  14676.                     'reorderLevel' => $p->getReorderLevel(),
  14677.                     'defaultImage' => $p->getDefaultImage(),
  14678.                     'status' => $p->getStatus()
  14679.                 ];
  14680.             }, $products);
  14681.             return $this->json($productData);
  14682.         } else {
  14683.             return new JsonResponse([
  14684.                 "status" => false,
  14685.                 "message" => "Please insert valid documentId or accountsHead!"
  14686.             ]);
  14687.         }
  14688.     }
  14689.     public function getQuantityBasedOnSubWareHouse(Request $request)
  14690.     {
  14691.         $em $this->getDoctrine()->getManager();
  14692.         $productId $request->get('product_id');
  14693.         $productName trim($request->get('product_name'));
  14694.         $warehouseId $request->get('warehouse_id');
  14695.         $warehouseActionId $request->get('warehouse_action_id');
  14696.         if (!$productId && $productName) {
  14697.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  14698.                 ->createQueryBuilder('p')
  14699.                 ->where('p.name LIKE :name')
  14700.                 ->setParameter('name''%' $productName '%')
  14701.                 ->setMaxResults(1)
  14702.                 ->getQuery()
  14703.                 ->getOneOrNullResult();
  14704.             if ($product) {
  14705.                 $productId $product->getId();
  14706.             }
  14707.         }
  14708.         if (!$productId || !$warehouseId || !$warehouseActionId) {
  14709.             return new JsonResponse(['error' => 'Product ID, Warehouse ID, and Action Tag ID are required'], 400);
  14710.         }
  14711.         $criteria = [
  14712.             'productId' => $productId,
  14713.             'warehouseId' => $warehouseId,
  14714.             'actionTagId' => $warehouseActionId,
  14715.         ];
  14716.         $invStorageItems $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy($criteria);
  14717.         if (empty($invStorageItems)) {
  14718.             return new JsonResponse([
  14719.                 'product_id' => $productId,
  14720.                 'quantities' => []
  14721.             ]);
  14722.         }
  14723.         $totalQty 0;
  14724.         $totalNonInvoicedQty 0;
  14725.         $totalPhysicalQty 0;
  14726.         $purchasePrice null;
  14727.         $salesPrice null;
  14728.         foreach ($invStorageItems as $item) {
  14729.             $totalQty += $item->getQty();
  14730.             $totalNonInvoicedQty += $item->getNonInvoicedQty();
  14731.             $totalPhysicalQty += $item->getPhysicalQty();
  14732.             $purchasePrice $item->getPurchasePrice();
  14733.             $salesPrice $item->getSalesPrice();
  14734.         }
  14735.         $subWarehouse $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')->find($warehouseActionId);
  14736.         $quantitiesBySubWarehouse = [[
  14737.             'action_tag_id' => $warehouseActionId,
  14738.             'sub_warehouse' => $subWarehouse $subWarehouse->getName() : '',
  14739.             'qty' => $totalQty,
  14740.             'non_invoiced_qty' => $totalNonInvoicedQty,
  14741.             'physical_qty' => $totalPhysicalQty,
  14742.             'purchase_price' => $purchasePrice,
  14743.             'sales_price' => $salesPrice,
  14744.         ]];
  14745.         return new JsonResponse([
  14746.             'product_id' => $productId,
  14747.             'quantities' => $quantitiesBySubWarehouse
  14748.         ]);
  14749.     }
  14750.     public function getPriceByWareHouseId(Request $request)
  14751.     {
  14752.         $em $this->getDoctrine()->getManager();
  14753.         $warehouseId $request->request->get('warehouseId');
  14754.         $productId $request->request->get('productId');
  14755.         $actionTagId $request->request->get('actionTagId');
  14756.         $unitPrice $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->createQueryBuilder('st')
  14757.             ->select('st.purchasePrice AS purchasePrice')
  14758.             ->where('st.productId = :productId')
  14759.             ->andWhere('st.warehouseId = :warehouseId')
  14760.             ->andWhere('st.actionTagId = :actionTagId')
  14761.             ->setParameter('productId'$productId)
  14762.             ->setParameter('warehouseId'$warehouseId)
  14763.             ->setParameter('actionTagId'$actionTagId)
  14764.             ->setMaxResults(1)
  14765.             ->getQuery()
  14766.             ->getOneOrNullResult();
  14767.         return new JsonResponse([
  14768.             'purchasePrice' => $unitPrice $unitPrice['purchasePrice'] : null
  14769.         ]);
  14770.     }
  14771.     public function getStockTransferList(Request $request)
  14772.     {
  14773.         $em $this->getDoctrine()->getManager();
  14774.         $warehouses $em->getRepository('ApplicationBundle\\Entity\\StockTransfer')
  14775.             ->createQueryBuilder('s')
  14776.             ->select('s.stockTransferId''s.documentHash')
  14777. //            ->orderBy('s.name', 'ASC')
  14778.             ->getQuery()
  14779.             ->getResult();
  14780.         return $this->json($warehouses);
  14781.     }
  14782.     public function stockTransferItemList(Request $request)
  14783.     {
  14784.         $em $this->getDoctrine()->getManager();
  14785.         $stockTransferId $request->query->get('stockTransferId');
  14786.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14787.         $qb $em->createQueryBuilder();
  14788.         $qb->select(
  14789.             'sti.id AS id',
  14790.             'sti.productId AS productId',
  14791.             'sti.stockTransferId AS stockTransferId',
  14792.             'p.name AS productName',
  14793.             'sti.price AS price',
  14794.             'p.images AS images',
  14795.             'ig.name AS itemGroupName',
  14796.             'w.name AS wareHouseName',
  14797.             'sti.warehouseId AS warehouseId',
  14798.             'wa.name AS subWareHouseName',
  14799.             'sti.warehouseActionId AS warehouseActionId',
  14800.             'sti.qty AS quantity',
  14801.             'b.name AS brandName',
  14802.             'u.name AS UnitName',
  14803.             'c.name AS color',
  14804.             's.name AS size'
  14805.         )
  14806.             ->from('ApplicationBundle:StockTransferItem''sti')
  14807.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''sti.productId = p.id')
  14808.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''p.igId = ig.id')
  14809.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''sti.warehouseId = w.id')
  14810.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''sti.warehouseActionId = wa.id')
  14811.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''p.brandCompany = b.id')
  14812.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''p.unitTypeId = u.id')
  14813.             ->leftJoin('ApplicationBundle:Colors''c''WITH''sti.colorId = c.id')
  14814.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''sti.sizeId = s.id')
  14815.             ->where('sti.stockTransferId = :stockTransferId')
  14816.             ->setParameter('stockTransferId'$stockTransferId);
  14817.         $results $qb->getQuery()->getResult();
  14818.         $response = [];
  14819.         foreach ($results as $item) {
  14820.             $response[] = [
  14821.                 'id' => $item['id'],
  14822.                 'stockTransferId' => $item['stockTransferId'],
  14823.                 'productId' => (int)$item['productId'],
  14824.                 'itemGroupName' => $item['itemGroupName'] ?? '',
  14825.                 'wareHouseName' => $item['wareHouseName'] ?? '',
  14826.                 'wareHouseId' => $item['warehouseId'] ?? '',
  14827.                 'subWareHouseName' => $item['subWareHouseName'] ?? '',
  14828.                 'subWareHouseId' => $item['warehouseActionId'] ?? '',
  14829.                 'quantity' => (int)$item['quantity'],
  14830.                 'brandName' => $item['brandName'] ?? '',
  14831.                 'UnitName' => $item['UnitName'] ?? '',
  14832.                 'color' => $item['color'] ?? '',
  14833.                 'size' => $item['size'] ?? '',
  14834.                 'price' => (float)$item['price'],
  14835.                 'productName' => $item['productName'] ?? '',
  14836.                 'image' => !empty($item['images']) ? $item['images'] : $defaultImage,
  14837.             ];
  14838.         }
  14839.         return $this->json($response);
  14840.     }
  14841.     public function inventoryStorageFilter(Request $request)
  14842.     {
  14843.         $em $this->getDoctrine()->getManager();
  14844.         $qb $em->createQueryBuilder();
  14845.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14846.         $qb->select(
  14847.             'i.productId',
  14848.             'ig.name AS itemGroupName',
  14849.             'w.name AS wareHouseName',
  14850.             'wa.name AS subWareHouseName',
  14851.             'i.qty AS quantity',
  14852.             'b.name AS brandName',
  14853.             'u.name AS UnitName',
  14854.             'c.name AS color',
  14855.             's.name AS size',
  14856.             'i.purchasePrice AS price',
  14857.             'p.name AS productName',
  14858.             'p.images'
  14859.         )
  14860.             ->from('ApplicationBundle:InventoryStorage''i')
  14861.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  14862.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''i.igId = ig.id')
  14863.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''i.warehouseId = w.id')
  14864.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''i.brandId = b.id')
  14865.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''i.unitTypeId = u.id')
  14866.             ->leftJoin('ApplicationBundle:Colors''c''WITH''i.color = c.id')
  14867.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''i.size = s.id')
  14868.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''i.actionTagId = wa.id');
  14869.         // Define available filters with their mappings
  14870.         $filters = [
  14871.             'itemGroup' => 'ig.id',
  14872.             'category' => 'p.categoryId',
  14873.             'warehouse' => 'w.id',
  14874.             'storageType' => 'i.actionTagId',
  14875.             'brand' => 'b.id',
  14876.             'color' => 'c.id',
  14877.             'colorCode' => 'c.hexCode',
  14878.             'size' => 's.id',
  14879.         ];
  14880.         foreach ($filters as $param => $field) {
  14881.             $value $request->query->get($param);
  14882.             if ($value !== null) {
  14883.                 $values array_map('trim'explode(','$value));
  14884.                 if (count($values) > 1) {
  14885.                     $qb->andWhere($qb->expr()->in($field":$param"))
  14886.                         ->setParameter($param$values);
  14887.                 } else {
  14888.                     $qb->andWhere("$field = :$param")
  14889.                         ->setParameter($param$values[0]);
  14890.                 }
  14891.             }
  14892.         }
  14893.         $rawResult $qb->getQuery()->getArrayResult();
  14894.         $finalResult = [];
  14895.         foreach ($rawResult as $row) {
  14896.             $finalResult[] = [
  14897.                 'productId' => $row['productId'],
  14898.                 'itemGroupName' => $row['itemGroupName'],
  14899.                 'wareHouseName' => $row['wareHouseName'],
  14900.                 'subWareHouseName' => $row['subWareHouseName'],
  14901.                 'quantity' => $row['quantity'],
  14902.                 'brandName' => $row['brandName'],
  14903.                 'UnitName' => $row['UnitName'],
  14904.                 'color' => $row['color'] ?? '',
  14905.                 'size' => $row['size'] ?? '',
  14906.                 'price' => $row['price'],
  14907.                 'productName' => $row['productName'],
  14908.                 'image' => !empty($row['images']) ? $row['images'] : $defaultImage,
  14909.             ];
  14910.         }
  14911.         // Check if finalResult is empty
  14912.         if (empty($finalResult)) {
  14913.             return $this->json([
  14914.                 'success' => false,
  14915.                 'message' => 'No inventory items found matching your criteria'
  14916.             ]);
  14917.         }
  14918.         return $this->json([
  14919.             'success' => true,
  14920.             'data' => $finalResult
  14921.         ]);
  14922.     }
  14923. //    public function inventoryStorageFilter(Request $request)
  14924. //    {
  14925. //        $em = $this->getDoctrine()->getManager();
  14926. //        $qb = $em->createQueryBuilder();
  14927. //        $defaultImage = 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14928. //
  14929. //        $qb->select(
  14930. //            'i.productId',
  14931. //            'ig.name AS itemGroupName',
  14932. //            'w.name AS wareHouseName',
  14933. //            'wa.name AS subWareHouseName',
  14934. //            'i.qty AS quantity',
  14935. //            'b.name AS brandName',
  14936. //            'u.name AS UnitName',
  14937. //            'c.name AS color',
  14938. //            's.name AS size',
  14939. //            'i.purchasePrice AS price',
  14940. //            'p.name AS productName',
  14941. //            'p.images'
  14942. //        )
  14943. //            ->from('ApplicationBundle:InventoryStorage', 'i')
  14944. //            ->leftJoin('ApplicationBundle:InvProducts', 'p', 'WITH', 'i.productId = p.id')
  14945. //            ->leftJoin('ApplicationBundle:InvItemGroup', 'ig', 'WITH', 'i.igId = ig.id')
  14946. //            ->leftJoin('ApplicationBundle:Warehouse', 'w', 'WITH', 'i.warehouseId = w.id')
  14947. //            ->leftJoin('ApplicationBundle:BrandCompany', 'b', 'WITH', 'i.brandId = b.id')
  14948. //            ->leftJoin('ApplicationBundle:UnitType', 'u', 'WITH', 'i.unitTypeId = u.id')
  14949. //            ->leftJoin('ApplicationBundle:Colors', 'c', 'WITH', 'i.color = c.id')
  14950. //            ->leftJoin('ApplicationBundle:ProductSizes', 's', 'WITH', 'i.size = s.id')
  14951. //            ->leftJoin('ApplicationBundle:WarehouseAction', 'wa', 'WITH', 'i.actionTagId = wa.id');
  14952. //
  14953. //        // Define available filters with their mappings
  14954. //        $filters = [
  14955. //            'itemGroup'    => 'ig.id',
  14956. //            'category'     => 'p.categoryId',
  14957. //            'warehouse'    => 'w.id',
  14958. //            'storageType'  => 'i.actionTagId',
  14959. //            'brand'        => 'b.id',
  14960. //            'color'        => 'c.id',
  14961. //            'colorCode'    => 'c.hexCode',
  14962. //            'size'         => 's.id',
  14963. //        ];
  14964. //
  14965. //        foreach ($filters as $param => $field) {
  14966. //            $value = $request->query->get($param);
  14967. //
  14968. //            if ($value !== null) {
  14969. //                $values = array_map('trim', explode(',', $value)); // handle multiple
  14970. //                if (count($values) > 1) {
  14971. //                    $qb->andWhere($qb->expr()->in($field, ":$param"))
  14972. //                        ->setParameter($param, $values);
  14973. //                } else {
  14974. //                    $qb->andWhere("$field = :$param")
  14975. //                        ->setParameter($param, $values[0]);
  14976. //                }
  14977. //            }
  14978. //        }
  14979. //
  14980. //        $rawResult = $qb->getQuery()->getArrayResult();
  14981. //
  14982. //        // Now process for validation (color, size, images)
  14983. //        $finalResult = [];
  14984. //
  14985. //        foreach ($rawResult as $row) {
  14986. //            $finalResult[] = [
  14987. //                'productId'     => $row['productId'],
  14988. //                'itemGroupName' => $row['itemGroupName'],
  14989. //                'wareHouseName' => $row['wareHouseName'],
  14990. //                'subWareHouseName' => $row['subWareHouseName'],
  14991. //                'quantity'      => $row['quantity'],
  14992. //                'brandName'     => $row['brandName'],
  14993. //                'UnitName'      => $row['UnitName'],
  14994. //                'color'         => $row['color'] ?? '',
  14995. //                'size'          => $row['size'] ?? '',
  14996. //                'price'         => $row['price'],
  14997. //                'productName'   => $row['productName'],
  14998. //                'image'         => !empty($row['images']) ? $row['images'] : $defaultImage,
  14999. //            ];
  15000. //        }
  15001. //
  15002. //
  15003. //
  15004. //        return $this->json($finalResult);
  15005. //    }
  15006.     public function getItemGroupList()
  15007.     {
  15008.         $em $this->getDoctrine()->getManager();
  15009.         $itemGroups $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')
  15010.             ->createQueryBuilder('ig')
  15011.             ->select('ig.id''ig.name')
  15012.             ->getQuery()
  15013.             ->getResult();
  15014.         return $this->json($itemGroups);
  15015.     }
  15016.     public function getProductCategoryList()
  15017.     {
  15018.         $em $this->getDoctrine()->getManager();
  15019.         $categories $em->getRepository('ApplicationBundle\\Entity\\InvProductCategories')
  15020.             ->createQueryBuilder('pc')
  15021.             ->select('pc.id''pc.name')
  15022.             ->getQuery()
  15023.             ->getResult();
  15024.         return $this->json($categories);
  15025.     }
  15026.     public function getBrandList()
  15027.     {
  15028.         $em $this->getDoctrine()->getManager();
  15029.         $brands $em->getRepository('ApplicationBundle\\Entity\\BrandCompany')
  15030.             ->createQueryBuilder('b')
  15031.             ->select('b.id''b.name')
  15032.             ->getQuery()
  15033.             ->getResult();
  15034.         return $this->json($brands);
  15035.     }
  15036.     public function getColorList()
  15037.     {
  15038.         $em $this->getDoctrine()->getManager();
  15039.         $colors $em->getRepository('ApplicationBundle\\Entity\\Colors')
  15040.             ->createQueryBuilder('c')
  15041.             ->select('c.id''c.name')
  15042.             ->getQuery()
  15043.             ->getResult();
  15044.         return $this->json($colors);
  15045.     }
  15046.     public function getColorCodeList()
  15047.     {
  15048.         $em $this->getDoctrine()->getManager();
  15049.         $colorCodes $em->getRepository('ApplicationBundle\\Entity\\Colors')
  15050.             ->createQueryBuilder('c')
  15051.             ->select('c.id''c.hexCode')
  15052.             ->getQuery()
  15053.             ->getResult();
  15054.         return $this->json($colorCodes);
  15055.     }
  15056.     public function getSizeList()
  15057.     {
  15058.         $em $this->getDoctrine()->getManager();
  15059.         $sizes $em->getRepository('ApplicationBundle\\Entity\\ProductSizes')
  15060.             ->createQueryBuilder('s')
  15061.             ->select('s.id''s.name')
  15062.             ->getQuery()
  15063.             ->getResult();
  15064.         if (empty($sizes)) {
  15065.             return $this->json([
  15066.                 'success' => false,
  15067.                 'message' => 'No data found'
  15068.             ]);
  15069.         }
  15070.         return $this->json($sizes);
  15071.     }
  15072.     public function productCodeList()
  15073.     {
  15074.         $em $this->getDoctrine()->getManager();
  15075.         $productCode $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  15076.             ->createQueryBuilder('p')
  15077.             ->select('p.productByCodeId''p.productId''p.salesCode')
  15078.             ->getQuery()
  15079.             ->getResult();
  15080.         if (empty($productCode)) {
  15081.             return $this->json([
  15082.                 'success' => false,
  15083.                 'message' => 'No data found'
  15084.             ]);
  15085.         }
  15086.         return $this->json($productCode);
  15087.     }
  15088.     public function getItemInOutHistory(Request $request)
  15089.     {
  15090.         $em $this->getDoctrine()->getManager();
  15091.         $qb $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')->createQueryBuilder('i')
  15092.             ->select([
  15093.                 'i.productId AS productId',
  15094.                 'i.transactionType AS transactionType',
  15095.                 'i.transactionDate AS transactionDate',
  15096.                 'toWarehouse.name AS toWarehouseId',
  15097.                 'toSubWarehouse.name AS toSubWarehouseId',
  15098.                 'fromWarehouse.name AS fromWarehouseId',
  15099.                 'fromSubWarehouse.name AS fromSubWarehouseId',
  15100.                 'i.qty AS quantity',
  15101.                 'i.entityDocHash AS document',
  15102.                 'i.entity AS entity',
  15103.                 'i.entityId AS entityId',
  15104.                 'p.name AS productName',
  15105.             ])
  15106.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  15107.             ->leftJoin('ApplicationBundle:Warehouse''toWarehouse''WITH''i.warehouseId = toWarehouse.id')
  15108.             ->leftJoin('ApplicationBundle:WarehouseAction''toSubWarehouse''WITH''i.actionTagId = toSubWarehouse.id')
  15109.             ->leftJoin('ApplicationBundle:Warehouse''fromWarehouse''WITH''i.fromWarehouseId = fromWarehouse.id')
  15110.             ->leftJoin('ApplicationBundle:WarehouseAction''fromSubWarehouse''WITH''i.fromActionTagId = fromSubWarehouse.id');
  15111.         // Parse dd-mm-yyyy to Y-m-d
  15112.         $startDateStr $request->query->get('startDate');
  15113.         $endDateStr $request->query->get('endDate');
  15114.         if ($startDateStr && $endDateStr) {
  15115.             try {
  15116.                 $startDate = \DateTime::createFromFormat('d-m-Y'$startDateStr)->setTime(000);
  15117.                 $endDate = \DateTime::createFromFormat('d-m-Y'$endDateStr)->setTime(235959);
  15118.                 $qb->andWhere('i.transactionDate BETWEEN :startDate AND :endDate')
  15119.                     ->setParameter('startDate'$startDate)
  15120.                     ->setParameter('endDate'$endDate);
  15121.             } catch (\Exception $e) {
  15122.                 return $this->json(['error' => 'Invalid date format. Use dd-mm-yyyy.'], 400);
  15123.             }
  15124.         }
  15125.         $results $qb->getQuery()->getResult();
  15126.         $data array_map(function ($item) {
  15127.             return [
  15128.                 'productId' => $item['productId'],
  15129.                 'transactionType' => $item['transactionType'] == 'IN' 'OUT',
  15130.                 'transactionDate' => $item['transactionDate']->format('Y-m-d'),
  15131.                 'toWarehouseId' => $item['toWarehouseId'] ?? '',
  15132.                 'toSubWarehouseId' => $item['toSubWarehouseId'] ?? '',
  15133.                 'toSubWarehouseShortName' => $item['toSubWarehouseId'] ?? '',
  15134.                 'fromWarehouseId' => $item['fromWarehouseId'] ?? '',
  15135.                 'fromSubWarehouseId' => $item['fromSubWarehouseId'] ?? '',
  15136.                 'fromSubWarehouseShortName' => $item['fromSubWarehouseId'] ?? '',
  15137.                 'quantity' => $item['quantity'],
  15138.                 'document' => !empty($item['document']) ? $item['document'] : 0,
  15139.                 'entity' => !empty($item['entity']) ? $item['entity'] : 0,
  15140.                 'entityId' => !empty($item['entityId']) ? $item['entityId'] : 0,
  15141.                 'productName' => $item['productName'],
  15142.             ];
  15143.         }, $results);
  15144.         return $this->json($data);
  15145.     }
  15146.     public function CreateStockReceivedNoteForApp(Request $request$id 0)
  15147.     {
  15148.         $em $this->getDoctrine()->getManager();
  15149.         $companyId $this->getLoggedUserCompanyId($request);
  15150.         $extDocData = [];
  15151.         $userId $request->getSession()->get(UserConstants::USER_ID);
  15152.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  15153.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  15154. //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  15155.         $userBranchIdList $request->getSession()->get('branchIdList');
  15156.         if ($userBranchIdList == null$userBranchIdList = [];
  15157.         $userBranchId $request->getSession()->get('branchId');
  15158.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  15159.             $em $this->getDoctrine()->getManager();
  15160.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //change
  15161.             $dochash $request->request->get('docHash'); //change
  15162.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  15163.             $approveRole $request->request->get('approvalRole');
  15164.             $approveHash $request->request->get('approvalHash');
  15165.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  15166.                 $loginId$approveRole$approveHash$id)
  15167.             ) {
  15168.                 if ($request->request->has('returnJson')) {
  15169.                     return new JsonResponse(array(
  15170.                         'success' => false,
  15171.                         'documentHash' => 0,
  15172.                         'documentId' => 0,
  15173.                         'billIds' => [],
  15174.                         'drIds' => [],
  15175.                         'pmntTransIds' => [],
  15176.                         'viewUrl' => '',
  15177.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  15178.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  15179.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  15180.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  15181.                     ));
  15182.                 } else
  15183.                     $this->addFlash(
  15184.                         'error',
  15185.                         'Sorry Could not insert Data.'
  15186.                     );
  15187.             } else {
  15188.                 if ($request->request->has('check_allowed'))
  15189.                     $check_allowed 1;
  15190.                 $StID Inventory::CreateNewStockReceivedNoteForApp(
  15191.                     $this->getDoctrine()->getManager(),
  15192.                     $request->request,
  15193.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  15194.                     $this->getLoggedUserCompanyId($request)
  15195.                 );
  15196.                 //now add Approval info
  15197.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  15198.                 $approveRole 1;  //created
  15199.                 $options = array(
  15200.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  15201.                     'notification_server' => $this->container->getParameter('notification_server'),
  15202.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  15203.                     'url' => $this->generateUrl(
  15204.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  15205.                         ['entity_view_route_path_name']
  15206.                     )
  15207.                 );
  15208.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  15209.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  15210.                     $StID,
  15211.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  15212.                 );
  15213.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  15214.                     $loginId,
  15215.                     $approveRole,
  15216.                     $request->request->get('approvalHash'));
  15217.                 $url $this->generateUrl(
  15218.                     'view_srcv'
  15219.                 );
  15220.                 if ($request->request->has('returnJson')) {
  15221.                     return new JsonResponse(array(
  15222.                         'success' => true,
  15223.                         'documentHash' => $dochash,
  15224.                         'documentId' => $StID,
  15225. //                        'viewUrl' => $url . "/" . $StID,
  15226.                     ));
  15227.                 } else {
  15228.                     $this->addFlash(
  15229.                         'success',
  15230.                         'Stock Received Note Added.'
  15231.                     );
  15232.                     return $this->redirect($url "/" $StID);
  15233.                 }
  15234.             }
  15235.         }
  15236.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  15237.             array(
  15238.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  15239.             )
  15240.         );
  15241.         if ($id == 0) {
  15242.         } else {
  15243.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')->findOneBy(
  15244.                 array(
  15245.                     'salesOrderId' => $id///material
  15246.                 )
  15247.             );
  15248.             //now if its not editable, redirect to view
  15249.             if ($extDoc) {
  15250.                 if ($extDoc->getEditFlag() != 1) {
  15251.                     $url $this->generateUrl(
  15252.                         'view_srcv'
  15253.                     );
  15254.                     return $this->redirect($url "/" $id);
  15255.                 } else {
  15256.                     $extDocData $extDoc;
  15257.                     $extDocDataDetails $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findOneBy(
  15258.                         array(
  15259.                             'stockReceivedNoteId' => $id///material
  15260.                         )
  15261.                     );
  15262.                 }
  15263.             } else {
  15264.             }
  15265.         }
  15266.         $INVLIST = [];
  15267.         foreach ($slotList as $slot) {
  15268.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  15269.         }
  15270.         $dataArray = array(
  15271.             'page_title' => 'Stock Received Note',
  15272. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  15273.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  15274.             'users' => Users::getUserListById($em),
  15275.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  15276.             'warehouseList' => Inventory::WarehouseList($em),
  15277.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  15278.             'warehouseActionList' => $warehouse_action_list,
  15279.             'warehouseActionListArray' => $warehouse_action_list_array,
  15280.             'extDocData' => $extDocData,
  15281.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  15282.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  15283.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  15284.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  15285. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  15286. //            'product_list' => Inventory::ProductList($em, $companyId),
  15287.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  15288.             'prefix_list' => array(
  15289.                 [
  15290.                     'id' => 1,
  15291.                     'value' => 'GN',
  15292.                     'text' => 'GN'
  15293.                 ]
  15294.             ),
  15295.             'assoc_list' => array(
  15296.                 [
  15297.                     'id' => 1,
  15298.                     'value' => 1,
  15299.                     'text' => 'GN'
  15300.                 ]
  15301.             ),
  15302.             'INVLIST' => $INVLIST,
  15303.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  15304.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  15305.             'userBranchIdList' => $userBranchIdList,
  15306.             'userBranchId' => $userBranchId,
  15307. //            'headList' => Accounts::HeadList($em),
  15308.         );
  15309.         //json
  15310.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  15311.         {
  15312.             $dataArray['success'] = true;
  15313.             return new JsonResponse(
  15314.                 $dataArray
  15315.             );
  15316.         }
  15317.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  15318.             $dataArray
  15319.         );
  15320.     }
  15321.     public function RefreshTaskOnSessionAction(Request $request)
  15322.     {
  15323.         $session $request->getSession();
  15324.         $em $this->getDoctrine()->getManager();
  15325.         $currentPlanningItemId 0;
  15326.         $currentTaskId 0;
  15327.         $taskActualStartTs 0;
  15328.         $currentTask $em->getRepository('ApplicationBundle\\Entity\\TaskLog')
  15329.             ->findOneBy(
  15330.                 array(
  15331.                     'userId' => $session->get(UserConstants::USER_ID),
  15332.                     'workingStatus' => 1
  15333.                 )
  15334.             );
  15335.         if ($currentTask) {
  15336.             $currentTaskId $currentTask->getId();
  15337.             $currentPlanningItemId $currentTask->getPlanningItemId();
  15338.             $taskActualStartTs $currentTask->getActualStartTs();
  15339.         }
  15340.         $session->set(UserConstants::USER_CURRENT_TASK_ID$currentTaskId);
  15341.         $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$currentPlanningItemId);
  15342.         return new JsonResponse(
  15343.             array(
  15344.                 'currentPlanningItemId' => $currentPlanningItemId,
  15345.                 'currentTaskId' => $currentTaskId,
  15346.                 'taskActualStartTs' => $taskActualStartTs,
  15347.             )
  15348.         );
  15349.     }
  15350.     private function getProductFormDefaults($em$companyId$loginId)
  15351.     {
  15352.         $defaults = array(
  15353.             'unitTypeId' => 0,
  15354.             'defaultTaxConfigId' => 0,
  15355.             'defaultPurchaseTaxConfigId' => 0,
  15356.             'defaultPurchaseActionTagId' => 0
  15357.         );
  15358.         if ($loginId != '' && $loginId != null) {
  15359.             $pref $em->getRepository('ApplicationBundle\\Entity\\InvProductFormPreference')->findOneBy(array(
  15360.                 'companyId' => $companyId,
  15361.                 'loginId' => $loginId
  15362.             ));
  15363.             if ($pref) {
  15364.                 $defaults['unitTypeId'] = (int) $pref->getUnitTypeId();
  15365.                 $defaults['defaultTaxConfigId'] = (int) $pref->getDefaultTaxConfigId();
  15366.                 $defaults['defaultPurchaseTaxConfigId'] = (int) $pref->getDefaultPurchaseTaxConfigId();
  15367.                 $defaults['defaultPurchaseActionTagId'] = (int) $pref->getDefaultPurchaseActionTagId();
  15368.             }
  15369.         }
  15370.         if ($defaults['unitTypeId'] == 0) {
  15371.             $defaults['unitTypeId'] = $this->resolveDefaultPcsUnitTypeId($em);
  15372.         }
  15373.         if ($defaults['defaultTaxConfigId'] == || $defaults['defaultPurchaseTaxConfigId'] == || $defaults['defaultPurchaseActionTagId'] == 0) {
  15374.             $defaultItemGroup $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(array(
  15375.                 'CompanyId' => $companyId,
  15376.                 'status' => GeneralConstant::ACTIVE
  15377.             ));
  15378.             if ($defaultItemGroup) {
  15379.                 if ($defaults['defaultTaxConfigId'] == 0) {
  15380.                     $defaults['defaultTaxConfigId'] = (int) $defaultItemGroup->getDefaultTaxConfigId();
  15381.                 }
  15382.                 if ($defaults['defaultPurchaseTaxConfigId'] == 0) {
  15383.                     $defaults['defaultPurchaseTaxConfigId'] = (int) $defaultItemGroup->getDefaultPurchaseTaxConfigId();
  15384.                 }
  15385.                 if ($defaults['defaultPurchaseActionTagId'] == 0) {
  15386.                     $defaults['defaultPurchaseActionTagId'] = (int) $defaultItemGroup->getDefaultPurchaseActionTagId();
  15387.                 }
  15388.                 if ($defaults['unitTypeId'] == 0) {
  15389.                     $defaults['unitTypeId'] = (int) $defaultItemGroup->getUnitTypeId();
  15390.                 }
  15391.             }
  15392.         }
  15393.         return $defaults;
  15394.     }
  15395.     private function resolveDefaultPcsUnitTypeId($em)
  15396.     {
  15397.         $unitTypes Inventory::UnitTypeList($em);
  15398.         foreach ($unitTypes as $unitType) {
  15399.             $name = isset($unitType['name']) ? strtoupper(trim($unitType['name'])) : '';
  15400.             $suffix = isset($unitType['classSuffix']) ? strtoupper(trim($unitType['classSuffix'])) : '';
  15401.             if ($name === 'PCS' || $suffix === 'PCS') {
  15402.                 return (int) $unitType['id'];
  15403.             }
  15404.         }
  15405.         foreach ($unitTypes as $unitType) {
  15406.             if (isset($unitType['id']) && $unitType['id'] != && $unitType['id'] != '') {
  15407.                 return (int) $unitType['id'];
  15408.             }
  15409.         }
  15410.         return 0;
  15411.     }
  15412.     private function saveProductFormDefaults($em$companyId$loginId$savedEntityRequest $request)
  15413.     {
  15414.         if ($loginId == '' || $loginId == null) {
  15415.             return;
  15416.         }
  15417.         $unitTypeId 0;
  15418.         $defaultTaxConfigId 0;
  15419.         $defaultPurchaseTaxConfigId 0;
  15420.         $defaultPurchaseActionTagId 0;
  15421.         if ($savedEntity) {
  15422.             if (method_exists($savedEntity'getUnitTypeId')) {
  15423.                 $unitTypeId = (int) $savedEntity->getUnitTypeId();
  15424.             }
  15425.             if (method_exists($savedEntity'getDefaultTaxConfigId')) {
  15426.                 $defaultTaxConfigId = (int) $savedEntity->getDefaultTaxConfigId();
  15427.             }
  15428.             if (method_exists($savedEntity'getDefaultPurchaseTaxConfigId')) {
  15429.                 $defaultPurchaseTaxConfigId = (int) $savedEntity->getDefaultPurchaseTaxConfigId();
  15430.             }
  15431.             if (method_exists($savedEntity'getDefaultPurchaseActionTagId')) {
  15432.                 $defaultPurchaseActionTagId = (int) $savedEntity->getDefaultPurchaseActionTagId();
  15433.             }
  15434.         }
  15435.         if ($unitTypeId == 0) {
  15436.             $unitTypeId = (int) $request->request->get('unitTypeId'0);
  15437.         }
  15438.         if ($defaultTaxConfigId == 0) {
  15439.             $defaultTaxConfigId = (int) $request->request->get('defaultTaxConfigId'0);
  15440.             if ($defaultTaxConfigId == 0) {
  15441.                 $taxConfigIds $request->request->get('taxConfigIds', array());
  15442.                 if (!empty($taxConfigIds)) {
  15443.                     $defaultTaxConfigId = (int) $taxConfigIds[0];
  15444.                 }
  15445.             }
  15446.         }
  15447.         if ($defaultPurchaseTaxConfigId == 0) {
  15448.             $defaultPurchaseTaxConfigId = (int) $request->request->get('defaultPurchaseTaxConfigId'0);
  15449.             if ($defaultPurchaseTaxConfigId == 0) {
  15450.                 $purchaseTaxConfigIds $request->request->get('purchaseTaxConfigIds', array());
  15451.                 if (!empty($purchaseTaxConfigIds)) {
  15452.                     $defaultPurchaseTaxConfigId = (int) $purchaseTaxConfigIds[0];
  15453.                 }
  15454.             }
  15455.         }
  15456.         if ($defaultPurchaseActionTagId == 0) {
  15457.             $defaultPurchaseActionTagId = (int) $request->request->get('defaultPurchaseActionTagId'0);
  15458.         }
  15459.         $pref $em->getRepository('ApplicationBundle\\Entity\\InvProductFormPreference')->findOneBy(array(
  15460.             'companyId' => $companyId,
  15461.             'loginId' => $loginId
  15462.         ));
  15463.         if (!$pref) {
  15464.             $pref = new \ApplicationBundle\Entity\InvProductFormPreference();
  15465.             $pref->setCompanyId($companyId);
  15466.             $pref->setLoginId($loginId);
  15467.             $em->persist($pref);
  15468.         }
  15469.         $pref->setUnitTypeId($unitTypeId);
  15470.         $pref->setDefaultTaxConfigId($defaultTaxConfigId);
  15471.         $pref->setDefaultPurchaseTaxConfigId($defaultPurchaseTaxConfigId);
  15472.         $pref->setDefaultPurchaseActionTagId($defaultPurchaseActionTagId);
  15473.         $em->flush();
  15474.     }
  15475.     // â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  15476.     // S2.2 â€” EPC Category catalog
  15477.     // â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  15478.     public function EpcCategoryListAction(Request $request)
  15479.     {
  15480.         $em $this->getDoctrine()->getManager();
  15481.         $categories $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')
  15482.             ->findBy([], ['displayOrder' => 'ASC''code' => 'ASC']);
  15483.         return $this->render('@Inventory/pages/list/list_epc_categories.html.twig', [
  15484.             'page_title'  => 'EPC Category Catalog',
  15485.             'categories'  => $categories,
  15486.         ]);
  15487.     }
  15488.     public function EpcCategoryEditAction(Request $request$id 0)
  15489.     {
  15490.         $em $this->getDoctrine()->getManager();
  15491.         $ex_id = (int)($request->request->get('ex_id'$id));
  15492.         $cat   null;
  15493.         if ($ex_id 0) {
  15494.             $cat $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')->find($ex_id);
  15495.         }
  15496.         if ($request->isMethod('POST')) {
  15497.             $entity $cat ?? new \ApplicationBundle\Entity\EpcCategory();
  15498.             $entity->setCode(strtoupper(trim($request->request->get('code'''))));
  15499.             $entity->setName(trim($request->request->get('name''')));
  15500.             $entity->setDescription(trim($request->request->get('description''')));
  15501.             $entity->setDisplayOrder((int)$request->request->get('display_order'99));
  15502.             $entity->setActive($request->request->get('active') ? 0);
  15503.             if (!$cat) {
  15504.                 $entity->setCreatedAt(new \DateTime());
  15505.                 $entity->setCreatedLoginId((int)$request->getSession()->get(UserConstants::USER_LOGIN_ID0));
  15506.             }
  15507.             $em->persist($entity);
  15508.             $em->flush();
  15509.             $this->addFlash('success''EPC Category saved.');
  15510.             return $this->redirectToRoute('epc_category_list');
  15511.         }
  15512.         return $this->render('@Inventory/pages/input_forms/edit_epc_category.html.twig', [
  15513.             'page_title' => $ex_id 'Edit EPC Category' 'New EPC Category',
  15514.             'ex_id'      => $ex_id,
  15515.             'cat'        => $cat,
  15516.         ]);
  15517.     }
  15518.     public function EpcCategoryGetAllAction(Request $request)
  15519.     {
  15520.         $em $this->getDoctrine()->getManager();
  15521.         $cats $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')
  15522.             ->findBy(['active' => 1], ['displayOrder' => 'ASC']);
  15523.         $data = [];
  15524.         foreach ($cats as $c) {
  15525.             $data[] = ['code' => $c->getCode(), 'name' => $c->getName()];
  15526.         }
  15527.         return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => true'categories' => $data]);
  15528.     }
  15529.     // â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  15530.     // S2.1 â€” Article Translation endpoints
  15531.     // â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  15532.     public function SuggestProductsFromCentralAction(Request $request)
  15533.     {
  15534.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15535.         if ($systemType === '_CENTRAL_') {
  15536.             return new JsonResponse(['success' => false'message' => 'Not applicable on central'], 403);
  15537.         }
  15538.         $em        $this->getDoctrine()->getManager();
  15539.         $companyId $this->getLoggedUserCompanyId($request);
  15540.         $query     trim($request->request->get('query'''));
  15541.         $igName    trim($request->request->get('igName'''));
  15542.         $modelNo   trim($request->request->get('modelNo'''));
  15543.         if (strlen($query) < && !$modelNo) {
  15544.             return new JsonResponse(['success' => true'results' => []]);
  15545.         }
  15546.         $results Inventory::SearchProductsOnCentral($query$igName$modelNo10);
  15547.         // filter out products already local for this company
  15548.         $filtered = [];
  15549.         foreach ($results as $row) {
  15550.             $globalId = (int)($row['globalId'] ?? 0);
  15551.             if ($globalId 0) {
  15552.                 $local $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  15553.                 if ($local) continue;
  15554.             }
  15555.             $filtered[] = $row;
  15556.         }
  15557.         return new JsonResponse(['success' => true'results' => $filtered]);
  15558.     }
  15559.     public function ImportProductFromCentralAction(Request $request)
  15560.     {
  15561.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15562.         if ($systemType === '_CENTRAL_') {
  15563.             return new JsonResponse(['success' => false'message' => 'Not applicable on central'], 403);
  15564.         }
  15565.         $em        $this->getDoctrine()->getManager();
  15566.         $companyId $this->getLoggedUserCompanyId($request);
  15567.         $globalId  = (int)$request->request->get('globalId'0);
  15568.         if ($globalId <= 0) {
  15569.             return new JsonResponse(['success' => false'message' => 'globalId is required'], 400);
  15570.         }
  15571.         // check idempotency
  15572.         $existing $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  15573.         if ($existing) {
  15574.             return new JsonResponse(['success' => true'productId' => $existing->getId(), 'message' => 'already_exists']);
  15575.         }
  15576.         // fetch the full row from central by globalId
  15577.         $centralUrl = \ApplicationBundle\Constants\GeneralConstant::HONEYBEE_CENTRAL_SERVER;
  15578.         $curl curl_init();
  15579.         curl_setopt_array($curl, [
  15580.             CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  15581.             CURLOPT_URL => $centralUrl '/api/search_global_products',
  15582.             CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 12,
  15583.             CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  15584.             CURLOPT_POSTFIELDS => http_build_query(['globalId' => $globalId]),
  15585.         ]);
  15586.         $response  curl_exec($curl);
  15587.         $curlError curl_error($curl);
  15588.         curl_close($curl);
  15589.         if ($curlError || !$response) {
  15590.             return new JsonResponse(['success' => false'message' => 'Central server unreachable'], 503);
  15591.         }
  15592.         $data json_decode($responsetrue);
  15593.         if (!is_array($data) || empty($data['success']) || empty($data['results'])) {
  15594.             return new JsonResponse(['success' => false'message' => 'Product not found on central'], 404);
  15595.         }
  15596.         try {
  15597.             $productId Inventory::MaterializeProductFromCentral($em$companyId$data['results'][0]);
  15598.         } catch (\Throwable $e) {
  15599.             return new JsonResponse(['success' => false'message' => $e->getMessage()], 500);
  15600.         }
  15601.         return new JsonResponse(['success' => true'productId' => $productId'message' => 'imported']);
  15602.     }
  15603.     /**
  15604.      * Dev-admin only: proxy a central product search so the create-product form can
  15605.      * "Load from Central". Returns the central rows (igName/categoryName/specDataNamed
  15606.      * + descriptive fields) for the JS to populate the form. No DB write happens here â€”
  15607.      * the user reviews and Saves to materialize. Gated by devAdminMode.
  15608.      */
  15609.     public function SearchCentralProductsAction(Request $request)
  15610.     {
  15611.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15612.         if ($systemType === '_CENTRAL_') {
  15613.             return new JsonResponse(['success' => false'message' => 'Not applicable on central'], 403);
  15614.         }
  15615.         if ((int) $request->getSession()->get('devAdminMode'0) !== 1) {
  15616.             return new JsonResponse(['success' => false'message' => 'Requires devAdmin mode (open with ?devAdminOn=1)'], 403);
  15617.         }
  15618.         $query    trim($request->request->get('query'''));
  15619.         $globalId = (int) $request->request->get('globalId'0);
  15620.         if ($globalId <= && strlen($query) < 2) {
  15621.             return new JsonResponse(['success' => false'message' => 'query must be at least 2 characters'], 400);
  15622.         }
  15623.         $centralUrl = \ApplicationBundle\Constants\GeneralConstant::HONEYBEE_CENTRAL_SERVER;
  15624.         $curl curl_init();
  15625.         curl_setopt_array($curl, [
  15626.             CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  15627.             CURLOPT_URL => $centralUrl '/api/search_global_products',
  15628.             CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 15,
  15629.             CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  15630.             CURLOPT_POSTFIELDS => http_build_query($globalId ? ['globalId' => $globalId] : ['query' => $query'limit' => 20]),
  15631.         ]);
  15632.         $response  curl_exec($curl);
  15633.         $curlError curl_error($curl);
  15634.         curl_close($curl);
  15635.         if ($curlError || !$response) {
  15636.             return new JsonResponse(['success' => false'message' => 'Central server unreachable' . ($curlError ': ' $curlError '')], 503);
  15637.         }
  15638.         $data json_decode($responsetrue);
  15639.         if (!is_array($data)) {
  15640.             return new JsonResponse(['success' => false'message' => 'Bad response from central'], 502);
  15641.         }
  15642.         return new JsonResponse($data);
  15643.     }
  15644.     public function ArticleTranslationSaveAction(Request $request)
  15645.     {
  15646.         $em        $this->getDoctrine()->getManager();
  15647.         $articleId = (int)$request->request->get('article_id'0);
  15648.         $data      $request->request->get('translations', []);
  15649.         $loginId   = (int)$request->getSession()->get(UserConstants::USER_LOGIN_ID0);
  15650.         if ($articleId === || !is_array($data)) {
  15651.             return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => false'message' => 'Invalid input']);
  15652.         }
  15653.         Inventory::saveArticleTranslations($em$articleId$data$loginId);
  15654.         return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => true]);
  15655.     }
  15656.     public function ArticleTranslationGetAction(Request $request$articleId 0)
  15657.     {
  15658.         $em $this->getDoctrine()->getManager();
  15659.         $translations Inventory::getArticleTranslations($em, (int)$articleId);
  15660.         return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => true'translations' => $translations]);
  15661.     }
  15662.     // ===== Global-product / central-product-control cluster â€” moved from the legacy
  15663.     // ApplicationBundle\Controller\InventoryController (2026-07-03 consolidation). Behavior
  15664.     // preserved verbatim; routes repointed here. =====
  15665.     public function SyncProductAction(Request $request$id)
  15666.     {
  15667.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15668.         $em_local $this->getDoctrine()->getManager();
  15669.         if ($systemType == '_ERP_') {
  15670.             $product $em_local->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($id);
  15671.             if (!$product) {
  15672.                 return new JsonResponse(['error' => 'Product not found'], 404);
  15673.             }
  15674.             // Get category details
  15675.             $category $em_local->getRepository('ApplicationBundle\\Entity\\InvProductCategories')->find($product->getCategoryId());
  15676.             $brand $em_local -> getRepository('ApplicationBundle\\Entity\\BrandCompany')->find($product->getBrandCompany());
  15677.             $productData = [];
  15678.             $categoryData = [];
  15679.             $brandData = [];
  15680.             // Get product fields
  15681.             $reflectionClass = new \ReflectionClass($product);
  15682.             foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  15683.                 if (strpos($method->getName(), 'get') === 0) {
  15684.                     $property lcfirst(str_replace('get'''$method->getName()));
  15685.                     $productData[$property] = $method->invoke($product);
  15686.                 }
  15687.             }
  15688.             // Get category fields
  15689.             if ($category) {
  15690.                 $categoryReflection = new \ReflectionClass($category);
  15691.                 foreach ($categoryReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  15692.                     if (strpos($method->getName(), 'get') === 0) {
  15693.                         $property lcfirst(str_replace('get'''$method->getName()));
  15694.                         $categoryData[$property] = $method->invoke($category);
  15695.                     }
  15696.                 }
  15697.             }
  15698.             // Brand data
  15699.             if ($brand) {
  15700.                 $brandReflection = new \ReflectionClass($brand);
  15701.                 foreach ($brandReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  15702.                     if (strpos($method->getName(), 'get') === 0) {
  15703.                         $property lcfirst(str_replace('get'''$method->getName()));
  15704.                         $brandData[$property] = $method->invoke($brand);
  15705.                     }
  15706.                 }
  15707.             }
  15708.             // Store product data in pending_data
  15709.             $product->setPendingData(json_encode($productData));
  15710.             $em_local->flush();
  15711.             // Send  product,brand & category to central
  15712.             $syncData = [
  15713.                 'product' => $productData,
  15714.                 'category' => $categoryData,
  15715.                 'brand' => $brandData
  15716.             ];
  15717.             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/product_sync/' $id;
  15718.             $curl curl_init();
  15719.             curl_setopt_array($curl, [
  15720.                 CURLOPT_RETURNTRANSFER => true,
  15721.                 CURLOPT_POST => true,
  15722.                 CURLOPT_URL => $urlToCall,
  15723.                 CURLOPT_CONNECTTIMEOUT => 10,
  15724.                 CURLOPT_SSL_VERIFYPEER => false,
  15725.                 CURLOPT_SSL_VERIFYHOST => false,
  15726.                 CURLOPT_HTTPHEADER => [],
  15727.                 CURLOPT_POSTFIELDS => ['syncData' => json_encode($syncData)]
  15728.             ]);
  15729.             $retData curl_exec($curl);
  15730.             $errData curl_error($curl);
  15731.             curl_close($curl);
  15732.             if ($errData) {
  15733.                 return new JsonResponse(['error' => $errData], 500);
  15734.             }
  15735.             $retDataObj json_decode($retDatatrue);
  15736.             if (isset($retDataObj['globalId'])) {
  15737.                 $product->setGlobalId($retDataObj['globalId']);
  15738.                 $em_local->flush();
  15739.             }
  15740.             return new JsonResponse(['message' => 'Product (pending) and category synced to central server!']);
  15741.         }
  15742.         // CENTRAL SYSTEM PROCESSING
  15743.         else if ($systemType == '_CENTRAL_') {
  15744.             $requestData $request->get('syncData');
  15745.             if (!$requestData) {
  15746.                 return new JsonResponse(['error' => 'Invalid data received'], 400);
  15747.             }
  15748.             $requestData json_decode($requestDatatrue);
  15749.             $productData $requestData['product'] ?? null;
  15750.             $categoryData $requestData['category'] ?? null;
  15751.             $brandData $requestData['brand'] ?? null;
  15752.             if (!$productData) {
  15753.                 return new JsonResponse(['error' => 'Product data missing'], 400);
  15754.             }
  15755.             // Process product (Store in pending_data)
  15756.             $product $em_local->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($productData['id']) ?? new InvProducts();
  15757.             // Store in pending_data until approval
  15758.             $product->setPendingData(json_encode($productData));
  15759.             $this->ApproveProductAction($id);
  15760.             $em_local->persist($product);
  15761.             // Process category (Save directly)
  15762.             if ($categoryData) {
  15763.                 $category $em_local->getRepository('ApplicationBundle\\Entity\\InvProductCategories')->find($categoryData['id']) ?? new InvProductCategories();
  15764.                 foreach ($categoryData as $field => $value) {
  15765.                     if ($field === 'id') continue;
  15766.                     $setterMethod 'set' ucfirst($field);
  15767.                     if (method_exists($category$setterMethod)) {
  15768.                         $category->$setterMethod($value);
  15769.                     }
  15770.                 }
  15771.                 $em_local->persist($category);
  15772.             }
  15773.             // process brand data
  15774.             if($brandData){
  15775.                 $brand $em_local->getRepository('ApplicationBundle\\Entity\\BrandCompany')->find($brandData['id']) ?? new BrandCompany();
  15776.                 foreach ($brandData as $field => $value){
  15777.                     if($field === 'id') continue;
  15778.                     $setterMethod 'set'.ucfirst($field);
  15779.                     if(method_exists($brand,$setterMethod)){
  15780.                         $brand->$setterMethod($value);
  15781.                     }
  15782.                 }
  15783.                 $em_local->persist($brand);
  15784.             }
  15785.             $em_local->flush();
  15786.             return new JsonResponse(['globalId' => $product->getId()]);
  15787.         }
  15788.         return new JsonResponse("Product (pending) and category updated successfully in central!");
  15789.     }
  15790.     public function CheckGlobalProductAction(Request $request)
  15791.     {
  15792.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15793.         if ($systemType !== '_CENTRAL_') {
  15794.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  15795.         }
  15796.         $em $this->getDoctrine()->getManager();
  15797.         $igName      trim($request->request->get('igName'''));
  15798.         $productName trim($request->request->get('productName'''));
  15799.         $modelNo     trim($request->request->get('modelNo'''));
  15800.         if (!$igName || !$productName) {
  15801.             return new JsonResponse(['success' => false'found' => false'message' => 'igName and productName are required']);
  15802.         }
  15803.         $ig $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(['name' => $igName'type' => 1]);
  15804.         if (!$ig) {
  15805.             return new JsonResponse(['success' => true'found' => false]);
  15806.         }
  15807.         $product null;
  15808.         if ($modelNo) {
  15809.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'modelNo' => $modelNo]);
  15810.         }
  15811.         if (!$product) {
  15812.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'name' => $productName]);
  15813.         }
  15814.         if (!$product) {
  15815.             return new JsonResponse(['success' => true'found' => false]);
  15816.         }
  15817.         return new JsonResponse(['success' => true'found' => true'globalId' => $product->getGlobalId() ?: $product->getId()]);
  15818.     }
  15819.     /** Tenant-side: pull this product's canonical version from the central catalog, overwriting local drift. */
  15820.     public function ResetProductFromCentralAction(Request $request$id)
  15821.     {
  15822.         $em $this->getDoctrine()->getManager();
  15823.         $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find((int) $id);
  15824.         if (!$product) {
  15825.             return new JsonResponse(['success' => false'message' => 'Product not found.'], 404);
  15826.         }
  15827.         $res = \ApplicationBundle\Modules\Inventory\Inventory::ResetLocalProductFromCentral($em$product);
  15828.         return new JsonResponse($res, !empty($res['success']) ? 200 400);
  15829.     }
  15830.     public function SearchGlobalProductsAction(Request $request)
  15831.     {
  15832.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15833.         if ($systemType !== '_CENTRAL_') {
  15834.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  15835.         }
  15836.         $em          $this->getDoctrine()->getManager();
  15837.         $query       trim($request->request->get('query'''));
  15838.         $igName      trim($request->request->get('igName'''));
  15839.         $modelNo     trim($request->request->get('modelNo'''));
  15840.         $globalId    = (int)$request->request->get('globalId'0);
  15841.         $limit       min((int)$request->request->get('limit'10), 25);
  15842.         if ($globalId 0) {
  15843.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  15844.             if (!$product) {
  15845.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  15846.             }
  15847.             if (!$product) {
  15848.                 return new JsonResponse(['success' => true'count' => 0'results' => []]);
  15849.             }
  15850.             $ig $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->find($product->getIgId());
  15851.             return new JsonResponse(['success' => true'count' => 1'results' => [
  15852.                 $this->buildGlobalProductRow($em$product$ig),
  15853.             ]]);
  15854.         }
  15855.         if (strlen($query) < && !$modelNo) {
  15856.             return new JsonResponse(['success' => false'message' => 'query must be at least 2 characters'], 400);
  15857.         }
  15858.         $conn $em->getConnection();
  15859.         // The central catalog DB is lean â€” it may not carry the full ERP inventory schema
  15860.         // (e.g. inv_product_brand). A LEFT JOIN still hard-fails on a missing table, so only join
  15861.         // the enrichment tables that actually exist; absent ones fall back to an empty literal.
  15862.         $existingTables = [];
  15863.         $productCols = [];
  15864.         try {
  15865.             foreach ($this->dbalFetchAllAssoc(
  15866.                 $conn,
  15867.                 "SELECT table_name AS t FROM information_schema.tables WHERE table_schema = DATABASE()"
  15868.             ) as $r) {
  15869.                 $existingTables[strtolower($r['t'])] = true;
  15870.             }
  15871.             // Also detect which COLUMNS exist on inv_products â€” a lean central may be missing
  15872.             // optional columns (description, alias, model_no, global_id, sync_flag, â€¦).
  15873.             foreach ($this->dbalFetchAllAssoc(
  15874.                 $conn,
  15875.                 "SELECT column_name AS c FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'inv_products'"
  15876.             ) as $r) {
  15877.                 $productCols[strtolower($r['c'])] = true;
  15878.             }
  15879.         } catch (\Throwable $e) { /* detection failed â†’ assume everything exists (old behaviour) */ }
  15880.         $hasTable = function ($t) use ($existingTables) {
  15881.             return empty($existingTables) || isset($existingTables[strtolower($t)]);
  15882.         };
  15883.         $hasCol = function ($c) use ($productCols) {
  15884.             return empty($productCols) || isset($productCols[strtolower($c)]);
  15885.         };
  15886.         $hasModelNo $hasCol('model_no');
  15887.         $where = [];
  15888.         $params = [];
  15889.         if ($query !== '') {
  15890.             $where[] = $hasModelNo '(p.name LIKE :q OR p.model_no LIKE :q)' 'p.name LIKE :q';
  15891.             $params['q'] = '%' $query '%';
  15892.         }
  15893.         if ($modelNo !== '' && $hasModelNo) {
  15894.             $where[] = 'p.model_no LIKE :model';
  15895.             $params['model'] = '%' $modelNo '%';
  15896.         }
  15897.         if ($igName !== '' && $hasTable('inv_item_group')) {
  15898.             $where[] = 'ig.name = :igName';
  15899.             $params['igName'] = $igName;
  15900.         }
  15901.         $whereSql $where ? ('WHERE ' implode(' AND '$where)) : '';
  15902.         // Base columns on inv_products â€” include only those that exist; missing ones become ''.
  15903.         $baseColumns = [
  15904.             ['id',          'p.id'],
  15905.             ['name',        'p.name'],
  15906.             ['modelNo',     'p.model_no'],
  15907.             ['productFdm',  'p.product_fdm'],
  15908.             ['globalId',    'p.global_id'],
  15909.             ['syncFlag',    'p.sync_flag'],
  15910.             ['description''p.description'],
  15911.             ['alias',       'p.alias'],
  15912.         ];
  15913.         $selects = [];
  15914.         foreach ($baseColumns as $bc) {
  15915.             list($as$col) = $bc;
  15916.             $rawCol substr($col2); // strip "p."
  15917.             if ($hasCol($rawCol)) {
  15918.                 $selects[] = ($rawCol === $as) ? $col : ($col ' AS ' $as);
  15919.             } else {
  15920.                 $selects[] = "'' AS $as";
  15921.             }
  15922.         }
  15923.         $joins '';
  15924.         $enrich = [
  15925.             ['inv_item_group',            'ig',  'ig.id = p.ig_id',                              'ig.name',       'igName'],
  15926.             ['inv_product_categories',    'cat''cat.id = p.category_id',                       'cat.name',      'categoryName'],
  15927.             ['inv_product_sub_categories','sub''sub.id = p.sub_category_id',                   'sub.name',      'subCategoryName'],
  15928.             ['brand_company',             'br',  'br.id = p.brand_company',                      'br.name',       'brandName'],
  15929.             ['unit_type',                 'ut',  'ut.id = p.unit_type_id',                       'ut.name',       'uomName'],
  15930.             ['inv_product_images',        'img''img.product_id = p.id AND img.is_default = 1''img.file_name''image'],
  15931.         ];
  15932.         foreach ($enrich as $e) {
  15933.             list($tbl$alias$on$col$as) = $e;
  15934.             if ($hasTable($tbl)) {
  15935.                 $selects[] = "$col AS $as";
  15936.                 $joins   .= "\n                LEFT JOIN $tbl $alias ON $on";
  15937.             } else {
  15938.                 $selects[] = "'' AS $as";
  15939.             }
  15940.         }
  15941.         // ORDER BY: exact-name first; the model_no tier only when that column exists.
  15942.         $orderSql "ORDER BY CASE WHEN p.name = :exactName THEN 0 ";
  15943.         if ($hasModelNo) {
  15944.             $orderSql .= "WHEN p.model_no = :exactModel THEN 1 ";
  15945.         }
  15946.         $orderSql .= "ELSE 2 END, p.name ASC";
  15947.         $sql "SELECT " implode(', '$selects) . "
  15948.                 FROM inv_products p" $joins "
  15949.                 $whereSql
  15950.                 $orderSql
  15951.                 LIMIT :lim";
  15952.         $params['exactName']  = $query ?: '';
  15953.         if ($hasModelNo) {
  15954.             $params['exactModel'] = $modelNo ?: $query;
  15955.         }
  15956.         $params['lim']        = $limit;
  15957.         $types = [];
  15958.         foreach ($params as $key => $val) {
  15959.             $types[$key] = is_int($val) ? \PDO::PARAM_INT : \PDO::PARAM_STR;
  15960.         }
  15961.         $rows $this->dbalFetchAllAssoc($conn$sql$params$types);
  15962.         foreach ($rows as &$row) {
  15963.             $row['globalId'] = (int)($row['globalId'] ?: $row['id']);
  15964.         }
  15965.         return new JsonResponse(['success' => true'count' => count($rows), 'results' => $rows]);
  15966.     }
  15967.     /**
  15968.      * Fetch all rows as associative arrays, portable across Doctrine DBAL versions.
  15969.      * The central server runs an older DBAL where fetchAllAssociative() does not exist â€” fall
  15970.      * back to the legacy Connection::fetchAll(). Both accept ($sql, $params, $types).
  15971.      */
  15972.     private function dbalFetchAllAssoc($conn$sql, array $params = [], array $types = [])
  15973.     {
  15974.         if (method_exists($conn'fetchAllAssociative')) {
  15975.             return $conn->fetchAllAssociative($sql$params$types);
  15976.         }
  15977.         return $conn->fetchAll($sql$params$types);
  15978.     }
  15979.     private function buildGlobalProductRow($em$product$ig)
  15980.     {
  15981.         $categoryName '';
  15982.         $subCategoryName '';
  15983.         $brandName '';
  15984.         $uomName '';
  15985.         // Enrichment tables may be absent on a lean central DB â€” never let a missing one break the row.
  15986.         try {
  15987.             if ($product->getCategoryId()) {
  15988.                 $cat $em->getRepository('ApplicationBundle\\Entity\\InvProductCategories')->find($product->getCategoryId());
  15989.                 if ($cat$categoryName $cat->getName();
  15990.             }
  15991.         } catch (\Throwable $e) { /* table absent */ }
  15992.         try {
  15993.             if ($product->getSubCategoryId()) {
  15994.                 $sub $em->getRepository('ApplicationBundle\\Entity\\InvProductSubCategories')->find($product->getSubCategoryId());
  15995.                 if ($sub$subCategoryName $sub->getName();
  15996.             }
  15997.         } catch (\Throwable $e) { /* table absent */ }
  15998.         try {
  15999.             if ($product->getBrandCompany()) {
  16000.                 $br $em->getRepository('ApplicationBundle\\Entity\\BrandCompany')->find($product->getBrandCompany());
  16001.                 if ($br$brandName $br->getName();
  16002.             }
  16003.         } catch (\Throwable $e) { /* table absent */ }
  16004.         try {
  16005.             if ($product->getUnitTypeId()) {
  16006.                 $ut $em->getRepository('ApplicationBundle\\Entity\\UnitType')->find($product->getUnitTypeId());
  16007.                 if ($ut$uomName $ut->getName();
  16008.             }
  16009.         } catch (\Throwable $e) { /* table absent */ }
  16010.         $row = [
  16011.             'id'              => $product->getId(),
  16012.             'globalId'        => $product->getGlobalId() ?: $product->getId(),
  16013.             'name'            => $product->getName(),
  16014.             'modelNo'         => $product->getModelNo(),
  16015.             'productFdm'      => $product->getProductFdm(),
  16016.             'description'     => $product->getNote(),
  16017.             'alias'           => $product->getAlias(),
  16018.             'igName'          => $ig $ig->getName() : '',
  16019.             'categoryName'    => $categoryName,
  16020.             'subCategoryName' => $subCategoryName,
  16021.             'brandName'       => $brandName,
  16022.             'uomName'         => $uomName,
  16023.             'image'           => '',
  16024.         ];
  16025.         // Publish the full descriptive catalog field set (specs, sizes, weights,
  16026.         // crate data, etc.) so a synced ERP can mirror almost the entire record.
  16027.         foreach (\ApplicationBundle\Modules\Inventory\Inventory::globalCatalogFields() as $field) {
  16028.             $getter 'get' ucfirst($field);
  16029.             if (method_exists($product$getter)) {
  16030.                 $row[$field] = $product->$getter();
  16031.             }
  16032.         }
  16033.         // Publish the spec table resolved to spec-type NAMES so a synced ERP can
  16034.         // recreate any missing spec type and carry the full spec table.
  16035.         $specDataNamed = [];
  16036.         try {
  16037.             $specArr $product->getSpecData() ? json_decode($product->getSpecData(), true) : [];
  16038.             if (is_array($specArr)) {
  16039.                 foreach ($specArr as $sd) {
  16040.                     $sid = isset($sd['id']) ? $sd['id'] : null;
  16041.                     if (!$sid) continue;
  16042.                     $st $em->getRepository('ApplicationBundle\\Entity\\SpecType')->find($sid);
  16043.                     $specDataNamed[] = ['name' => $st $st->getName() : '''value' => isset($sd['value']) ? $sd['value'] : ''];
  16044.                 }
  16045.             }
  16046.         } catch (\Throwable $e) { /* spec table absent on lean central */ }
  16047.         $row['specDataNamed'] = $specDataNamed;
  16048.         return $row;
  16049.     }
  16050.     public function RegisterGlobalProductAction(Request $request)
  16051.     {
  16052.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16053.         if ($systemType !== '_CENTRAL_') {
  16054.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16055.         }
  16056.         $em $this->getDoctrine()->getManager();
  16057.         $igName      trim($request->request->get('igName'''));
  16058.         $productName trim($request->request->get('productName'''));
  16059.         $modelNo     trim($request->request->get('modelNo'''));
  16060.         $productFdm  $request->request->get('productFdm''');
  16061.         if (!$igName || !$productName) {
  16062.             return new JsonResponse(['success' => false'message' => 'igName and productName are required'], 400);
  16063.         }
  16064.         $ig $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(['name' => $igName'type' => 1]);
  16065.         if (!$ig) {
  16066.             $ig = new \ApplicationBundle\Entity\InvItemGroup();
  16067.             $ig->setName($igName);
  16068.             $ig->setType(1);
  16069.             $em->persist($ig);
  16070.             $em->flush();
  16071.             $ig->setGlobalId($ig->getId());
  16072.             $em->flush();
  16073.         }
  16074.         // Race-condition guard: check again after potential ig creation
  16075.         $existing null;
  16076.         if ($modelNo) {
  16077.             $existing $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'modelNo' => $modelNo]);
  16078.         }
  16079.         if (!$existing) {
  16080.             $existing $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'name' => $productName]);
  16081.         }
  16082.         if ($existing) {
  16083.             return new JsonResponse(['success' => true'globalId' => $existing->getGlobalId() ?: $existing->getId()]);
  16084.         }
  16085.         $product = new \ApplicationBundle\Entity\InvProducts();
  16086.         $product->setName($productName);
  16087.         $product->setModelNo($modelNo);
  16088.         $product->setProductFdm($productFdm);
  16089.         $product->setIgId($ig->getId());
  16090.         $product->setSyncFlag(2);
  16091.         $em->persist($product);
  16092.         $em->flush();
  16093.         $product->setGlobalId($product->getId());
  16094.         $em->flush();
  16095.         return new JsonResponse(['success' => true'globalId' => $product->getId()]);
  16096.     }
  16097.     public function PushGlobalProductToErpsAction(Request $request)
  16098.     {
  16099.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16100.         if ($systemType !== '_CENTRAL_') {
  16101.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16102.         }
  16103.         $globalId = (int)$request->request->get('globalId'0);
  16104.         $data     $request->request->get('data', []);
  16105.         if (!$globalId) {
  16106.             return new JsonResponse(['success' => false'message' => 'globalId is required'], 400);
  16107.         }
  16108.         // Build the full central record ONCE (descriptive fields + igName/category +
  16109.         // named spec list) so each tenant sync applies it without calling back.
  16110.         $em $this->getDoctrine()->getManager();
  16111.         $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  16112.         if (!$product$product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  16113.         if (!$product) {
  16114.             return new JsonResponse(['success' => false'message' => 'Central product not found for globalId ' $globalId], 404);
  16115.         }
  16116.         $ig  $product->getIgId() ? $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->find($product->getIgId()) : null;
  16117.         $row $this->buildGlobalProductRow($em$product$ig);
  16118.         $em_goc $this->getDoctrine()->getManager('company_group');
  16119.         $em_goc->getConnection()->connect();
  16120.         if (!$em_goc->getConnection()->isConnected()) {
  16121.             return new JsonResponse(['success' => false'message' => 'Cannot connect to company_group DB'], 500);
  16122.         }
  16123.         $gocList $em_goc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy(['active' => 1]);
  16124.         // Tenants live on DIFFERENT servers (their DBs are localhost to THEIR server,
  16125.         // not to central). So push once to each distinct server, and let that server's
  16126.         // receiver update ALL of its own local tenants. Resolve the address from
  16127.         // company_group_server_address â€” the field that's actually populated; the old
  16128.         // loop read *_domain_full_link (NULL for everyone), which is why it collapsed
  16129.         // to "1 server" and never reached SG.
  16130.         $seen = [];
  16131.         $servers = [];
  16132.         foreach ($gocList as $entry) {
  16133.             $addr rtrim(
  16134.                 ($entry->getCompanyGroupServerAddress() ?: $entry->getCurrentServerAddress())
  16135.                 ?: ($entry->getCurrentServerDomainFullLink() ?: ($entry->getCompanyGroupServerDomainFullLink() ?: '')),
  16136.                 '/'
  16137.             );
  16138.             if (!$addr || isset($seen[$addr])) continue;
  16139.             $seen[$addr] = true;
  16140.             $servers[] = $addr;
  16141.         }
  16142.         $results = [];
  16143.         $tenantsUpdated 0;
  16144.         foreach ($servers as $addr) {
  16145.             $curl curl_init();
  16146.             curl_setopt_array($curl, [
  16147.                 CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  16148.                 CURLOPT_URL => $addr '/api/sync_product_from_central',
  16149.                 CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 90// receiver loops its tenants
  16150.                 CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  16151.                 CURLOPT_POSTFIELDS => http_build_query(['globalId' => $globalId'data' => $row'force' => 1]),
  16152.             ]);
  16153.             $response  curl_exec($curl);
  16154.             $curlError curl_error($curl);
  16155.             curl_close($curl);
  16156.             $decoded $curlError ? ['error' => $curlError] : json_decode($responsetrue);
  16157.             $results[$addr] = $decoded;
  16158.             if (is_array($decoded) && !empty($decoded['tenants_updated'])) {
  16159.                 $tenantsUpdated += (int) $decoded['tenants_updated'];
  16160.             }
  16161.         }
  16162.         return new JsonResponse([
  16163.             'success'         => true,
  16164.             'globalId'        => $globalId,
  16165.             'pushed'          => count($servers),   // UI label: "Pushed to N server(s)"
  16166.             'servers'         => count($servers),
  16167.             'tenants_updated' => $tenantsUpdated,
  16168.             'results'         => $results,
  16169.         ]);
  16170.     }
  16171.     public function SuggestProductUpdateAction(Request $request)
  16172.     {
  16173.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16174.         if ($systemType !== '_CENTRAL_') {
  16175.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16176.         }
  16177.         $em             $this->getDoctrine()->getManager();
  16178.         $globalId       = (int)$request->request->get('globalId'0);
  16179.         $suggestedFields $request->request->get('suggestedFields', []);
  16180.         $suggestedBy    = (int)$request->request->get('suggestedBy'0);
  16181.         $sourceNote     trim($request->request->get('sourceNote'''));
  16182.         if (!$globalId || empty($suggestedFields)) {
  16183.             return new JsonResponse(['success' => false'message' => 'globalId and suggestedFields are required'], 400);
  16184.         }
  16185.         // validate: igId and modelNo cannot be suggested for change
  16186.         $forbidden = ['igId''ig_id''modelNo''model_no'];
  16187.         foreach ($forbidden as $f) {
  16188.             if (isset($suggestedFields[$f])) {
  16189.                 return new JsonResponse(['success' => false'message' => "Field '{$f}' is a global identity anchor and cannot be changed"], 422);
  16190.             }
  16191.         }
  16192.         $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  16193.         if (!$product) {
  16194.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  16195.         }
  16196.         if (!$product) {
  16197.             return new JsonResponse(['success' => false'message' => 'Product not found on central'], 404);
  16198.         }
  16199.         $suggestion = new \ApplicationBundle\Entity\InvProductCentralSuggestion();
  16200.         $suggestion->setGlobalId($globalId);
  16201.         $suggestion->setSuggestedFields(json_encode($suggestedFields));
  16202.         $suggestion->setSuggestedBy($suggestedBy ?: null);
  16203.         $suggestion->setSourceNote($sourceNote ?: null);
  16204.         $suggestion->setStatus(\ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_PENDING);
  16205.         $em->persist($suggestion);
  16206.         $em->flush();
  16207.         return new JsonResponse(['success' => true'suggestionId' => $suggestion->getId()]);
  16208.     }
  16209.     public function ApproveProductAction(Request $request$id)
  16210.     {
  16211.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16212.         if ($systemType !== '_CENTRAL_') {
  16213.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16214.         }
  16215.         $em         $this->getDoctrine()->getManager();
  16216.         $approvedBy = (int)$request->request->get('approvedBy'0);
  16217.         $suggestion $em->getRepository('ApplicationBundle\\Entity\\InvProductCentralSuggestion')->find((int)$id);
  16218.         if (!$suggestion) {
  16219.             return new JsonResponse(['error' => 'Suggestion not found'], 404);
  16220.         }
  16221.         if ($suggestion->getStatus() !== \ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_PENDING) {
  16222.             return new JsonResponse(['error' => 'Suggestion already ' $suggestion->getStatus()], 409);
  16223.         }
  16224.         $globalId $suggestion->getGlobalId();
  16225.         $product  $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  16226.         if (!$product) {
  16227.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  16228.         }
  16229.         if (!$product) {
  16230.             return new JsonResponse(['error' => 'Central product not found for globalId ' $globalId], 404);
  16231.         }
  16232.         $fields   $suggestion->getSuggestedFieldsArray();
  16233.         $locked   = ['igId''ig_id''modelNo''model_no''id''globalId'];
  16234.         $applied  = [];
  16235.         foreach ($fields as $field => $value) {
  16236.             if (in_array($field$lockedtrue)) continue;
  16237.             $setter 'set' ucfirst($field);
  16238.             if (method_exists($product$setter)) {
  16239.                 $product->$setter($value);
  16240.                 $applied[$field] = $value;
  16241.             }
  16242.         }
  16243.         $em->flush();
  16244.         // mark suggestion approved
  16245.         $suggestion->setStatus(\ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_APPROVED);
  16246.         $suggestion->setApprovedBy($approvedBy ?: null);
  16247.         $suggestion->setApprovedAt(new \DateTime());
  16248.         $em->flush();
  16249.         // propagate approved changes to all linked ERP servers
  16250.         $em_goc $this->getDoctrine()->getManager('company_group');
  16251.         $gocList = [];
  16252.         try {
  16253.             $gocList $em_goc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy(['active' => 1]);
  16254.         } catch (\Exception $e) {}
  16255.         $seenServers = [];
  16256.         $pushResults = [];
  16257.         foreach ($gocList as $entry) {
  16258.             $serverAddress rtrim(
  16259.                 $entry->getCurrentServerDomainFullLink() ?: $entry->getCompanyGroupServerDomainFullLink(),
  16260.                 '/'
  16261.             );
  16262.             if (!$serverAddress || isset($seenServers[$serverAddress])) continue;
  16263.             $seenServers[$serverAddress] = true;
  16264.             $curl curl_init();
  16265.             curl_setopt_array($curl, [
  16266.                 CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  16267.                 CURLOPT_URL => $serverAddress '/api/sync_product_from_central',
  16268.                 CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 15,
  16269.                 CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  16270.                 CURLOPT_POSTFIELDS => http_build_query(['globalId' => $globalId'data' => $applied]),
  16271.             ]);
  16272.             $response  curl_exec($curl);
  16273.             $curlError curl_error($curl);
  16274.             curl_close($curl);
  16275.             $pushResults[$serverAddress] = $curlError
  16276.                 ? ['error' => $curlError]
  16277.                 : json_decode($responsetrue);
  16278.         }
  16279.         return new JsonResponse([
  16280.             'success'     => true,
  16281.             'globalId'    => $globalId,
  16282.             'appliedFields' => array_keys($applied),
  16283.             'pushedTo'    => count($seenServers),
  16284.             'pushResults' => $pushResults,
  16285.         ]);
  16286.     }
  16287.     public function RejectProductSuggestionAction(Request $request$id)
  16288.     {
  16289.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16290.         if ($systemType !== '_CENTRAL_') {
  16291.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16292.         }
  16293.         $em           $this->getDoctrine()->getManager();
  16294.         $rejectedBy   = (int)$request->request->get('rejectedBy'0);
  16295.         $rejectionNote trim($request->request->get('rejectionNote'''));
  16296.         $suggestion $em->getRepository('ApplicationBundle\\Entity\\InvProductCentralSuggestion')->find((int)$id);
  16297.         if (!$suggestion) {
  16298.             return new JsonResponse(['error' => 'Suggestion not found'], 404);
  16299.         }
  16300.         if ($suggestion->getStatus() !== \ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_PENDING) {
  16301.             return new JsonResponse(['error' => 'Suggestion already ' $suggestion->getStatus()], 409);
  16302.         }
  16303.         $suggestion->setStatus(\ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_REJECTED);
  16304.         $suggestion->setRejectedBy($rejectedBy ?: null);
  16305.         $suggestion->setRejectedAt(new \DateTime());
  16306.         $suggestion->setRejectionNote($rejectionNote ?: null);
  16307.         $em->flush();
  16308.         return new JsonResponse(['success' => true'suggestionId' => $suggestion->getId()]);
  16309.     }
  16310. }