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

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.                 // A GRN is always received against a Purchase Order â€” CreateGrn reads line prices,
  4742.                 // the supplier head and expense tags from it. An empty/stale poId leaves $po null
  4743.                 // and used to 500 deep inside CreateGrn. Reject it here with a clear message.
  4744.                 $poCheck $data->get('poId')
  4745.                     ? $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')
  4746.                         ->findOneBy(array('purchaseOrderId' => $data->get('poId')))
  4747.                     : null;
  4748.                 if (!$poCheck) {
  4749.                     $this->addFlash('error''Select a valid Purchase Order before saving the GRN.');
  4750.                     return $this->redirect($request->getUri());
  4751.                 }
  4752.                 try {
  4753.                     $grnId Inventory::CreateGrn($this->getDoctrine()->getManager(), $data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4754.                 } catch (\Throwable $e) {
  4755.                     // Convert any residual failure into a graceful message rather than a raw error page.
  4756.                     $this->addFlash('error''Could not save the GRN: ' $e->getMessage());
  4757.                     return $this->redirect($request->getUri());
  4758.                 }
  4759.                 //now add Approval info
  4760.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4761.                 $approveRole 1;  //created
  4762.                 $options = array(
  4763.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4764.                     'notification_server' => $this->container->getParameter('notification_server'),
  4765.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4766.                     'url' => $this->generateUrl(
  4767.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['Grn']]
  4768.                         ['entity_view_route_path_name']
  4769.                     )
  4770.                 );
  4771.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4772.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  4773.                     $grnId,
  4774.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4775.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['Grn'], $grnId,
  4776.                     $loginId,
  4777.                     $approveRole,
  4778.                     $request->request->get('approvalHash'));
  4779.                 $this->addFlash(
  4780.                     'success',
  4781.                     'New GRN Added.'
  4782.                 );
  4783.                 $url $this->generateUrl(
  4784.                     'view_grn'
  4785.                 );
  4786.                 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),
  4787.                     "Good Received Note : " $dochash " Has Been Created And is Under Processing",
  4788.                     'pos',
  4789.                     System::getPositionIdsByDepartment($em, [GeneralConstant::SALES_DEPARTMENTGeneralConstant::PURCHASE_DEPARTMENTGeneralConstant::ACCOUNTS_DEPARTMENTGeneralConstant::INVENTORY_DEPARTMENT]),
  4790.                     'success',
  4791.                     $url "/" $grnId,
  4792.                     "GRN"
  4793.                 );
  4794.                 return $this->redirect($url "/" $grnId);
  4795.             }
  4796.         }
  4797.         return $this->render('@Inventory/pages/input_forms/received_note.html.twig',
  4798.             array(
  4799.                 'page_title' => 'GRN',
  4800.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  4801.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  4802.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  4803.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  4804.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  4805.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  4806.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  4807.                 'material_inward' => $this->getDoctrine()
  4808.                     ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  4809.                     ->findBy(
  4810.                         array(
  4811.                             'stage' => GeneralConstant::STAGE_PENDING_TAG
  4812.                         )
  4813.                     )
  4814. //                'po'=>Inventory::getPurchaseOrderList
  4815.             )
  4816.         );
  4817.     }
  4818.     public function GetQcListForGrnAction(Request $request)
  4819.     {
  4820.         if ($request->isMethod('POST')) {
  4821.             $find_array = array(
  4822.                 'stage' => GeneralConstant::STAGE_PENDING_TAG
  4823.             );
  4824.             $Content = [];
  4825.             $ContentByProductId = [];
  4826.             $Transport_data = [];
  4827.             $Lul_data = [];
  4828.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4829.             if ($request->request->get('poId') != '')
  4830.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4831.             if ($request->request->get('warehouseId') != '')
  4832.                 $find_array['warehouseId'] = $request->request->get('warehouseId');
  4833.             $QD $this->getDoctrine()
  4834.                 ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  4835.                 ->findBy(
  4836.                     $find_array,
  4837.                     array(
  4838.                         'inwardDate' => 'ASC',
  4839.                         'qcDate' => 'ASC'
  4840.                     )
  4841.                 );
  4842.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4843.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4844.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4845.             $lotNumArray = [];
  4846.             foreach ($QD as $entry) {
  4847. //                $inwardDate=strtotime($entry->getInwardDate());
  4848. //                $qcDate=strtotime($entry->getQcDate());
  4849.                 $inwardDate = ($entry->getInwardDate() instanceof \DateTime) ? $entry->getInwardDate()->format('m/d/Y') : '';
  4850.                 $qcDate = ($entry->getQcDate() instanceof \DateTime) ? $entry->getQcDate()->format('m/d/Y') : '';
  4851.                 if (!in_array($entry->getLotNumber(), $lotNumArray))
  4852.                     $lotNumArray[] = $entry->getLotNumber();
  4853.                 if (isset($ContentByProductId[$entry->getPurchaseOrderItemId()])) {
  4854.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['inwardDateList'][] = $inwardDate;
  4855.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcDateList'][] = $inwardDate;
  4856.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcIdList'][] = $entry->getQcId();
  4857.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['appQtyList'][] = $entry->getApprovedQty();
  4858.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['totQty'] += ($entry->getApprovedQty());
  4859.                 } else {
  4860.                     $ContentByProductId[$entry->getPurchaseOrderItemId()] = array(
  4861.                         'productName' => $productList[$entry->getProductId()]['name'],
  4862.                         'productUnitName' => $unitList[$productList[$entry->getProductId()]['unit_type']]['name'],
  4863.                         'qcHash' => $entry->getDocumentHash(),
  4864.                         'warehouseName' => $warehouse[$entry->getWarehouseId()]['name'],
  4865.                         'inwardDate' => $inwardDate,
  4866.                         'inwardDateList' => [$inwardDate],
  4867.                         'qcDateList' => [$qcDate],
  4868.                         'qcIdList' => [$entry->getQcId()],
  4869.                         'qcDate' => $qcDate,
  4870.                         'poQty' => $entry->getPoQty(),
  4871.                         'poPrevbalance' => $entry->getPoBalance(),
  4872.                         'appQty' => $entry->getApprovedQty(),
  4873.                         'appQtyList' => [$entry->getApprovedQty()],
  4874.                         'totQty' => $entry->getApprovedQty(),
  4875.                         'poBalance' => $entry->getPoBalance() - $entry->getApprovedQty(),
  4876.                         'qcId' => $entry->getQcId(),
  4877.                         'productId' => $entry->getProductId()
  4878.                     );
  4879.                 }
  4880.                 $Expense_Cost[$entry->getQcId()] = json_decode($entry->getExpenseCost());
  4881.                 $Expense_Id[$entry->getQcId()] = json_decode($entry->getExpenseId());
  4882.             }
  4883.             foreach ($ContentByProductId as $c) {
  4884.                 $Content[] = $c;
  4885.             }
  4886.             if ($QD) {
  4887.                 return new JsonResponse(array("success" => true"content" => $Content"lotNumber" => implode(', '$lotNumArray), 'Expense_Cost' => $Expense_Cost'Expense_Id' => $Expense_Id));
  4888.             }
  4889.             return new JsonResponse(array("success" => false));
  4890.         }
  4891.         return new JsonResponse(array("success" => false));
  4892.     }
  4893.     public function GetSrListForIrAction(Request $request)
  4894.     {
  4895.         if ($request->isMethod('POST')) {
  4896.             $find_array = array();
  4897.             $Content = [];
  4898.             if ($request->request->get('srId') != '')
  4899.                 $find_array['stockRequisitionId'] = $request->request->get('srId');
  4900.             $find_array['forceSkipTag'] = [0null];
  4901.             $QD $this->getDoctrine()
  4902.                 ->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')
  4903.                 ->findBy(
  4904.                     $find_array
  4905.                 );
  4906.             $itemList Inventory::ItemGroupList($this->getDoctrine()->getManager());
  4907.             $catgoryList Inventory::ProductCategoryList($this->getDoctrine()->getManager());
  4908.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4909.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4910.             $fdmData = array();
  4911.             $em $this->getDoctrine()->getManager();
  4912.             $matchType 'MAXIMUM';
  4913.             if ($request->request->has('matchType') != '') {
  4914.                 $matchType $request->request->get('matchType');
  4915.             }
  4916.             if ($matchType == 'MINIMUM') {
  4917.                 foreach ($QD as $entry) {
  4918.                     if ($entry->getTagPendingAmount() <= 0)
  4919.                         continue;
  4920.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4921.                     $combined_id $entry->getProductFdm();
  4922.                     if (isset($fdmData[$combined_id])) {
  4923.                         $fdmData[$combined_id]['unit'] += $entry->getTagPendingAmount();
  4924.                         $fdmData[$combined_id]['specific_unit'][] = $entry->getTagPendingAmount();
  4925.                         $fdmData[$combined_id]['detailsIds'][] = $entry->getId();
  4926.                         $fdmData[$combined_id]['docIds'][] = $entry->getStockRequisitionId();
  4927.                     } else {
  4928.                         $fdmData[$combined_id] = array(
  4929.                             'id' => 0,
  4930.                             'alias' => $entry->getNote(),
  4931.                             'unit' => $entry->getTagPendingAmount(),
  4932.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4933.                             'warranty' => 0,
  4934.                             'unitTypeId' => 0,
  4935.                             'unit_price' => 0,
  4936.                             'fdm' => $combined_id,
  4937.                             'extDetailsId' => 0,
  4938.                             'product_name' => $productData['productName'],
  4939.                             'total_price' => 0,
  4940.                             'detailsIds' => [$entry->getId()],
  4941.                             'docIds' => [$entry->getStockRequisitionId()],
  4942.                         );
  4943.                     }
  4944.                 }
  4945.             }
  4946.             if ($matchType == 'MAXIMUM') {
  4947.                 foreach ($QD as $entry) {
  4948.                     if ($entry->getTagPendingAmount() <= 0)
  4949.                         continue;
  4950.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4951.                     $combined_id $entry->getProductFdm();
  4952.                     $assigned 0;
  4953.                     foreach ($fdmData as $key_ind => $rel_val) {
  4954.                         $matchFdm Inventory::MatchFdm($key_ind$combined_id);
  4955.                         if ($matchFdm['hasMatched'] == 1) {
  4956.                             if ($matchFdm['isIdentical'] == 1) {
  4957.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4958.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4959.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4960.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4961.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4962.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4963.                                 $assigned 1;
  4964.                             } elseif ($matchFdm['SecondBelongsToFirst'] == 1) {
  4965.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4966.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4967.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4968.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4969.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4970.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4971.                                 $assigned 1;
  4972.                             } elseif ($matchFdm['FirstBelongsToSecond'] == 1) {
  4973.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4974.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4975.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4976.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4977.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4978.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4979.                                 $fdmData[$combined_id] = $fdmData[$key_ind];
  4980.                                 unset($fdmData[$key_ind]);
  4981.                                 $assigned 1;
  4982.                             }
  4983.                         } else {
  4984.                         }
  4985.                         if ($assigned == 1)
  4986.                             break;
  4987.                     }
  4988.                     if ($assigned == 0) {
  4989.                         $fdmData[$combined_id] = array(
  4990.                             'id' => 0,
  4991.                             'alias' => $entry->getNote(),
  4992.                             'unit' => $entry->getTagPendingAmount(),
  4993.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4994.                             'specific_unit_type_id' => [$entry->getUnitTypeId()],
  4995.                             'warranty' => 0,
  4996.                             'unitTypeId' => $productData['unitTypeId'],
  4997. //                            'unitTypeId' => $productData['unitTypeId'],
  4998.                             'unit_price' => 0,
  4999.                             'fdm' => $combined_id,
  5000.                             'extDetailsId' => 0,
  5001.                             'product_name' => htmlspecialchars($productData['productName']),
  5002.                             'total_price' => 0,
  5003.                             'detailsIds' => [$entry->getId()],
  5004.                             'docIds' => [$entry->getStockRequisitionId()],
  5005.                         );
  5006.                     }
  5007.                     if (isset($fdmData[$combined_id])) {
  5008.                     } else {
  5009.                     }
  5010.                 }
  5011.             }
  5012.             $QD $this->getDoctrine()
  5013.                 ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  5014.                 ->findBy(
  5015.                     array('stockRequisitionId' => $request->request->get('srId'))
  5016.                 );
  5017.             $contentNote "";
  5018.             foreach ($QD as $r) {
  5019.                 $contentNote .= $r->getNote();
  5020.                 $contentNote .= " , ";
  5021.             }
  5022.             foreach ($fdmData as $dt) {
  5023.                 $Content[] = $dt;
  5024.             }
  5025.             if ($Content) {
  5026.                 return new JsonResponse(array("success" => true"content" => $Content"contentNote" => $contentNote));
  5027.             }
  5028.             return new JsonResponse(array("success" => false));
  5029.         }
  5030.         return new JsonResponse(array("success" => false));
  5031.     }
  5032.     public function GetGrnListForEiAction(Request $request)
  5033.     {
  5034.         if ($request->isMethod('POST')) {
  5035.             $find_array = array(
  5036.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  5037.                 'approved' => GeneralConstant::APPROVED,
  5038.                 'invoiceTagged' => 1
  5039.             );
  5040.             $Content = [];
  5041.             $Content_obj = [];
  5042.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  5043.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  5044.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  5045.             if ($request->request->get('poId') != '')
  5046.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  5047.             if ($request->request->get('grnId') != '')
  5048.                 $find_array['grnId'] = $request->request->get('grnId');
  5049.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5050.             $QD_GRN $this->getDoctrine()
  5051.                 ->getRepository('ApplicationBundle\\Entity\\Grn')
  5052.                 ->findBy(
  5053.                     $find_array,
  5054.                     array(
  5055.                         'grnDate' => 'ASC'
  5056.                     )
  5057.                 );
  5058.             $poId 0;
  5059. //
  5060. //            $expense_id=$QD_GRN->getExpenseId()!=''?json_decode($QD_GRN->getExpenseId()):[];
  5061. //                $expense_list=$QD_GRN->getExpenseCost()!=''?json_decode($QD_GRN->getExpenseCost()):[];
  5062. //                $expense_tagged=$QD_GRN->getExpenseTagged()!=''?json_decode($QD_GRN->getExpenseTagged()):[];
  5063.             $partyId $request->request->get('partyId');
  5064.             $bill_details = [];
  5065.             $bill_details_data = [];
  5066.             $bill_details_for_grn = [];
  5067.             $exp_list InventoryConstant::$Expense_list_details;
  5068.             $supp_list Inventory::ProductSupplierList($this->getDoctrine()->getManager());
  5069.             $head_qry $this->getDoctrine()
  5070.                 ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  5071.                 ->findAll();
  5072.             $head_list = [];
  5073.             $head_list_by_advance = [];
  5074.             foreach ($head_qry as $data) {
  5075.                 $head_list[$data->getAccountsHeadId()] = array(
  5076.                     'id' => $data->getAccountsHeadId(),
  5077.                     'name' => $data->getName(),
  5078.                     'advanceTagged' => $data->getAdvanceTagged(),
  5079.                     'advanceOf' => $data->getAdvanceOf(),
  5080.                     'balance' => $data->getCurrentBalance()
  5081.                 );
  5082.                 if ($data->getAdvanceOf() != null && $data->getAdvanceOf() != && $data->getAdvanceOf() != '')
  5083.                     $head_list_by_advance[$data->getAdvanceOf()] = array(
  5084.                         'id' => $data->getAccountsHeadId(),
  5085.                         'name' => $data->getName(),
  5086.                         'advanceTagged' => $data->getAdvanceTagged(),
  5087.                         'advanceOf' => $data->getAdvanceOf(),
  5088.                         'balance' => $data->getCurrentBalance()
  5089.                     );
  5090.             }
  5091.             $exp_def_head = [];
  5092.             foreach ($exp_list as $key => $item) {
  5093.                 $def_settings $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  5094.                     'name' => $item['name'] . '_onsite_head'
  5095.                 ));
  5096.                 if ($def_settings)
  5097.                     $exp_def_head[$item['id']] = $def_settings->getData();
  5098.                 else
  5099.                     $exp_def_head[$item['id']] = '';
  5100.             }
  5101.             $bill_details_by_party = [];
  5102. //            System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($QD_GRN),'debug_data');
  5103. //            System::log_it($this->container->getParameter('kernel.root_dir'),$partyId,'debug_data');
  5104. //            System::log_it($this->container->getParameter('kernel.root_dir'),"\nexp list here".json_encode($exp_list),'debug_data');
  5105. //
  5106.             foreach ($QD_GRN as $key => $value) {
  5107.                 $expense_id $value->getExpenseId() != '' json_decode($value->getExpenseId(), true) : [];
  5108.                 $expense_list $value->getExpenseCost() != '' json_decode($value->getExpenseCost(), true) : [];
  5109.                 $expense_tagged $value->getExpenseTagged() != '' json_decode($value->getExpenseTagged(), true) : [];
  5110. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_id),'debug_data');
  5111. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_list),'debug_data');
  5112.                 foreach ($exp_list as $chabi => $entry) {
  5113. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nChabi ".$chabi,'debug_data');
  5114. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nkeys are ".array_keys($expense_id),'debug_data');
  5115.                     if (array_key_exists($chabi$expense_id)) {
  5116. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nFOUND KEY!! ",'debug_data');
  5117.                         if ($partyId == ''//all
  5118.                         {
  5119.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  5120.                                 $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  5121.                                 $advance_balance 0;
  5122.                                 if ($partyHeadId != 0) {
  5123.                                     $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  5124.                                     $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  5125.                                     $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  5126.                                 }
  5127.                                 $bill_details_by_party[$my_val][] = array(
  5128.                                     'partyId' => $my_val,
  5129.                                     'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  5130.                                     'partyHeadId' => $partyHeadId,
  5131.                                     'expTypeId' => $chabi,
  5132.                                     'expTypeName' => $exp_list[$chabi]['name'],
  5133.                                     'expTypeAlias' => $exp_list[$chabi]['alias'],
  5134.                                     'expAmount' => $expense_list[$chabi][$index],
  5135.                                     'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  5136.                                     'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  5137.                                     'AdvanceBalance' => $advance_balance,
  5138.                                     'grnId' => $value->getGrnId(),
  5139.                                     'grnName' => $value->getDocumentHash(),
  5140.                                 );
  5141.                             }
  5142.                         } else {
  5143.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  5144.                                 if (in_array($my_val$partyId)) {
  5145.                                     $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  5146.                                     $advance_balance 0;
  5147.                                     if ($partyHeadId != 0) {
  5148.                                         $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  5149.                                         $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  5150.                                         $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  5151.                                     }
  5152.                                     $bill_details_by_party[$my_val][] = array(
  5153.                                         'partyId' => $my_val,
  5154.                                         'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  5155.                                         'partyHeadId' => $partyHeadId,
  5156.                                         'expTypeId' => $chabi,
  5157.                                         'expTypeName' => $exp_list[$chabi]['name'],
  5158.                                         'expTypeAlias' => $exp_list[$chabi]['alias'],
  5159.                                         'expAmount' => $expense_list[$chabi][$index],
  5160.                                         'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  5161.                                         'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  5162.                                         'AdvanceBalance' => $advance_balance,
  5163.                                         'grnId' => $value->getGrnId(),
  5164.                                         'grnName' => $value->getDocumentHash(),
  5165.                                     );
  5166.                                 }
  5167.                             }
  5168.                         }
  5169.                     }
  5170.                 }
  5171.             }
  5172. //            $Content_obj=
  5173. //
  5174. //            foreach($Content_obj as $item)
  5175. //            {
  5176. //                $Content[]=$item;
  5177. //
  5178. //            }
  5179.             $list_of_keys array_keys($bill_details_by_party);
  5180.             if ($bill_details_by_party) {
  5181.                 return new JsonResponse(array("success" => true"content" => $bill_details_by_party'index' => $list_of_keys'h_l_b_a' => $head_list_by_advance));
  5182.             }
  5183.             return new JsonResponse(array("success" => false));
  5184.         }
  5185.         return new JsonResponse(array("success" => false));
  5186.     }
  5187.     public function GetServiceListForPiAction(Request $request)
  5188.     {
  5189.         if ($request->isMethod('POST')) {
  5190. //            $find_array=array(
  5191. //                'stage' =>  GeneralConstant::STAGE_PENDING_TAG,
  5192. //                'approved'=>GeneralConstant::APPROVED
  5193. //            );
  5194.             $Content = [];
  5195.             $Content_obj = [];
  5196.             $ContentService = [];
  5197.             $Content_service_obj = [];
  5198. //            $warehouse=Inventory::WarehouseList($this->getDoctrine()->getManager());
  5199. //            $poList=Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  5200. //            $productList=Inventory::ProductList($this->getDoctrine()->getManager());
  5201.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  5202.             if ($request->request->get('poId') != '')
  5203.                 $poId $request->request->get('poId');
  5204.             if ($request->request->get('grnId') != '')
  5205.                 $find_array['grnId'] = $request->request->get('grnId');
  5206.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5207.             //adding service data temporarily
  5208.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(
  5209.                 array('purchaseOrderId' => $poId));
  5210.             $multiply_type $po->getCurrencyMultiply();
  5211.             $multiply_rate $po->getCurrencyMultiplyRate();
  5212.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  5213.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  5214.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5215.                 array('purchaseOrderId' => $poId));
  5216.             foreach ($po_items as $item) {
  5217. //                $po_item_list[$item->getProductId()]=$item;
  5218.                 //temporary service add
  5219.                 if ($item->getType() == 2)
  5220.                     $Content_service_obj[$item->getId()] = array(
  5221.                         'serviceId' => $item->getServiceId(),
  5222.                         'poItemId' => $item->getId(),
  5223.                         'colorId' => 0,
  5224.                         'sizeId' => 0,
  5225.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  5226.                         'qty' => $item->getQty(),
  5227.                         'balance' => $item->getBalance(),
  5228.                         'unit_name' => '',
  5229.                         'unit_price' => $item->getPrice() * $multiplier,
  5230.                         'grn_id' => 0,
  5231.                     );
  5232.                 //temprary service add end
  5233.             }
  5234.             //temporary service data adding done
  5235.             $po_data = [];
  5236.             $po_data = array(
  5237.                 'docHash' => $po->getDocumentHash(),
  5238.                 'docDate' => $po->getPurchaseOrderDate(),
  5239.                 'supplierId' => $po->getSupplierId(),
  5240.                 'supplierName' => $po->getSupplierId(),
  5241.                 'vatRate' => $po->getVatRate(),
  5242.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  5243.                 'aitRate' => $po->getAitRate(),
  5244.                 'aitAmount' => $po->getAitAmount(),
  5245.                 'tdsRate' => $po->getTdsRate(),
  5246.                 'tdsAmount' => $po->getTdsAmount(),
  5247.                 'vdsRate' => $po->getVdsRate(),
  5248.                 'vdsAmount' => $po->getVdsAmount(),
  5249.                 'discountRate' => $po->getDiscountRate(),
  5250.                 'discountAmount' => $po->getVatAmount(),
  5251.             );
  5252.             foreach ($Content_obj as $item) {
  5253.                 $Content[] = $item;
  5254.             }
  5255.             foreach ($Content_service_obj as $item) {
  5256.                 $ContentService[] = $item;
  5257.             }
  5258.             if ($Content || $ContentService) {
  5259.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  5260.             }
  5261.             return new JsonResponse(array("success" => false));
  5262.         }
  5263.         return new JsonResponse(array("success" => false));
  5264.     }
  5265.     public function GetGrnListForPiAction(Request $request)
  5266.     {
  5267.         if ($request->isMethod('POST')) {
  5268.             $find_array = array(
  5269.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  5270.                 'approved' => GeneralConstant::APPROVED
  5271.             );
  5272.             $Content = [];
  5273.             $Content_obj = [];
  5274.             $ContentService = [];
  5275.             $Content_service_obj = [];
  5276.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  5277.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  5278.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  5279.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  5280.             if ($request->request->get('poId') != '')
  5281.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  5282.             if ($request->request->get('grnId') != '')
  5283.                 $find_array['grnId'] = $request->request->get('grnId');
  5284.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5285.             $QD_GRN $this->getDoctrine()
  5286.                 ->getRepository('ApplicationBundle\\Entity\\Grn')
  5287.                 ->findBy(
  5288.                     $find_array,
  5289.                     array(
  5290.                         'grnDate' => 'ASC'
  5291.                     )
  5292.                 );
  5293.             $poId 0;
  5294.             foreach ($QD_GRN as $value) {
  5295.                 $grn_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\GrnItem')->findBy(
  5296.                     array('grnId' => $value->getGrnId()));
  5297.                 $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5298.                     array('purchaseOrderId' => $value->getPurchaseOrderId()));
  5299.                 $poId $value->getPurchaseOrderId();
  5300.                 $po_item_list = [];
  5301.                 foreach ($po_items as $item) {
  5302.                     $po_item_list[$item->getProductId()] = $item;
  5303.                 }
  5304.                 foreach ($grn_items as $entry) {
  5305.                     //adding transaction
  5306. //                    System::log_it($this->container->getParameter('kernel.root_dir'),$entry->getProductId(),'debug_data');
  5307.                     $Content_obj[$entry->getId()] = array(
  5308.                         'productId' => $entry->getProductId(),
  5309.                         'poItemId' => $entry->getPurchaseOrderItemId(),
  5310.                         'productName' => $productList[$entry->getProductId()]['name'],
  5311.                         'colorId' => $entry->getColorId(),
  5312.                         'sizeId' => $entry->getSizeId(),
  5313.                         'qty' => isset($Content_obj[$entry->getId()]) ? $Content_obj[$entry->getId()]['qty'] + $entry->getQty() : $entry->getQty(),
  5314.                         'unit_name' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  5315. //                            'unit_price'=>$po_item_list[$entry->getProductId()]->getPrice(),
  5316.                         'unit_price' => $entry->getPrice(),
  5317.                         'grn_id' => $entry->getId(),
  5318.                     );
  5319.                 }
  5320. //            for
  5321.             }
  5322.             //adding service data temporarily
  5323.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findOneBy(
  5324.                 array('purchaseOrderId' => $poId));
  5325.             $multiply_type $po->getCurrencyMultiply();
  5326.             $multiply_rate $po->getCurrencyMultiplyRate();
  5327.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  5328.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  5329.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5330.                 array('purchaseOrderId' => $poId));
  5331.             foreach ($po_items as $item) {
  5332. //                $po_item_list[$item->getProductId()]=$item;
  5333.                 //temporary service add
  5334.                 if ($item->getType() == 2)
  5335.                     $Content_service_obj[$item->getId()] = array(
  5336.                         'serviceId' => $item->getServiceId(),
  5337.                         'poItemId' => $item->getId(),
  5338.                         'colorId' => 0,
  5339.                         'sizeId' => 0,
  5340.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  5341.                         'qty' => $item->getQty(),
  5342.                         'balance' => $item->getBalance(),
  5343.                         'unit_name' => '',
  5344.                         'unit_price' => $item->getPrice() * $multiplier,
  5345.                         'grn_id' => 0,
  5346.                     );
  5347.                 //temprary service add end
  5348.             }
  5349.             //temporary service data adding done
  5350.             $po_data = [];
  5351.             $vatAmount $po->getVatAmount();
  5352.             $priceAfterDiscount $po->getSupplierPayableAmount() - $po->getVatAmount();
  5353.             $vatRate = ($vatAmount $priceAfterDiscount) * 100;
  5354.             $po_data = array(
  5355.                 'docHash' => $po->getDocumentHash(),
  5356.                 'docDate' => $po->getPurchaseOrderDate(),
  5357.                 'supplierId' => $po->getSupplierId(),
  5358.                 'supplierName' => $po->getSupplierId(),
  5359.                 'vatRate' => $vatRate,
  5360.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  5361.                 'aitRate' => $po->getAitRate(),
  5362.                 'aitAmount' => $po->getAitAmount(),
  5363.                 'tdsRate' => $po->getTdsRate(),
  5364.                 'tdsAmount' => $po->getTdsAmount(),
  5365.                 'vdsRate' => $po->getVdsRate(),
  5366.                 'vdsAmount' => $po->getVdsAmount(),
  5367.                 'discountRate' => $po->getDiscountRate(),
  5368. //                'discountAmount' => $po->getVatAmount(),
  5369.                 'vatAmount' => $vatAmount,
  5370.                 'discountAmount' => $po->getDiscountAmount(),
  5371.                 'supplierPayableAmount' => $po->getSupplierPayableAmount(),
  5372.                 'priceAfterDiscount' => $priceAfterDiscount
  5373.             );
  5374.             foreach ($Content_obj as $item) {
  5375.                 $Content[] = $item;
  5376.             }
  5377.             foreach ($Content_service_obj as $item) {
  5378.                 $ContentService[] = $item;
  5379.             }
  5380.             if ($Content) {
  5381.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  5382.             }
  5383.             return new JsonResponse(array("success" => false));
  5384.         }
  5385.         return new JsonResponse(array("success" => false));
  5386.     }
  5387.     public function GetPoDetailsForPiAction(Request $request$poId)
  5388.     {
  5389.     }
  5390.     public function GetPoDetailsAction(Request $request$poId)
  5391.     {
  5392.         if ($request->isMethod('POST')) {
  5393.             $po $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findBy(
  5394.                 array('purchaseOrderId' => $poId));
  5395.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')->findBy(
  5396.                 array('purchaseOrderId' => $poId));
  5397.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  5398.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  5399.             $spec_type Inventory::SpecTypeList($this->getDoctrine()->getManager());
  5400.             $Content = [];
  5401.             $po_items_list = [];
  5402.             foreach ($po_items as $entry) {
  5403.                 $po_items_list[] = array(
  5404.                     'productId' => $entry->getProductId(),
  5405.                     'productName' => $productList[$entry->getProductId()]['name'],
  5406.                     'price' => $entry->getPrice(),
  5407.                     'unit' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  5408.                     'spec' => $spec_type[$productList[$entry->getProductId()]['spec_type']]['name'],
  5409.                     'received' => $entry->getReceived(),
  5410.                     'qty' => $entry->getQty(),
  5411.                     'balance' => $entry->getBalance()
  5412.                 );
  5413.             }
  5414.             $po_data = [];
  5415.             $po_data = array(
  5416.                 'docHash' => $po->getDocumentHash(),
  5417.                 'docDate' => $po->getPurchaseOrderDate(),
  5418.                 'supplierId' => $po->getSupplierId(),
  5419.                 'supplierName' => $po->getSupplierId(),
  5420.             );
  5421.             if ($po_data) {
  5422.                 return new JsonResponse(array("success" => true"content" => $po_data));
  5423.             }
  5424.             return new JsonResponse(array("success" => false));
  5425.         }
  5426.         return new JsonResponse(array("success" => false));
  5427.     }
  5428.     public function CreateSalesReplacementAction(Request $request)
  5429.     {
  5430.         $em $this->getDoctrine()->getManager();
  5431.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5432.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5433.         if ($request->isMethod('POST')) {
  5434.             $em $this->getDoctrine()->getManager();
  5435.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesReplacement']; //change
  5436.             $dochash $request->request->get('voucherNumber'); //change
  5437.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5438.             $approveRole $request->request->get('approvalRole');
  5439.             $approveHash $request->request->get('approvalHash');
  5440.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5441.                 $loginId$approveRole$approveHash)
  5442.             ) {
  5443.                 $this->addFlash(
  5444.                     'error',
  5445.                     'Sorry Couldnot insert Data.'
  5446.                 );
  5447.             } else {
  5448.                 if ($request->request->has('check_allowed'))
  5449.                     $check_allowed 1;
  5450.                 $StID Inventory::CreateNewSalesReplacement(
  5451.                     $this->getDoctrine()->getManager(),
  5452.                     $request->request,
  5453.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5454.                     $this->getLoggedUserCompanyId($request)
  5455.                 );
  5456.                 //now add Approval info
  5457.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5458.                 $approveRole 1;  //created
  5459.                 $options = array(
  5460.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5461.                     'notification_server' => $this->container->getParameter('notification_server'),
  5462.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5463.                     'url' => $this->generateUrl(
  5464.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesReplacement']]
  5465.                         ['entity_view_route_path_name']
  5466.                     )
  5467.                 );
  5468.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5469.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5470.                     $StID,
  5471.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5472.                 );
  5473.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesReplacement'], $StID,
  5474.                     $loginId,
  5475.                     $approveRole,
  5476.                     $request->request->get('approvalHash'));
  5477.                 $this->addFlash(
  5478.                     'success',
  5479.                     'Stock Transfer Added.'
  5480.                 );
  5481.                 $url $this->generateUrl(
  5482.                     'view_st'
  5483.                 );
  5484.                 return $this->redirect($url "/" $StID);
  5485.             }
  5486.         }
  5487.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  5488.             array(
  5489.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5490.             )
  5491.         );
  5492.         $INVLIST = [];
  5493.         foreach ($slotList as $slot) {
  5494.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5495.         }
  5496.         return $this->render('@Inventory/pages/input_forms/sales_replacement.html.twig',
  5497.             array(
  5498.                 'page_title' => 'Sales Replacement Note',
  5499.                 'warehouseList' => Inventory::WarehouseList($em),
  5500.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5501.                 'warehouseActionList' => $warehouse_action_list,
  5502.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5503.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5504.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5505.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5506.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5507.                 'prefix_list' => array(
  5508.                     [
  5509.                         'id' => 1,
  5510.                         'value' => 'GN',
  5511.                         'text' => 'GN'
  5512.                     ]
  5513.                 ),
  5514.                 'assoc_list' => array(
  5515.                     [
  5516.                         'id' => 1,
  5517.                         'value' => 1,
  5518.                         'text' => 'GN'
  5519.                     ]
  5520.                 ),
  5521.                 'INVLIST' => $INVLIST
  5522.             )
  5523.         );
  5524.     }
  5525.     public function SalesReplacementListAction(Request $request)
  5526.     {
  5527.         $q $this->getDoctrine()
  5528.             ->getRepository('ApplicationBundle\\Entity\\SalesReplacement')
  5529.             ->findBy(
  5530.                 array(
  5531.                     'status' => GeneralConstant::ACTIVE,
  5532.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5533. //                    'approved' =>  GeneralConstant::APPROVED,
  5534.                 )
  5535.             );
  5536.         $stage_list = array(
  5537.             => 'Pending',
  5538.             => 'Pending',
  5539.             => 'Complete',
  5540.             => 'Partial',
  5541.         );
  5542.         $data = [];
  5543.         foreach ($q as $entry) {
  5544.             $data[] = array(
  5545.                 'doc_date' => $entry->getSalesReplacementDate(),
  5546.                 'id' => $entry->getSalesReplacementId(),
  5547.                 'doc_hash' => $entry->getDocumentHash(),
  5548.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5549.                 'stage' => $stage_list[$entry->getStage()]
  5550.             );
  5551.         }
  5552.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5553.             array(
  5554.                 'page_title' => 'Stock Transfer List',
  5555.                 'data' => $data
  5556.             )
  5557.         );
  5558.     }
  5559.     public function ViewSalesReplacementAction(Request $request$id)
  5560.     {
  5561.         $em $this->getDoctrine()->getManager();
  5562.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5563.         return $this->render('@Inventory/pages/views/view_stock_transfer.html.twig',
  5564.             array(
  5565.                 'page_title' => 'Stock Transfer',
  5566.                 'data' => $dt,
  5567.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5568.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5569.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5570.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5571.                     $id,
  5572.                     $dt['created_by'],
  5573.                     $dt['edited_by'])
  5574.             )
  5575.         );
  5576.     }
  5577.     public function PrintSalesReplacementAction(Request $request$id)
  5578.     {
  5579.         $em $this->getDoctrine()->getManager();
  5580.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5581.         $company_data Company::getCompanyData($em1);
  5582.         $document_mark = array(
  5583.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5584.             'copy' => ''
  5585.         );
  5586.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5587.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5588.                 array(
  5589.                     //full array here
  5590.                     'pdf' => true,
  5591.                     'page_title' => 'Stock Transfer',
  5592.                     'export' => 'pdf,print',
  5593.                     'data' => $dt,
  5594.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5595.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5596.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5597.                         array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5598.                         $id,
  5599.                         $dt['created_by'],
  5600.                         $dt['edited_by']),
  5601.                     'document_mark_image' => $document_mark['original'],
  5602.                     'company_name' => $company_data->getName(),
  5603.                     'company_data' => $company_data,
  5604.                     'company_address' => $company_data->getAddress(),
  5605.                     'company_image' => $company_data->getImage(),
  5606.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5607.                     'red' => 0
  5608.                 )
  5609.             );
  5610.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5611. //                'orientation' => 'landscape',
  5612. //                'enable-javascript' => true,
  5613. //                'javascript-delay' => 1000,
  5614.                 'no-stop-slow-scripts' => false,
  5615.                 'no-background' => false,
  5616.                 'lowquality' => false,
  5617.                 'encoding' => 'utf-8',
  5618. //            'images' => true,
  5619. //            'cookie' => array(),
  5620.                 'dpi' => 300,
  5621.                 'image-dpi' => 300,
  5622. //                'enable-external-links' => true,
  5623. //                'enable-internal-links' => true
  5624.             ));
  5625.             return new Response(
  5626.                 $pdf_response,
  5627.                 200,
  5628.                 array(
  5629.                     'Content-Type' => 'application/pdf',
  5630.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5631.                 )
  5632.             );
  5633.         }
  5634.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5635.             array(
  5636.                 'page_title' => 'Stock Transfer',
  5637.                 'export' => 'pdf,print',
  5638.                 'data' => $dt,
  5639.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5640.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5641.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5642.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5643.                     $id,
  5644.                     $dt['created_by'],
  5645.                     $dt['edited_by']),
  5646.                 'document_mark_image' => $document_mark['original'],
  5647.                 'company_name' => $company_data->getName(),
  5648.                 'company_data' => $company_data,
  5649.                 'company_address' => $company_data->getAddress(),
  5650.                 'company_image' => $company_data->getImage(),
  5651.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5652.                 'red' => 0
  5653.             )
  5654.         );
  5655.     }
  5656.     public function CreateStockTransferAction(Request $request)
  5657.     {
  5658.         $em $this->getDoctrine()->getManager();
  5659.         $companyId $this->getLoggedUserCompanyId($request);
  5660.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5661.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5662.         if ($request->isMethod('POST')) {
  5663.             $em $this->getDoctrine()->getManager();
  5664.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  5665.             $dochash $request->request->get('docHash'); //change
  5666.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5667.             $approveRole $request->request->get('approvalRole');
  5668.             $approveHash $request->request->get('approvalHash');
  5669.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5670.                 $loginId$approveRole$approveHash)
  5671.             ) {
  5672.                 $this->addFlash(
  5673.                     'error',
  5674.                     'Sorry Couldnot insert Data.'
  5675.                 );
  5676.             } else {
  5677.                 if ($request->request->has('check_allowed'))
  5678.                     $check_allowed 1;
  5679.                 $StID Inventory::CreateNewStockTransfer(
  5680.                     $this->getDoctrine()->getManager(),
  5681.                     $request->request,
  5682.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5683.                     $this->getLoggedUserCompanyId($request)
  5684.                 );
  5685.                 //now add Approval info
  5686.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5687.                 $approveRole 1;  //created
  5688.                 $options = array(
  5689.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5690.                     'notification_server' => $this->container->getParameter('notification_server'),
  5691.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5692.                     'url' => $this->generateUrl(
  5693.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  5694.                         ['entity_view_route_path_name']
  5695.                     )
  5696.                 );
  5697.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5698.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5699.                     $StID,
  5700.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  5701.                 );
  5702.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  5703.                     $loginId,
  5704.                     $approveRole,
  5705.                     $request->request->get('approvalHash'));
  5706.                 $this->addFlash(
  5707.                     'success',
  5708.                     'Stock Transfer Added.'
  5709.                 );
  5710.                 $url $this->generateUrl(
  5711.                     'view_st'
  5712.                 );
  5713.                 return $this->redirect($url "/" $StID);
  5714.             }
  5715.         }
  5716. //        $slotList = $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  5717. //            array(
  5718. //                'CompanyId' => $this->getLoggedUserCompanyId($request),
  5719. //
  5720. //            )
  5721. //        );
  5722.         $INVLIST = [];
  5723. //        foreach ($slotList as $slot) {
  5724. //            $INVLIST[$slot->getWarehouseId() . '_' . $slot->getActionTagId() . '_' . $slot->getproductId()] = $slot->getQty();
  5725. //        }
  5726.         return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  5727.             array(
  5728.                 'page_title' => 'Stock Transfer Note',
  5729.                 'warehouseList' => Inventory::WarehouseList($em),
  5730.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5731.                 'colorList' => Inventory::GetColorList($em),
  5732.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  5733.                 'srList' => [],
  5734.                 'warehouseActionList' => $warehouse_action_list,
  5735.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5736.                 'item_list' => Inventory::ItemGroupList($em),
  5737.                 'item_list_array' => Inventory::ItemGroupListArray($em),
  5738.                 'category_list_array' => Inventory::ProductCategoryListArray($em),
  5739.                 'product_list_array' => Inventory::ProductListDetailedArray($em),
  5740. //                'product_list_array' => [],
  5741.                 'product_list' => Inventory::ProductList($em$companyId),
  5742. //                'product_list' => [],
  5743.                 'prefix_list' => array(
  5744.                     [
  5745.                         'id' => 1,
  5746.                         'value' => 'GN',
  5747.                         'text' => 'GN'
  5748.                     ]
  5749.                 ),
  5750.                 'assoc_list' => array(
  5751.                     [
  5752.                         'id' => 1,
  5753.                         'value' => 1,
  5754.                         'text' => 'GN'
  5755.                     ]
  5756.                 ),
  5757.                 'INVLIST' => $INVLIST
  5758.             )
  5759.         );
  5760.     }
  5761.     public function GetSrItemForTransferAction(Request $request)
  5762.     {
  5763.         $em $this->getDoctrine()->getManager();
  5764.         $search_query = [];
  5765.         $res_data_by_so_item_id = [];
  5766.         $Content = [];
  5767.         $productionProcessSettings = array(
  5768.             'id' => 0
  5769.         );
  5770.         if ($request->query->has('srId'))
  5771.             $search_query['stockRequisitionId'] = $request->query->get('srId');
  5772.         $DT $this->getDoctrine()
  5773.             ->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')
  5774.             ->findBy(
  5775.                 $search_query
  5776.             );
  5777.         $Content = array(
  5778.             'requisitioned_product_item_id' => [],
  5779.             'requisitioned_products' => [],
  5780.             'requisitioned_product_fdm' => [],
  5781.             'requisitioned_product_name' => [],
  5782.             'requisitioned_product_units' => [],
  5783.             'requisitioned_product_unit_type' => [],
  5784.             'requisitioned_product_balance' => [],
  5785.         );
  5786.         foreach ($DT as $dt) {
  5787. //            $data=json_decode($DT->getData(),true);
  5788.             $Content['requisitioned_products'][] = $dt->getProductId();
  5789.             $Content['requisitioned_product_item_id'][] = $dt->getId();
  5790.             $Content['requisitioned_product_fdm'][] = $dt->getProductFdm();
  5791.             $Content['requisitioned_product_name'][] = $dt->getProductNameFdm();
  5792.             $Content['requisitioned_product_units'][] = $dt->getQty();
  5793.             $Content['requisitioned_product_balance'][] = $dt->getAlottmentPendingAmount();
  5794.         }
  5795.         $INVLIST = [];
  5796.         if (!empty($Content)) {
  5797.             return new JsonResponse(array("success" => true"content" => $Content"INVLIST" => $INVLIST));
  5798.         } else {
  5799.             return new JsonResponse(array("success" => false"content" => $Content"INVLIST" => $INVLIST));
  5800.         }
  5801.     }
  5802.     public function StockTransferListAction(Request $request)
  5803.     {
  5804.         $q $this->getDoctrine()
  5805.             ->getRepository('ApplicationBundle\\Entity\\StockTransfer')
  5806.             ->findBy(
  5807.                 array(
  5808.                     'status' => GeneralConstant::ACTIVE,
  5809.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5810. //                    'approved' =>  GeneralConstant::APPROVED,
  5811.                 )
  5812.             );
  5813.         $stage_list = array(
  5814.             => 'Pending',
  5815.             => 'Pending',
  5816.             => 'Complete',
  5817.             => 'Partial',
  5818.         );
  5819.         $data = [];
  5820.         foreach ($q as $entry) {
  5821.             $data[] = array(
  5822.                 'doc_date' => $entry->getStockTransferDate(),
  5823.                 'id' => $entry->getStockTransferId(),
  5824.                 'doc_hash' => $entry->getDocumentHash(),
  5825.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5826.                 'stage' => $stage_list[$entry->getStage()]
  5827.             );
  5828.         }
  5829.         return $this->render('@Inventory/pages/views/stock_transfer_list.html.twig',
  5830.             array(
  5831.                 'page_title' => 'Stock Transfer List',
  5832.                 'data' => $data
  5833.             )
  5834.         );
  5835.     }
  5836.     public function ViewStockTransferAction(Request $request$id)
  5837.     {
  5838.         $em $this->getDoctrine()->getManager();
  5839.         $dt Inventory::GetStockTransferDetails($em$id);
  5840.         return $this->render(
  5841.             '@Inventory/pages/views/view_stock_transfer.html.twig',
  5842.             array(
  5843.                 'page_title' => 'Stock Transfer',
  5844.                 'data' => $dt,
  5845.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5846.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5847.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5848.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5849.                     $id,
  5850.                     $dt['created_by'],
  5851.                     $dt['edited_by'])
  5852.             )
  5853.         );
  5854.     }
  5855.     public function PrintStockTransferAction(Request $request$id)
  5856.     {
  5857.         $em $this->getDoctrine()->getManager();
  5858.         $dt Inventory::GetStockTransferDetails($em$id);
  5859.         $company_data Company::getCompanyData($em1);
  5860.         $document_mark = array(
  5861.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5862.             'copy' => ''
  5863.         );
  5864.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5865.             $html $this->renderView('@Inventory/pages/print/print_stock_transfer.html.twig',
  5866.                 array(
  5867.                     //full array here
  5868.                     'pdf' => true,
  5869.                     'page_title' => 'Stock Transfer',
  5870.                     'export' => 'pdf,print',
  5871.                     'data' => $dt,
  5872.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5873.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5874.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5875.                         array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5876.                         $id,
  5877.                         $dt['created_by'],
  5878.                         $dt['edited_by']),
  5879.                     'document_mark_image' => $document_mark['original'],
  5880.                     'company_name' => $company_data->getName(),
  5881.                     'company_data' => $company_data,
  5882.                     'company_address' => $company_data->getAddress(),
  5883.                     'company_image' => $company_data->getImage(),
  5884.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5885.                     'red' => 0
  5886.                 )
  5887.             );
  5888.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5889. //                'orientation' => 'landscape',
  5890. //                'enable-javascript' => true,
  5891. //                'javascript-delay' => 1000,
  5892.                 'no-stop-slow-scripts' => false,
  5893.                 'no-background' => false,
  5894.                 'lowquality' => false,
  5895.                 'encoding' => 'utf-8',
  5896. //            'images' => true,
  5897. //            'cookie' => array(),
  5898.                 'dpi' => 300,
  5899.                 'image-dpi' => 300,
  5900. //                'enable-external-links' => true,
  5901. //                'enable-internal-links' => true
  5902.             ));
  5903.             return new Response(
  5904.                 $pdf_response,
  5905.                 200,
  5906.                 array(
  5907.                     'Content-Type' => 'application/pdf',
  5908.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5909.                 )
  5910.             );
  5911.         }
  5912.         return $this->render('@Inventory/pages/print/print_stock_transfer.html.twig',
  5913.             array(
  5914.                 'page_title' => 'Stock Transfer',
  5915.                 'export' => 'pdf,print',
  5916.                 'data' => $dt,
  5917.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5918.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5919.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5920.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5921.                     $id,
  5922.                     $dt['created_by'],
  5923.                     $dt['edited_by']),
  5924.                 'document_mark_image' => $document_mark['original'],
  5925.                 'company_name' => $company_data->getName(),
  5926.                 'company_data' => $company_data,
  5927.                 'company_address' => $company_data->getAddress(),
  5928.                 'company_image' => $company_data->getImage(),
  5929.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5930.                 'red' => 0
  5931.             )
  5932.         );
  5933.     }
  5934.     public function CreateStockConsumptionNoteAction(Request $request)
  5935.     {
  5936.         $em $this->getDoctrine()->getManager();
  5937.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5938.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5939.         if ($request->isMethod('POST')) {
  5940.             $em $this->getDoctrine()->getManager();
  5941.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']; //change
  5942.             $dochash $request->request->get('voucherNumber'); //change
  5943.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5944.             $approveRole $request->request->get('approvalRole');
  5945.             $approveHash $request->request->get('approvalHash');
  5946.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5947.                 $loginId$approveRole$approveHash)
  5948.             ) {
  5949.                 $this->addFlash(
  5950.                     'error',
  5951.                     'Sorry Could not insert Data.'
  5952.                 );
  5953.             } else {
  5954.                 if ($request->request->has('check_allowed'))
  5955.                     $check_allowed 1;
  5956.                 $StID Inventory::CreateNewStockConsumptionNote(
  5957.                     $this->getDoctrine()->getManager(),
  5958.                     $request->request,
  5959.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5960.                     $this->getLoggedUserCompanyId($request)
  5961.                 );
  5962.                 //now add Approval info
  5963.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5964.                 $approveRole 1;  //created
  5965.                 $options = array(
  5966.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5967.                     'notification_server' => $this->container->getParameter('notification_server'),
  5968.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5969.                     'url' => $this->generateUrl(
  5970.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']]
  5971.                         ['entity_view_route_path_name']
  5972.                     )
  5973.                 );
  5974.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5975.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5976.                     $StID,
  5977.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5978.                 );
  5979.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'], $StID,
  5980.                     $loginId,
  5981.                     $approveRole,
  5982.                     $request->request->get('approvalHash'));
  5983.                 $this->addFlash(
  5984.                     'success',
  5985.                     'Stock Consumption Added.'
  5986.                 );
  5987.                 $url $this->generateUrl(
  5988.                     'view_stock_consumption_note'
  5989.                 );
  5990.                 return $this->redirect($url "/" $StID);
  5991.             }
  5992.         }
  5993.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  5994.             array(
  5995.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5996.             )
  5997.         );
  5998.         $INVLIST = [];
  5999.         foreach ($slotList as $slot) {
  6000.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  6001.         }
  6002.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  6003.             array(
  6004.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6005.             )
  6006.         );
  6007.         $consumptionTypeList = [];
  6008.         $consumptionTypeListArray = [];
  6009.         foreach ($consumptionTypeQry as $entry) {
  6010.             $p = array(
  6011.                 'name' => $entry->getName(),
  6012.                 'id' => $entry->getConsumptionTypeId(),
  6013.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  6014.                 'cost_center_id' => $entry->getCostCenterId(),
  6015.             );
  6016.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  6017.             $consumptionTypeListArray[] = $p;
  6018.         }
  6019.         //add bill list
  6020.         $service_purchase_bill_query $this->getDoctrine()
  6021.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  6022.             ->findBy(
  6023.                 array(
  6024.                     'typeHash' => 'SPB',
  6025.                     'approved' => GeneralConstant::APPROVED
  6026.                 )
  6027.             );
  6028.         $service_purchase_bill_list = [];
  6029.         $service_purchase_bill_list_array = [];
  6030.         $bill = array(
  6031.             'id' => 0,
  6032.             'type' => 'SPB',
  6033.             'name' => 'New Expense',
  6034.             'text' => 'New Expense',
  6035.             'amount' => 0,
  6036.         );
  6037.         $service_purchase_bill_list[0] = $bill;
  6038.         $service_purchase_bill_list_array[] = $bill;
  6039.         foreach ($service_purchase_bill_query as $d) {
  6040.             $bill = array(
  6041.                 'id' => $d->getPurchaseInvoiceId(),
  6042.                 'type' => 'SPB',
  6043.                 'name' => $d->getDocumentHash(),
  6044.                 'text' => $d->getDocumentHash(),
  6045.                 'amount' => $d->getInvoiceAmount(),
  6046.             );
  6047.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  6048.             $service_purchase_bill_list_array[] = $bill;
  6049.         }
  6050.         return $this->render('@Inventory/pages/input_forms/stock_consumption_note.html.twig',
  6051.             array(
  6052.                 'page_title' => 'Stock Consumption Note',
  6053.                 'warehouseList' => Inventory::WarehouseList($em),
  6054.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  6055.                 'consumptionTypeList' => $consumptionTypeList,
  6056.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  6057.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  6058.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6059.                 'warehouseActionList' => $warehouse_action_list,
  6060.                 'warehouseActionListArray' => $warehouse_action_list_array,
  6061.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6062.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6063.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6064.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6065.                 'product_list' => Inventory::ProductListDetailed($this->getDoctrine()->getManager()),
  6066.                 'prefix_list' => array(
  6067.                     [
  6068.                         'id' => 1,
  6069.                         'value' => 'GN',
  6070.                         'text' => 'GN'
  6071.                     ]
  6072.                 ),
  6073.                 'assoc_list' => array(
  6074.                     [
  6075.                         'id' => 1,
  6076.                         'value' => 1,
  6077.                         'text' => 'GN'
  6078.                     ]
  6079.                 ),
  6080.                 'INVLIST' => $INVLIST,
  6081.                 'project_list_array' => ProjectM::GetProjectList($em)
  6082.             )
  6083.         );
  6084.     }
  6085.     public function StockConsumptionNoteListAction(Request $request)
  6086.     {
  6087.         $q $this->getDoctrine()
  6088.             ->getRepository('ApplicationBundle\\Entity\\StockConsumptionNote')
  6089.             ->findBy(
  6090.                 array(
  6091.                     'status' => GeneralConstant::ACTIVE,
  6092.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  6093. //                    'approved' =>  GeneralConstant::APPROVED,
  6094.                 )
  6095.             );
  6096.         $stage_list = array(
  6097.             => 'Pending',
  6098.             => 'Pending',
  6099.             => 'Complete',
  6100.             => 'Partial',
  6101.         );
  6102.         $data = [];
  6103.         foreach ($q as $entry) {
  6104.             $data[] = array(
  6105.                 'doc_date' => $entry->getStockConsumptionNoteDate(),
  6106.                 'id' => $entry->getStockConsumptionNoteId(),
  6107.                 'doc_hash' => $entry->getDocumentHash(),
  6108.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  6109.                 'stage' => $stage_list[$entry->getStage()]
  6110.             );
  6111.         }
  6112.         return $this->render('@Inventory/pages/views/stock_consumption_note_list.html.twig',
  6113.             array(
  6114.                 'page_title' => 'Stock Consumption Note List',
  6115.                 'data' => $data
  6116.             )
  6117.         );
  6118.     }
  6119.     public function ViewStockConsumptionNoteAction(Request $request$id)
  6120.     {
  6121.         $em $this->getDoctrine()->getManager();
  6122.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  6123.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  6124.             array(
  6125.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6126.             )
  6127.         );
  6128.         $consumptionTypeList = [];
  6129.         $consumptionTypeListArray = [];
  6130.         foreach ($consumptionTypeQry as $entry) {
  6131.             $p = array(
  6132.                 'name' => $entry->getName(),
  6133.                 'id' => $entry->getConsumptionTypeId(),
  6134.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  6135.                 'cost_center_id' => $entry->getCostCenterId(),
  6136.             );
  6137.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  6138.             $consumptionTypeListArray[] = $p;
  6139.         }
  6140.         //add bill list
  6141.         $service_purchase_bill_query $this->getDoctrine()
  6142.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  6143.             ->findBy(
  6144.                 array(
  6145.                     'typeHash' => 'SPB',
  6146.                     'approved' => GeneralConstant::APPROVED
  6147.                 )
  6148.             );
  6149.         $service_purchase_bill_list = [];
  6150.         $service_purchase_bill_list_array = [];
  6151.         $bill = array(
  6152.             'id' => 0,
  6153.             'type' => 'SPB',
  6154.             'name' => 'New Expense',
  6155.             'text' => 'New Expense',
  6156.             'amount' => 0,
  6157.         );
  6158.         $service_purchase_bill_list[0] = $bill;
  6159.         $service_purchase_bill_list_array[] = $bill;
  6160.         foreach ($service_purchase_bill_query as $d) {
  6161.             $bill = array(
  6162.                 'id' => $d->getPurchaseInvoiceId(),
  6163.                 'type' => 'SPB',
  6164.                 'name' => $d->getDocumentHash(),
  6165.                 'text' => $d->getDocumentHash(),
  6166.                 'amount' => $d->getInvoiceAmount(),
  6167.             );
  6168.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  6169.             $service_purchase_bill_list_array[] = $bill;
  6170.         }
  6171.         return $this->render(
  6172.             '@Inventory/pages/views/view_stock_consumption_note.html.twig',
  6173.             array(
  6174.                 'page_title' => 'Stock Transfer',
  6175.                 'data' => $dt,
  6176.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  6177.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6178.                 'consumptionTypeList' => $consumptionTypeList,
  6179.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  6180.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6181.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6182.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6183.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6184.                     $id,
  6185.                     $dt['created_by'],
  6186.                     $dt['edited_by'])
  6187.             )
  6188.         );
  6189.     }
  6190.     public function PrintStockConsumptionNoteAction(Request $request$id)
  6191.     {
  6192.         $em $this->getDoctrine()->getManager();
  6193.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  6194.         $company_data Company::getCompanyData($em1);
  6195.         $document_mark = array(
  6196.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6197.             'copy' => ''
  6198.         );
  6199.         $consumptionTypeQry $em->getRepository('ApplicationBundle\\Entity\\ConsumptionType')->findBy(
  6200.             array(
  6201.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6202.             )
  6203.         );
  6204.         $consumptionTypeList = [];
  6205.         $consumptionTypeListArray = [];
  6206.         foreach ($consumptionTypeQry as $entry) {
  6207.             $p = array(
  6208.                 'name' => $entry->getName(),
  6209.                 'id' => $entry->getConsumptionTypeId(),
  6210.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  6211.                 'cost_center_id' => $entry->getCostCenterId(),
  6212.             );
  6213.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  6214.             $consumptionTypeListArray[] = $p;
  6215.         }
  6216.         //add bill list
  6217.         $service_purchase_bill_query $this->getDoctrine()
  6218.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  6219.             ->findBy(
  6220.                 array(
  6221.                     'typeHash' => 'SPB',
  6222.                     'approved' => GeneralConstant::APPROVED
  6223.                 )
  6224.             );
  6225.         $service_purchase_bill_list = [];
  6226.         $service_purchase_bill_list_array = [];
  6227.         $bill = array(
  6228.             'id' => 0,
  6229.             'type' => 'SPB',
  6230.             'name' => 'New Expense',
  6231.             'text' => 'New Expense',
  6232.             'amount' => 0,
  6233.         );
  6234.         $service_purchase_bill_list[0] = $bill;
  6235.         $service_purchase_bill_list_array[] = $bill;
  6236.         foreach ($service_purchase_bill_query as $d) {
  6237.             $bill = array(
  6238.                 'id' => $d->getPurchaseInvoiceId(),
  6239.                 'type' => 'SPB',
  6240.                 'name' => $d->getDocumentHash(),
  6241.                 'text' => $d->getDocumentHash(),
  6242.                 'amount' => $d->getInvoiceAmount(),
  6243.             );
  6244.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  6245.             $service_purchase_bill_list_array[] = $bill;
  6246.         }
  6247.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6248.             $html $this->renderView('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  6249.                 array(
  6250.                     //full array here
  6251.                     'pdf' => true,
  6252.                     'page_title' => 'Stock Consumption',
  6253.                     'export' => 'pdf,print',
  6254.                     'data' => $dt,
  6255.                     'service_purchase_bill_list' => $service_purchase_bill_list,
  6256.                     'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6257.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6258.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6259.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6260.                         array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6261.                         $id,
  6262.                         $dt['created_by'],
  6263.                         $dt['edited_by']),
  6264.                     'document_mark_image' => $document_mark['original'],
  6265.                     'consumptionTypeList' => $consumptionTypeList,
  6266.                     'consumptionTypeListArray' => $consumptionTypeListArray,
  6267.                     'company_name' => $company_data->getName(),
  6268.                     'company_data' => $company_data,
  6269.                     'company_address' => $company_data->getAddress(),
  6270.                     'company_image' => $company_data->getImage(),
  6271.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6272.                     'red' => 0
  6273.                 )
  6274.             );
  6275.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6276. //                'orientation' => 'landscape',
  6277. //                'enable-javascript' => true,
  6278. //                'javascript-delay' => 1000,
  6279.                 'no-stop-slow-scripts' => false,
  6280.                 'no-background' => false,
  6281.                 'lowquality' => false,
  6282.                 'encoding' => 'utf-8',
  6283. //            'images' => true,
  6284. //            'cookie' => array(),
  6285.                 'dpi' => 300,
  6286.                 'image-dpi' => 300,
  6287. //                'enable-external-links' => true,
  6288. //                'enable-internal-links' => true
  6289.             ));
  6290.             return new Response(
  6291.                 $pdf_response,
  6292.                 200,
  6293.                 array(
  6294.                     'Content-Type' => 'application/pdf',
  6295.                     'Content-Disposition' => 'attachment; filename="stock_consumption_note_' $id '.pdf"'
  6296.                 )
  6297.             );
  6298.         }
  6299.         return $this->render('@Inventory/pages/print/print_stock_consumption_note.html.twig',
  6300.             array(
  6301.                 'page_title' => 'Stock Consumption',
  6302.                 'export' => 'pdf,print',
  6303.                 'data' => $dt,
  6304.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  6305.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  6306.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6307.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6308.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6309.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  6310.                     $id,
  6311.                     $dt['created_by'],
  6312.                     $dt['edited_by']),
  6313.                 'document_mark_image' => $document_mark['original'],
  6314.                 'consumptionTypeList' => $consumptionTypeList,
  6315.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  6316.                 'company_name' => $company_data->getName(),
  6317.                 'company_data' => $company_data,
  6318.                 'company_address' => $company_data->getAddress(),
  6319.                 'company_image' => $company_data->getImage(),
  6320.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6321.                 'red' => 0
  6322.             )
  6323.         );
  6324.     }
  6325.     public function CreateStockReceivedNoteAction(Request $request$id 0)
  6326.     {
  6327.         $em $this->getDoctrine()->getManager();
  6328.         $companyId $this->getLoggedUserCompanyId($request);
  6329.         $extDocData = [];
  6330.         $userId $request->getSession()->get(UserConstants::USER_ID);
  6331.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  6332.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  6333. //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  6334.         $userBranchIdList $request->getSession()->get('branchIdList');
  6335.         if ($userBranchIdList == null$userBranchIdList = [];
  6336.         $userBranchId $request->getSession()->get('branchId');
  6337.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  6338.             $em $this->getDoctrine()->getManager();
  6339.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //change
  6340.             $dochash $request->request->get('docHash'); //change
  6341.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6342.             $approveRole $request->request->get('approvalRole');
  6343.             $approveHash $request->request->get('approvalHash');
  6344.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6345.                 $loginId$approveRole$approveHash$id)
  6346.             ) {
  6347.                 if ($request->request->has('returnJson')) {
  6348.                     return new JsonResponse(array(
  6349.                         'success' => false,
  6350.                         'documentHash' => 0,
  6351.                         'documentId' => 0,
  6352.                         'billIds' => [],
  6353.                         'drIds' => [],
  6354.                         'pmntTransIds' => [],
  6355.                         'viewUrl' => '',
  6356.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  6357.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  6358.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  6359.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  6360.                     ));
  6361.                 } else
  6362.                     $this->addFlash(
  6363.                         'error',
  6364.                         'Sorry Could not insert Data.'
  6365.                     );
  6366.             } else {
  6367.                 if ($request->request->has('check_allowed'))
  6368.                     $check_allowed 1;
  6369.                 try {
  6370.                     $StID Inventory::CreateNewStockReceivedNote(
  6371.                         $this->getDoctrine()->getManager(),
  6372.                         $request->request,
  6373.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6374.                         $this->getLoggedUserCompanyId($request),
  6375.                         0,
  6376.                         (int) $id   // edit id from the route â†’ update in place instead of duplicating
  6377.                     );
  6378.                 } catch (\InvalidArgumentException $e) {
  6379.                     if ($request->request->has('returnJson')) {
  6380.                         return new JsonResponse(array(
  6381.                             'success' => false,
  6382.                             'message' => $e->getMessage(),
  6383.                         ));
  6384.                     }
  6385.                     $this->addFlash('error'$e->getMessage());
  6386.                     return $this->redirect($request->getUri());
  6387.                 } catch (\Exception $e) {
  6388.                     if ($request->request->has('returnJson')) {
  6389.                         return new JsonResponse(array(
  6390.                             'success' => false,
  6391.                             'message' => 'Sorry Could not insert Data.',
  6392.                         ));
  6393.                     }
  6394.                     $this->addFlash('error''Sorry Could not insert Data.');
  6395.                     return $this->redirect($request->getUri());
  6396.                 }
  6397.                 //now add Approval info
  6398.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6399.                 $approveRole 1;  //created
  6400.                 $options = array(
  6401.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6402.                     'notification_server' => $this->container->getParameter('notification_server'),
  6403.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6404.                     'url' => $this->generateUrl(
  6405.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  6406.                         ['entity_view_route_path_name']
  6407.                     )
  6408.                 );
  6409.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6410.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6411.                     $StID,
  6412.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6413.                 );
  6414.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  6415.                     $loginId,
  6416.                     $approveRole,
  6417.                     $request->request->get('approvalHash'));
  6418.                 $url $this->generateUrl(
  6419.                     'view_srcv'
  6420.                 );
  6421.                 if ($request->request->has('returnJson')) {
  6422.                     return new JsonResponse(array(
  6423.                         'success' => true,
  6424.                         'documentHash' => $dochash,
  6425.                         'documentId' => $StID,
  6426.                         'viewUrl' => $url "/" $StID,
  6427.                     ));
  6428.                 } else {
  6429.                     $this->addFlash(
  6430.                         'success',
  6431.                         'Stock Received Note Added.'
  6432.                     );
  6433.                     return $this->redirect($url "/" $StID);
  6434.                 }
  6435.             }
  6436.         }
  6437.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  6438.             array(
  6439.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  6440.             )
  6441.         );
  6442.         $extDocItems = [];
  6443.         if ($id == 0) {
  6444.         } else {
  6445.             $extDoc $em->getRepository('ApplicationBundle\Entity\StockReceivedNote')->findOneBy(
  6446.                 array(
  6447.                     'stockReceivedNoteId' => $id,
  6448.                 )
  6449.             );
  6450.             //now if its not editable, redirect to view
  6451.             if ($extDoc) {
  6452.                 if ($extDoc->getEditFlag() != 1) {
  6453.                     $url $this->generateUrl(
  6454.                         'view_srcv'
  6455.                     );
  6456.                     return $this->redirect($url "/" $id);
  6457.                 } else {
  6458.                     $extDocData $extDoc;
  6459.                     $extDocDataDetails $em->getRepository('ApplicationBundle\Entity\StockReceivedNoteItem')->findBy(
  6460.                         array(
  6461.                             'stockReceivedNoteId' => $id,
  6462.                         )
  6463.                     );
  6464.                     foreach ($extDocDataDetails as $itemEntry) {
  6465.                         $product $em->getRepository('ApplicationBundle\Entity\InvProducts')->findOneBy(
  6466.                             array('id' => $itemEntry->getProductId())
  6467.                         );
  6468.                         $extDocItems[] = array(
  6469.                             'productId' => $itemEntry->getProductId(),
  6470.                             'productName' => $product $product->getName() : '',
  6471.                             'warehouseId' => $itemEntry->getWarehouseId(),
  6472.                             'warehouseActionId' => $itemEntry->getWarehouseActionId(),
  6473.                             'qty' => $itemEntry->getQty(),
  6474.                             'price' => $itemEntry->getPrice(),
  6475.                             'warrantyMon' => $itemEntry->getWarrantyMon(),
  6476.                             'batchNo' => $itemEntry->getBatchNo(),
  6477.                             'mfgDate' => $itemEntry->getMfgDate() ? $itemEntry->getMfgDate()->format('Y-m-d') : '',
  6478.                             'expiryDate' => $itemEntry->getExpiryDate() ? $itemEntry->getExpiryDate()->format('Y-m-d') : '',
  6479.                         );
  6480.                     }
  6481.                 }
  6482.             } else {
  6483.             }
  6484.         }
  6485.         $INVLIST = [];
  6486.         foreach ($slotList as $slot) {
  6487.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  6488.         }
  6489.         $dataArray = array(
  6490.             'page_title' => 'Stock Received Note',
  6491. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  6492.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  6493.             'users' => Users::getUserListById($em),
  6494.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  6495.             'warehouseList' => Inventory::WarehouseList($em),
  6496.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  6497.             'warehouseActionList' => $warehouse_action_list,
  6498.             'warehouseActionListArray' => $warehouse_action_list_array,
  6499.             'extDocItems' => $extDocItems,
  6500.             'extDocData' => $extDocData,
  6501.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  6502.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6503.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6504.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6505. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6506. //            'product_list' => Inventory::ProductList($em, $companyId),
  6507.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  6508.             'prefix_list' => array(
  6509.                 [
  6510.                     'id' => 1,
  6511.                     'value' => 'GN',
  6512.                     'text' => 'GN'
  6513.                 ]
  6514.             ),
  6515.             'assoc_list' => array(
  6516.                 [
  6517.                     'id' => 1,
  6518.                     'value' => 1,
  6519.                     'text' => 'GN'
  6520.                 ]
  6521.             ),
  6522.             'INVLIST' => $INVLIST,
  6523.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  6524.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  6525.             'userBranchIdList' => $userBranchIdList,
  6526.             'userBranchId' => $userBranchId,
  6527. //            'headList' => Accounts::HeadList($em),
  6528.         );
  6529.         //json
  6530.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  6531.         {
  6532.             $dataArray['success'] = true;
  6533.             return new JsonResponse(
  6534.                 $dataArray
  6535.             );
  6536.         }
  6537.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  6538.             $dataArray
  6539.         );
  6540.     }
  6541.     public function GetItemListForStockReceivedAction(Request $request)
  6542.     {
  6543.         if ($request->isMethod('POST')) {
  6544.             $em $this->getDoctrine();
  6545.             $receiveType 1;//transfer
  6546.             if ($request->request->has('receiveType'))
  6547.                 $receiveType $request->request->get('receiveType');
  6548.             $QD = [];
  6549.             if ($receiveType == 1)
  6550.                 $QD $this->getDoctrine()
  6551.                     ->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  6552.                     ->findBy(
  6553.                         array(
  6554. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  6555.                             'stockTransferId' => $request->request->get('stId')
  6556.                         ),
  6557.                         array()
  6558.                     );
  6559.             if ($receiveType == 2)
  6560.                 $QD $this->getDoctrine()
  6561.                     ->getRepository('ApplicationBundle\\Entity\\SalesOrderItem')
  6562.                     ->findBy(
  6563.                         array(
  6564. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  6565.                             'salesOrderId' => $request->request->get('soId')
  6566.                         ),
  6567.                         array()
  6568.                     );
  6569. //            if($request->request->get('wareHouseId')!='')
  6570. //
  6571. //            $DO=$this->getDoctrine()
  6572. //                ->getRepository('ApplicationBundle\\Entity\\DeliveryOrder')
  6573. //                ->findOneBy(
  6574. //                    $find_array,
  6575. //                    array(
  6576. //
  6577. //                    )
  6578. //                );
  6579.             $sendData = array(
  6580. //                'salesType'=>$SO->getSalesType(),
  6581. //                'packageData'=>[],
  6582.                 'productList' => [],
  6583. //                'productListByPackage'=>[],
  6584.             );
  6585.             $productList Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request));
  6586.             $pckg_item_cross_match_data = [];
  6587.             foreach ($QD as $product) {
  6588. //                $b_code=json_decode($product->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  6589.                 $b_code = [];
  6590.                 $newProductId $product->getProductId();
  6591.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  6592.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6593.                     if ($to_analyze_codes_str != null)
  6594.                         $b_code json_decode($to_analyze_codes_strtrue512JSON_BIGINT_AS_STRING);
  6595.                     else
  6596.                         $b_code = [];
  6597.                 } else {
  6598.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6599.                     if ($to_analyze_codes_str != null) {
  6600.                         $max_int_length strlen((string)PHP_INT_MAX) - 1;
  6601.                         $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$to_analyze_codes_str);
  6602.                         $b_code json_decode($json_without_bigintstrue);
  6603.                     } else {
  6604.                         $b_code = [];
  6605.                     }
  6606.                 }
  6607.                 $b_code_data = [];
  6608.                 foreach ($b_code as $d) {
  6609.                     $b_code_data[] = array(
  6610.                         'id' => $d,
  6611.                         'name' => str_pad($d13'0'STR_PAD_LEFT),
  6612.                     );
  6613.                 }
  6614.                 $p_data = array(
  6615.                     'details_id' => $product->getId(),
  6616.                     'productId' => $product->getProductId(),
  6617.                     'product_name' => isset($productList[$product->getProductId()]) ? $productList[$product->getProductId()]['name'] : 'Unknown Product',
  6618.                     'product_barcodes' => $b_code_data,
  6619. //                    'available_inventory'=>$inventory_by_warehouse?$inventory_by_warehouse->getQty():0,
  6620. //                        'package_id'=>$product->getPackageId(),
  6621.                     'qty' => $receiveType == $product->getQty() : $product->getToBeReceived(),
  6622.                     'unit_price' => $receiveType == $product->getPrice() : $productList[$product->getProductId()]['purchase_price'],
  6623.                     'balance' => $receiveType == $product->getBalance() : ($product->getToBeReceived() - $product->getReceived()),
  6624. //                        'delivered'=>$product->getDelivered(),
  6625.                 );
  6626.                 $sendData['productList'][] = $p_data;
  6627.             }
  6628.             //now package data
  6629.             if ($sendData) {
  6630.                 return new JsonResponse(array("success" => true"content" => $sendData));
  6631.             }
  6632.             return new JsonResponse(array("success" => false));
  6633.         }
  6634.         return new JsonResponse(array("success" => false));
  6635.     }
  6636.     public function StockReceivedNoteListAction(Request $request)
  6637.     {
  6638.         $q $this->getDoctrine()
  6639.             ->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')
  6640.             ->findBy(
  6641.                 array(
  6642.                     'status' => GeneralConstant::ACTIVE,
  6643.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  6644. //                    'approved' =>  GeneralConstant::APPROVED,
  6645.                 )
  6646.             );
  6647.         $stage_list = array(
  6648.             => 'Pending',
  6649.             => 'Pending',
  6650.             => 'Complete',
  6651.             => 'Partial',
  6652.         );
  6653.         $data = [];
  6654.         foreach ($q as $entry) {
  6655.             $data[] = array(
  6656.                 'doc_date' => $entry->getStockReceivedNoteDate(),
  6657.                 'id' => $entry->getStockReceivedNoteId(),
  6658.                 'doc_hash' => $entry->getDocumentHash(),
  6659.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  6660.                 'stage' => $stage_list[$entry->getStage()]
  6661.             );
  6662.         }
  6663.         return $this->render('@Inventory/pages/views/stock_received_note_list.html.twig',
  6664.             array(
  6665.                 'page_title' => 'Stock Received List',
  6666.                 'data' => $data
  6667.             )
  6668.         );
  6669.     }
  6670.     public function ViewStockReceivedNoteAction(Request $request$id)
  6671.     {
  6672.         $em $this->getDoctrine()->getManager();
  6673.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6674.         return $this->render(
  6675.             '@Inventory/pages/views/view_stock_received_note.html.twig',
  6676.             array(
  6677.                 'page_title' => 'Stock Received Note',
  6678.                 'data' => $dt,
  6679.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  6680.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6681.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6682.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6683.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6684.                     $id,
  6685.                     $dt['created_by'],
  6686.                     $dt['edited_by'])
  6687.             )
  6688.         );
  6689.     }
  6690.     public function PrintStockReceivedNoteAction(Request $request$id)
  6691.     {
  6692.         $em $this->getDoctrine()->getManager();
  6693.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6694.         $company_data Company::getCompanyData($em1);
  6695.         $document_mark = array(
  6696.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6697.             'copy' => ''
  6698.         );
  6699.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6700.             $html $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
  6701.                 array(
  6702.                     //full array here
  6703.                     'pdf' => true,
  6704.                     'page_title' => 'Stock Received Note',
  6705.                     'export' => 'pdf,print',
  6706.                     'data' => $dt,
  6707.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6708.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6709.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6710.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6711.                         $id,
  6712.                         $dt['created_by'],
  6713.                         $dt['edited_by']),
  6714.                     'document_mark_image' => $document_mark['original'],
  6715.                     'company_name' => $company_data->getName(),
  6716.                     'company_data' => $company_data,
  6717.                     'company_address' => $company_data->getAddress(),
  6718.                     'company_image' => $company_data->getImage(),
  6719.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6720.                     'red' => 0
  6721.                 )
  6722.             );
  6723.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6724. //                'orientation' => 'landscape',
  6725. //                'enable-javascript' => true,
  6726. //                'javascript-delay' => 1000,
  6727.                 'no-stop-slow-scripts' => false,
  6728.                 'no-background' => false,
  6729.                 'lowquality' => false,
  6730.                 'encoding' => 'utf-8',
  6731. //            'images' => true,
  6732. //            'cookie' => array(),
  6733.                 'dpi' => 300,
  6734.                 'image-dpi' => 300,
  6735. //                'enable-external-links' => true,
  6736. //                'enable-internal-links' => true
  6737.             ));
  6738.             return new Response(
  6739.                 $pdf_response,
  6740.                 200,
  6741.                 array(
  6742.                     'Content-Type' => 'application/pdf',
  6743.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  6744.                 )
  6745.             );
  6746.         }
  6747.         return $this->render('@Inventory/pages/print/print_stock_received_note.html.twig',
  6748.             array(
  6749.                 'page_title' => 'Stock Received Note',
  6750.                 'export' => 'pdf,print',
  6751.                 'data' => $dt,
  6752.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6753.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6754.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6755.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6756.                     $id,
  6757.                     $dt['created_by'],
  6758.                     $dt['edited_by']),
  6759.                 'document_mark_image' => $document_mark['original'],
  6760.                 'company_name' => $company_data->getName(),
  6761.                 'company_data' => $company_data,
  6762.                 'company_address' => $company_data->getAddress(),
  6763.                 'company_image' => $company_data->getImage(),
  6764.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6765.                 'red' => 0
  6766.             )
  6767.         );
  6768.     }
  6769.     public function CreateStoreRequisitionSlipAction(Request $request$id 0)
  6770.     {
  6771.         $em $this->getDoctrine()->getManager();
  6772. //        $id;
  6773.         if ($request->isMethod('POST')) {
  6774.             $em $this->getDoctrine()->getManager();
  6775.             $entity_id array_flip(GeneralConstant::$Entity_list)['StoreRequisition']; //change
  6776.             $dochash $request->request->get('voucherNumber'); //change
  6777.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6778.             $approveRole $request->request->get('approvalRole');
  6779.             $approveHash $request->request->get('approvalHash');
  6780.             $validation Inventory::ValidateStoreRequisitionSlip($request->request);
  6781.             if (!$validation['success']) {
  6782.                 $this->addFlash(
  6783.                     'error',
  6784.                     $validation['error']
  6785.                 );
  6786.             } else if (!DocValidation::isInsertable($em$entity_id$dochash,
  6787.                 $loginId$approveRole$approveHash$id)
  6788.             ) {
  6789.                 $this->addFlash(
  6790.                     'error',
  6791.                     'Sorry, could not insert Data.'
  6792.                 );
  6793.             } else {
  6794.                 if ($request->request->has('check_allowed'))
  6795.                     $check_allowed 1;
  6796.                 $IrID Inventory::CreateNewStoreRequisition($id,
  6797.                     $this->getDoctrine()->getManager(),
  6798.                     $request->request,
  6799.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6800.                     $this->getLoggedUserCompanyId($request)
  6801.                 );
  6802.                 //now add Approval info
  6803.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6804.                 $approveRole $request->request->get('approvalRole');
  6805.                 $options = array(
  6806.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6807.                     'notification_server' => $this->container->getParameter('notification_server'),
  6808.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6809.                     'url' => $this->generateUrl(
  6810.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StoreRequisition']]
  6811.                         ['entity_view_route_path_name']
  6812.                     )
  6813.                 );
  6814.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6815.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  6816.                     $IrID,
  6817.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6818.                 );
  6819.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StoreRequisition'], $IrID,
  6820.                     $loginId,
  6821.                     $approveRole,
  6822.                     $request->request->get('approvalHash'));
  6823.                 $this->addFlash(
  6824.                     'success',
  6825.                     'New Indent Added.'
  6826.                 );
  6827.                 $url $this->generateUrl(
  6828.                     'view_ir'
  6829.                 );
  6830.                 return $this->redirect($url "/" $IrID);
  6831.             }
  6832.         }
  6833.         $extDocData = [];
  6834.         $extDocDetailsData = [];
  6835.         if ($id == 0) {
  6836.         } else {
  6837.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StoreRequisition')->findOneBy(
  6838.                 array(
  6839.                     'storeRequisitionId' => $id///material
  6840.                 )
  6841.             );
  6842.             //now if its not editable, redirect to view
  6843.             if ($extDoc) {
  6844.                 if ($extDoc->getEditFlag() != 1) {
  6845.                     $url $this->generateUrl(
  6846.                         'view_ir'
  6847.                     );
  6848.                     return $this->redirect($url "/" $id);
  6849.                 } else {
  6850.                     $extDocData $extDoc;
  6851.                     $extDocDetailsData $em->getRepository('ApplicationBundle\\Entity\\StoreRequisitionItem')->findBy(
  6852.                         array(
  6853.                             'storeRequisitionId' => $id///material
  6854.                         )
  6855.                     );;
  6856.                 }
  6857.             } else {
  6858.             }
  6859.         }
  6860.         $companyId $this->getLoggedUserCompanyId($request);
  6861.         $productListArray = [];
  6862.         $subCategoryListArray = [];
  6863.         $categoryListArray = [];
  6864.         $igListArray = [];
  6865.         $unitListArray = [];
  6866.         $brandListArray = [];
  6867.         $productList Inventory::ProductList($em$companyId);
  6868.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6869.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6870.         $igList Inventory::ItemGroupList($em$companyId);
  6871.         $unitList Inventory::UnitTypeList($em);
  6872.         $brandList Inventory::GetBrandList($em$companyId);
  6873.         foreach ($productList as $product$productListArray[] = $product;
  6874.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6875.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6876.         foreach ($igList as $product$igListArray[] = $product;
  6877.         foreach ($unitList as $product$unitListArray[] = $product;
  6878.         foreach ($brandList as $product$brandListArray[] = $product;
  6879.         $sr_list = [];
  6880.         $QD $this->getDoctrine()
  6881.             ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  6882.             ->findBy(
  6883.                 array(
  6884.                     'indentTagged' => 0,
  6885.                     'approved' => 1
  6886.                 )
  6887.             );
  6888.         foreach ($QD as $dt) {
  6889.             $sr_list[$dt->getStockRequisitionId()] = array(
  6890.                 'id' => $dt->getStockRequisitionId(),
  6891.                 'name' => $dt->getDocumentHash(),
  6892.                 'text' => $dt->getDocumentHash(),
  6893.             );
  6894.         }
  6895.         return $this->render('@Inventory/pages/input_forms/store_requisition.html.twig',
  6896.             array(
  6897.                 'page_title' => 'Indent Requisition Slip',
  6898.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6899.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6900.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6901.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6902.                 'sr_list' => $sr_list,
  6903.                 'productList' => $productList,
  6904.                 'subCategoryList' => $subCategoryList,
  6905.                 'categoryList' => $categoryList,
  6906.                 'igList' => $igList,
  6907.                 'extId' => $id,
  6908.                 'extDocDetailsData' => $extDocDetailsData,
  6909.                 'extDocData' => $extDocData,
  6910.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6911.                 'unitList' => $unitList,
  6912.                 'brandList' => $brandList,
  6913.                 'brandListArray' => $brandListArray,
  6914.                 'productListArray' => $productListArray,
  6915.                 'subCategoryListArray' => $subCategoryListArray,
  6916.                 'categoryListArray' => $categoryListArray,
  6917.                 'igListArray' => $igListArray,
  6918.                 'unitListArray' => $unitListArray,
  6919.                 'prefix_list' => array(
  6920.                     [
  6921.                         'id' => 1,
  6922.                         'value' => 'GN',
  6923.                         'text' => 'General'
  6924.                     ],
  6925.                     [
  6926.                         'id' => 1,
  6927.                         'value' => 'SD',
  6928.                         'text' => 'For Sales Demand'
  6929.                     ]
  6930.                 ),
  6931.                 'assoc_list' => array(
  6932.                     [
  6933.                         'id' => 1,
  6934.                         'value' => 1,
  6935.                         'text' => 'GN'
  6936.                     ]
  6937.                 )
  6938.             )
  6939.         );
  6940.     }
  6941.     public function CreateStockRequisitionSlipAction(Request $request$id 0)
  6942.     {
  6943.         $em $this->getDoctrine()->getManager();
  6944.         if ($request->isMethod('POST')) {
  6945.             $em $this->getDoctrine()->getManager();
  6946.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockRequisition']; //change
  6947.             $dochash $request->request->get('voucherNumber'); //change
  6948.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6949.             $approveRole $request->request->get('approvalRole');
  6950.             $approveHash $request->request->get('approvalHash');
  6951.             $validation Inventory::ValidateStockRequisitionSlip($request->request);
  6952.             if (!$validation['success']) {
  6953.                 $this->addFlash(
  6954.                     'error',
  6955.                     $validation['error']
  6956.                 );
  6957.             } else if (!DocValidation::isInsertable($em$entity_id$dochash,
  6958.                 $loginId$approveRole$approveHash$id)
  6959.             ) {
  6960.                 $this->addFlash(
  6961.                     'error',
  6962.                     'Sorry, could not insert Data.'
  6963.                 );
  6964.             } else {
  6965.                 if ($request->request->has('check_allowed'))
  6966.                     $check_allowed 1;
  6967.                 $SrID Inventory::CreateNewStockRequisition($id,
  6968.                     $this->getDoctrine()->getManager(),
  6969.                     $request->request,
  6970.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6971.                     $this->getLoggedUserCompanyId($request)
  6972.                 );
  6973.                 //now add Approval info
  6974.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6975.                 $approveRole $request->request->get('approvalRole');
  6976.                 $options = array(
  6977.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6978.                     'notification_server' => $this->container->getParameter('notification_server'),
  6979.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6980.                     'url' => $this->generateUrl(
  6981.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockRequisition']]
  6982.                         ['entity_view_route_path_name']
  6983.                     )
  6984.                 );
  6985.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6986.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  6987.                     $SrID,
  6988.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6989.                 );
  6990.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockRequisition'], $SrID,
  6991.                     $loginId,
  6992.                     $approveRole,
  6993.                     $request->request->get('approvalHash'));
  6994.                 $this->addFlash(
  6995.                     'success',
  6996.                     'New Requisition Added.'
  6997.                 );
  6998.                 $url $this->generateUrl(
  6999.                     'view_sr'
  7000.                 );
  7001. //                return $this->redirect($url . "/" . $SrID);
  7002.             }
  7003.         }
  7004.         $extDocData = [];
  7005.         $extDocDetailsData = [];
  7006.         if ($id == 0) {
  7007.         } else {
  7008.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StockRequisition')->findOneBy(
  7009.                 array(
  7010.                     'stockRequisitionId' => $id///material
  7011.                 )
  7012.             );
  7013.             //now if its not editable, redirect to view
  7014.             if ($extDoc) {
  7015.                 if ($extDoc->getEditFlag() != 1) {
  7016.                     $url $this->generateUrl(
  7017.                         'view_sr'
  7018.                     );
  7019.                     return $this->redirect($url "/" $id);
  7020.                 } else {
  7021.                     $extDocData $extDoc;
  7022.                     $extDocDetailsData $em->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')->findBy(
  7023.                         array(
  7024.                             'stockRequisitionId' => $id///material
  7025.                         )
  7026.                     );;
  7027.                 }
  7028.             } else {
  7029.             }
  7030.         }
  7031.         $companyId $this->getLoggedUserCompanyId($request);
  7032.         $productListArray = [];
  7033.         $subCategoryListArray = [];
  7034.         $categoryListArray = [];
  7035.         $igListArray = [];
  7036.         $unitListArray = [];
  7037.         $brandListArray = [];
  7038.         $productList Inventory::ProductList($em$companyId);
  7039.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  7040.         $categoryList Inventory::ProductCategoryList($em$companyId);
  7041.         $igList Inventory::ItemGroupList($em$companyId);
  7042.         $unitList Inventory::UnitTypeList($em);
  7043.         $brandList Inventory::GetBrandList($em$companyId);
  7044.         foreach ($productList as $product$productListArray[] = $product;
  7045.         foreach ($categoryList as $product$categoryListArray[] = $product;
  7046.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  7047.         foreach ($igList as $product$igListArray[] = $product;
  7048.         foreach ($unitList as $product$unitListArray[] = $product;
  7049.         foreach ($brandList as $product$brandListArray[] = $product;
  7050.         return $this->render('@Inventory/pages/input_forms/stock_requisition_slip.html.twig',
  7051.             array(
  7052.                 'page_title' => 'Stock Requisition Slip',
  7053.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7054.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  7055.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  7056.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  7057.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  7058.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  7059.                 'productList' => $productList,
  7060.                 'extId' => $id,
  7061.                 'extDocDetailsData' => $extDocDetailsData,
  7062.                 'extDocData' => $extDocData,
  7063.                 'subCategoryList' => $subCategoryList,
  7064.                 'categoryList' => $categoryList,
  7065.                 'igList' => $igList,
  7066.                 'unitList' => $unitList,
  7067.                 'brandList' => $brandList,
  7068.                 'brandListArray' => $brandListArray,
  7069.                 'productListArray' => $productListArray,
  7070.                 'subCategoryListArray' => $subCategoryListArray,
  7071.                 'categoryListArray' => $categoryListArray,
  7072.                 'igListArray' => $igListArray,
  7073.                 'unitListArray' => $unitListArray,
  7074.                 'productionBomList' => ProductionM::ProductionBomList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  7075.                 'productionScheduleList' => ProductionM::ProductionScheduleList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  7076.                 'prefix_list' => array(
  7077.                     [
  7078.                         'id' => 1,
  7079.                         'value' => 'GN',
  7080.                         'text' => 'General'
  7081.                     ],
  7082.                     [
  7083.                         'id' => 1,
  7084.                         'value' => 'SD',
  7085.                         'text' => 'For Sales Demand'
  7086.                     ]
  7087.                 ),
  7088.                 'projectList' => $em->getRepository('ApplicationBundle\\Entity\\Project')->findBy(
  7089.                     array(
  7090.                         'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  7091.                     ), array('projectDate' => 'desc')
  7092.                 ),
  7093.                 'salesOrderList' => SalesOrderM::SalesOrderListPendingDelivery($em),
  7094.                 'assoc_list' => array(
  7095.                     [
  7096.                         'id' => 1,
  7097.                         'value' => 'GN',
  7098.                         'text' => 'General'
  7099.                     ]
  7100.                 )
  7101.             )
  7102.         );
  7103.     }
  7104.     public function CreateStockReturnAction(Request $request)
  7105.     {
  7106.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  7107.             array(
  7108.                 'page_title' => 'Stock Return',
  7109. //                'dataList'=>$dta_list
  7110.             )
  7111.         );
  7112.     }
  7113.     public function MaterialInwardAction(Request $request)
  7114.     {
  7115.         $data = [];
  7116.         if ($request->isMethod('POST')) {
  7117.             $errors = [];
  7118.             $poId = (int)$request->request->get('poId');
  7119.             $warehouseId = (int)$request->request->get('warehouseId');
  7120.             $docHash trim((string)$request->request->get('docHash'));
  7121.             $products $request->request->get('products', []);
  7122.             $receivedQty $request->request->get('receivedQty', []);
  7123.             $purchaseOrderItemId $request->request->get('purchaseOrderItemId', []);
  7124.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  7125.             if ($poId <= 0) {
  7126.                 $errors[] = 'Please select a purchase order.';
  7127.             } elseif (!isset($poList[$poId])) {
  7128.                 $errors[] = 'Please select a valid purchase order.';
  7129.             }
  7130.             if ($warehouseId <= 0) {
  7131.                 $errors[] = 'Please select a warehouse.';
  7132.             }
  7133.             if (empty($products) || !is_array($products)) {
  7134.                 $errors[] = 'Please add at least one item.';
  7135.             }
  7136.             $hasPositiveQty false;
  7137.             foreach ((array)$receivedQty as $qty) {
  7138.                 if ($qty === '' || !is_numeric($qty)) {
  7139.                     $errors[] = 'Please enter a valid received quantity.';
  7140.                     break;
  7141.                 }
  7142.                 if ((float)$qty 0) {
  7143.                     $errors[] = 'Received quantity cannot be negative.';
  7144.                     break;
  7145.                 }
  7146.                 if ((float)$qty 0) {
  7147.                     $hasPositiveQty true;
  7148.                 }
  7149.             }
  7150.             if (!$hasPositiveQty) {
  7151.                 $errors[] = 'Please enter received quantity greater than zero for at least one item.';
  7152.             }
  7153.             if ($docHash === '' || stripos($docHash'undefined') !== false || stripos($docHash'document') !== false) {
  7154.                 $errors[] = 'Please generate a valid document number.';
  7155.             }
  7156.             if (empty($errors)) {
  7157.                 //first of all resolve the transport costs
  7158.                 $total_price_value 0;
  7159.                 $data_list $this->getDoctrine()
  7160.                     ->getRepository('ApplicationBundle\\Entity\\PurchaseOrderItem')
  7161.                     ->findBy(
  7162.                         array(
  7163.                             'purchaseOrderId' => $poId,
  7164.                             'productId' => $products
  7165.                         )
  7166.                     );
  7167.                 $purchase_items = [];
  7168.                 foreach ($data_list as $key => $value) {
  7169.                     $purchase_items[$value->getProductId()] = $value;
  7170.                 }
  7171.                 foreach ($products as $key => $entry) {
  7172.                     if (!isset($purchase_items[$entry])) {
  7173.                         $errors[] = 'Selected product list does not match the chosen purchase order.';
  7174.                         break;
  7175.                     }
  7176.                     $total_price_value $total_price_value + ($receivedQty[$key]) * ($purchase_items[$entry]->getPrice());
  7177.                 }
  7178.                 if (empty($errors)) {
  7179.                     $po_data $poList[$poId];
  7180.                     $supplier_id $po_data['supplier_id'];
  7181.                     $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  7182.                     foreach ($products as $key => $entry) {
  7183.                         if ((float)$receivedQty[$key] > 0) {
  7184.                             Inventory::NewMaterialInward($this->getDoctrine()->getManager(),
  7185.                                 $request->request,
  7186.                                 $key,
  7187.                                 $poId,
  7188.                                 $purchaseOrderItemId,
  7189.                                 $supplier_id,
  7190.                                 $warehouseId,
  7191.                                 $request->request->get('lotNumber'),
  7192.                                 $request->request->get('type_hash'),
  7193.                                 $request->request->get('prefix_hash'),
  7194.                                 $request->request->get('assoc_hash'),
  7195.                                 $request->request->get('number_hash'),
  7196.                                 $docHash,
  7197.                                 $request->request->get('docDate'),
  7198.                                 $purchase_items[$entry],
  7199.                                 $total_price_value,
  7200.                                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7201.                         }
  7202.                     }
  7203.                     $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$warehouseId]['name'];
  7204. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  7205.                     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),
  7206.                         "A stack of material Has Arrived at The " $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  7207.                         'all',
  7208.                         "",
  7209.                         'information',
  7210.                         "",
  7211.                         "Inbound Material"
  7212.                     );
  7213.                 }
  7214.             }
  7215.             foreach ($errors as $error) {
  7216.                 $this->addFlash('error'$error);
  7217.             }
  7218. //                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);
  7219.         }
  7220.         return $this->render('@Inventory/pages/input_forms/material_inward.html.twig',
  7221.             array(
  7222.                 'page_title' => 'Material Inward',
  7223.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  7224.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  7225.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  7226.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  7227.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  7228.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  7229.                 "unitList" => Inventory::UnitTypeList($this->getDoctrine()->getManager())
  7230. //                'po'=>Inventory::getPurchaseOrderList
  7231.             )
  7232.         );
  7233.     }
  7234.     public function QualityControlAction(Request $request)
  7235.     {
  7236.         $checked_qc_list_flag 0;
  7237.         if ($request->query->has('checked_qc_list_flag'))
  7238.             $checked_qc_list_flag $request->query->has('checked_qc_list_flag');
  7239.         if ($request->isMethod('POST')) {
  7240.             $errors = [];
  7241.             $checkedRows $request->request->get('qc_checked', []);
  7242.             $approvedQty $request->request->get('approvedQty', []);
  7243.             if (empty($checkedRows)) {
  7244.                 $errors[] = 'Please select at least one QC item.';
  7245.             }
  7246.             $positiveQtyFound false;
  7247.             foreach ($approvedQty as $qcId => $qty) {
  7248.                 $qtyValue trim((string)$qty);
  7249.                 if ($qtyValue === '' || !is_numeric($qtyValue)) {
  7250.                     $errors[] = 'Approved quantity must be numeric.';
  7251.                     break;
  7252.                 }
  7253.                 if ((float)$qtyValue 0) {
  7254.                     $errors[] = 'Approved quantity cannot be negative.';
  7255.                     break;
  7256.                 }
  7257.                 if ((float)$qtyValue 0) {
  7258.                     $positiveQtyFound true;
  7259.                     if (!in_array($qcId$checkedRows)) {
  7260.                         $errors[] = 'Please check QC before submitting approved rows.';
  7261.                         break;
  7262.                     }
  7263.                 }
  7264.             }
  7265.             if (empty($errors) && !$positiveQtyFound) {
  7266.                 $errors[] = 'Please enter approved quantity greater than zero for at least one QC item.';
  7267.             }
  7268.             if (empty($errors)) {
  7269.                 foreach ($checkedRows as $key => $entry) {
  7270.                     $em $this->getDoctrine()->getManager();
  7271.                     $data $this->getDoctrine()
  7272.                         ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  7273.                         ->findOneBy(
  7274.                             array(
  7275.                                 'qcId' => $entry
  7276.                             )
  7277.                         );
  7278.                     if (!$data) {
  7279.                         $errors[] = 'Invalid QC row selected.';
  7280.                         break;
  7281.                     }
  7282.                     $data->setApprovedQty($approvedQty[$entry]);
  7283.                     $data->setRejectedQty($data->getInwardQty() - $approvedQty[$entry]);
  7284.                     $data->setQcDate(new \DateTime($request->request->get('qcDate')));
  7285.                     $data->setStage(GeneralConstant::STAGE_PENDING_TAG);
  7286.                     $em->flush();
  7287.                     //notification
  7288.                     $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$data->getPurchaseOrderId()];
  7289.                     $supplier_id $po_data['supplier_id'];
  7290.                     $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  7291.                     $product_name Inventory::ProductList($this->getDoctrine()->getManager())[$data->getProductId()]['name'];
  7292.                     $qty $approvedQty[$entry];
  7293.                     $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$data->getWarehouseId()]['name'];
  7294. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  7295.                     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),
  7296.                         $qty " among " $data->getInwardQty() . " units of " $product_name " has passed the Quality Control in " .
  7297.                         $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  7298.                         'all',
  7299.                         "",
  7300.                         'success',
  7301.                         "",
  7302.                         "Quality Control"
  7303.                     );
  7304.                 }
  7305.             }
  7306.             foreach ($errors as $error) {
  7307.                 $this->addFlash('error'$error);
  7308.             }
  7309.         }
  7310.         return $this->render('@Inventory/pages/input_forms/qc.html.twig',
  7311.             array(
  7312.                 'page_title' => 'Quality Control',
  7313.                 'checked_qc_list_flag' => $checked_qc_list_flag,
  7314.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  7315.                 'warehouse_indexed' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7316.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  7317.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  7318.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  7319.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  7320.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7321.                 'material_inward' => $this->getDoctrine()
  7322.                     ->getRepository('ApplicationBundle\\Entity\\MaterialInward')
  7323.                     ->findBy(
  7324.                         array(
  7325.                             'stage' => $checked_qc_list_flag == GeneralConstant::STAGE_PENDING GeneralConstant::STAGE_PENDING_TAG
  7326.                         )
  7327.                     )
  7328. //                'po'=>Inventory::getPurchaseOrderList
  7329.             )
  7330.         );
  7331.     }
  7332.     public function InventoryTransactionViewAction(Request $request)
  7333.     {
  7334.         $em $this->getDoctrine()->getManager();
  7335.         $qry_data = array(
  7336.             'warehouseId' => [0],
  7337.             'igId' => [0],
  7338.             'brandId' => [0],
  7339.             'categoryId' => [0],
  7340.             'actionTagId' => [0],
  7341.         );
  7342.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  7343.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  7344.         $data_searched = [];
  7345.         $em $this->getDoctrine()->getManager();
  7346.         $companyId $this->getLoggedUserCompanyId($request);
  7347.         $company_data Company::getCompanyData($em$companyId);
  7348.         $data = [];
  7349.         $print_title "Inventory Report";
  7350.         $document_mark = array(
  7351.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  7352.             'copy' => ''
  7353.         );
  7354.         if ($request->isMethod('POST'))
  7355.             $method 'POST';
  7356.         else
  7357.             $method 'GET';
  7358.         {
  7359.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  7360.                 $request->request$method,
  7361.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7362.                 $companyId);
  7363.             if ($request->query->has('returnJson') || $request->request->has('returnJson')) {
  7364.                 return new JsonResponse(
  7365.                     array(
  7366.                         'success' => true,
  7367. //                    'page_title' => 'Product Details',
  7368. //                    'company_data' => $company_data,
  7369.                         'page_title' => 'Inventory Transactions',
  7370.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7371.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7372.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7373.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7374.                         'data_products' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7375.                         'action_tag' => $warehouse_action_list,
  7376.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7377.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7378.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7379.                         'data_searched' => $data_searched
  7380.                     )
  7381.                 );
  7382.             } else if ($request->request->get('print_data_enabled') == 1) {
  7383.                 $print_sub_title "";
  7384.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  7385.                     array(
  7386.                         'page_title' => 'Inventory Report',
  7387.                         'page_header' => 'Report',
  7388.                         'print_title' => $print_title,
  7389.                         'document_type' => 'Journal voucher',
  7390.                         'document_mark_image' => $document_mark['original'],
  7391.                         'page_header_sub' => 'Add',
  7392.                         'item_data' => [],
  7393.                         'received' => 2,
  7394.                         'return' => 1,
  7395.                         'total_w_vat' => 1,
  7396.                         'total_vat' => 1,
  7397.                         'total_wo_vat' => 1,
  7398.                         'invoice_id' => 'abcd1234',
  7399.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  7400.                         'created_by' => 'created by',
  7401.                         'created_at' => '',
  7402.                         'red' => 0,
  7403.                         'company_name' => $company_data->getName(),
  7404.                         'company_data' => $company_data,
  7405.                         'company_address' => $company_data->getAddress(),
  7406.                         'company_image' => $company_data->getImage(),
  7407.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7408.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7409.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7410.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7411.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7412.                         'action_tag' => $warehouse_action_list,
  7413.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7414.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7415.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7416.                         'data_searched' => $data_searched
  7417.                     )
  7418.                 );
  7419.             }
  7420.         }
  7421.         return $this->render('@Inventory/pages/report/inventory_transaction_view.html.twig',
  7422.             array(
  7423.                 'page_title' => 'Inventory Transactions',
  7424.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7425.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7426.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7427.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7428.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7429.                 'action_tag' => $warehouse_action_list,
  7430.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7431.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7432.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7433.                 'data_searched' => $data_searched
  7434.             )
  7435.         );
  7436.     }
  7437.     public function StockConsumptionViewAction(Request $request)
  7438.     {
  7439.         $em $this->getDoctrine()->getManager();
  7440.         $start_date $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
  7441.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : new \DateTime();
  7442.         $qry_data = array(
  7443.             'warehouseId' => [0],
  7444.             'igId' => [0],
  7445.             'brandId' => [0],
  7446.             'categoryId' => [0],
  7447.             'actionTagId' => [0],
  7448.         );
  7449.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  7450.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  7451.         $data_searched = [];
  7452.         $em $this->getDoctrine()->getManager();
  7453.         $company_data Company::getCompanyData($em1);
  7454.         $data = [];
  7455.         $print_title "Inventory Report";
  7456.         $document_mark = array(
  7457.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  7458.             'copy' => ''
  7459.         );
  7460.         if ($request->isMethod('POST'))
  7461.             $method 'POST';
  7462.         else
  7463.             $method 'GET';
  7464.         $post_data $method == 'POST' $request->request $request->query;
  7465.         $data_searched Inventory::GetStockConsumptionData($this->getDoctrine()->getManager(),
  7466.             $post_data,
  7467.             $method,
  7468.             $start_date,
  7469.             $end_date,
  7470.             $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7471.         if ($post_data->get('print_data_enabled') == 1) {
  7472.             $print_sub_title "";
  7473.             if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  7474.                 $html $this->renderView('@Inventory/pages/print/print_stock_consumption.html.twig',
  7475.                     array(
  7476.                         'pdf' => 'true',
  7477.                         'page_title' => 'Inventory Report',
  7478.                         'page_header' => 'Report',
  7479.                         'print_title' => $print_title,
  7480.                         'document_type' => 'Journal voucher',
  7481.                         'document_mark_image' => $document_mark['original'],
  7482.                         'page_header_sub' => 'Add',
  7483.                         'item_data' => [],
  7484.                         'received' => 2,
  7485.                         'return' => 1,
  7486.                         'total_w_vat' => 1,
  7487.                         'total_vat' => 1,
  7488.                         'total_wo_vat' => 1,
  7489.                         'invoice_id' => 'abcd1234',
  7490.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  7491.                         'created_by' => 'created by',
  7492.                         'created_at' => '',
  7493.                         'red' => 0,
  7494.                         'start_date' => $start_date,
  7495.                         'end_date' => $end_date,
  7496.                         'openFilter' => empty($post_data->keys()) ? 0,
  7497.                         'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  7498.                         'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  7499.                         'company_name' => $company_data->getName(),
  7500.                         'company_data' => $company_data,
  7501.                         'company_address' => $company_data->getAddress(),
  7502.                         'company_image' => $company_data->getImage(),
  7503.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7504.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7505.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7506.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7507.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7508.                         'action_tag' => $warehouse_action_list,
  7509.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7510.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7511.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7512.                         'data_searched' => $data_searched,
  7513.                         'export' => 'all'
  7514.                     )
  7515.                 );
  7516.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  7517.                     'orientation' => count($data_searched['query_columns_filter']) > 'landscape' 'portrait',
  7518.                     'no-stop-slow-scripts' => true,
  7519.                     'no-background' => false,
  7520.                     'lowquality' => false,
  7521.                     'encoding' => 'utf-8',
  7522.                     'dpi' => 300,
  7523.                     'image-dpi' => 300,
  7524.                 ));
  7525.                 return new Response(
  7526.                     $pdf_response,
  7527.                     200,
  7528.                     array(
  7529.                         'Content-Type' => 'application/pdf',
  7530.                         'Content-Disposition' => 'attachment; filename="Stock_Consumption.pdf"'
  7531.                     )
  7532.                 );
  7533.             }
  7534.             return $this->render('@Inventory/pages/print/print_stock_consumption.html.twig',
  7535.                 array(
  7536.                     'page_title' => 'Inventory Report',
  7537.                     'page_header' => 'Report',
  7538.                     'print_title' => $print_title,
  7539.                     'document_type' => 'Journal voucher',
  7540.                     'document_mark_image' => $document_mark['original'],
  7541.                     'page_header_sub' => 'Add',
  7542.                     'item_data' => [],
  7543.                     'received' => 2,
  7544.                     'return' => 1,
  7545.                     'total_w_vat' => 1,
  7546.                     'total_vat' => 1,
  7547.                     'total_wo_vat' => 1,
  7548.                     'invoice_id' => 'abcd1234',
  7549.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  7550.                     'created_by' => 'created by',
  7551.                     'created_at' => '',
  7552.                     'red' => 0,
  7553.                     'start_date' => $start_date,
  7554.                     'end_date' => $end_date,
  7555.                     'openFilter' => empty($post_data->keys()) ? 0,
  7556.                     'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  7557.                     'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  7558.                     'company_name' => $company_data->getName(),
  7559.                     'company_data' => $company_data,
  7560.                     'company_address' => $company_data->getAddress(),
  7561.                     'company_image' => $company_data->getImage(),
  7562.                     'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7563.                     'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7564.                     'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7565.                     'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7566.                     'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7567.                     'action_tag' => $warehouse_action_list,
  7568.                     'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7569.                     'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7570.                     'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7571.                     'data_searched' => $data_searched,
  7572.                     'export' => 'all'
  7573.                 )
  7574.             );
  7575.         }
  7576. //        return new JsonResponse(Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()));
  7577.         return $this->render('@Inventory/pages/report/stock_consumption.html.twig',
  7578.             array(
  7579.                 'page_title' => 'Stock Consumption',
  7580.                 'start_date' => $start_date,
  7581.                 'end_date' => $end_date,
  7582.                 'openFilter' => empty($post_data->keys()) ? 0,
  7583.                 'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  7584.                 'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  7585.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  7586.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  7587.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  7588.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  7589.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  7590.                 'action_tag' => $warehouse_action_list,
  7591.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  7592.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7593.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  7594.                 'data_searched' => $data_searched
  7595.             )
  7596.         );
  7597.     }
  7598.     public function ItemViewAction(Request $request)
  7599.     {
  7600.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  7601.             array(
  7602.                 'page_title' => 'Stock Return'
  7603.             )
  7604.         );
  7605.     }
  7606.     public function ProductViewAction(Request $request$id 0)
  7607.     {
  7608.         $em $this->getDoctrine()->getManager();
  7609.         $companyId $this->getLoggedUserCompanyId($request);
  7610.         $company_data Company::getCompanyData($em$companyId);
  7611.         $data = [];
  7612.         $specData = [];
  7613.         $specIds = [];
  7614.         $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  7615.             ->findOneBy(
  7616.                 array(
  7617.                     'id' => $id
  7618.                 )
  7619.             );
  7620.         if ($productData) {
  7621.             $tempSpecData json_decode($productData->getSpecData(), true);
  7622.             if ($tempSpecData == null) {
  7623.                 $tempSpecData = [];
  7624.             }
  7625.             foreach ($tempSpecData as $indSpecData) {
  7626. //                $specId = $indSpecData['id'];
  7627.                 $specData[] = [
  7628.                     'id' => $indSpecData['id'],
  7629.                     'value' => $indSpecData['value']
  7630.                 ];
  7631.                 $specIds[] = $indSpecData['id'];
  7632.             }
  7633.         }
  7634.         $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  7635.             ->findBy(
  7636.                 array(
  7637.                     'productId' => $id
  7638.                 )
  7639.             );
  7640.         $trans_history $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')
  7641.             ->findBy(
  7642.                 array(
  7643.                     'productId' => $id
  7644.                 ), array(
  7645.                     'transactionDate' => 'ASC',
  7646.                     'id' => 'ASC'
  7647.                 )
  7648.             );
  7649. //        $specId = array_keys($specData);
  7650.         $finSpecData = [];
  7651. //        if($productData){
  7652. //            $tempSpec = json_decode($productData->getSpecData(),true);
  7653. //
  7654. //            if($tempSpec == null){
  7655. //                $tempSpecName=[];
  7656. //            }
  7657. //            foreach ($tempSpec as $indSpec)
  7658. //            {
  7659. //                $specIds[]=$indSpec['id'];
  7660. //
  7661. //                $spec = $em->getRepository('ApplicationBundle\\Entity\\SpecType')
  7662. //                    ->findOneBy(
  7663. //                        array(
  7664. //                            'id' => $indSpec['id']
  7665. //                        )
  7666. //                    );
  7667. //
  7668. //                if($spec)
  7669. //                    $indSpec['name']=$spec->getName();
  7670. //                else
  7671. //                    $indSpec['name']='';
  7672. ////                $specId = $indSpecData['id'];
  7673. //
  7674. //                $finSpecData[]=$indSpec;
  7675. //
  7676. //            }
  7677. //        }
  7678.         $specList $em->getRepository('ApplicationBundle\\Entity\\SpecType')
  7679.             ->findBy(
  7680.                 array(
  7681.                     'id' => $specIds
  7682.                 )
  7683.             );
  7684.         $specListById = [];
  7685.         foreach ($specList as $specHere) {
  7686.             $specListById[$specHere->getId()] = $specHere->getName();
  7687.         }
  7688.         foreach ($specData as $specDatum) {
  7689.             $finSpecData[] = [
  7690.                 'id' => $specDatum['id'],
  7691.                 'name' => isset($specListById[$specDatum['id']]) ? $specListById[$specDatum['id']] : '',
  7692.                 'value' => $specDatum['value']
  7693.             ];
  7694.         }
  7695.         $productDataObj = array();
  7696.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  7697.             $getters array_filter(get_class_methods($productData), function ($method) {
  7698.                 return 'get' === substr($method03);
  7699.             });
  7700.             foreach ($getters as $getter) {
  7701.                 if ($getter == 'getGlobalId')
  7702.                     continue;
  7703. //                    if ($getter == 'getId')
  7704. //                        continue;
  7705.                 $Fieldname str_replace('get'''$getter);
  7706.                 $productDataObj[$Fieldname] = $productData->{$getter}(); // `foo!`
  7707.             }
  7708.             if ($request->request->has('genInfoOnly') && $request->request->get('genInfoOnly') == 1) {
  7709.                 $dataArray = array(
  7710.                     'success' => true,
  7711.                     'page_title' => 'Product Details',
  7712.                     'company_data' => $company_data,
  7713.                     'productData' => $productData,
  7714.                     'productDataObj' => $productDataObj,
  7715.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7716.                 );
  7717.             } else {
  7718.                 $dataArray = array(
  7719.                     'success' => true,
  7720.                     'page_title' => 'Product Details',
  7721.                     'company_data' => $company_data,
  7722.                     'productData' => $productData,
  7723.                     'productDataObj' => $productDataObj,
  7724.                     'currInvList' => $currInvList,
  7725.                     'finSpecData' => $finSpecData,
  7726.                     'specList' => $specList,
  7727.                     'trans_history' => $trans_history,
  7728.                     'entityList' => GeneralConstant::$Entity_list_details,
  7729. //                    'productList' => Inventory::ProductList($em, $companyId),
  7730.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7731.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7732.                     'igList' => Inventory::ItemGroupList($em$companyId),
  7733.                     'unitList' => Inventory::UnitTypeList($em),
  7734.                     'brandList' => Inventory::GetBrandList($em$companyId),
  7735.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7736.                     'warehouseList' => Inventory::WarehouseList($em),
  7737.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7738.                 );
  7739.             }
  7740.             return new JsonResponse(
  7741.                 $dataArray
  7742.             );
  7743.         }
  7744.         $dataArray = array(
  7745.             'page_title' => 'Product Details',
  7746.             'company_data' => $company_data,
  7747.             'productData' => $productData,
  7748.             'currInvList' => $currInvList,
  7749.             'specData' => $specData,
  7750. //            'specListById' => $specListById,
  7751.             'finSpecData' => $finSpecData,
  7752.             'trans_history' => $trans_history,
  7753.             'entityList' => GeneralConstant::$Entity_list_details,
  7754. //            'productList' => Inventory::ProductList($em, $companyId),
  7755.             'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7756.             'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7757.             'igList' => Inventory::ItemGroupList($em$companyId),
  7758.             'unitList' => Inventory::UnitTypeList($em),
  7759.             'brandList' => Inventory::GetBrandList($em$companyId),
  7760.             'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7761.             'warehouseList' => Inventory::WarehouseList($em),
  7762.         );
  7763.         return $this->render('@Inventory/pages/views/product_view.html.twig'$dataArray
  7764.         );
  7765.     }
  7766.     public function CheckForProductInWarehouseAction(Request $request$queryStr '')
  7767.     {
  7768.         $em $this->getDoctrine()->getManager();
  7769.         $companyId $this->getLoggedUserCompanyId($request);
  7770.         $data = [
  7771.             'availableQty' => 0,
  7772.             'productByCodesArray' => [],
  7773.             'indRowId' => 0
  7774.         ];
  7775.         $html '';
  7776.         $productByCodeData = [];
  7777.         if ($request->isMethod('POST')) {
  7778.             $warehouseId $request->request->get('warehouseId'0);
  7779.             $warehouseActionId $request->request->get('warehouseActionId'0);
  7780.             $productId $request->request->get('productId'0);
  7781.             $indRowId $request->request->get('indRowId'0);
  7782.             $data['indRowId'] = $indRowId;
  7783.             $inStorage $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  7784.                 ->findBy(
  7785.                     array(
  7786.                         'productId' => $productId,
  7787.                         'warehouseId' => $warehouseId,
  7788.                         'actionTagId' => $warehouseActionId,
  7789.                         'CompanyId' => $companyId,
  7790.                     )
  7791.                 );
  7792.             foreach ($inStorage as $strg) {
  7793.                 $data['availableQty'] += $strg->getQty();
  7794.             }
  7795.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  7796.                 ->findBy(
  7797.                     array(
  7798.                         'productId' => $productId,
  7799.                         'warehouseId' => $warehouseId,
  7800.                         'warehouseActionId' => $warehouseActionId,
  7801.                         'CompanyId' => $companyId,
  7802.                     )
  7803.                 );
  7804.             foreach ($productByCodeData as $pbc) {
  7805.                 $data['productByCodesArray'][] = array(
  7806.                     'id' => $pbc->getProductByCodeId(),
  7807.                     'productId' => $pbc->getProductId(),
  7808.                     'warehouseId' => $pbc->getWarehouseId(),
  7809.                     'warehouseActionId' => $pbc->getWarehouseActionId(),
  7810. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7811.                     'sales_code' => str_pad($pbc->getSalesCode(), 13'0'STR_PAD_LEFT),
  7812. //                'sales_code'=>$d['sales_code'],
  7813.                 );
  7814.             }
  7815.             return new JsonResponse(array(
  7816.                     'success' => true,
  7817.                     'data' => $data,
  7818.                 )
  7819.             );
  7820.         }
  7821.         return new JsonResponse(
  7822.             array(
  7823.                 'success' => false,
  7824.                 'data' => $data,
  7825.             )
  7826.         );
  7827.     }
  7828.     public function ProductByCodeListAjaxAction(Request $request$queryStr '')
  7829.     {
  7830.         $em $this->getDoctrine()->getManager();
  7831.         $companyId $this->getLoggedUserCompanyId($request);
  7832.         $company_data Company::getCompanyData($em$companyId);
  7833.         $data = [];
  7834.         $html '';
  7835.         $productByCodeData = [];
  7836.         if ($request->request->has('query') && $queryStr == '')
  7837.             $queryStr $request->request->get('queryStr');
  7838.         $likeQueryStr '%' $queryStr '%';
  7839.         $get_kids_sql "select product_by_code_id id, product_id, warehouse_id, warehouse_action_id,
  7840.                             sales_code ,
  7841.                             serial_no,
  7842.                             imei1,
  7843.                             imei2,
  7844.                             imei3,
  7845.                             imei4
  7846.                             from product_by_code
  7847.                             where ( CONVERT(sales_code,char)  like :queryStr
  7848.                                     or  CONVERT(serial_no,char)  like :queryStr
  7849.                                     or  CONVERT(imei1,char)  like :queryStr
  7850.                                     or  CONVERT(imei2,char)  like :queryStr
  7851.                                     or  CONVERT(imei3,char)  like :queryStr
  7852.                                     or  CONVERT(imei4,char)  like :queryStr
  7853.                                     ) ";
  7854.         $queryParams = array(
  7855.             'queryStr' => $likeQueryStr,
  7856.             'companyId' => (int) $companyId,
  7857.         );
  7858.         if ($request->query->has('warehouseId')) {
  7859.             $get_kids_sql .= " and warehouse_id = :warehouseId ";
  7860.             $queryParams['warehouseId'] = (int) $request->query->get('warehouseId');
  7861.         }
  7862.         if ($request->query->has('position')) {
  7863.             $get_kids_sql .= " and position = :position ";
  7864.             $queryParams['position'] = (int) $request->query->get('position');
  7865.         }
  7866.         if ($request->query->has('deliveryReceiptId')) {
  7867.             $get_kids_sql .= " and deliveryReceiptId = :deliveryReceiptId ";
  7868.             $queryParams['deliveryReceiptId'] = (int) $request->query->get('deliveryReceiptId');
  7869.         }
  7870.         if ($request->query->has('warehouseActionId')) {
  7871.             $get_kids_sql .= " and warehouse_action_id = :warehouseActionId ";
  7872.             $queryParams['warehouseActionId'] = (int) $request->query->get('warehouseActionId');
  7873.         }
  7874.         if ($request->query->has('productId')) {
  7875.             $get_kids_sql .= " and product_id = :productId ";
  7876.             $queryParams['productId'] = (int) $request->query->get('productId');
  7877.         }
  7878.         $get_kids_sql .= " and company_id = :companyId limit 25";
  7879.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$queryParams);
  7880.         $get_kids $stmt;
  7881.         if (!empty($get_kids)) {
  7882.             foreach ($get_kids as $d) {
  7883.                 $dt = array(
  7884.                     'id' => $d['id'],
  7885.                     'productId' => $d['product_id'],
  7886.                     'warehouseId' => $d['warehouse_id'],
  7887.                     'warehouseActionId' => $d['warehouse_action_id'],
  7888. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7889.                     'sales_code' => str_pad($d['sales_code'], 13'0'STR_PAD_LEFT),
  7890.                     'serial_no' => str_pad($d['serial_no'], 13'0'STR_PAD_LEFT),
  7891.                     'imei1' => str_pad($d['imei1'], 13'0'STR_PAD_LEFT),
  7892.                     'imei2' => str_pad($d['imei2'], 13'0'STR_PAD_LEFT),
  7893.                     'imei3' => str_pad($d['imei3'], 13'0'STR_PAD_LEFT),
  7894.                     'imei4' => str_pad($d['imei4'], 13'0'STR_PAD_LEFT),
  7895. //                'sales_code'=>$d['sales_code'],
  7896.                 );
  7897.                 $data[] = $dt;
  7898.             }
  7899.         }
  7900. //        if($request->query->has('returnJson'))
  7901.         {
  7902.             return new JsonResponse(
  7903.                 array(
  7904.                     'success' => true,
  7905. //                    'page_title' => 'Product Details',
  7906. //                    'company_data' => $company_data,
  7907.                     'data' => $data,
  7908. //                    'exId'=>$id,
  7909. //                'productByCodeData' => $productByCodeData,
  7910. //                'productData' => $productData,
  7911. //                'currInvList' => $currInvList,
  7912. //                'productList' => Inventory::ProductList($em, $companyId),
  7913. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  7914. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  7915. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  7916. //                'unitList' => Inventory::UnitTypeList($em),
  7917. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  7918. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  7919. //                'warehouseList' => Inventory::WarehouseList($em),
  7920.                 )
  7921.             );
  7922.         }
  7923.     }
  7924.     public function selectDataAjaxAction(Request $request$queryStr '',
  7925.                                                  $version 'latest',
  7926.                                                  $identifier '_default_',
  7927.                                                  $apiKey '_ignore_'
  7928.     )
  7929.     {
  7930.         $em $this->getDoctrine()->getManager();
  7931.         $em_goc $this->getDoctrine()->getManager('company_group');
  7932.         $companyId 0;
  7933.         $skipCurrentUserIdRestriction $request->get('skipCurrentUserIdRestriction'0);
  7934.         $dataOnly $request->get('dataOnly'0);
  7935.         $skipCurrentEmployeeIdRestriction $request->get('skipCurrentEmployeeIdRestriction'0);
  7936.         $skipCurrentUserLoginIdRestriction $request->get('skipCurrentUserLoginIdRestriction'0);
  7937.         $currentUserId $request->getSession()->get(UserConstants::USER_ID0);
  7938.         $currentEmployeeId $request->getSession()->get(UserConstants::USER_EMPLOYEE_ID0);
  7939.         $currentUserLoginIds = [];
  7940.         if ($request->request->get('entity_group'0)) {
  7941.             $companyId 0;
  7942.             $em $this->getDoctrine()->getManager('company_group');
  7943.         } else {
  7944.             if ($request->request->get('appId'0) != 0) {
  7945.                 $gocEnabled 0;
  7946.                 if ($this->container->hasParameter('entity_group_enabled'))
  7947.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7948.                 else
  7949.                     $gocEnabled 1;
  7950.                 if ($gocEnabled == 1) {
  7951.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7952.                         $this->getDoctrine()->getManager('company_group'),
  7953.                         $gocEnabled,
  7954.                         $request->request->get('appId'0)
  7955.                     );
  7956.                     if (!empty($dataToConnect)) {
  7957.                         $connector $this->container->get('application_connector');
  7958.                         $connector->resetConnection(
  7959.                             'default',
  7960.                             $dataToConnect['dbName'],
  7961.                             $dataToConnect['dbUser'],
  7962.                             $dataToConnect['dbPass'],
  7963.                             $dataToConnect['dbHost'],
  7964.                             $reset true
  7965.                         );
  7966.                         $em $this->getDoctrine()->getManager();
  7967.                     }
  7968.                 }
  7969.             } else if ($request->getSession()->get(UserConstants::USER_APP_ID) != && $request->getSession()->get(UserConstants::USER_APP_ID) != null) {
  7970.                 $gocEnabled 0;
  7971.                 if ($this->container->hasParameter('entity_group_enabled'))
  7972.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7973.                 else
  7974.                     $gocEnabled 1;
  7975.                 if ($gocEnabled == 1) {
  7976.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7977.                         $this->getDoctrine()->getManager('company_group'),
  7978.                         $gocEnabled,
  7979.                         $request->getSession()->get(UserConstants::USER_APP_ID)
  7980.                     );
  7981.                     if (!empty($dataToConnect)) {
  7982.                         $connector $this->container->get('application_connector');
  7983.                         $connector->resetConnection(
  7984.                             'default',
  7985.                             $dataToConnect['dbName'],
  7986.                             $dataToConnect['dbUser'],
  7987.                             $dataToConnect['dbPass'],
  7988.                             $dataToConnect['dbHost'],
  7989.                             $reset true
  7990.                         );
  7991.                         $em $this->getDoctrine()->getManager();
  7992.                     }
  7993.                 }
  7994.             }
  7995.             $companyId $this->getLoggedUserCompanyId($request);
  7996.         }
  7997.         $configData = [];
  7998.         $isSingleDataset 1;
  7999.         $dataSet $request->request->has('dataset') ? $request->request->get('dataset') : [];
  8000.         if (is_string($dataSet)) $dataSet json_decode($dataSettrue);
  8001.         $valuePairs $request->get('valuePairs', []);
  8002.         if (is_string($valuePairs)) $valuePairs json_decode($valuePairstrue);
  8003.         $allResult = [];
  8004.         $datasetFromConfig = [];
  8005.         if ($identifier != '_default_') {
  8006.             $config_file $this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' $identifier 'Config.json';
  8007.             if (!file_exists($config_file)) {
  8008.             } else {
  8009.                 $fileText file_get_contents($config_file);
  8010.                 //now replace any value pairs
  8011.                 foreach ($valuePairs as $kkeeyy => $vvaalluuee) {
  8012.                     if (is_array($vvaalluuee)) {
  8013.                         if (isset($vvaalluuee['value']) && isset($vvaalluuee['type'])) {
  8014.                             if ($vvaalluuee['type'] == 'array'$fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee['value']), $fileText);
  8015.                             if ($vvaalluuee['type'] == 'value'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  8016.                             if ($vvaalluuee['type'] == 'text'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  8017.                         } else {
  8018.                             $fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee), $fileText);
  8019.                         }
  8020.                     } else
  8021.                         $fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee$fileText);
  8022.                 }
  8023.                 $fileText str_ireplace('_query_'$request->get('query'$queryStr), $fileText);
  8024.                 $fileText str_ireplace('_itemLimit_'$request->get('itemLimit''_all_'), $fileText);
  8025.                 $fileText str_ireplace('_offset_'$request->get('offset', ($request->get('itemLimit'10)) * ($request->get('page'1) - 1)), $fileText);
  8026.                 if (!(strpos($fileText'_CURRENT_USER_LOGIN_IDS_') === false) && $skipCurrentUserLoginIdRestriction == 0) {
  8027.                     $userInfo = [];
  8028.                     if ($request->getSession()->get(UserConstants::USER_TYPE0) == UserConstants::USER_TYPE_APPLICANT) {
  8029.                         $userInfo $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityLoginLog')->findBy(
  8030.                             array('userId' => $currentUserId)
  8031.                         );
  8032.                     } else {
  8033.                         $userInfo $em->getRepository('ApplicationBundle\\Entity\\SysLoginLog')->findBy(
  8034.                             array('userId' => $currentUserId)
  8035.                         );
  8036.                     }
  8037.                     foreach ($userInfo as $uLogininfo) {
  8038.                         $currentUserLoginIds[] = $uLogininfo->getLoginId();
  8039.                     }
  8040.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_'json_encode($currentUserLoginIds), $fileText);
  8041.                 } else {
  8042.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_''_EMPTY_'$fileText);
  8043.                 }
  8044.                 if (!(strpos($fileText'_CURRENT_USER_ID_') === false) && $skipCurrentUserIdRestriction == 0) {
  8045.                     $fileText str_ireplace('_CURRENT_USER_ID_'$currentUserId$fileText);
  8046.                 } else {
  8047.                     $fileText str_ireplace('_CURRENT_USER_ID_''_EMPTY_'$fileText);
  8048.                 }
  8049.                 if (!(strpos($fileText'_CURRENT_USER_EMPLOYEE_ID_') === false) && $skipCurrentEmployeeIdRestriction == 0) {
  8050.                     if ((strpos($fileText'skipCurrentEmployeeIdRestriction') === false)) {
  8051.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_'$currentEmployeeId$fileText);
  8052.                     } else {
  8053.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  8054.                     }
  8055.                 } else {
  8056.                     $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  8057.                 }
  8058.                 if ($fileText)
  8059.                     $datasetFromConfig json_decode($fileTexttrue);
  8060.                 $skipCurrentUserIdRestriction = isset($datasetFromConfig['skipCurrentUserIdRestriction']) ? $datasetFromConfig['skipCurrentUserIdRestriction'] : $skipCurrentUserIdRestriction;
  8061.                 $skipCurrentEmployeeIdRestriction = isset($datasetFromConfig['skipCurrentEmployeeIdRestriction']) ? $datasetFromConfig['skipCurrentEmployeeIdRestriction'] : $skipCurrentEmployeeIdRestriction;
  8062.                 $skipCurrentUserLoginIdRestriction = isset($datasetFromConfig['skipCurrentUserLoginIdRestriction']) ? $datasetFromConfig['skipCurrentUserLoginIdRestriction'] : $skipCurrentUserLoginIdRestriction;
  8063.             }
  8064.         }
  8065.         if ($dataSet == null$dataSet = [];
  8066. //        return new JsonResponse(array(
  8067. //            'queryStr'=>$queryStr
  8068. //        ));
  8069.         if (!empty($datasetFromConfig)) {
  8070.             if (isset($datasetFromConfig['tableName'])) {
  8071.                 $isSingleDataset 1;
  8072.                 $dataSet[] = $datasetFromConfig;
  8073.             } else {
  8074.                 if (count($datasetFromConfig) == 1)
  8075.                     $isSingleDataset 1;
  8076.                 $dataSet $datasetFromConfig;
  8077.             }
  8078.         }
  8079.         if (empty($dataSet)) {
  8080.             $isSingleDataset 1;
  8081.             $singleDataSet = array(
  8082.                 "valueField" => $request->request->has('valueField') ? $request->request->get('valueField') : 'id',
  8083.                 "query" => $request->get('query'$queryStr),
  8084.                 "headMarkers" => $request->get('headMarkers'''),
  8085.                 "headMarkersStrictMatch" => $request->get('headMarkersStrictMatch'0),
  8086.                 "itemLimit" => $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25,
  8087.                 "selectorId" => $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_',
  8088.                 "textField" => $request->request->has('textField') ? $request->request->get('textField') : 'name',
  8089.                 "tableName" => $request->request->has('tableName') ? $request->request->get('tableName') : '',
  8090.                 "isMultiple" => $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0,
  8091.                 "orConditions" => $request->request->has('orConditions') ? $request->request->get('orConditions') : [],
  8092.                 "andConditions" => $request->request->has('andConditions') ? $request->request->get('andConditions') : [],
  8093.                 "andOrConditions" => $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [],
  8094.                 "mustConditions" => $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [],
  8095.                 "joinTableData" => $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [],
  8096.                 "selectFieldList" => $request->request->has('selectFieldList') ? $request->request->get('selectFieldList') : ['*'],
  8097.                 "renderTextFormat" => $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '',
  8098.                 "setDataForSingle" => $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0,
  8099.                 "dataId" => $request->request->has('dataId') ? $request->request->get('dataId') : 0,
  8100.                 "lastChildrenOnly" => $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0,
  8101.                 "parentOnly" => $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0,
  8102.                 "parentIdField" => $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id',
  8103.                 "skipDefaultCompanyId" => $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1,
  8104.                 "offset" => $request->request->has('offset') ? $request->request->get('offset') : 0,
  8105.                 "returnTotalMatchedEntriesFlag" => $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0,
  8106.                 "nextOffset" => 0,
  8107.                 "totalMatchedEntries" => 0,
  8108.                 "convertToObject" => $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [],
  8109.                 "convertDateToStringFieldList" => $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [],
  8110.                 "orderByConditions" => $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [],
  8111.                 "convertToUrl" => $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [],
  8112.                 "fullPathList" => $request->request->has('fullPathList') ? $request->request->get('fullPathList') : [],
  8113.                 "ret_data" => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8114.             );
  8115.             $dataSet[] = $singleDataSet;
  8116.         }
  8117. //        $lastResult = [
  8118. //            'identifier' => $identifier,
  8119. //            'dataSet' => $dataSet,
  8120. //        ];
  8121. //        return new JsonResponse($lastResult);
  8122.         $userId $request->getSession()->get(UserConstants::USER_ID);
  8123. //        public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [],$userId=0)
  8124.         foreach ($dataSet as $dsIndex => $dataConfig) {
  8125.             $companyId 0;
  8126.             $queryStringIndividual $queryStr;
  8127.             $data = [];
  8128.             $data_by_id = [];
  8129.             $setValueArray = [];
  8130.             $silentChangeSelectize 0;
  8131.             $setValue 0;
  8132.             $setValueType 0;// 0 for id , 1 for query
  8133.             $selectAll 0;
  8134.             $selectAllFound 0;
  8135.             if (isset($dataConfig['query']))
  8136.                 $queryStringIndividual $dataConfig['query'];
  8137.             if ((strpos($queryStringIndividual'_set_matching_value_') !== false)) {
  8138.                 $selectAllFound 1;
  8139.                 $queryStringIndividual str_ireplace('_set_matching_value_'''$queryStringIndividual);
  8140.             }
  8141.             if ($queryStringIndividual == '_EMPTY_')
  8142.                 $queryStringIndividual '';
  8143.             if ($queryStringIndividual == '_EMPTY_')
  8144.                 $queryStringIndividual '';
  8145.             $queryStringIndividual str_replace('_FSLASH_''/'$queryStringIndividual);
  8146.             if ($queryStringIndividual === '#setValue:') {
  8147.                 $queryStringIndividual '';
  8148.             }
  8149.             if (!(strpos($queryStringIndividual'_silent_change_') === false)) {
  8150.                 $silentChangeSelectize 1;
  8151.                 $queryStringIndividual str_ireplace('_silent_change_'''$queryStringIndividual);
  8152.             }
  8153.             if (!(strpos($queryStringIndividual'#setValue:') === false)) {
  8154.                 $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStringIndividual));
  8155.                 foreach ($setValueArrayBeforeFilter as $svf) {
  8156.                     if ($svf == '_ALL_') {
  8157.                         $selectAll 1;
  8158.                         $setValueArray = [];
  8159.                         continue;
  8160.                     }
  8161.                     if (is_numeric($svf)) {
  8162.                         $setValueArray[] = ($svf 1);
  8163.                         $setValue $svf 1;
  8164.                     }
  8165.                 }
  8166.                 $queryStringIndividual '';
  8167.             }
  8168.             $valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
  8169.             $headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''//Special Field
  8170.             $headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0//Special Field
  8171.             $itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
  8172.             $selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
  8173.             $textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
  8174.             $table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
  8175.             $isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
  8176.             $orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
  8177.             $andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
  8178.             $andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
  8179.             $mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
  8180.             $joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
  8181.             $renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
  8182.             $setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
  8183.             $dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
  8184.             $lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
  8185.             $parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
  8186.             $parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
  8187.             $skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
  8188.             $offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
  8189.             $returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
  8190.             $nextOffset 0;
  8191.             $totalMatchedEntries 0;
  8192.             $convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
  8193.             $convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
  8194.             $orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
  8195.             $convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
  8196.             $fullPathList = isset($dataConfig['fullPathList']) ? $dataConfig['fullPathList'] : [];
  8197.             if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  8198.             if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  8199.             if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  8200.             if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  8201.             if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  8202.             if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  8203.             if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  8204.             if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  8205.             if (is_string($fullPathList)) $fullPathList json_decode($fullPathListtrue);
  8206. //            return new JsonResponse(array(
  8207. //                'dataSet'=>$dataSet,
  8208. //                'dataConfig'=>$dataConfig,
  8209. //                'hi'=>$this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json',
  8210. //                'hiD'=>file_get_contents($this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json')
  8211. //            ));
  8212.             if ($table == '') {
  8213.                 $lastResult = array(
  8214.                     'success' => false,
  8215.                     'currentTs' => (new \Datetime())->format('U'),
  8216.                     'isMultiple' => $isMultiple,
  8217.                     'setValueArray' => $setValueArray,
  8218.                     'setValue' => $setValue,
  8219.                     'data' => $data,
  8220.                     'dataId' => $dataId,
  8221.                     'selectorId' => $selectorId,
  8222.                     'dataById' => $data_by_id,
  8223.                     'selectedId' => 0,
  8224.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  8225.                 );
  8226.             } else {
  8227.                 $restrictionData = array(
  8228. //            'table'=>'relevantField in restriction'
  8229.                     'warehouse_action' => 'warehouseActionIds',
  8230.                     'branch' => 'branchIds',
  8231.                     'warehouse' => 'warehouseIds',
  8232.                     'production_process_settings' => 'productionProcessIds',
  8233.                 );
  8234.                 $restrictionIdList = [];
  8235.                 $filterQryForCriteria "select ";
  8236.                 $selectQry "";
  8237. //        $selectQry=" `$table`.* ";
  8238.                 $selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
  8239.                 $selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
  8240.                 if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  8241.                 foreach ($selectFieldList as $selFieldFull) {
  8242.                     if ($selectQry != '')
  8243.                         $selectQry .= ", ";
  8244.                     $selFieldArray explode(' '$selFieldFull);
  8245.                     $selField $selFieldArray[0];
  8246.                     $selFieldAlias $selFieldArray[1] ?? '';
  8247.                     if ($selField == '*')
  8248.                         $selectQry .= " `$table`.$selField ";
  8249.                     else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  8250.                         if ($selectPrefix == '')
  8251.                             $selectQry .= " count(*)  ";
  8252.                         else
  8253.                             $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  8254.                     } else {
  8255.                         if ($selectPrefix == '')
  8256.                             $selectQry .= " `$table`.`$selField`  $selFieldAlias";
  8257.                         else
  8258.                             $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  8259.                     }
  8260.                 }
  8261.                 $joinQry " from $table ";
  8262. //        $filterQryForCriteria = "select * from $table ";
  8263.                 foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  8264. //            $conditionStr.=' 1=1 ';
  8265.                     $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  8266.                     $joinTableAlias $joinTableName '_' $joinIndex;
  8267.                     $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  8268.                     $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  8269.                     $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  8270.                     $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  8271.                     $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  8272.                     $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  8273.                     $joinMustConditions = isset($joinTableDatum['joinMustConditions']) ? $joinTableDatum['joinMustConditions'] : [];
  8274.                     $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  8275.                     $joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
  8276.                     $joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
  8277.                     if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  8278.                     if (is_string($joinMustConditions)) $joinMustConditions json_decode($joinMustConditionstrue);
  8279.                     if (is_string($joinAndOrConditions)) $joinAndOrConditions json_decode($joinAndOrConditionstrue);
  8280.                     if (is_string($joinOrConditions)) $joinOrConditions json_decode($joinOrConditionstrue);
  8281.                     foreach ($selectFieldList as $selFieldFull) {
  8282.                         $selFieldArray explode(' '$selFieldFull);
  8283.                         $selField $selFieldArray[0];
  8284.                         $selFieldAlias $selFieldArray[1] ?? '';
  8285.                         if ($selField == '*')
  8286.                             $selectQry .= ", `$joinTableAlias`.$selField ";
  8287.                         else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  8288.                             if ($selectPrefix == '')
  8289.                                 $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  8290.                             else
  8291.                                 $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  8292.                         } else {
  8293.                             if ($selectPrefix == '')
  8294.                                 $selectQry .= ", `$joinTableAlias`.`$selField`  $selFieldAlias";
  8295.                             else
  8296.                                 $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  8297.                         }
  8298.                     }
  8299.                     $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  8300. //            if($joinTablePrimaryField!='')
  8301. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8302. //            $joinAndString = '';
  8303.                     $joinMustString '';
  8304.                     if ($joinTablePrimaryField != '') {
  8305.                         if (!(strpos($joinTablePrimaryField'.') === false)) {
  8306.                             $joinQry .= "  `$joinTableAlias`.`$joinTableOnField`  $fieldJoinType $joinTablePrimaryField ";
  8307.                         } else
  8308.                             $joinQry .= "  `$joinTableAlias`.`$joinTableOnField`  $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8309.                     }
  8310.                     foreach ($joinMustConditions as $mustCondition) {
  8311. //            $conditionStr.=' 1=1 ';
  8312.                         $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  8313.                         $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  8314.                         $aliasInCondition $table;
  8315.                         if (!(strpos($cfield'.') === false)) {
  8316.                             $fullCfieldArray explode('.'$cfield);
  8317.                             $aliasInCondition $fullCfieldArray[0];
  8318.                             $cfield $fullCfieldArray[1];
  8319.                         }
  8320.                         $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  8321.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8322.                             if ($joinMustString != '')
  8323.                                 $joinMustString .= " and ";
  8324.                             if ($ctype == 'like') {
  8325.                                 $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8326.                                 $wordsBySpaces explode(' '$cvalue);
  8327.                                 foreach ($wordsBySpaces as $word) {
  8328.                                     if ($joinMustString != '')
  8329.                                         $joinMustString .= " and ";
  8330.                                     $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8331.                                 }
  8332.                             } else if ($ctype == 'not like') {
  8333.                                 $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8334.                                 $wordsBySpaces explode(' '$cvalue);
  8335.                                 foreach ($wordsBySpaces as $word) {
  8336.                                     if ($joinMustString != '')
  8337.                                         $joinMustString .= " and ";
  8338.                                     $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8339.                                 }
  8340.                             } else if ($ctype == 'not_in') {
  8341.                                 $joinMustString .= " ( ";
  8342.                                 if (in_array('null'$cvalue)) {
  8343.                                     $joinMustString .= " `$joinTableAlias`.$cfield is not null";
  8344.                                     $cvalue array_diff($cvalue, ['null']);
  8345.                                     if (!empty($cvalue))
  8346.                                         $joinMustString .= " and ";
  8347.                                 }
  8348.                                 if (in_array(''$cvalue)) {
  8349.                                     $joinMustString .= "`$joinTableAlias`.$cfield != '' ";
  8350.                                     $cvalue array_diff($cvalue, ['']);
  8351.                                     if (!empty($cvalue))
  8352.                                         $joinMustString .= " and ";
  8353.                                 }
  8354.                                 $joinMustString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8355.                             } else if ($ctype == 'in') {
  8356.                                 if (in_array('null'$cvalue)) {
  8357.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null";
  8358.                                     $cvalue array_diff($cvalue, ['null']);
  8359.                                     if (!empty($cvalue))
  8360.                                         $joinMustString .= " and ";
  8361.                                 }
  8362.                                 if (in_array(''$cvalue)) {
  8363.                                     $joinMustString .= "`$joinTableAlias`.$cfield = '' ";
  8364.                                     $cvalue array_diff($cvalue, ['']);
  8365.                                     if (!empty($cvalue))
  8366.                                         $joinMustString .= " and ";
  8367.                                 }
  8368.                                 $joinMustString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8369.                             } else if ($ctype == '=') {
  8370. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8371. //                            $fullCfieldArray = explode('.', $cfield);
  8372. //                            $aliasInCondition = $fullCfieldArray[0];
  8373. //                            $cfield = $fullCfieldArray[1];
  8374. //                        }
  8375.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8376.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null ";
  8377.                                 else
  8378.                                     $joinMustString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8379.                             } else if ($ctype == '!=') {
  8380.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8381.                                     $joinMustString .= "`$joinTableAlias`.$cfield is not null ";
  8382.                                 else
  8383.                                     $joinMustString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8384.                             } else {
  8385.                                 if (is_string($cvalue))
  8386.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8387.                                 else
  8388.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8389.                             }
  8390.                         }
  8391.                     }
  8392. //            if ($joinMustString != '') {
  8393. //                if ($conditionStr != '')
  8394. //                    $conditionStr .= (" and (" . $joinMustString . ") ");
  8395. //                else
  8396. //                    $conditionStr .= ("  (" . $joinMustString . ") ");
  8397. //            }
  8398.                     if ($joinMustString != '') {
  8399.                         $joinQry .= (' and ' $joinMustString);
  8400. //                        $joinQry.=' and (';
  8401.                     }
  8402.                     $mustBracketDone 0;
  8403.                     $joinAndString '';
  8404. //                    if ($joinTablePrimaryField != '')
  8405. //                        $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8406.                     foreach ($joinAndConditions as $andCondition) {
  8407. //            $conditionStr.=' 1=1 ';
  8408.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  8409.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  8410.                         $aliasInCondition $table;
  8411.                         if (!(strpos($cfield'.') === false)) {
  8412.                             $fullCfieldArray explode('.'$cfield);
  8413.                             $aliasInCondition $fullCfieldArray[0];
  8414.                             $cfield $fullCfieldArray[1];
  8415.                         }
  8416.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  8417.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8418.                             if ($joinAndString != '')
  8419.                                 $joinAndString .= " and ";
  8420.                             if ($ctype == 'like') {
  8421.                                 $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8422.                                 $wordsBySpaces explode(' '$cvalue);
  8423.                                 foreach ($wordsBySpaces as $word) {
  8424.                                     if ($joinAndString != '')
  8425.                                         $joinAndString .= " and ";
  8426.                                     $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8427.                                 }
  8428.                             } else if ($ctype == 'not like') {
  8429.                                 $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8430.                                 $wordsBySpaces explode(' '$cvalue);
  8431.                                 foreach ($wordsBySpaces as $word) {
  8432.                                     if ($joinAndString != '')
  8433.                                         $joinAndString .= " and ";
  8434.                                     $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8435.                                 }
  8436.                             } else if ($ctype == 'not_in') {
  8437.                                 $joinAndString .= " ( ";
  8438.                                 if (in_array('null'$cvalue)) {
  8439.                                     $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  8440.                                     $cvalue array_diff($cvalue, ['null']);
  8441.                                     if (!empty($cvalue))
  8442.                                         $joinAndString .= " and ";
  8443.                                 }
  8444.                                 if (in_array(''$cvalue)) {
  8445.                                     $joinAndString .= "`$joinTableAlias`.$cfield != '' ";
  8446.                                     $cvalue array_diff($cvalue, ['']);
  8447.                                     if (!empty($cvalue))
  8448.                                         $joinAndString .= " and ";
  8449.                                 }
  8450.                                 $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8451.                             } else if ($ctype == 'in') {
  8452.                                 if (in_array('null'$cvalue)) {
  8453.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null";
  8454.                                     $cvalue array_diff($cvalue, ['null']);
  8455.                                     if (!empty($cvalue))
  8456.                                         $joinAndString .= " and ";
  8457.                                 }
  8458.                                 if (in_array(''$cvalue)) {
  8459.                                     $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  8460.                                     $cvalue array_diff($cvalue, ['']);
  8461.                                     if (!empty($cvalue))
  8462.                                         $joinAndString .= " and ";
  8463.                                 }
  8464.                                 $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8465.                             } else if ($ctype == '=') {
  8466. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8467. //                            $fullCfieldArray = explode('.', $cfield);
  8468. //                            $aliasInCondition = $fullCfieldArray[0];
  8469. //                            $cfield = $fullCfieldArray[1];
  8470. //                        }
  8471.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8472.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  8473.                                 else
  8474.                                     $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8475.                             } else if ($ctype == '!=') {
  8476.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8477.                                     $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  8478.                                 else
  8479.                                     $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8480.                             } else {
  8481.                                 if (is_string($cvalue))
  8482.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8483.                                 else
  8484.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8485.                             }
  8486.                         }
  8487.                     }
  8488. //            if ($joinAndString != '') {
  8489. //                if ($conditionStr != '')
  8490. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  8491. //                else
  8492. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  8493. //            }
  8494.                     if ($joinAndString != '') {
  8495.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  8496.                             $joinQry .= ' and (';
  8497.                             $mustBracketDone 1;
  8498.                         }
  8499.                         if ($joinQry != '')
  8500.                             $joinQry .= (" and (" $joinAndString ") ");
  8501.                         else
  8502.                             $joinQry .= ("  (" $joinAndString ") ");
  8503.                     }
  8504.                     $joinAndOrString "";
  8505.                     foreach ($joinAndOrConditions as $andOrCondition) {
  8506. //            $conditionStr.=' 1=1 ';
  8507.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  8508.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  8509.                         $aliasInCondition $table;
  8510.                         if (!(strpos($cfield'.') === false)) {
  8511.                             $fullCfieldArray explode('.'$cfield);
  8512.                             $aliasInCondition $fullCfieldArray[0];
  8513.                             $cfield $fullCfieldArray[1];
  8514.                         }
  8515.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  8516.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8517.                             if ($joinAndOrString != '')
  8518.                                 $joinAndOrString .= " or ";
  8519.                             if ($ctype == 'like') {
  8520.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8521.                                 $wordsBySpaces explode(' '$cvalue);
  8522.                                 foreach ($wordsBySpaces as $word) {
  8523.                                     if ($joinAndOrString != '')
  8524.                                         $joinAndOrString .= " or ";
  8525.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8526.                                 }
  8527.                             } else if ($ctype == 'not like') {
  8528.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8529.                                 $wordsBySpaces explode(' '$cvalue);
  8530.                                 foreach ($wordsBySpaces as $word) {
  8531.                                     if ($joinAndOrString != '')
  8532.                                         $joinAndOrString .= " or ";
  8533.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8534.                                 }
  8535.                             } else if ($ctype == 'not_in') {
  8536.                                 $joinAndOrString .= " ( ";
  8537.                                 if (in_array('null'$cvalue)) {
  8538.                                     $joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
  8539.                                     $cvalue array_diff($cvalue, ['null']);
  8540.                                     if (!empty($cvalue))
  8541.                                         $joinAndOrString .= " or ";
  8542.                                 }
  8543.                                 if (in_array(''$cvalue)) {
  8544.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != '' ";
  8545.                                     $cvalue array_diff($cvalue, ['']);
  8546.                                     if (!empty($cvalue))
  8547.                                         $joinAndOrString .= " or ";
  8548.                                 }
  8549.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8550.                             } else if ($ctype == 'in') {
  8551.                                 if (in_array('null'$cvalue)) {
  8552.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null";
  8553.                                     $cvalue array_diff($cvalue, ['null']);
  8554.                                     if (!empty($cvalue))
  8555.                                         $joinAndOrString .= " or ";
  8556.                                 }
  8557.                                 if (in_array(''$cvalue)) {
  8558.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  8559.                                     $cvalue array_diff($cvalue, ['']);
  8560.                                     if (!empty($cvalue))
  8561.                                         $joinAndOrString .= " or ";
  8562.                                 }
  8563.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8564.                             } else if ($ctype == '=') {
  8565. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8566. //                            $fullCfieldArray = explode('.', $cfield);
  8567. //                            $aliasInCondition = $fullCfieldArray[0];
  8568. //                            $cfield = $fullCfieldArray[1];
  8569. //                        }
  8570.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8571.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
  8572.                                 else
  8573.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8574.                             } else if ($ctype == '!=') {
  8575.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8576.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
  8577.                                 else
  8578.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8579.                             } else {
  8580.                                 if (is_string($cvalue))
  8581.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8582.                                 else
  8583.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8584.                             }
  8585.                         }
  8586.                     }
  8587. //            if ($joinAndOrString != '')
  8588. //                $joinQry .= $joinAndOrString;
  8589.                     if ($joinAndOrString != '') {
  8590.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  8591.                             $joinQry .= ' and (';
  8592.                             $mustBracketDone 1;
  8593.                         }
  8594.                         if ($joinQry != '')
  8595.                             $joinQry .= (" and (" $joinAndOrString ") ");
  8596.                         else
  8597.                             $joinQry .= ("  (" $joinAndOrString ") ");
  8598.                     }
  8599.                     //pika
  8600.                     $joinOrString "";
  8601.                     foreach ($joinOrConditions as $orCondition) {
  8602. //            $conditionStr.=' 1=1 ';
  8603.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  8604.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  8605.                         $aliasInCondition $table;
  8606.                         if (!(strpos($cfield'.') === false)) {
  8607.                             $fullCfieldArray explode('.'$cfield);
  8608.                             $aliasInCondition $fullCfieldArray[0];
  8609.                             $cfield $fullCfieldArray[1];
  8610.                         }
  8611.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  8612.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8613.                             if ($joinOrString != '' || $joinAndString != '' || $joinMustString != '')
  8614.                                 $joinOrString .= " or ";
  8615.                             if ($ctype == 'like') {
  8616.                                 $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  8617.                                 $wordsBySpaces explode(' '$cvalue);
  8618.                                 foreach ($wordsBySpaces as $word) {
  8619.                                     if ($joinOrString != '')
  8620.                                         $joinOrString .= " or ";
  8621.                                     $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  8622.                                 }
  8623.                             } else if ($ctype == 'not like') {
  8624.                                 $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  8625.                                 $wordsBySpaces explode(' '$cvalue);
  8626.                                 foreach ($wordsBySpaces as $word) {
  8627.                                     if ($joinOrString != '')
  8628.                                         $joinOrString .= " or ";
  8629.                                     $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  8630.                                 }
  8631.                             } else if ($ctype == 'not_in') {
  8632.                                 $joinOrString .= " ( ";
  8633.                                 if (in_array('null'$cvalue)) {
  8634.                                     $joinOrString .= " `$joinTableAlias`.$cfield is not null";
  8635.                                     $cvalue array_diff($cvalue, ['null']);
  8636.                                     if (!empty($cvalue))
  8637.                                         $joinOrString .= " or ";
  8638.                                 }
  8639.                                 if (in_array(''$cvalue)) {
  8640.                                     $joinOrString .= "`$joinTableAlias`.$cfield != '' ";
  8641.                                     $cvalue array_diff($cvalue, ['']);
  8642.                                     if (!empty($cvalue))
  8643.                                         $joinOrString .= " or ";
  8644.                                 }
  8645.                                 $joinOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8646.                             } else if ($ctype == 'in') {
  8647.                                 if (in_array('null'$cvalue)) {
  8648.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null";
  8649.                                     $cvalue array_diff($cvalue, ['null']);
  8650.                                     if (!empty($cvalue))
  8651.                                         $joinOrString .= " or ";
  8652.                                 }
  8653.                                 if (in_array(''$cvalue)) {
  8654.                                     $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  8655.                                     $cvalue array_diff($cvalue, ['']);
  8656.                                     if (!empty($cvalue))
  8657.                                         $joinOrString .= " or ";
  8658.                                 }
  8659.                                 $joinOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  8660.                             } else if ($ctype == '=') {
  8661. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  8662. //                            $fullCfieldArray = explode('.', $cfield);
  8663. //                            $aliasInCondition = $fullCfieldArray[0];
  8664. //                            $cfield = $fullCfieldArray[1];
  8665. //                        }
  8666.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8667.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null ";
  8668.                                 else
  8669.                                     $joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  8670.                             } else if ($ctype == '!=') {
  8671.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8672.                                     $joinOrString .= "`$joinTableAlias`.$cfield is not null ";
  8673.                                 else
  8674.                                     $joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  8675.                             } else {
  8676.                                 if (is_string($cvalue))
  8677.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  8678.                                 else
  8679.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  8680.                             }
  8681.                         }
  8682.                     }
  8683. //            if ($joinOrString != '')
  8684. //                $joinQry .= $joinOrString;
  8685.                     if ($joinOrString != '') {
  8686.                         if ($joinMustString != '' && $mustBracketDone == 0) {
  8687.                             $joinQry .= ' and (';
  8688.                             $mustBracketDone 1;
  8689.                         }
  8690.                         if ($joinQry != '')
  8691.                             $joinQry .= (" or (" $joinOrString ") ");
  8692.                         else
  8693.                             $joinQry .= ("  (" $joinOrString ") ");
  8694.                     }
  8695.                     if ($joinMustString != '' && $mustBracketDone == 1) {
  8696.                         $joinQry .= ' ) ';
  8697.                     }
  8698. //
  8699. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  8700.                 }
  8701.                 $filterQryForCriteria .= $selectQry;
  8702.                 $filterQryForCriteria .= $joinQry;
  8703.                 if ($skipDefaultCompanyId == && $companyId != && !isset($dataConfig['entity_group']))
  8704.                     $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  8705.                 else
  8706.                     $filterQryForCriteria .= " where 1=1 ";
  8707.                 $conditionStr "";
  8708.                 $aliasInCondition $table;
  8709.                 if ($headMarkers != '' && $table == 'acc_accounts_head') {
  8710.                     $markerList explode(','$headMarkers);
  8711.                     $spMarkerQry "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
  8712.                     $markerPassedHeads = [];
  8713.                     foreach ($markerList as $mrkr) {
  8714.                         $spMarkerQry .= " and marker_hash like '%" $mrkr "%'";
  8715.                     }
  8716.                     $spStmt $em->getConnection()->fetchAllAssociative($spMarkerQry);
  8717.                     $spStmtResults $spStmt;
  8718.                     foreach ($spStmtResults as $ggres) {
  8719.                         $markerPassedHeads[] = $ggres['accounts_head_id'];
  8720.                     }
  8721.                     if (!empty($markerPassedHeads)) {
  8722.                         if ($conditionStr != '')
  8723.                             $conditionStr .= " and (";
  8724.                         else
  8725.                             $conditionStr .= " (";
  8726.                         if ($headMarkersStrictMatch != 1) {
  8727.                             foreach ($markerPassedHeads as $mh) {
  8728.                                 $conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" $mh "/%' or ";
  8729.                             }
  8730.                         }
  8731.                         $conditionStr .= "  `$aliasInCondition`.`accounts_head_id` in (" implode(','$markerPassedHeads) . ") ";
  8732.                         $conditionStr .= " )";
  8733.                     }
  8734.                 }
  8735.                 if (isset($restrictionData[$table])) {
  8736.                     $userRestrictionData Users::getUserApplicationAccessSettings($em$userId)['options'];
  8737.                     if (isset($userRestrictionData[$restrictionData[$table]])) {
  8738.                         $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  8739.                         if ($restrictionIdList == null)
  8740.                             $restrictionIdList = [];
  8741.                     }
  8742.                     if (!empty($restrictionIdList)) {
  8743.                         if ($conditionStr != '')
  8744.                             $conditionStr .= " and ";
  8745.                         $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  8746.                     }
  8747.                 }
  8748. //        $aliasInCondition = $table;
  8749.                 if (!empty($setValueArray) || $selectAll == 1) {
  8750.                     if (!empty($setValueArray)) {
  8751.                         if ($conditionStr != '')
  8752.                             $conditionStr .= " and ";
  8753.                         $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  8754.                     }
  8755.                 } else {
  8756.                     $andString '';
  8757.                     foreach ($andConditions as $andCondition) {
  8758. //            $conditionStr.=' 1=1 ';
  8759.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  8760.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  8761.                         $aliasInCondition $table;
  8762.                         if (!(strpos($cfield'.') === false)) {
  8763.                             $fullCfieldArray explode('.'$cfield);
  8764.                             $aliasInCondition $fullCfieldArray[0];
  8765.                             $cfield $fullCfieldArray[1];
  8766.                         }
  8767.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  8768.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8769.                             if ($andString != '')
  8770.                                 $andString .= " and ";
  8771.                             if ($ctype == 'like') {
  8772.                                 $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8773.                                 $wordsBySpaces explode(' '$cvalue);
  8774.                                 foreach ($wordsBySpaces as $word) {
  8775.                                     if ($andString != '')
  8776.                                         $andString .= " and ";
  8777.                                     $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8778.                                 }
  8779.                             } else if ($ctype == 'not like') {
  8780.                                 $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8781.                                 $wordsBySpaces explode(' '$cvalue);
  8782.                                 foreach ($wordsBySpaces as $word) {
  8783.                                     if ($andString != '')
  8784.                                         $andString .= " and ";
  8785.                                     $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8786.                                 }
  8787.                             } else if ($ctype == 'not_in') {
  8788.                                 $andString .= " ( ";
  8789.                                 if (in_array('null'$cvalue)) {
  8790.                                     $andString .= " `$aliasInCondition`.$cfield is not null";
  8791.                                     $cvalue array_diff($cvalue, ['null']);
  8792.                                     if (!empty($cvalue))
  8793.                                         $andString .= " and ";
  8794.                                 }
  8795.                                 if (in_array(''$cvalue)) {
  8796.                                     $andString .= "`$aliasInCondition`.$cfield != '' ";
  8797.                                     $cvalue array_diff($cvalue, ['']);
  8798.                                     if (!empty($cvalue))
  8799.                                         $andString .= " and ";
  8800.                                 }
  8801.                                 $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8802.                             } else if ($ctype == 'in') {
  8803.                                 if (in_array('null'$cvalue)) {
  8804.                                     $andString .= "`$aliasInCondition`.$cfield is null";
  8805.                                     $cvalue array_diff($cvalue, ['null']);
  8806.                                     if (!empty($cvalue))
  8807.                                         $andString .= " and ";
  8808.                                 }
  8809.                                 if (in_array(''$cvalue)) {
  8810.                                     $andString .= "`$aliasInCondition`.$cfield = '' ";
  8811.                                     $cvalue array_diff($cvalue, ['']);
  8812.                                     if (!empty($cvalue))
  8813.                                         $andString .= " and ";
  8814.                                 }
  8815.                                 $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  8816.                             } else if ($ctype == '=') {
  8817.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8818.                                     $andString .= "`$aliasInCondition`.$cfield is null ";
  8819.                                 else
  8820.                                     if (is_string($cvalue))
  8821.                                         $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8822.                                     else
  8823.                                         $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8824.                             } else if ($ctype == '!=') {
  8825.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8826.                                     $andString .= "`$aliasInCondition`.$cfield is not null ";
  8827.                                 else
  8828.                                     $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8829.                             } else {
  8830.                                 if (is_string($cvalue))
  8831.                                     $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8832.                                 else
  8833.                                     $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8834.                             }
  8835.                         }
  8836.                     }
  8837.                     if ($andString != '') {
  8838.                         if ($conditionStr != '')
  8839.                             $conditionStr .= (" and (" $andString ") ");
  8840.                         else
  8841.                             $conditionStr .= ("  (" $andString ") ");
  8842.                     }
  8843.                     $orString '';
  8844.                     foreach ($orConditions as $orCondition) {
  8845.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  8846.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  8847.                         $aliasInCondition $table;
  8848.                         if (!(strpos($cfield'.') === false)) {
  8849.                             $fullCfieldArray explode('.'$cfield);
  8850.                             $aliasInCondition $fullCfieldArray[0];
  8851.                             $cfield $fullCfieldArray[1];
  8852.                         }
  8853.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  8854.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8855.                             if ($orString != '')
  8856.                                 $orString .= " or ";
  8857.                             if ($ctype == 'like') {
  8858.                                 $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8859.                                 $wordsBySpaces explode(' '$cvalue);
  8860.                                 foreach ($wordsBySpaces as $word) {
  8861.                                     if ($orString != '')
  8862.                                         $orString .= " or ";
  8863.                                     $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8864.                                 }
  8865.                             } else if ($ctype == 'not like') {
  8866.                                 $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8867.                                 $wordsBySpaces explode(' '$cvalue);
  8868.                                 foreach ($wordsBySpaces as $word) {
  8869.                                     if ($orString != '')
  8870.                                         $orString .= " or ";
  8871.                                     $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8872.                                 }
  8873.                             } else if ($ctype == 'not_in') {
  8874.                                 $orString .= " ( ";
  8875.                                 if (in_array('null'$cvalue)) {
  8876.                                     $orString .= " `$aliasInCondition`.$cfield is not null";
  8877.                                     $cvalue array_diff($cvalue, ['null']);
  8878.                                     if (!empty($cvalue))
  8879.                                         $orString .= " or ";
  8880.                                 }
  8881.                                 if (in_array(''$cvalue)) {
  8882.                                     $orString .= "`$aliasInCondition`.$cfield != '' ";
  8883.                                     $cvalue array_diff($cvalue, ['']);
  8884.                                     if (!empty($cvalue))
  8885.                                         $orString .= " or ";
  8886.                                 }
  8887.                                 $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8888.                             } else if ($ctype == 'in') {
  8889.                                 $orString .= " ( ";
  8890.                                 if (in_array('null'$cvalue)) {
  8891.                                     $orString .= " `$aliasInCondition`.$cfield is null";
  8892.                                     $cvalue array_diff($cvalue, ['null']);
  8893.                                     if (!empty($cvalue))
  8894.                                         $orString .= " or ";
  8895.                                 }
  8896.                                 if (in_array(''$cvalue)) {
  8897.                                     $orString .= "`$aliasInCondition`.$cfield = '' ";
  8898.                                     $cvalue array_diff($cvalue, ['']);
  8899.                                     if (!empty($cvalue))
  8900.                                         $orString .= " or ";
  8901.                                 }
  8902.                                 $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8903.                             } else if ($ctype == '=') {
  8904.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8905.                                     $orString .= "`$aliasInCondition`.$cfield is null ";
  8906.                                 else
  8907.                                     if (is_string($cvalue))
  8908.                                         $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8909.                                     else
  8910.                                         $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8911.                             } else if ($ctype == '!=') {
  8912.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8913.                                     $orString .= "`$aliasInCondition`.$cfield is not null ";
  8914.                                 else
  8915.                                     $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  8916.                             } else {
  8917.                                 if (is_string($cvalue))
  8918.                                     $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  8919.                                 else
  8920.                                     $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  8921.                             }
  8922.                         }
  8923.                     }
  8924.                     if ($orString != '') {
  8925.                         if ($conditionStr != '')
  8926.                             $conditionStr .= (" or (" $orString ") ");
  8927.                         else
  8928.                             $conditionStr .= ("  (" $orString ") ");
  8929.                     }
  8930.                     $andOrString '';
  8931.                     foreach ($andOrConditions as $andOrCondition) {
  8932.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  8933.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  8934.                         $aliasInCondition $table;
  8935.                         if (!(strpos($cfield'.') === false)) {
  8936.                             $fullCfieldArray explode('.'$cfield);
  8937.                             $aliasInCondition $fullCfieldArray[0];
  8938.                             $cfield $fullCfieldArray[1];
  8939.                         }
  8940.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  8941.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  8942.                             if ($andOrString != '')
  8943.                                 $andOrString .= " or ";
  8944.                             if ($ctype == 'like') {
  8945.                                 $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  8946.                                 $wordsBySpaces explode(' '$cvalue);
  8947.                                 foreach ($wordsBySpaces as $word) {
  8948.                                     if ($andOrString != '')
  8949.                                         $andOrString .= " or ";
  8950.                                     $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  8951.                                 }
  8952.                             } else if ($ctype == 'not like') {
  8953.                                 $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  8954.                                 $wordsBySpaces explode(' '$cvalue);
  8955.                                 foreach ($wordsBySpaces as $word) {
  8956.                                     if ($andOrString != '')
  8957.                                         $andOrString .= " or ";
  8958.                                     $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  8959.                                 }
  8960.                             } else if ($ctype == 'in') {
  8961.                                 $andOrString .= " ( ";
  8962.                                 if (in_array('null'$cvalue)) {
  8963.                                     $andOrString .= " `$aliasInCondition`.$cfield is null";
  8964.                                     $cvalue array_diff($cvalue, ['null']);
  8965.                                     if (!empty($cvalue))
  8966.                                         $andOrString .= " or ";
  8967.                                 }
  8968.                                 if (in_array(''$cvalue)) {
  8969.                                     $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  8970.                                     $cvalue array_diff($cvalue, ['']);
  8971.                                     if (!empty($cvalue))
  8972.                                         $andOrString .= " or ";
  8973.                                 }
  8974.                                 if (!empty($cvalue))
  8975.                                     $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  8976.                                 else
  8977.                                     $andOrString .= "  ) ";
  8978.                             } else if ($ctype == 'not_in') {
  8979.                                 $andOrString .= " ( ";
  8980.                                 if (in_array('null'$cvalue)) {
  8981.                                     $andOrString .= " `$aliasInCondition`.$cfield is not null";
  8982.                                     $cvalue array_diff($cvalue, ['null']);
  8983.                                     if (!empty($cvalue))
  8984.                                         $andOrString .= " or ";
  8985.                                 }
  8986.                                 if (in_array(''$cvalue)) {
  8987.                                     $andOrString .= "`$aliasInCondition`.$cfield != '' ";
  8988.                                     $cvalue array_diff($cvalue, ['']);
  8989.                                     if (!empty($cvalue))
  8990.                                         $andOrString .= " or ";
  8991.                                 }
  8992.                                 if (!empty($cvalue))
  8993.                                     $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  8994.                                 else
  8995.                                     $andOrString .= "  ) ";
  8996.                             } else if ($ctype == '=') {
  8997.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  8998.                                     $andOrString .= "`$aliasInCondition`.$cfield is null ";
  8999.                                 else
  9000.                                     if (is_string($cvalue))
  9001.                                         $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  9002.                                     else
  9003.                                         $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  9004.                             } else if ($ctype == '!=') {
  9005.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  9006.                                     $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  9007.                                 else
  9008.                                     $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  9009.                             } else {
  9010.                                 if (is_string($cvalue))
  9011.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  9012.                                 else
  9013.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  9014.                             }
  9015.                         }
  9016.                     }
  9017.                     if ($andOrString != '') {
  9018.                         if ($conditionStr != '')
  9019.                             $conditionStr .= (" and (" $andOrString ") ");
  9020.                         else
  9021.                             $conditionStr .= ("  (" $andOrString ") ");
  9022.                     }
  9023.                 }
  9024.                 $mustStr '';
  9025. ///now must conditions
  9026.                 foreach ($mustConditions as $mustCondition) {
  9027. //            $conditionStr.=' 1=1 ';
  9028.                     $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  9029.                     $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  9030.                     $aliasInCondition $table;
  9031.                     if (!(strpos($cfield'.') === false)) {
  9032.                         $fullCfieldArray explode('.'$cfield);
  9033.                         $aliasInCondition $fullCfieldArray[0];
  9034.                         $cfield $fullCfieldArray[1];
  9035.                     }
  9036.                     $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  9037.                     if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  9038.                         if ($mustStr != '')
  9039.                             $mustStr .= " and ";
  9040.                         if ($ctype == 'like') {
  9041.                             $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  9042.                             $wordsBySpaces explode(' '$cvalue);
  9043.                             foreach ($wordsBySpaces as $word) {
  9044.                                 if ($mustStr != '')
  9045.                                     $mustStr .= " or ";
  9046.                                 $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  9047.                             }
  9048.                             $mustStr .= " )";
  9049.                         } else if ($ctype == 'not like') {
  9050.                             $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  9051.                             $wordsBySpaces explode(' '$cvalue);
  9052.                             foreach ($wordsBySpaces as $word) {
  9053.                                 if ($mustStr != '')
  9054.                                     $mustStr .= " and ";
  9055.                                 $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  9056.                             }
  9057.                         } else if ($ctype == 'in') {
  9058.                             $mustStr .= " ( ";
  9059.                             if (in_array('null'$cvalue)) {
  9060.                                 $mustStr .= " `$aliasInCondition`.$cfield is null";
  9061.                                 $cvalue array_diff($cvalue, ['null']);
  9062.                                 if (!empty($cvalue))
  9063.                                     $mustStr .= " or ";
  9064.                             }
  9065.                             if (in_array(''$cvalue)) {
  9066.                                 $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  9067.                                 $cvalue array_diff($cvalue, ['']);
  9068.                                 if (!empty($cvalue))
  9069.                                     $mustStr .= " or ";
  9070.                             }
  9071.                             $formattedValues array_map(function ($val) {
  9072.                                 $val trim($val);
  9073.                                 if (is_numeric($val)) {
  9074.                                     return $val;
  9075.                                 }
  9076.                                 return "'" addslashes($val) . "'";
  9077.                             }, $cvalue);
  9078.                             $mustStr .= "`$aliasInCondition`.$cfield IN (" implode(','$formattedValues) . ") ) ";
  9079. //                            $mustStr .= "`$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ) ";
  9080.                         } else if ($ctype == 'not_in') {
  9081.                             $mustStr .= " ( ";
  9082.                             if (in_array('null'$cvalue)) {
  9083.                                 $mustStr .= " `$aliasInCondition`.$cfield is not null";
  9084.                                 $cvalue array_diff($cvalue, ['null']);
  9085.                                 if (!empty($cvalue))
  9086.                                     $mustStr .= " and ";
  9087.                             }
  9088.                             if (in_array(''$cvalue)) {
  9089.                                 $mustStr .= "`$aliasInCondition`.$cfield != '' ";
  9090.                                 $cvalue array_diff($cvalue, ['']);
  9091.                                 if (!empty($cvalue))
  9092.                                     $mustStr .= " and ";
  9093.                             }
  9094.                             $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  9095.                         } else if ($ctype == '=') {
  9096.                             if ($cvalue == 'null' || $cvalue == 'Null')
  9097.                                 $mustStr .= "`$aliasInCondition`.$cfield is null ";
  9098.                             else
  9099.                                 if (is_string($cvalue))
  9100.                                     $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  9101.                                 else
  9102.                                     $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  9103.                         } else if ($ctype == '!=') {
  9104.                             if ($cvalue == 'null' || $cvalue == 'Null')
  9105.                                 $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  9106.                             else
  9107.                                 $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  9108.                         } else {
  9109.                             if (is_string($cvalue))
  9110.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  9111.                             else
  9112.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  9113.                         }
  9114.                     }
  9115.                 }
  9116.                 if ($mustStr != '') {
  9117.                     if ($conditionStr != '')
  9118.                         $conditionStr .= (" and (" $mustStr ") ");
  9119.                     else
  9120.                         $conditionStr .= ("  (" $mustStr ") ");
  9121.                 }
  9122.                 if ($conditionStr != '')
  9123.                     $filterQryForCriteria .= (" and (" $conditionStr ") ");
  9124.                 if ($lastChildrenOnly == 1) {
  9125.                     if ($filterQryForCriteria != '')
  9126.                         $filterQryForCriteria .= ' and ';
  9127.                     $filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  9128.                 } else if ($parentOnly == 1) {
  9129.                     if ($filterQryForCriteria != '')
  9130.                         $filterQryForCriteria .= ' and ';
  9131.                     $filterQryForCriteria .= "`$table`.`$valueField`  in ( select distinct $parentIdField from  $table)";
  9132.                 }
  9133.                 if (!empty($orderByConditions)) {
  9134.                     $filterQryForCriteria .= "  order by ";
  9135.                     $fone 1;
  9136.                     foreach ($orderByConditions as $orderByCondition) {
  9137.                         if ($fone != 1) {
  9138.                             $filterQryForCriteria .= " , ";
  9139.                         }
  9140.                         if (isset($orderByCondition['valueList'])) {
  9141.                             if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  9142.                             if ($orderByCondition['valueList'] == null)
  9143.                                 $orderByCondition['valueList'] = [];
  9144.                             $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  9145.                         } else
  9146.                             $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  9147.                         $fone 0;
  9148.                     }
  9149.                 }
  9150.                 if ($returnTotalMatchedEntriesFlag == 1) {
  9151. //            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9152. //            
  9153. //            $get_kids = $stmt;
  9154.                 }
  9155.                 if ($filterQryForCriteria != '')
  9156.                     if (!empty($setValueArray) || $selectAll == 1) {
  9157.                     } else {
  9158.                         if ($itemLimit != '_ALL_')
  9159.                             $filterQryForCriteria .= "  limit $offset$itemLimit ";
  9160.                         else
  9161.                             $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  9162.                     }
  9163.                 $get_kids_sql $filterQryForCriteria;
  9164.                 $get_kids_sql str_ireplace('_set_matching_value_'''$get_kids_sql);
  9165.                 // TODO: This generic selector assembles SQL across many request-driven table branches.
  9166.                 // Converting it safely requires untangling the shared builder so each branch can bind
  9167.                 // its own parameters without changing selector behavior in unrelated endpoints.
  9168.                 $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9169.                 $get_kids $stmt;
  9170.                 $selectedId 0;
  9171.                 if ($table == 'warehouse_action') {
  9172.                     if (empty($get_kids)) {
  9173.                         $get_kids_sql_2 "select * from warehouse_action";
  9174.                         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql_2);
  9175.                         $get_kids2 $stmt;
  9176.                         if (empty($get_kids2))
  9177.                             $get_kids GeneralConstant::$warehouse_action_list;
  9178.                     }
  9179.                 }
  9180.                 if (!empty($get_kids)) {
  9181.                     $nextOffset $offset count($get_kids);
  9182.                     $nextOffset++;
  9183.                     foreach ($get_kids as $pa) {
  9184.                         if (!empty($setValueArray) && $selectAll == 0) {
  9185.                             if (!in_array($pa[$valueField], $setValueArray))
  9186.                                 continue;
  9187.                         }
  9188.                         if (!empty($restrictionIdList)) {
  9189.                             if (!in_array($pa[$valueField], $restrictionIdList))
  9190.                                 continue;
  9191.                         }
  9192.                         if ($selectAll == || $selectAllFound==1) {
  9193.                             $setValueArray[] = $pa[$valueField];
  9194.                             $setValue $pa[$valueField];
  9195.                         } else if (count($get_kids) == && $setDataForSingle == 1) {
  9196.                             $setValueArray[] = $pa[$valueField];
  9197.                             $setValue $pa[$valueField];
  9198.                         }
  9199.                         if ($valueField != '')
  9200.                             $pa['value'] = $pa[$valueField];
  9201.                         $renderedText $renderTextFormat;
  9202.                         $compare_array = [];
  9203.                         if ($renderTextFormat != '') {
  9204.                             $renderedText $renderTextFormat;
  9205.                             $compare_arrayFull = [];
  9206.                             $compare_array = [];
  9207.                             $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  9208.                             );
  9209.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  9210.                             if (isset($compare_arrayFull[0]))
  9211.                                 $compare_array $compare_arrayFull[0];
  9212. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  9213.                             foreach ($compare_array as $cmpdt) {
  9214.                                 $tbr str_replace("__"""$cmpdt);
  9215.                                 if ($tbr != '') {
  9216.                                     if (isset($pa[$tbr])) {
  9217.                                         if ($pa[$tbr] == null)
  9218.                                             $renderedText str_replace($cmpdt''$renderedText);
  9219.                                         else
  9220.                                             $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  9221.                                     } else {
  9222.                                         $renderedText str_replace($cmpdt''$renderedText);
  9223.                                     }
  9224.                                 }
  9225.                             }
  9226.                         }
  9227.                         $pa['rendered_text'] = $renderedText;
  9228.                         $pa['text'] = ($textField != '' $pa[$textField] : '');
  9229. //                $pa['compare_array'] = $compare_array;
  9230.                         foreach ($convertToObjectFieldList as $convField) {
  9231.                             if (isset($pa[$convField])) {
  9232.                                 $taA json_decode($pa[$convField], true);
  9233.                                 if ($taA == null$taA = [];
  9234.                                 $pa[$convField] = $taA;
  9235.                             } else {
  9236.                                 $pa[$convField] = [];
  9237.                             }
  9238.                         }
  9239.                         foreach ($convertDateToStringFieldList as $convField) {
  9240.                             if (is_array($convField)) {
  9241.                                 $fld $convField['field'];
  9242.                                 $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  9243.                             } else {
  9244.                                 $fld $convField;
  9245.                                 $frmt 'Y-m-d H:i:s';
  9246.                             }
  9247.                             if (isset($pa[$fld])) {
  9248.                                 $taA = new \DateTime($pa[$fld]);
  9249.                                 $pa[$fld] = $taA->format($frmt);
  9250.                             }
  9251.                         }
  9252.                         foreach ($convertToUrl as $convField) {
  9253. //
  9254. //                            $fld = $convField;
  9255. //
  9256. //
  9257. //                            if (isset($pa[$fld])) {
  9258. //
  9259. //
  9260. //                                $pa[$fld] =
  9261. //                                    $this->generateUrl(
  9262. //                                        'dashboard', [
  9263. //
  9264. //                                    ], UrlGenerator::ABSOLUTE_URL
  9265. //                                    ).'/'.$pa[$fld];
  9266. //
  9267. //                            }
  9268.                         }
  9269.                         foreach ($fullPathList as $pathField) {
  9270.                             $fld $pathField;
  9271.                             if (isset($pa[$fld])) {
  9272.                                 if ($pa[$fld] != '' && $pa[$fld] != null) {
  9273.                                     $pa[$fld] = ($this->generateUrl(
  9274.                                             'dashboard', [
  9275.                                         ], UrlGenerator::ABSOLUTE_URL
  9276.                                         ) . $pa[$fld]);
  9277.                                 }
  9278.                             }
  9279.                         }
  9280.                         $pa['currentTs'] = (new \Datetime())->format('U');
  9281.                         $data[] = $pa;
  9282.                         if ($valueField != '') {
  9283.                             $data_by_id[$pa[$valueField]] = $pa;
  9284.                             $selectedId $pa[$valueField];
  9285.                         }
  9286.                     }
  9287.                 }
  9288.                 if ($dataOnly == 1)
  9289.                     $lastResult = array(
  9290.                         'success' => true,
  9291.                         'data' => $data,
  9292.                         'currentTs' => (new \Datetime())->format('U'),
  9293.                         'restrictionIdList' => $restrictionIdList,
  9294.                         'nextOffset' => $nextOffset,
  9295.                         'totalMatchedEntries' => $totalMatchedEntries,
  9296.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  9297.                     );
  9298.                 else
  9299.                     $lastResult = array(
  9300.                         'success' => true,
  9301.                         'data' => $data,
  9302.                         'tableName' => $table,
  9303.                         'setValue' => $setValue,
  9304.                         'currentTs' => (new \Datetime())->format('U'),
  9305.                         'restrictionIdList' => $restrictionIdList,
  9306.                         'andConditions' => $andConditions,
  9307.                         'selectFieldList' => $selectFieldList,
  9308.                         'queryStr' => $queryStringIndividual,
  9309.                         'isMultiple' => $isMultiple,
  9310.                         'nextOffset' => $nextOffset,
  9311.                         'totalMatchedEntries' => $totalMatchedEntries,
  9312.                         'selectorId' => $selectorId,
  9313.                         'setValueArray' => $setValueArray,
  9314.                         'silentChangeSelectize' => $silentChangeSelectize,
  9315.                         'convertToObjectFieldList' => $convertToObjectFieldList,
  9316.                         'conditionStr' => $conditionStr,
  9317.                         'selectAll' => $selectAll,
  9318. //                    'andStr' => $andString,
  9319. //                    'andOrStr' => $andOrString,
  9320.                         'dataById' => $data_by_id,
  9321.                         'selectedId' => $selectedId,
  9322.                         'dataId' => $dataId,
  9323.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  9324.                     );
  9325.             }
  9326.             $allResult[] = $lastResult;
  9327.         }
  9328.         if ($isSingleDataset == 1)
  9329.             return new JsonResponse($lastResult);
  9330.         else
  9331.             return new JsonResponse($allResult);
  9332.     }
  9333.     public function updatePlanningItemSequenceAction(Request $request$queryStr '')
  9334.     {
  9335.         $em $this->getDoctrine()->getManager();
  9336.         $stmt $em->getConnection()->fetchAllAssociative("select  `id` , parent_id, sequence from planning_item where sequence is null 
  9337.             ORDER BY parent_id ASC, id ASC
  9338.                         ");
  9339.         $query_output $stmt;
  9340.         foreach ($query_output as $dupe) {
  9341.             System::updatePlanningItemSequence($em$dupe["id"]);
  9342.         }
  9343.         System::updatePlanningItemSequence(
  9344.             $em,
  9345.             $request->request->get('planningItemId'0),
  9346.             $request->request->get('assignType''_ASSIGN_')   ///can be _MOVE_UP_ or _MOVE_DOWN_
  9347.         );
  9348. //        if($request->query->has('returnJson'))
  9349.         return new JsonResponse(
  9350.             array(
  9351.                 'success' => true,
  9352.                 'data' => [],
  9353.             )
  9354.         );
  9355.     }
  9356.     public function insertDataAjaxAction(Request $request$queryStr '')
  9357.     {
  9358.         $em $this->getDoctrine()->getManager();
  9359. //        if($request->query->has('big_data_test'))
  9360. //        {
  9361. //            for($t=0;$t<$request->request->get('big_data_test',10000);$t++) {
  9362. //                $em = $this->getDoctrine()->getManager('company_group');
  9363. //                $NOTIFICATION = new EntityNotification();
  9364. //                $NOTIFICATION->setAppId(1);
  9365. //                $NOTIFICATION->setCompanyId(0);
  9366. //                $NOTIFICATION->setCompanyId(0);
  9367. //                $NOTIFICATION->setBody('Test Description'.$t);
  9368. //                $NOTIFICATION->setTitle('Test Title'.$t);
  9369. //                $NOTIFICATION->setExpireTs(0);
  9370. //                $NOTIFICATION->setIsBuddybee(0);
  9371. //                $NOTIFICATION->setType(0);
  9372. //                $em->persist($NOTIFICATION);
  9373. //                $em->flush();
  9374. //            }
  9375. //
  9376. //            return new JsonResponse(
  9377. //                array(
  9378. //                    'success' => true,
  9379. //                    'data' => [],
  9380. //
  9381. //
  9382. //                )
  9383. //            );
  9384. //
  9385. //
  9386. //        }
  9387.         if ($request->request->get('entity_group'0)) {
  9388.             $companyId 0;
  9389.             $em $this->getDoctrine()->getManager('company_group');
  9390.         } else
  9391.             $companyId $this->getLoggedUserCompanyId($request);
  9392.         if ($companyId) {
  9393.             $company_data = [];
  9394. //            $company_data = Company::getCompanyData($em, $companyId);
  9395.         } else {
  9396.             $companyId 0;
  9397.             $company_data = [];
  9398.         }
  9399. //        $theEntity= new EntityNotification();
  9400. //        $entityName = 'EntityNotification';
  9401. //
  9402. //        $className='\\CompanyGroupBundle\\Entity\\'.$entityName;
  9403. //
  9404. //
  9405. //            $theEntity= new $className();
  9406.         $dataToAdd $request->request->has('dataToAdd') ? $request->request->get('dataToAdd') : [];
  9407.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  9408.         if ($dataToAdd == null$dataToAdd = [];
  9409.         $dataToRemove $request->request->has('dataToRemove') ? $request->request->get('dataToRemove') : [];
  9410.         if (is_string($dataToRemove)) $dataToAdd json_decode($dataToRemovetrue);
  9411.         if ($dataToRemove == null$dataToRemove = [];
  9412.         $relData = [];
  9413.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  9414.         $updatedDataList = [];
  9415.         foreach ($dataToAdd as $dataInd => $dat) {
  9416.             $entityName $dat['entityName'];
  9417.             $idField $dat['idField'];
  9418.             $findByField = isset($dat['findByField']) ? $dat['findByField'] : '';
  9419.             $findByValue = isset($dat['findByValue']) ? $dat['findByValue'] : '';
  9420.             $returnRefIndex $dat['returnRefIndex'];
  9421.             $findById $dat['findId'];
  9422.             $dataFields = isset($dat['dataFields']) ? $dat['dataFields'] : [];
  9423.             $noCreation = isset($dat['noCreation']) ? $dat['noCreation'] : 0;
  9424.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  9425.             $preAdditionalSql = isset($dat['preAdditionalSql']) ? $dat['preAdditionalSql'] : '';
  9426.             if ($preAdditionalSql != '') {
  9427. //            if ($entityName == 'PlanningItem') {
  9428. //
  9429. //                $stmt='select disctinct parent_id from planning_item;';
  9430. //                
  9431. //                $get_kids = $stmt;
  9432. //                $p_ids=[];
  9433. //                foreach($get_kids as $g)
  9434. //                {
  9435. //                    $p_ids[]=$g['parent_id'];
  9436. //                }
  9437. //
  9438. //
  9439. //
  9440.                 $stmt $em->getConnection()->executeStatement($preAdditionalSql);
  9441. //
  9442. //
  9443.             }
  9444.             if ($entityName == 'PlanningItem') {
  9445.                 $stmt $em->getConnection()->fetchAllAssociative("select  `id` , parent_id, sequence from planning_item where sequence is null
  9446.             ORDER BY parent_id ASC, id ASC
  9447.                         ");
  9448.                 $query_output $stmt;
  9449.                 foreach ($query_output as $dupe) {
  9450.                     System::updatePlanningItemSequence($em$dupe["id"]);
  9451.                 }
  9452.             }
  9453.             $className = ($request->request->get('entity_group'0) ? '\\CompanyGroupBundle\\Entity\\' '\\ApplicationBundle\\Entity\\') . $entityName;
  9454.             if (
  9455.                 ($findById == || $findById == '_NA_') && $findByField == '' && $noCreation == 0
  9456.             ) {
  9457.                 $theEntity = new $className();
  9458. //                $theEntity= new EntityNotification();
  9459.             } else {
  9460.                 if ($findByField != '') {
  9461.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle\\Entity\\' 'ApplicationBundle\\Entity\\') . $entityName)->findOneBy(
  9462.                         array
  9463.                         (
  9464.                             $findByField => $findByValue,
  9465.                         )
  9466.                     );
  9467.                 } else {
  9468.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle\\Entity\\' 'ApplicationBundle\\Entity\\') . $entityName)->findOneBy(
  9469.                         array
  9470.                         (
  9471.                             $idField => $findById,
  9472.                         )
  9473.                     );
  9474.                 }
  9475.             }
  9476.             if (!$theEntity && $noCreation == 0)
  9477.                 $theEntity = new $className();
  9478.             foreach ($dataFields as $dt) {
  9479.                 $setMethod 'set' ucfirst($dt['field']);
  9480.                 $getMethod 'get' ucfirst($dt['field']);
  9481.                 $type = isset($dt['type']) ? $dt['type'] : '_VALUE_';
  9482.                 $action = isset($dt['action']) ? $dt['action'] : '_REPLACE_';
  9483.                 if (method_exists($theEntity$setMethod)) {
  9484.                     $oldValue $theEntity->{$getMethod}();
  9485.                     $newValue $oldValue;
  9486.                     if ($type == '_VALUE_') {
  9487.                         $newValue $dt['value'];
  9488.                     }
  9489.                     if ($type == '_DECIMAL_') {
  9490.                         $newValue $dt['value'];
  9491.                     }
  9492.                     if ($type == '_DATE_') {
  9493.                         $newValue = new \DateTime($dt['value']);
  9494.                     }
  9495.                     if ($type == '_ARRAY_') {
  9496.                         $oldValue json_decode($oldValue);
  9497.                         if ($oldValue == null$oldValue = [];
  9498.                         if ($action == '_REPLACE_') {
  9499.                             $newValue json_encode($dt['value']);
  9500.                         }
  9501.                         if ($action == '_APPEND_') {
  9502.                             $newValue array_merge($oldValuearray_values(array_diff([$dt['value']], $oldValue)));
  9503.                         }
  9504.                         if ($action == '_MERGE_') {
  9505.                             $newValue array_merge($oldValuearray_values(array_diff($dt['value'], $oldValue)));
  9506.                         }
  9507.                         if ($action == '_EXCLUDE_') {
  9508.                             $newValue array_values(array_diff($oldValue, [$dt['value']]));
  9509.                         }
  9510.                         if ($action == '_EXCLUDE_ARRAY_') {
  9511.                             $newValue array_values(array_diff($oldValue$dt['value']));
  9512.                         }
  9513.                         $newValue json_encode($newValue);
  9514.                     }
  9515.                     $theEntity->{$setMethod}($newValue); // `foo!`
  9516. //                    $theEntity->setCompletionPercentage(78); // `foo!`
  9517.                 }
  9518.             }
  9519.             if ($additionalSql != '') {
  9520. //            if ($entityName == 'PlanningItem') {
  9521. //
  9522. //                $stmt='select disctinct parent_id from planning_item;';
  9523. //                
  9524. //                $get_kids = $stmt;
  9525. //                $p_ids=[];
  9526. //                foreach($get_kids as $g)
  9527. //                {
  9528. //                    $p_ids[]=$g['parent_id'];
  9529. //                }
  9530. //
  9531. //
  9532. //
  9533.                 $stmt $em->getConnection()->fetchAllAssociative($additionalSql);
  9534. //
  9535. //
  9536.             }
  9537.             if (($findById == || $findById == '_NA_') && $noCreation == 0) {
  9538.                 $em->persist($theEntity);
  9539.                 $em->flush();
  9540.                 $getMethod 'get' ucfirst($idField);
  9541.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  9542.             } else if ($theEntity) {
  9543.                 $em->flush();
  9544.                 $getMethod 'get' ucfirst($idField);
  9545.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  9546.             }
  9547.             if ($entityName == 'PlanningItem') {
  9548.                 $stmt $em->getConnection()->fetchAllAssociative('select distinct parent_id from planning_item;');
  9549.                 $get_kids $stmt;
  9550.                 $p_ids = [];
  9551.                 foreach ($get_kids as $g) {
  9552.                     $p_ids[] = $g['parent_id'];
  9553.                 }
  9554.                 // Only real parent ids: strip NULL / 0 (top-level marker) so the IN list never has a
  9555.                 // stray/leading comma. Run as TWO separate statements â€” executeStatement is single-statement.
  9556.                 $p_ids array_values(array_unique(array_filter(array_map('intval'$p_ids))));
  9557.                 if (!empty($p_ids)) {
  9558.                     $idList implode(','$p_ids);
  9559.                     $em->getConnection()->executeStatement('UPDATE planning_item d SET d.`has_child` = 0 WHERE d.id NOT IN (' $idList ')');
  9560.                     $em->getConnection()->executeStatement('UPDATE planning_item d SET d.`has_child` = 1 WHERE d.id IN (' $idList ')');
  9561.                 } else {
  9562.                     // no parents recorded â†’ nothing has children
  9563.                     $em->getConnection()->executeStatement('UPDATE planning_item d SET d.`has_child` = 0');
  9564.                 }
  9565.                 $updatedData System::updatePlanningItemSequence($em$theEntity->getId());
  9566.                 $theEntity $updatedData['primaryOne'];
  9567.                 $theEntityUpdated $theEntity;
  9568.                 if ($theEntityUpdated->getEntryType() == 4)///cashflow
  9569.                 {
  9570.                     MiscActions::AddCashFlowProjection($em0, [
  9571.                         'planningItemId' => $theEntityUpdated->getId(),
  9572.                         'fundRequisitionId' => 0,
  9573.                         'concernedPersonId' => 0,
  9574.                         'type' => 1//exp
  9575.                         'subType' => 1//1== khoroch hobe 2: ashbe
  9576.                         'cashFlowType' => 1//2== RCV /in  1: Payment/out
  9577.                         'creationType' => 1//auto
  9578.                         'amountType' => 1//fund
  9579.                         'cashFlowAmount' => 0,
  9580.                         'expAstAmount' => 0,
  9581.                         'accumulatedCashFlowAmount' => 0,
  9582.                         'accumulatedCashFlowBalance' => 0,
  9583.                         'accumulatedExpAstAmount' => 0,
  9584.                         'relevantExpAstHeadId' => 0,
  9585.                         'balancingHeadId' => 0,
  9586.                         'cashFlowHeadId' => 0,
  9587.                         'cashFlowHeadType' => 1,
  9588.                         'relevantProductIds' => [],
  9589.                         'reminderDateTs' => 0,
  9590.                         'cashFlowDateTs' => 0,
  9591.                         'expAstRealizationDateTs' => 0,
  9592.                     ]);
  9593.                 }
  9594.             } else if ($entityName == 'TaskLog') {
  9595.                 $session $request->getSession();
  9596.                 if ($theEntity) {
  9597.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  9598.                     $currTime = new \DateTime();
  9599.                     $options = array(
  9600.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  9601.                         'notification_server' => $this->container->getParameter('notification_server'),
  9602.                     );
  9603.                     $positionsArray = [
  9604.                         array(
  9605.                             'employeeId' => $empId,
  9606.                             'userId' => $session->get(UserConstants::USER_ID0),
  9607.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  9608.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  9609.                             'lat' => 23.8623834,
  9610.                             'lng' => 90.3979294,
  9611.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING,
  9612. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  9613.                         )
  9614.                     ];
  9615.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  9616.                     if ($positionsArray == null$positionsArray = [];
  9617.                     $dataByAttId = [];
  9618.                     $workPlaceType '_UNSET_';
  9619.                     foreach ($positionsArray as $findex => $d) {
  9620.                         $sysUserId 0;
  9621.                         $userId 0;
  9622.                         $empId 0;
  9623.                         $dtTs 0;
  9624.                         $timeZoneStr '+0000';
  9625.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  9626.                         if (isset($d['userId'])) $userId $d['userId'];
  9627.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  9628.                         if (isset($d['tsMilSec'])) {
  9629.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  9630.                         }
  9631.                         if ($dtTs == 0) {
  9632.                             $currTsTime = new \DateTime();
  9633.                             $dtTs $currTsTime->format('U');
  9634.                         } else {
  9635.                             $currTsTime = new \DateTime('@' $dtTs);
  9636.                         }
  9637.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  9638.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  9639.                         $EmployeeAttendance $this->getDoctrine()
  9640.                             ->getRepository(EmployeeAttendance::class)
  9641.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  9642.                         if (!$EmployeeAttendance) {
  9643.                             $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9644.                             $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9645.                             $EmployeeAttendance = new EmployeeAttendance;
  9646.                         } else {
  9647.                             if ($EmployeeAttendance->getCurrentLocation() == 'out') {
  9648.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9649.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  9650.                             } else {
  9651.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  9652.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  9653.                             }
  9654.                         }
  9655.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  9656.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  9657.                             $workPlaceType '_STATIC_';
  9658.                         }
  9659.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  9660.                             $dataByAttId[$attendanceInfo->getId()] = array(
  9661.                                 'attendanceInfo' => $attendanceInfo,
  9662.                                 'empId' => $empId,
  9663.                                 'lat' => 0,
  9664.                                 'lng' => 0,
  9665.                                 'address' => 0,
  9666.                                 'sysUserId' => $sysUserId,
  9667.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  9668.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  9669.                                 'positionArray' => []
  9670.                             );
  9671.                         $posData = array(
  9672.                             'ts' => $dtTs,
  9673.                             'lat' => $d['lat'],
  9674.                             'lng' => $d['lng'],
  9675.                             'marker' => $d['markerId'],
  9676.                             'src' => 2,
  9677.                         );
  9678.                         $posDataArray = array(
  9679.                             $dtTs,
  9680.                             $d['lat'],
  9681.                             $d['lng'],
  9682.                             $d['markerId'],
  9683.                             2
  9684.                         );
  9685.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  9686.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  9687.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  9688.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  9689.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  9690.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  9691.                         if (isset($d['address']))
  9692.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  9693. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  9694.                     }
  9695.                     $response = array(
  9696.                         'success' => true,
  9697.                     );
  9698.                     foreach ($dataByAttId as $attInfoId => $d) {
  9699.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  9700.                             $d['empId'],
  9701.                             $d['sysUserId'],
  9702.                             $d['companyId'],
  9703.                             $d['appId'],
  9704.                             $request,
  9705.                             $d['attendanceInfo'],
  9706.                             $options,
  9707.                             $d['positionArray'],
  9708.                             $d['lat'],
  9709.                             $d['lng'],
  9710.                             $d['address'],
  9711.                             $d['markerId']
  9712.                         );
  9713.                     }
  9714.                     $session->set(UserConstants::USER_CURRENT_TASK_ID$theEntity->getId());
  9715.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$theEntity->getPlanningItemId());
  9716.                 } else {
  9717.                     $session->set(UserConstants::USER_CURRENT_TASK_ID0);
  9718.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID0);
  9719.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  9720.                     $currTime = new \DateTime();
  9721.                     $options = array(
  9722.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  9723.                         'notification_server' => $this->container->getParameter('notification_server'),
  9724.                     );
  9725.                     $positionsArray = [
  9726.                         array(
  9727.                             'employeeId' => $empId,
  9728.                             'userId' => $session->get(UserConstants::USER_ID0),
  9729.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  9730.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  9731.                             'lat' => 23.8623834,
  9732.                             'lng' => 90.3979294,
  9733.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT,
  9734. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  9735.                         )
  9736.                     ];
  9737.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  9738.                     if ($positionsArray == null$positionsArray = [];
  9739.                     $dataByAttId = [];
  9740.                     $workPlaceType '_UNSET_';
  9741.                     foreach ($positionsArray as $findex => $d) {
  9742.                         $sysUserId 0;
  9743.                         $userId 0;
  9744.                         $empId 0;
  9745.                         $dtTs 0;
  9746.                         $timeZoneStr '+0000';
  9747.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  9748.                         if (isset($d['userId'])) $userId $d['userId'];
  9749.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  9750.                         if (isset($d['tsMilSec'])) {
  9751.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  9752.                         }
  9753.                         if ($dtTs == 0) {
  9754.                             $currTsTime = new \DateTime();
  9755.                             $dtTs $currTsTime->format('U');
  9756.                         } else {
  9757.                             $currTsTime = new \DateTime('@' $dtTs);
  9758.                         }
  9759.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  9760.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  9761.                         $EmployeeAttendance $this->getDoctrine()
  9762.                             ->getRepository(EmployeeAttendance::class)
  9763.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  9764.                         if (!$EmployeeAttendance) {
  9765.                             continue;
  9766.                         } else {
  9767.                         }
  9768.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  9769.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT) {
  9770.                             $workPlaceType '_STATIC_';
  9771.                         }
  9772.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  9773.                             $dataByAttId[$attendanceInfo->getId()] = array(
  9774.                                 'attendanceInfo' => $attendanceInfo,
  9775.                                 'empId' => $empId,
  9776.                                 'lat' => 0,
  9777.                                 'lng' => 0,
  9778.                                 'address' => 0,
  9779.                                 'sysUserId' => $sysUserId,
  9780.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  9781.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  9782.                                 'positionArray' => []
  9783.                             );
  9784.                         $posData = array(
  9785.                             'ts' => $dtTs,
  9786.                             'lat' => $d['lat'],
  9787.                             'lng' => $d['lng'],
  9788.                             'marker' => $d['markerId'],
  9789.                             'src' => 2,
  9790.                         );
  9791.                         $posDataArray = array(
  9792.                             $dtTs,
  9793.                             $d['lat'],
  9794.                             $d['lng'],
  9795.                             $d['markerId'],
  9796.                             2
  9797.                         );
  9798.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  9799.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  9800.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  9801.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  9802.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  9803.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  9804.                         if (isset($d['address']))
  9805.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  9806. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  9807.                     }
  9808.                     $response = array(
  9809.                         'success' => true,
  9810.                     );
  9811.                     foreach ($dataByAttId as $attInfoId => $d) {
  9812.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  9813.                             $d['empId'],
  9814.                             $d['sysUserId'],
  9815.                             $d['companyId'],
  9816.                             $d['appId'],
  9817.                             $request,
  9818.                             $d['attendanceInfo'],
  9819.                             $options,
  9820.                             $d['positionArray'],
  9821.                             $d['lat'],
  9822.                             $d['lng'],
  9823.                             $d['address'],
  9824.                             $d['markerId']
  9825.                         );
  9826.                     }
  9827.                 }
  9828.                 $theEntityUpdated $theEntity;
  9829.             } else
  9830.                 $theEntityUpdated $theEntity;
  9831. //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  9832.             $getters = [];
  9833.             if ($theEntityUpdated)
  9834.                 $getters array_filter(get_class_methods($theEntityUpdated), function ($method) {
  9835.                     return 'get' === substr($method03);
  9836.                 });
  9837.             $updatedData = [];
  9838.             foreach ($getters as $getter) {
  9839.                 $indForThis str_replace('get'''$getter);
  9840.                 $indForThis lcfirst($indForThis);
  9841.                 $updatedData[$indForThis] = $theEntityUpdated->{$getter}();
  9842.             }
  9843.             $updatedDataList[$dataInd] = $updatedData;
  9844.         }
  9845.         foreach ($dataToRemove as $dataInd => $dat) {
  9846.             $entityName $dat['entityName'];
  9847.             $idField $dat['idField'];
  9848.             $findById $dat['findId'];
  9849.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  9850.             $theEntityList $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle\\Entity\\' 'ApplicationBundle\\Entity\\') . $entityName)->findBy(
  9851.                 array
  9852.                 (
  9853.                     $idField => $findById,
  9854.                 )
  9855.             );
  9856.             foreach ($theEntityList as $dt) {
  9857.                 $em->remove($dt);
  9858.                 $em->flush();
  9859.             }
  9860.             if ($additionalSql != '') {
  9861. //            if ($entityName == 'PlanningItem') {
  9862. //
  9863. //                $stmt='select disctinct parent_id from planning_item;';
  9864. //                
  9865. //                $get_kids = $stmt;
  9866. //                $p_ids=[];
  9867. //                foreach($get_kids as $g)
  9868. //                {
  9869. //                    $p_ids[]=$g['parent_id'];
  9870. //                }
  9871. //
  9872. //
  9873. //
  9874.                 $stmt $em->getConnection()->fetchAllAssociative($additionalSql);
  9875. //
  9876. //
  9877.             }
  9878.             $updatedDataList[$dataInd] = [];
  9879.         }
  9880. //        if ($table == '') {
  9881. //            return new JsonResponse(
  9882. //                array(
  9883. //                    'success' => false,
  9884. ////                    'page_title' => 'Product Details',
  9885. ////                    'company_data' => $company_data,
  9886. //                    'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9887. //
  9888. //                )
  9889. //            );
  9890. //        }
  9891. //        if($request->query->has('returnJson'))
  9892.         return new JsonResponse(
  9893.             array(
  9894.                 'success' => true,
  9895.                 'data' => $relData,
  9896.                 'updatedDataList' => $updatedDataList,
  9897.             )
  9898.         );
  9899.     }
  9900.     public function GetAvailableQtyAction(Request $request$id 0)
  9901.     {
  9902.         $em $this->getDoctrine()->getManager();
  9903.         $productId $request->request->has('productId') ? $request->request->get('productId') : 0;
  9904.         $colorId $request->request->has('colorId') ? $request->request->get('colorId') : 0;
  9905.         $dataId $request->request->has('dataId') ? $request->request->get('dataId') : 0;
  9906.         $allowedWarehouseIds $request->request->has('warehouseId') ? [$request->request->get('warehouseId')] : [];
  9907.         $allowedWarehouseActionIds $request->request->has('warehouseActionId') ? [$request->request->get('warehouseActionId')] : [];
  9908.         $qty Inventory::getSellableProductQty($em$productId$allowedWarehouseIds$allowedWarehouseActionIds$colorId);
  9909.         return new JsonResponse(array("success" => true,
  9910.             "qty" => $qty,
  9911.             "dataId" => $dataId,
  9912.         ));
  9913.     }
  9914.     public
  9915.     function ProductListSelectAjaxAction(Request $request$queryStr '')
  9916.     {
  9917.         $em $this->getDoctrine()->getManager();
  9918.         $companyId $this->getLoggedUserCompanyId($request);
  9919.         $company_data Company::getCompanyData($em$companyId);
  9920.         $data = [];
  9921.         $data_by_id = [];
  9922.         $html '';
  9923.         $productByCodeData = [];
  9924.         if ($queryStr == '_EMPTY_')
  9925.             $queryStr '';
  9926.         if ($request->request->has('query') && $queryStr == '')
  9927.             $queryStr $request->request->get('queryStr');
  9928.         if ($queryStr == '_EMPTY_')
  9929.             $queryStr '';
  9930. //        $queryStr=urldecode($queryStr);
  9931.         $queryStr str_replace('_FSLASH_''/'$queryStr);
  9932.         $filterQryForCriteria "select * from inv_products where 1=1 ";
  9933.         $filterParams = array();
  9934.         if ($request->request->has('sellableOnly') && $request->request->get('sellableOnly') != 0)
  9935.             $filterQryForCriteria .= " and sellable=1";
  9936.         if ($request->request->has('categorizationValues') && $request->request->get('categorizationValues') != '') {
  9937.             foreach ($request->request->get('categorizationValues') as $level => $value) {
  9938.                 if ($value != '' && $value != 0) {
  9939.                     $searchParam GeneralConstant::$fdmSubCatMarkers[$level] . $value '_';
  9940.                     $paramName 'categorizationValue' $level;
  9941.                     $filterQryForCriteria .= " and product_fdm like :" $paramName " ";
  9942.                     $filterParams[$paramName] = '%' $searchParam '%';
  9943.                 }
  9944.             }
  9945.         }
  9946.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9947.             $filterQryForCriteria .= " and sub_category_id = :subCategoryId";
  9948.         else if ($request->request->has('categoryId') && $request->request->get('categoryId') != '')
  9949.             $filterQryForCriteria .= " and category_id = :categoryId";
  9950.         else if ($request->request->has('igId') && $request->request->get('igId') != '')
  9951.             $filterQryForCriteria .= " and ig_id = :igId";
  9952.         if ($request->request->has('brandId') && $request->request->get('brandId') != '')
  9953.             $filterQryForCriteria .= " and brand_company = :brandId";
  9954.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  9955.             $filterParams['subCategoryId'] = (int) $request->request->get('subCategoryId');
  9956.         else if ($request->request->has('categoryId') && $request->request->get('categoryId') != '')
  9957.             $filterParams['categoryId'] = (int) $request->request->get('categoryId');
  9958.         else if ($request->request->has('igId') && $request->request->get('igId') != '')
  9959.             $filterParams['igId'] = (int) $request->request->get('igId');
  9960.         if ($request->request->has('brandId') && $request->request->get('brandId') != '')
  9961.             $filterParams['brandId'] = (int) $request->request->get('brandId');
  9962.         if ($request->request->has('restrictedBrandIds') && $request->request->get('restrictedBrandIds') != []) {
  9963.             $restrictedBrandIds $this->normalizeSqlIntList($request->request->get('restrictedBrandIds'));
  9964.             if (!empty($restrictedBrandIds)) {
  9965.                 $filterQryForCriteria .= " and brand_company in (" $this->buildNamedInClause($restrictedBrandIds'restrictedBrandId'$filterParams) . ")";
  9966.             }
  9967.         }
  9968.         if ($request->request->has('productIds')) {
  9969.             $productIds $this->normalizeSqlIntList($request->request->get('productIds'));
  9970.             if (!empty($productIds)) {
  9971.                 $filterQryForCriteria .= " and id in (" $this->buildNamedInClause($productIds'productId'$filterParams) . ") ";
  9972.             }
  9973.         } else if ($request->request->has('productCode')) {
  9974.             $filterQryForCriteria .= " and product_code like :productCode ";
  9975.             $filterParams['productCode'] = '%' $request->request->get('productCode') . '%';
  9976.         } else if ($queryStr != '') {
  9977.             $filterQryForCriteria .= " and  (product_code like :queryProductCode or `name` like :queryName or model_no like :queryModelNo) ";
  9978.             $filterParams['queryProductCode'] = '%' $queryStr '%';
  9979.             $filterParams['queryName'] = '%' $queryStr '%';
  9980.             $filterParams['queryModelNo'] = '%' $queryStr '%';
  9981.         }
  9982.         if ($filterQryForCriteria != '')
  9983.             $filterQryForCriteria .= "  limit 25";
  9984.         $get_kids_sql $filterQryForCriteria;
  9985. //        if ($request->request->has('productIds'))
  9986. //
  9987. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9988. //        else if ($request->request->has('productCode'))
  9989. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9990. //        else if ($filterQryForCriteria!='')
  9991. //            $get_kids_sql = $filterQryForCriteria;
  9992. //
  9993. //        else
  9994. //               $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";
  9995.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  9996.         $get_kids $stmt;
  9997.         $productId 0;
  9998.         if (!empty($get_kids)) {
  9999.             foreach ($get_kids as $product) {
  10000.                 $pa = array();
  10001.                 $pa['id'] = $product['id'];
  10002.                 $pa['name'] = $product['name'];
  10003.                 $pa['id_name'] = $product['id'] . '. ' $product['name'];
  10004.                 $pa['id_mn'] = $product['id'] . '. ' $product['model_no'];;
  10005.                 $pa['id_name_mn'] = $product['id'] . '. ' $product['name'] . ' ( ' $product['model_no'] . ' )';
  10006.                 $pa['globalId'] = $product['global_id'];
  10007.                 $pa['classSuffix'] = $product['class_suffix'];
  10008.                 $pa['productFdm'] = $product['product_fdm'];
  10009.                 $pa['modelNo'] = $product['model_no'];
  10010.                 $pa['partId'] = $product['part_id'];
  10011.                 $pa['hsCode'] = $product['hs_code'];
  10012.                 $pa['productCode'] = $product['product_code'];
  10013.                 $pa['text'] = $product['name'];
  10014.                 $pa['value'] = $product['id'];
  10015.                 $pa['tac'] = $product['tac'];
  10016.                 $pa['igId'] = $product['ig_id'];
  10017.                 $pa['categoryId'] = $product['category_id'];
  10018.                 $pa['subCategoryId'] = $product['sub_category_id'];
  10019.                 $pa['brandCompany'] = $product['brand_company'];
  10020.                 $pa['sales_price'] = $product['curr_sales_price'];
  10021.                 $pa['purchase_price'] = $product['curr_purchase_price'];
  10022.                 $pa['unit_type'] = $product['unit_type_id'];
  10023.                 $pa['single_weight'] = $product['single_weight'];
  10024.                 $pa['single_weight_variance_type'] = $product['single_weight_variance_type'];
  10025.                 $pa['single_weight_variance_value'] = $product['single_weight_variance_value'];
  10026.                 $pa['weight'] = $product['weight'];
  10027.                 $pa['weight_variance_type'] = $product['weight_variance_type'];
  10028.                 $pa['weight_variance_value'] = $product['weight_variance_value'];
  10029.                 $pa['carton_capacity_count'] = $product['carton_capacity_count'];
  10030.                 $pa['type'] = $product['type'];
  10031.                 $pa['qty'] = $product['qty'];
  10032. //                $pa['alias'] = '';
  10033.                 $pa['alias'] = $product['alias'];
  10034.                 $pa['note'] = $product['note'];
  10035.                 $pa['defaultTaxConfigId'] = $product['default_tax_config_id'] == null $product['default_tax_config_id'];
  10036.                 $pa['defaultPurchaseTaxConfigId'] = $product['default_purchase_tax_config_id'] == null $product['default_purchase_tax_config_id'];
  10037.                 $tax_config_ids json_decode($product['tax_config_ids'], true);
  10038.                 if ($tax_config_ids == null)
  10039.                     $tax_config_ids = [];
  10040.                 $pa['taxConfigIds'] = $tax_config_ids;
  10041.                 $purchase_tax_config_ids json_decode($product['purchase_tax_config_ids'], true);
  10042.                 if ($purchase_tax_config_ids == null)
  10043.                     $purchase_tax_config_ids = [];
  10044.                 $pa['purchaseTaxConfigIds'] = $tax_config_ids;
  10045.                 $inco_terms json_decode($product['inco_terms'], true);
  10046.                 if ($inco_terms == null)
  10047.                     $inco_terms = [];
  10048.                 $pa['incoTerms'] = $inco_terms;
  10049.                 $pa['defaultIncoTerm'] = $product['default_inco_term'] == null $product['default_inco_term'];
  10050.                 $pa['has_serial'] = $product['has_serial'];
  10051.                 $pa['expiry_days'] = $product['expiry_days'];
  10052.                 $pa['image'] = $product['default_image'];
  10053.                 $pa['sales_warranty'] = $product['sales_warranty_months'];;
  10054.                 $pa['defaultColorId'] = $product['default_color_id'];;
  10055.                 $allowedColorIds json_decode($product['colors'], true);
  10056.                 if ($allowedColorIds == null$allowedColorIds = [];
  10057.                 if (!in_array($product['default_color_id'], $allowedColorIds))
  10058.                     $allowedColorIds[] = $product['default_color_id'];
  10059.                 $pa['allowedColorIds'] = $allowedColorIds;;
  10060.                 $data[] = $pa;
  10061.                 $data_by_id[$product['id']] = $pa;
  10062.                 $productId $product['id'];
  10063.             }
  10064.         }
  10065. //        if($request->query->has('returnJson'))
  10066.         {
  10067.             return new JsonResponse(
  10068.                 array(
  10069.                     'success' => true,
  10070. //                    'page_title' => 'Product Details',
  10071. //                    'company_data' => $company_data,
  10072.                     'data' => $data,
  10073.                     'dataById' => $data_by_id,
  10074.                     'productId' => $productId,
  10075.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10076. //                    'exId'=>$id,
  10077. //                'productByCodeData' => $productByCodeData,
  10078. //                'productData' => $productData,
  10079. //                'currInvList' => $currInvList,
  10080. //                'productList' => Inventory::ProductList($em, $companyId),
  10081. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10082. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10083. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10084. //                'unitList' => Inventory::UnitTypeList($em),
  10085. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10086. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10087. //                'warehouseList' => Inventory::WarehouseList($em),
  10088.                 )
  10089.             );
  10090.         }
  10091.     }
  10092.     public function SearchByPopulateQueryAction(Request $request$queryStr '')
  10093.     {
  10094.         $em $this->getDoctrine()->getManager();
  10095.         $companyId $this->getLoggedUserCompanyId($request);
  10096.         $company_data Company::getCompanyData($em$companyId);
  10097.         $data = [];
  10098.         //1st search in products
  10099.         foreach ($request->request->get('queryData', []) as $item) {
  10100.             $dt = array(
  10101.                 'dataId' => $item['dataId'] ?? 0,
  10102.                 'id' => 0,
  10103.                 'fdm' => '',
  10104.             );
  10105.             $qryStrForSearch $item['value'] ?? '';
  10106.             $qryArray explode(','$qryStrForSearch);
  10107.             $checkFields = ['name'];
  10108.             list($qryForSearch$queryParams) = $this->buildTokenizedLikeSearchFragment($checkFields$qryArray'or''populateQueryGroup');
  10109.             //selct item group
  10110.             $igId 0;
  10111.             $catId 0;
  10112.             $parId 0;
  10113.             $brandId 0;
  10114.             $fdmSearchQry = [];
  10115.             $result $em->getConnection()->fetchAllAssociative("select * from inv_item_group where 1=0   " $qryForSearch " limit 1"$queryParams);
  10116.             if (!empty($result)) {
  10117.                 $dt['fdm'] .= ('I' $result[0]['id'] . '_');
  10118.                 $fdmSearchQry[] = ('I' $result[0]['id'] . '_');
  10119.                 $igId $result[0]['id'];
  10120.             }
  10121.             list($qryForSearch$queryParams) = $this->buildTokenizedLikeSearchFragment($checkFields$qryArray'and''populateScopedQueryGroup');
  10122.             //then category
  10123.             $result $em->getConnection()->fetchAllAssociative(
  10124.                 "select * from inv_product_categories where ig_id = :igId " $qryForSearch " limit 1",
  10125.                 array_merge(array('igId' => (int) $igId), $queryParams)
  10126.             );
  10127.             if (!empty($result)) {
  10128.                 $dt['fdm'] .= ('C' $result[0]['id'] . '_');
  10129.                 $fdmSearchQry[] = ('C' $result[0]['id'] . '_');
  10130.                 $catId $result[0]['id'];
  10131.             }
  10132.             //then sub category
  10133.             foreach (GeneralConstant::$fdmSubCatMarkers as $ind => $marker) {
  10134.                 $result $em->getConnection()->fetchAllAssociative(
  10135.                     "select * from inv_product_sub_categories where ig_id = :igId and category_id = :catId and parent_id = :parId " $qryForSearch " limit 1",
  10136.                     array_merge(array(
  10137.                         'igId' => (int) $igId,
  10138.                         'catId' => (int) $catId,
  10139.                         'parId' => (int) $parId,
  10140.                     ), $queryParams)
  10141.                 );
  10142.                 if (!empty($result)) {
  10143.                     $dt['fdm'] .= ($marker $result[0]['id'] . '_');
  10144.                     $fdmSearchQry[] = ($marker $result[0]['id'] . '_');
  10145.                     $parId $result[0]['id'];
  10146.                 }
  10147.             }
  10148.             $result $em->getConnection()->fetchAllAssociative("select * from brand_company where 1=1   " $qryForSearch " limit 1"$queryParams);
  10149.             if (!empty($result)) {
  10150.                 $dt['fdm'] .= ('B' $result[0]['id'] . '_');
  10151.                 $fdmSearchQry[] = ('B' $result[0]['id'] . '_');
  10152.                 $brandId $result[0]['id'];
  10153.             }
  10154.             list($qryForSearch$fdmSearchParams) = $this->buildConjunctiveLikeFragment('product_fdm'$fdmSearchQry'populateFdm');
  10155.             $result $em->getConnection()->fetchAllAssociative("select * from inv_products where 1=1   " $qryForSearch " limit 1"$fdmSearchParams);
  10156.             if (!empty($result)) {
  10157.                 $dt['id'] .= $result[0]['id'];
  10158.             }
  10159.             $data[] = $dt;
  10160.         }
  10161.         return new JsonResponse(
  10162.             array(
  10163.                 'success' => !empty($data) ? true false,
  10164.                 'data' => $data
  10165.             )
  10166.         );
  10167.     }
  10168.     public function addProductByGeneralDataAction(Request $request$queryStr '')
  10169.     {
  10170.         $em $this->getDoctrine()->getManager();
  10171.         $companyId $this->getLoggedUserCompanyId($request);
  10172.         $company_data Company::getCompanyData($em$companyId);
  10173.         $data = [];
  10174.         //1st search in products
  10175.         foreach ($request->request->get('dataList', []) as $item) {
  10176. //            $item=Inventory::GetImmutableKeysForProductSyncFromCentralToLocal();
  10177.             //add each part and if not exists, add it
  10178.             $currProductInfo = array(
  10179.                 'dataId' => $item['dataId'] ?? 0,
  10180.                 'id' => 0,
  10181.                 'igId' => 0,
  10182.                 'categoryId' => 0,
  10183.                 'subCategoryIds' => [
  10184.                     => 0,
  10185.                 ],
  10186.                 'fdm' => '',
  10187.             );
  10188.             //iten group
  10189.             if (isset($item['ItemGroup'])) {
  10190.                 $result $em->getConnection()->fetchAllAssociative(
  10191.                     "select * from inv_item_group where id = :itemGroupId or name like :itemGroupName limit 1",
  10192.                     array(
  10193.                         'itemGroupId' => (int) ($item['ItemGroup']['Id'] ?? 0),
  10194.                         'itemGroupName' => (string) ($item['ItemGroup']['Name'] ?? 0),
  10195.                     )
  10196.                 );
  10197.                 if (!empty($result)) {
  10198.                     $currProductInfo['igId'] = $result[0]['id'];
  10199.                 } else {
  10200.                     Inventory::CreateItemGroup($em1);
  10201.                 }
  10202.             }
  10203.             $dt = array(
  10204.                 'dataId' => $item['dataId'] ?? 0,
  10205.                 'id' => 0,
  10206.                 'fdm' => '',
  10207.             );
  10208.             $qryStrForSearch $item['value'] ?? '';
  10209.             $qryArray explode(','$qryStrForSearch);
  10210.             $checkFields = ['name'];
  10211.             list($qryForSearch$queryParams) = $this->buildFlatLikeSearchFragment($checkFields$qryArray'and''generalDataQuery');
  10212.             //selct item group
  10213.             $igId 0;
  10214.             $catId 0;
  10215.             $parId 0;
  10216.             $brandId 0;
  10217.             $fdmSearchQry = [];
  10218.             $result $em->getConnection()->fetchAllAssociative("select * from inv_item_group where 1=1 " $qryForSearch " limit 1"$queryParams);
  10219.             if (!empty($result)) {
  10220.                 $dt['fdm'] .= ('I' $result[0]['id'] . '_');
  10221.                 $fdmSearchQry[] = ('I' $result[0]['id'] . '_');
  10222.                 $igId $result[0]['id'];
  10223.             }
  10224.             //then category
  10225.             $result $em->getConnection()->fetchAllAssociative(
  10226.                 "select * from inv_product_categories where ig_id = :igId " $qryForSearch " limit 1",
  10227.                 array_merge(array('igId' => (int) $igId), $queryParams)
  10228.             );
  10229.             if (!empty($result)) {
  10230.                 $dt['fdm'] .= ('C' $result[0]['id'] . '_');
  10231.                 $fdmSearchQry[] = ('C' $result[0]['id'] . '_');
  10232.                 $catId $result[0]['id'];
  10233.             }
  10234.             //then sub category
  10235.             foreach (GeneralConstant::$fdmSubCatMarkers as $ind => $marker) {
  10236.                 $result $em->getConnection()->fetchAllAssociative(
  10237.                     "select * from inv_product_sub_categories where ig_id = :igId and category_id = :catId and parent_id = :parId " $qryForSearch " limit 1",
  10238.                     array_merge(array(
  10239.                         'igId' => (int) $igId,
  10240.                         'catId' => (int) $catId,
  10241.                         'parId' => (int) $parId,
  10242.                     ), $queryParams)
  10243.                 );
  10244.                 if (!empty($result)) {
  10245.                     $dt['fdm'] .= ($marker $result[0]['id'] . '_');
  10246.                     $fdmSearchQry[] = ($marker $result[0]['id'] . '_');
  10247.                     $parId $result[0]['id'];
  10248.                 }
  10249.             }
  10250.             $result $em->getConnection()->fetchAllAssociative("select * from brand_company where 1=1 " $qryForSearch " limit 1"$queryParams);
  10251.             if (!empty($result)) {
  10252.                 $dt['fdm'] .= ('B' $result[0]['id'] . '_');
  10253.                 $fdmSearchQry[] = ('B' $result[0]['id'] . '_');
  10254.                 $brandId $result[0]['id'];
  10255.             }
  10256.             list($qryForSearch$fdmSearchParams) = $this->buildConjunctiveLikeFragment('product_fdm'$fdmSearchQry'generalDataFdm');
  10257.             $result $em->getConnection()->fetchAllAssociative("select * from inv_products where 1=1 " $qryForSearch " limit 1"$fdmSearchParams);
  10258.             if (!empty($result)) {
  10259.                 $dt['id'] .= $result[0]['id'];
  10260.             }
  10261.             $data[] = $dt;
  10262.         }
  10263.         return new JsonResponse(
  10264.             array(
  10265.                 'success' => empty($data) ? true false,
  10266.                 'data' => $data
  10267.             )
  10268.         );
  10269.     }
  10270.     public function labelFormatSelectAjaxAction(Request $request$queryStr '')
  10271.     {
  10272.         $em $this->getDoctrine()->getManager();
  10273.         $companyId $this->getLoggedUserCompanyId($request);
  10274.         $company_data Company::getCompanyData($em$companyId);
  10275.         $data = [];
  10276.         $data_by_id = [];
  10277.         $html '';
  10278.         $productByCodeData = [];
  10279.         if ($queryStr == '_EMPTY_')
  10280.             $queryStr '';
  10281.         if ($request->request->has('query') && $queryStr == '')
  10282.             $queryStr $request->request->get('queryStr');
  10283.         if ($queryStr == '_EMPTY_')
  10284.             $queryStr '';
  10285.         $filterQryForCriteria "select * from label_format where company_id = :companyId ";
  10286.         $filterParams = array(
  10287.             'companyId' => (int) $companyId,
  10288.         );
  10289.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  10290.             $filterQryForCriteria .= " and label_type = :dataType";
  10291.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  10292.             $filterQryForCriteria .= " and format_id = :formatId";
  10293.         else if ($queryStr != '') {
  10294.             $filterQryForCriteria .= " and (`name` like :labelNameQuery or `format_code` like :labelCodeQuery) ";
  10295.             $filterParams['labelNameQuery'] = '%' $queryStr '%';
  10296.             $filterParams['labelCodeQuery'] = '%' $queryStr '%';
  10297.         }
  10298.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  10299.             $filterParams['dataType'] = (int) $request->request->get('dataType');
  10300.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  10301.             $filterParams['formatId'] = (int) $request->request->get('formatId');
  10302.         if ($filterQryForCriteria != '')
  10303.             $filterQryForCriteria .= "  limit 25";
  10304.         $get_kids_sql $filterQryForCriteria;
  10305. //        if ($request->request->has('productIds'))
  10306. //
  10307. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  10308. //        else if ($request->request->has('productCode'))
  10309. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  10310. //        else if ($filterQryForCriteria!='')
  10311. //            $get_kids_sql = $filterQryForCriteria;
  10312. //
  10313. //        else
  10314. //               $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";
  10315.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  10316.         $get_kids $stmt;
  10317.         $productId 0;
  10318.         if (!empty($get_kids)) {
  10319.             foreach ($get_kids as $product) {
  10320.                 $pa = array();
  10321.                 $pa['id'] = $product['format_id'];
  10322.                 $pa['name'] = $product['name'];
  10323.                 $pa['format_code'] = $product['format_code'] . '. ' $product['name'];
  10324.                 $pa['id_code_name'] = $product['format_id'] . '. ' $product['format_code'] . ' - ' $product['name'] . ' ';
  10325.                 $pa['text'] = $product['name'];
  10326.                 $pa['value'] = $product['format_id'];
  10327.                 $data[] = $pa;
  10328.                 $data_by_id[$product['format_id']] = $pa;
  10329.                 $productId $product['format_id'];
  10330.             }
  10331.         }
  10332. //        if($request->query->has('returnJson'))
  10333.         {
  10334.             return new JsonResponse(
  10335.                 array(
  10336.                     'success' => true,
  10337. //                    'page_title' => 'Product Details',
  10338. //                    'company_data' => $company_data,
  10339.                     'data' => $data,
  10340.                     'dataById' => $data_by_id,
  10341.                     'productId' => $productId,
  10342.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10343. //                    'exId'=>$id,
  10344. //                'productByCodeData' => $productByCodeData,
  10345. //                'productData' => $productData,
  10346. //                'currInvList' => $currInvList,
  10347. //                'productList' => Inventory::ProductList($em, $companyId),
  10348. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10349. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10350. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10351. //                'unitList' => Inventory::UnitTypeList($em),
  10352. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10353. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10354. //                'warehouseList' => Inventory::WarehouseList($em),
  10355.                 )
  10356.             );
  10357.         }
  10358.     }
  10359.     public function CategoryListSelectAjaxAction(Request $request$queryStr '')
  10360.     {
  10361.         $em $this->getDoctrine()->getManager();
  10362.         $companyId $this->getLoggedUserCompanyId($request);
  10363.         $company_data Company::getCompanyData($em$companyId);
  10364.         $data = [];
  10365.         $data_by_id = [];
  10366.         $html '';
  10367.         $productByCodeData = [];
  10368.         if ($queryStr == '_EMPTY_')
  10369.             $queryStr '';
  10370.         if ($request->request->has('query') && $queryStr == '')
  10371.             $queryStr $request->request->get('queryStr');
  10372.         if ($queryStr == '_EMPTY_')
  10373.             $queryStr '';
  10374.         $filterQryForCriteria "select * from inv_product_categories where company_id = :companyId ";
  10375.         $filterParams = array(
  10376.             'companyId' => (int) $companyId,
  10377.             'categoryNameQuery' => '%' $queryStr '%',
  10378.         );
  10379.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10380.             $filterQryForCriteria .= " and ig_id = :igId";
  10381.         $filterQryForCriteria .= " and (`name` like :categoryNameQuery) ";
  10382.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10383.             $filterParams['igId'] = (int) $request->request->get('igId');
  10384.         if ($filterQryForCriteria != '')
  10385.             $filterQryForCriteria .= "  limit 25";
  10386.         $get_kids_sql $filterQryForCriteria;
  10387. //        if ($request->request->has('productIds'))
  10388. //
  10389. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  10390. //        else if ($request->request->has('productCode'))
  10391. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  10392. //        else if ($filterQryForCriteria!='')
  10393. //            $get_kids_sql = $filterQryForCriteria;
  10394. //
  10395. //        else
  10396. //               $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";
  10397.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  10398.         $get_kids $stmt;
  10399.         $productId 0;
  10400.         if (!empty($get_kids)) {
  10401.             foreach ($get_kids as $product) {
  10402.                 $pa = array();
  10403.                 $pa['id'] = $product['id'];
  10404.                 $pa['name'] = $product['name'];
  10405.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  10406.                 $pa['globalId'] = $product['global_id'];
  10407.                 $pa['text'] = $product['name'];
  10408.                 $pa['value'] = $product['id'];
  10409.                 $pa['igId'] = $product['ig_id'];
  10410. //                $pa['categoryId'] = $product['category_id'];
  10411. //                $pa['subCategoryId'] = $product['sub_category_id'];
  10412.                 $data[] = $pa;
  10413.                 $data_by_id[$product['id']] = $pa;
  10414.                 $productId $product['id'];
  10415.             }
  10416.         }
  10417. //        if($request->query->has('returnJson'))
  10418.         {
  10419.             return new JsonResponse(
  10420.                 array(
  10421.                     'success' => true,
  10422. //                    'page_title' => 'Product Details',
  10423. //                    'company_data' => $company_data,
  10424.                     'data' => $data,
  10425.                     'dataById' => $data_by_id,
  10426.                     'productId' => $productId,
  10427.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10428. //                    'exId'=>$id,
  10429. //                'productByCodeData' => $productByCodeData,
  10430. //                'productData' => $productData,
  10431. //                'currInvList' => $currInvList,
  10432. //                'productList' => Inventory::ProductList($em, $companyId),
  10433. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10434. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10435. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10436. //                'unitList' => Inventory::UnitTypeList($em),
  10437. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10438. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10439. //                'warehouseList' => Inventory::WarehouseList($em),
  10440.                 )
  10441.             );
  10442.         }
  10443.     }
  10444.     public function SubCategoryListSelectAjaxAction(Request $request$queryStr '')
  10445.     {
  10446.         $em $this->getDoctrine()->getManager();
  10447.         $companyId $this->getLoggedUserCompanyId($request);
  10448.         $company_data Company::getCompanyData($em$companyId);
  10449.         $data = [];
  10450.         $data_by_id = [];
  10451.         $html '';
  10452.         $productByCodeData = [];
  10453.         if ($queryStr == '_EMPTY_')
  10454.             $queryStr '';
  10455.         if ($request->request->has('query') && $queryStr == '')
  10456.             $queryStr $request->request->get('queryStr');
  10457.         if ($queryStr == '_EMPTY_')
  10458.             $queryStr '';
  10459.         $filterQryForCriteria "select * from inv_product_sub_categories where company_id = :companyId ";
  10460.         $filterParams = array(
  10461.             'companyId' => (int) $companyId,
  10462.             'subCategoryNameQuery' => '%' $queryStr '%',
  10463.         );
  10464.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  10465.             $filterQryForCriteria .= " and sub_category_id = :subCategoryId";
  10466.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  10467.             $filterQryForCriteria .= " and category_id = :categoryId";
  10468.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10469.             $filterQryForCriteria .= " and ig_id = :igId";
  10470.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  10471.             if ($request->request->get('parentId') != 0)
  10472.                 $filterQryForCriteria .= " and parent_id = :parentId";
  10473.             else
  10474.                 $filterQryForCriteria .= " and ( parent_id =0 or parent_id is null ) ";
  10475.         if ($request->request->has('level') && $request->request->get('level') != '')
  10476.             if ($request->request->get('level') != 0)
  10477.                 $filterQryForCriteria .= " and level = :level";
  10478.             else
  10479.                 $filterQryForCriteria .= " and ( level =0 or level is null) ";
  10480.         $filterQryForCriteria .= " and (`name` like :subCategoryNameQuery) ";
  10481.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  10482.             $filterParams['subCategoryId'] = (int) $request->request->get('subCategoryId');
  10483.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  10484.             $filterParams['categoryId'] = (int) $request->request->get('categoryId');
  10485.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  10486.             $filterParams['igId'] = (int) $request->request->get('igId');
  10487.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  10488.             if ($request->request->get('parentId') != 0)
  10489.                 $filterParams['parentId'] = (int) $request->request->get('parentId');
  10490.         if ($request->request->has('level') && $request->request->get('level') != '')
  10491.             if ($request->request->get('level') != 0)
  10492.                 $filterParams['level'] = (int) $request->request->get('level');
  10493.         if ($filterQryForCriteria != '')
  10494.             $filterQryForCriteria .= "  limit 25";
  10495.         $get_kids_sql $filterQryForCriteria;
  10496. //        if ($request->request->has('productIds'))
  10497. //
  10498. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  10499. //        else if ($request->request->has('productCode'))
  10500. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  10501. //        else if ($filterQryForCriteria!='')
  10502. //            $get_kids_sql = $filterQryForCriteria;
  10503. //
  10504. //        else
  10505. //               $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";
  10506.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql$filterParams);
  10507.         $get_kids $stmt;
  10508.         $productId 0;
  10509.         if (!empty($get_kids)) {
  10510.             foreach ($get_kids as $product) {
  10511.                 $pa = array();
  10512.                 $pa['id'] = $product['id'];
  10513.                 $pa['name'] = $product['name'];
  10514.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  10515.                 $pa['globalId'] = $product['global_id'];
  10516.                 $pa['parentId'] = $product['parent_id'];
  10517.                 $pa['text'] = $product['name'];
  10518.                 $pa['value'] = $product['id'];
  10519.                 $pa['igId'] = $product['ig_id'];
  10520.                 $pa['categoryId'] = $product['category_id'];
  10521. //                $pa['subCategoryId'] = $product['sub_category_id'];
  10522.                 $data[] = $pa;
  10523.                 $data_by_id[$product['id']] = $pa;
  10524.                 $productId $product['id'];
  10525.             }
  10526.         }
  10527. //        if($request->query->has('returnJson'))
  10528.         {
  10529.             return new JsonResponse(
  10530.                 array(
  10531.                     'success' => true,
  10532. //                    'page_title' => 'Product Details',
  10533. //                    'company_data' => $company_data,
  10534.                     'data' => $data,
  10535.                     'dataById' => $data_by_id,
  10536.                     'productId' => $productId,
  10537.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  10538. //                    'exId'=>$id,
  10539. //                'productByCodeData' => $productByCodeData,
  10540. //                'productData' => $productData,
  10541. //                'currInvList' => $currInvList,
  10542. //                'productList' => Inventory::ProductList($em, $companyId),
  10543. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10544. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10545. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10546. //                'unitList' => Inventory::UnitTypeList($em),
  10547. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10548. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10549. //                'warehouseList' => Inventory::WarehouseList($em),
  10550.                 )
  10551.             );
  10552.         }
  10553.     }
  10554.     public
  10555.     function ProductByCodeViewAction(Request $request$id 0)
  10556.     {
  10557.         $em $this->getDoctrine()->getManager();
  10558.         $companyId $this->getLoggedUserCompanyId($request);
  10559.         $company_data Company::getCompanyData($em$companyId);
  10560.         $data = [];
  10561.         $html '';
  10562.         $productByCodeData = [];
  10563.         if ($id != 0) {
  10564.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10565.                 ->findOneBy(
  10566.                     array(
  10567.                         'productByCodeId' => $id
  10568.                     )
  10569.                 );
  10570.         } else {
  10571.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10572.                 ->findOneBy(
  10573.                     array(
  10574. //                        'productByCodeId' => $id,
  10575.                         'CompanyId' => $companyId
  10576.                     ), array(
  10577.                         'productByCodeId' => 'DESC'
  10578.                     )
  10579.                 );
  10580.             if ($productByCodeData)
  10581.                 $id $productByCodeData->getProductByCodeId();
  10582.         }
  10583.         if ($id != 0) {
  10584.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  10585.                 ->findOneBy(
  10586.                     array(
  10587.                         'id' => $productByCodeData->getProductId()
  10588.                     )
  10589.                 );
  10590.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  10591.                 ->findBy(
  10592.                     array(
  10593.                         'productId' => $id
  10594.                     )
  10595.                 );
  10596.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  10597.                 array(
  10598.                     'page_title' => 'Product Details',
  10599.                     'company_data' => $company_data,
  10600.                     'productByCodeData' => $productByCodeData,
  10601.                     'productData' => $productData,
  10602.                     'currInvList' => $currInvList,
  10603.                     'exId' => $id,
  10604.                     'clientList' => Client::GetExistingClientList($em$companyId),
  10605.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  10606.                     'productList' => Inventory::ProductList($em$companyId),
  10607.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10608.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10609.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10610.                     'unitList' => Inventory::UnitTypeList($em),
  10611.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10612.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10613.                     'warehouseList' => Inventory::WarehouseList($em),
  10614.                 )
  10615.             );
  10616.         } else {
  10617.             $html $this->renderView('@Inventory/pages/views/product_by_code_snippet.html.twig',
  10618.                 array(
  10619.                     'exId' => $id,
  10620.                 )
  10621.             );
  10622.         }
  10623.         if ($request->query->has('returnJson')) {
  10624.             return new JsonResponse(
  10625.                 array(
  10626.                     'success' => true,
  10627.                     'page_title' => 'Product Details',
  10628.                     'company_data' => $company_data,
  10629.                     'renderedHtml' => $html,
  10630.                     'exId' => $id,
  10631. //                'productByCodeData' => $productByCodeData,
  10632. //                'productData' => $productData,
  10633. //                'currInvList' => $currInvList,
  10634. //                'productList' => Inventory::ProductList($em, $companyId),
  10635. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10636. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10637. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10638. //                'unitList' => Inventory::UnitTypeList($em),
  10639. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10640. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10641. //                'warehouseList' => Inventory::WarehouseList($em),
  10642.                 )
  10643.             );
  10644.         } else {
  10645. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10646. //                ->findBy(
  10647. //                    array(
  10648. ////                        'productByCodeId' => $id,
  10649. //                    'CompanyId'=>$companyId
  10650. //                    )
  10651. //                );
  10652.             $productByCodeList = []; //called by ajax
  10653.             return $this->render('@Inventory/pages/views/product_by_code_view.html.twig',
  10654.                 array(
  10655.                     'page_title' => 'Product Details',
  10656.                     'company_data' => $company_data,
  10657.                     'renderedHtml' => $html,
  10658.                     'exId' => $id,
  10659.                     'productByCodeList' => $productByCodeList,
  10660. //                'productByCodeData' => $productByCodeData,
  10661. //                'productData' => $productData,
  10662. //                'currInvList' => $currInvList,
  10663. //                'productList' => Inventory::ProductList($em, $companyId),
  10664. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10665. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10666. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10667. //                'unitList' => Inventory::UnitTypeList($em),
  10668. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10669. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10670. //                'warehouseList' => Inventory::WarehouseList($em),
  10671.                 )
  10672.             );
  10673.         }
  10674.     }
  10675.     public
  10676.     function ConsumptionSettingsAction(Request $request$id)
  10677.     {
  10678.         $cc_id '';
  10679.         $cc_name '';
  10680.         $em $this->getDoctrine()->getManager();
  10681.         $companyId $this->getLoggedUserCompanyId($request);
  10682.         $consumptionTypeId 0;
  10683.         if ($request->isMethod('POST')) {
  10684.             $new_cc = [];
  10685.             if ($request->request->get('consumptionTypeId') != '' && $request->request->get('consumptionTypeId') != 0) {
  10686.                 $em $this->getDoctrine()->getManager();
  10687.                 $new_cc $this->getDoctrine()
  10688.                     ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  10689.                     ->findOneBy(
  10690.                         array(
  10691.                             'consumptionTypeId' => $request->request->get('consumptionTypeId'),
  10692.                         )
  10693.                     );
  10694.                 $new_cc->setName($request->request->get('name'));
  10695.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  10696.                 $new_cc->setCompanyId($companyId);
  10697.                 $em->flush();
  10698.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  10699.                 $this->addFlash(
  10700.                     'success',
  10701.                     'Consumption Information Updated'
  10702.                 );
  10703.             } else {
  10704.                 $new_cc = new ConsumptionType();
  10705.                 $new_cc->setName($request->request->get('name'));
  10706.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  10707.                 $new_cc->setCompanyId($companyId);
  10708.                 $em->persist($new_cc);
  10709.                 $em->flush();
  10710.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  10711.                 $em->flush();
  10712.                 $this->addFlash(
  10713.                     'success',
  10714.                     'New Consumption Type Added'
  10715.                 );
  10716.             }
  10717.         }
  10718.         $extData = [];
  10719.         if ($id != 0) {
  10720.             $extData $this->getDoctrine()
  10721.                 ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  10722.                 ->findOneBy(
  10723.                     array(
  10724.                         'consumptionTypeId' => $id
  10725.                     )
  10726.                 );
  10727. //            $cc_data_list = [];
  10728. //            foreach ($cc_data as $value) {
  10729. //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  10730. //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  10731. //
  10732. //                if ($value->getSupplierCategoryId() == $id) {
  10733. //                    $cc_id = $value->getSupplierCategoryId();
  10734. //                    $cc_name = $value->getName();
  10735. //                }
  10736. //            }
  10737.         }
  10738.         return $this->render('@Inventory/pages/input_forms/consumption_settings.html.twig',
  10739.             array(
  10740.                 'page_title' => 'Consumption Settings',
  10741.                 'consumptionTypeList' => $this->getDoctrine()
  10742.                     ->getRepository('ApplicationBundle\\Entity\\ConsumptionType')
  10743.                     ->findBy(
  10744.                         array(
  10745.                             'CompanyId' => $companyId
  10746.                         )
  10747.                     ),
  10748.                 'extData' => $extData,
  10749.                 'headList' => Accounts::getParentLedgerHeads($em),
  10750. //                'countryList'=>SalesOrderM::Co
  10751.             )
  10752.         );
  10753.     }
  10754.     public
  10755.     function ProductByCodeCheckAssignPrintAction(Request $request$id 0)
  10756.     {
  10757.         $em $this->getDoctrine()->getManager();
  10758.         $companyId $this->getLoggedUserCompanyId($request);
  10759.         $company_data Company::getCompanyData($em$companyId);
  10760.         $data = [];
  10761.         $html '';
  10762.         $productByCodeData = [];
  10763.         $productDataWeightPackageGm '';
  10764.         $productDataWeightVarianceValue 0;
  10765.         $productDataWeightVarianceType 0;
  10766.         $productByCodeDataObj = [];
  10767.         $dr_id 0;//for dr_id
  10768.         $skipRenderData 0;
  10769.         if ($request->query->has('skipRenderData'))
  10770.             $skipRenderData $request->query->get('skipRenderData');
  10771.         if ($id != 0) {
  10772.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10773.                 ->findOneBy(
  10774.                     array(
  10775.                         'productByCodeId' => $id
  10776.                     )
  10777.                 );
  10778.         } else {
  10779.             if ($request->query->has('scanCode')) {
  10780.                 $query $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10781.                     ->createQueryBuilder('p');
  10782.                 if ($request->query->has('assigned')) {
  10783.                     $query->where('p.assigned > :av')
  10784.                         ->setParameter('av'$request->query->get('assigned'));
  10785.                 } else
  10786.                     $query->where("1=0");
  10787.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  10788.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  10789.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  10790.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  10791.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  10792.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  10793.                 $query->setMaxResults(1);
  10794.                 $results $query->getQuery()->getResult();
  10795.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  10796.             } else
  10797.                 $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10798.                     ->findOneBy(
  10799.                         array(
  10800. //                        'productByCodeId' => $id,
  10801.                             'CompanyId' => $companyId
  10802.                         ), array(
  10803.                             'productByCodeId' => 'DESC'
  10804.                         )
  10805.                     );
  10806.             if ($productByCodeData)
  10807.                 $id $productByCodeData->getProductByCodeId();
  10808.         }
  10809.         if ($id != 0) {
  10810.             $productByCodeDataObj = array(
  10811.                 'salesCode' => $productByCodeData->getSalesCode(),
  10812.                 'sales_code' => $productByCodeData->getSalesCode(),
  10813.                 'sn' => $productByCodeData->getSerialNo(),
  10814.                 'serialNo' => $productByCodeData->getSerialNo(),
  10815.                 'imei1' => $productByCodeData->getImei1(),
  10816.                 'imei2' => $productByCodeData->getImei2(),
  10817.                 'soId' => $productByCodeData->getSalesOrderId(),
  10818.                 'poId' => $productByCodeData->getPurchaseOrderId(),
  10819.                 'irrId' => $productByCodeData->getIrrId(),
  10820.                 'productId' => $productByCodeData->getProductId(),
  10821.                 'productByCodeId' => $productByCodeData->getProductByCodeId(),
  10822.                 'warehouseId' => $productByCodeData->getWarehouseId(),
  10823.                 'warehouseActionId' => $productByCodeData->getWarehouseActionId(),
  10824.                 'stId' => $productByCodeData->getStockTransferId(),
  10825.                 'srId' => $productByCodeData->getStockReceivedNoteId(),
  10826.                 'scmpId' => $productByCodeData->getStockConsumptionNoteId(),
  10827.                 'clientId' => $productByCodeData->getClientId(),
  10828.                 'supplierId' => $productByCodeData->getSupplierId(),
  10829.                 'drId' => $productByCodeData->getDeliveryReceiptId(),
  10830.                 'consumerName' => $productByCodeData->getConsumerName(),
  10831.                 'drItemData' => [],
  10832. //                'salesCodes' => $productByCodeData->getDeliveryReceiptId(),
  10833.             );
  10834.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  10835.                 ->findOneBy(
  10836.                     array(
  10837.                         'id' => $productByCodeData->getProductId()
  10838.                     )
  10839.                 );
  10840.             if ($productByCodeData->getProductionId() != null) {
  10841.                 $productionDataHere $em->getRepository('ApplicationBundle\\Entity\\Production')
  10842.                     ->findOneBy(
  10843.                         array(
  10844.                             'productionId' => $productByCodeData->getProductionId()
  10845.                         )
  10846.                     );
  10847.                 if ($productionDataHere) {
  10848.                     $productDataWeightPackageGm $productionDataHere->getPackageWeight();
  10849.                     $productDataWeightVarianceValue $productionDataHere->getPackageWeightVarianceValue();
  10850.                     $productDataWeightVarianceType $productionDataHere->getPackageWeightVarianceType();
  10851.                 }
  10852.             } else {
  10853.                 if ($productData) {
  10854.                     $productDataWeightPackageGm $productData->getWeight();
  10855.                     $productDataWeightVarianceValue $productData->getWeightVarianceValue();
  10856.                     $productDataWeightVarianceType $productData->getWeightVarianceType();
  10857.                 }
  10858.             }
  10859.             if ($productData) {
  10860.                 $productByCodeDataObj['unitTypeId'] = $productData->getUnitTypeId();
  10861.                 $productByCodeDataObj['purchasePrice'] = $productData->getPurchasePrice();
  10862.                 $productByCodeDataObj['productFdm'] = $productData->getProductFdm();
  10863.                 $productByCodeDataObj['productName'] = $productData->getName();
  10864.                 if ($request->request->has('forSalesReturn') || $request->query->has('forSalesReturn')) {
  10865.                     $QD $this->getDoctrine()
  10866.                         ->getRepository('ApplicationBundle\\Entity\\DeliveryReceiptItem')
  10867.                         ->findOneBy(
  10868.                             array(
  10869.                                 'deliveryReceiptId' => $productByCodeData->getDeliveryReceiptId(),
  10870.                                 'productId' => $productByCodeData->getProductId(),
  10871.                             )
  10872.                         );
  10873. //            if($request->request->get('wareHouseId')!='')
  10874.                     if ($QD) {
  10875.                         $new_pid $QD->getProductId();
  10876.                         $sales_code_range = [];
  10877.                         if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  10878.                             $sales_code_range json_decode($QD->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  10879.                         } else {
  10880.                             $max_int_length strlen((string)PHP_INT_MAX) - 1;
  10881.                             $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$QD->getSalesCodeRange());
  10882.                             $sales_code_range json_decode($json_without_bigintstrue);
  10883.                         }
  10884.                         $p_data = array(
  10885.                             'details_id' => $QD->getId(),
  10886.                             'productId' => $new_pid,
  10887.                             'dr_id' => $productByCodeData->getDeliveryReceiptId(),
  10888.                             'product_name' => $productData->getName(),
  10889.                             'qty' => $QD->getQty(),
  10890.                             'delivered' => $QD->getDelivered(),
  10891.                             'unitTypeId' => $QD->getUnitTypeId(),
  10892.                             'deliverable' => $QD->getDeliverable(),
  10893.                             'balance' => $QD->getBalance(),
  10894.                             'salesCodeRangeStr' => $QD->getSalesCodeRange(),
  10895.                             'salesCodeRange' => $sales_code_range,
  10896.                             'sales_codes' => $sales_code_range,
  10897.                             'sales_price' => $QD->getPrice(),
  10898.                             'purchase_price' => $QD->getCurrentPurchasePrice()
  10899. //                        'delivered'=>$product->getDelivered(),
  10900.                         );
  10901.                         $productByCodeDataObj['drItemData'][] = $p_data;
  10902.                     }
  10903.                 }
  10904.             }
  10905.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  10906.                 ->findBy(
  10907.                     array(
  10908.                         'productId' => $id
  10909.                     )
  10910.                 );
  10911.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  10912.                 array(
  10913.                     'page_title' => 'Details',
  10914.                     'company_data' => $company_data,
  10915.                     'productByCodeData' => $productByCodeData,
  10916.                     'productByCodeDataObj' => $productByCodeDataObj,
  10917.                     'productData' => $productData,
  10918.                     'currInvList' => $currInvList,
  10919.                     'productDataWeightPackageGm' => $productDataWeightPackageGm,
  10920.                     'productDataWeightVarianceValue' => $productDataWeightVarianceValue,
  10921.                     'productDataWeightVarianceType' => $productDataWeightVarianceType,
  10922.                     'exId' => $id,
  10923.                     'clientList' => Client::GetExistingClientList($em$companyId),
  10924.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  10925.                     'productList' => Inventory::ProductList($em$companyId),
  10926.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  10927.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  10928.                     'igList' => Inventory::ItemGroupList($em$companyId),
  10929.                     'unitList' => Inventory::UnitTypeList($em),
  10930.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10931.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  10932.                     'warehouseList' => Inventory::WarehouseList($em),
  10933.                 )
  10934.             ));
  10935.         } else {
  10936.             $html = ($skipRenderData == '' $this->renderView('@Inventory/pages/views/product_by_code_for_print_check_snippet.html.twig',
  10937.                 array(
  10938.                     'exId' => $id,
  10939.                 )
  10940.             ));
  10941.         }
  10942.         if ($request->query->has('returnJson')) {
  10943.             return new JsonResponse(
  10944.                 array(
  10945.                     'success' => true,
  10946.                     'page_title' => 'Product Details',
  10947.                     'company_data' => $company_data,
  10948.                     'renderedHtml' => $html,
  10949.                     'exId' => $id,
  10950.                     'productByCodeDataObj' => $productByCodeDataObj,
  10951. //                'productData' => $productData,
  10952. //                'currInvList' => $currInvList,
  10953. //                'productList' => Inventory::ProductList($em, $companyId),
  10954. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10955. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10956. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10957. //                'unitList' => Inventory::UnitTypeList($em),
  10958. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10959. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10960. //                'warehouseList' => Inventory::WarehouseList($em),
  10961.                 )
  10962.             );
  10963.         } else {
  10964. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  10965. //                ->findBy(
  10966. //                    array(
  10967. ////                        'productByCodeId' => $id,
  10968. //                    'CompanyId'=>$companyId
  10969. //                    )
  10970. //                );
  10971.             $productByCodeList = []; //called by ajax
  10972.             return $this->render('@Inventory/pages/views/product_by_code_assign_check_print.html.twig',
  10973.                 array(
  10974.                     'page_title' => 'Serial Manager',
  10975.                     'company_data' => $company_data,
  10976.                     'renderedHtml' => $html,
  10977.                     'exId' => $id,
  10978.                     'productByCodeList' => $productByCodeList,
  10979.                     'productByCodeDataObj' => $productByCodeDataObj,
  10980. //                'productByCodeData' => $productByCodeData,
  10981. //                'productData' => $productData,
  10982. //                'currInvList' => $currInvList,
  10983. //                'productList' => Inventory::ProductList($em, $companyId),
  10984. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  10985. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  10986. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  10987. //                'unitList' => Inventory::UnitTypeList($em),
  10988. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  10989. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  10990. //                'warehouseList' => Inventory::WarehouseList($em),
  10991.                 )
  10992.             );
  10993.         }
  10994.     }
  10995.     public
  10996.     function TestProductByCodeCheckAssignPrintAction(Request $request$id 0)
  10997.     {
  10998.         $em $this->getDoctrine()->getManager();
  10999.         $companyId $this->getLoggedUserCompanyId($request);
  11000.         $company_data Company::getCompanyData($em$companyId);
  11001.         $data = [];
  11002.         $html '';
  11003.         $productByCodeData = [];
  11004.         $productByCodeDataObj = [];
  11005.         if ($id != 0) {
  11006.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11007.                 ->findOneBy(
  11008.                     array(
  11009.                         'productByCodeId' => $id
  11010.                     )
  11011.                 );
  11012.         } else {
  11013.             if ($request->query->has('scanCode')) {
  11014.                 $query $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11015.                     ->createQueryBuilder('p');
  11016.                 if ($request->query->has('assigned')) {
  11017.                     $query->where('p.assigned > :av')
  11018.                         ->setParameter('av'$request->query->get('assigned'));
  11019.                 } else
  11020.                     $query->where("1=0");
  11021.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  11022.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  11023.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  11024.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  11025.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  11026.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  11027.                 $query->setMaxResults(1);
  11028.                 $results $query->getQuery()->getResult();
  11029.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  11030.             } else
  11031.                 $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11032.                     ->findOneBy(
  11033.                         array(
  11034. //                        'productByCodeId' => $id,
  11035.                             'CompanyId' => $companyId
  11036.                         ), array(
  11037.                             'productByCodeId' => 'DESC'
  11038.                         )
  11039.                     );
  11040.             if ($productByCodeData)
  11041.                 $id $productByCodeData->getProductByCodeId();
  11042.         }
  11043.         if ($id != 0) {
  11044.             $productByCodeDataObj = array(
  11045.                 'sn' => $productByCodeData->getSalesCode(),
  11046.                 'imei1' => $productByCodeData->getImei1(),
  11047.                 'imei2' => $productByCodeData->getImei2(),
  11048.                 'colorId' => $productByCodeData->getColorId(),
  11049.             );
  11050.             $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  11051.                 ->findOneBy(
  11052.                     array(
  11053.                         'id' => $productByCodeData->getProductId()
  11054.                     )
  11055.                 );
  11056.             $currInvList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')
  11057.                 ->findBy(
  11058.                     array(
  11059.                         'productId' => $id
  11060.                     )
  11061.                 );
  11062.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  11063.                 array(
  11064.                     'page_title' => 'Details',
  11065.                     'company_data' => $company_data,
  11066.                     'productByCodeData' => $productByCodeData,
  11067.                     'productData' => $productData,
  11068.                     'currInvList' => $currInvList,
  11069.                     'exId' => $id,
  11070.                     'clientList' => Client::GetExistingClientList($em$companyId),
  11071.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  11072.                     'productList' => Inventory::ProductList($em$companyId),
  11073.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  11074.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  11075.                     'igList' => Inventory::ItemGroupList($em$companyId),
  11076.                     'unitList' => Inventory::UnitTypeList($em),
  11077.                     'brandList' => Inventory::GetBrandList($em$companyId),
  11078.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  11079.                     'warehouseList' => Inventory::WarehouseList($em),
  11080.                 )
  11081.             );
  11082.         } else {
  11083.             $html $this->renderView('@Inventory/pages/views/test_product_by_code_for_print_check_snippet.html.twig',
  11084.                 array(
  11085.                     'exId' => $id,
  11086.                 )
  11087.             );
  11088.         }
  11089.         if ($request->query->has('returnJson')) {
  11090.             return new JsonResponse(
  11091.                 array(
  11092.                     'success' => true,
  11093.                     'page_title' => 'Product Details',
  11094.                     'company_data' => $company_data,
  11095.                     'renderedHtml' => $html,
  11096.                     'exId' => $id,
  11097.                     'productByCodeDataObj' => $productByCodeDataObj,
  11098. //                'productData' => $productData,
  11099. //                'currInvList' => $currInvList,
  11100. //                'productList' => Inventory::ProductList($em, $companyId),
  11101. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11102. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11103. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11104. //                'unitList' => Inventory::UnitTypeList($em),
  11105. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11106. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11107. //                'warehouseList' => Inventory::WarehouseList($em),
  11108.                 )
  11109.             );
  11110.         } else {
  11111. //            $productByCodeList=$em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11112. //                ->findBy(
  11113. //                    array(
  11114. ////                        'productByCodeId' => $id,
  11115. //                    'CompanyId'=>$companyId
  11116. //                    )
  11117. //                );
  11118.             $productByCodeList = []; //called by ajax
  11119.             return $this->render('@Inventory/pages/views/test_product_by_code_assign_check_print.html.twig',
  11120.                 array(
  11121.                     'page_title' => ' Test Serial Manager',
  11122.                     'company_data' => $company_data,
  11123.                     'renderedHtml' => $html,
  11124.                     'exId' => $id,
  11125.                     'productByCodeList' => $productByCodeList,
  11126.                     'productByCodeDataObj' => $productByCodeDataObj,
  11127. //                'productByCodeData' => $productByCodeData,
  11128. //                'productData' => $productData,
  11129. //                'currInvList' => $currInvList,
  11130. //                'productList' => Inventory::ProductList($em, $companyId),
  11131. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11132. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11133. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11134. //                'unitList' => Inventory::UnitTypeList($em),
  11135. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11136. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11137. //                'warehouseList' => Inventory::WarehouseList($em),
  11138.                 )
  11139.             );
  11140.         }
  11141.     }
  11142.     public function DeleteProductAction(Request $request$id '')
  11143.     {
  11144.         $em $this->getDoctrine()->getManager();
  11145.         $idListArray = [];
  11146.         if ($request->isMethod('POST')) {
  11147.             if ($id == 0)
  11148.                 $id $request->request->get('productId');
  11149.             //now check the product closing , if nothing then we cna remove it
  11150.             $query_here $this->getDoctrine()
  11151.                 ->getRepository('ApplicationBundle\\Entity\\InvClosingBalance')
  11152.                 ->findBy(
  11153.                     array(
  11154.                         'productId' => $request->request->get('productId')
  11155.                     )
  11156.                 );
  11157.             if (!empty($query_here)) {
  11158.                 return new JsonResponse(
  11159.                     array(
  11160.                         'success' => false,
  11161.                     )
  11162.                 );
  11163.             } else {
  11164.                 $qry $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')->findBy(array(
  11165.                     'productId' => $id
  11166.                 ));
  11167.                 foreach ($qry as $det) {
  11168.                     //remove any barcoded products
  11169.                     $em->remove($det);
  11170.                     $em->flush();
  11171.                 }
  11172.                 $qry $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findBy(array(
  11173.                     'id' => $id
  11174.                 ));
  11175.                 foreach ($qry as $det) {
  11176.                     //remove any barcoded products
  11177.                     $em->remove($det);
  11178.                     $em->flush();
  11179.                 }
  11180.                 $qry $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')->findBy(array(
  11181.                     'productId' => $id
  11182.                 ));
  11183.                 foreach ($qry as $det) {
  11184.                     //remove any barcoded products
  11185.                     $em->remove($det);
  11186.                     $em->flush();
  11187.                 }
  11188.                 return new JsonResponse(
  11189.                     array(
  11190.                         'success' => true,
  11191.                     )
  11192.                 );
  11193.             }
  11194.         }
  11195.         return new JsonResponse(
  11196.             array(
  11197.                 'success' => false,
  11198.             )
  11199.         );
  11200.     }
  11201.     public
  11202.     function RegisterProductAction(Request $request$idListStr '')
  11203.     {
  11204.         $em $this->getDoctrine()->getManager();
  11205.         $companyId $this->getLoggedUserCompanyId($request);
  11206.         $company_data Company::getCompanyData($em$companyId);
  11207.         $session $request->getSession();
  11208. //        System::setSessionForUser($session );
  11209.         $idListArray = [];
  11210.         if ($idListStr != '')
  11211.             $idListArray explode(','$idListStr);
  11212.         $data = [];
  11213. //        if ($request->isMethod('POST')) {
  11214. //            $post = $request->request;
  11215. //            if ($request->request->get('formatId') != '') {
  11216. //                $query_here = $this->getDoctrine()
  11217. //                    ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  11218. //                    ->findOneBy(
  11219. //                        array(
  11220. //                            'formatId' => $request->request->get('formatId')
  11221. //                        )
  11222. //                    );
  11223. //                if (!empty($query_here))
  11224. //                    $new = $query_here;
  11225. //            } else
  11226. //                $new = new CheckFormat();
  11227. //            $new->setName($request->request->get('name'));
  11228. //            $new->setWidth($request->request->get('width'));
  11229. //            $new->setHeight($request->request->get('height'));
  11230. //            $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
  11231. //            $new->setCheckPayToTop($request->request->get('checkPayToTop'));
  11232. //            $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
  11233. //            $new->setCheckAmountTop($request->request->get('checkAmountTop'));
  11234. //            $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
  11235. //            $new->setCheckAiWTop($request->request->get('checkAiWTop'));
  11236. //            $new->setCheckDateLeft($request->request->get('checkDateLeft'));
  11237. //            $new->setCheckDateTop($request->request->get('checkDateTop'));
  11238. //            $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
  11239. //            $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
  11240. //            $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
  11241. //            $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
  11242. //            $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
  11243. //            $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
  11244. //            $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
  11245. //            $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
  11246. //            $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
  11247. //            $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
  11248. //            $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 1 : 0);
  11249. //            $new->setCheckImage($request->request->get('checkImage'));
  11250. //
  11251. //            $em = $this->getDoctrine()->getManager();
  11252. //            $em->persist($new);
  11253. //            $em->flush();
  11254. //
  11255. //        }
  11256. //        if (!empty($idListArray)) {
  11257. //            $query_here = $this->getDoctrine()
  11258. //                ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11259. //                ->findBy(
  11260. //                    array(
  11261. //                        'productByCodeId' => $idListArray
  11262. //                    )
  11263. //                );
  11264. //            if (!empty($query_here))
  11265. //                $data = $query_here;
  11266. //
  11267. //        }
  11268. //        else if ($request->query->has('formatId')) {
  11269. //            $query_here = $this->getDoctrine()
  11270. //                ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  11271. //                ->findOneBy(
  11272. //                    array(
  11273. //                        'formatId' => $request->query->get('formatId')
  11274. //                    )
  11275. //                );
  11276. //            if (!empty($query_here))
  11277. //                $data = $query_here;
  11278. //        }
  11279.         $data = [];
  11280.         $html '';
  11281.         $productByCodeData = [];
  11282.         if ($request->query->has('returnJson')) {
  11283.             return new JsonResponse(
  11284.                 array(
  11285.                     'success' => true,
  11286.                     'page_title' => 'Product Details',
  11287.                     'company_data' => $company_data,
  11288.                     'renderedHtml' => $html,
  11289.                     'data' => $data,
  11290.                     'idListArray' => $idListArray,
  11291. //                    'exId'=>$id,
  11292. //                'productByCodeData' => $productByCodeData,
  11293. //                'productData' => $productData,
  11294. //                'currInvList' => $currInvList,
  11295. //                'productList' => Inventory::ProductList($em, $companyId),
  11296. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11297. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11298. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11299. //                'unitList' => Inventory::UnitTypeList($em),
  11300. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11301. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11302. //                'warehouseList' => Inventory::WarehouseList($em),
  11303.                 )
  11304.             );
  11305.         } else {
  11306.             return $this->render('@Inventory/pages/input_forms/register_product.html.twig',
  11307.                 array(
  11308.                     'page_title' => 'Register Product',
  11309.                     'company_data' => $company_data,
  11310.                     'renderedHtml' => $html,
  11311. //                    'exIdList'=>$i,
  11312.                     'idListArray' => $idListArray,
  11313.                     'data' => $data,
  11314.                     'productByCodeList' => [],
  11315.                     'productByCodeData' => [],
  11316.                     'productList' => Inventory::ProductList($em$companyId),
  11317.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  11318.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  11319.                     'igList' => Inventory::ItemGroupList($em$companyId),
  11320.                     'unitList' => Inventory::UnitTypeList($em),
  11321.                     'brandList' => Inventory::GetBrandList($em$companyId),
  11322.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  11323.                     'warehouseList' => Inventory::WarehouseList($em),
  11324.                 )
  11325.             );
  11326.         }
  11327.     }
  11328.     public
  11329.     function BrandViewAction(Request $request)
  11330.     {
  11331.         return $this->render('@Inventory/pages/input_forms/stock_return.html.twig',
  11332.             array(
  11333.                 'page_title' => 'Stock Return'
  11334.             )
  11335.         );
  11336.     }
  11337.     public
  11338.     function PrintTableDataAction(Request $request)
  11339.     {
  11340.         $em $this->getDoctrine()->getManager();
  11341.         $company_data Company::getCompanyData($em1);
  11342.         $data = [];
  11343.         $print_title "test";
  11344.         $document_mark = array(
  11345.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11346.             'copy' => ''
  11347.         );
  11348.         $mis_data = [];
  11349.         $p 1;
  11350.         return $this->render('@Inventory/pages/print/print_table_data.html.twig',
  11351.             array(
  11352.                 'page_title' => 'Data Report',
  11353.                 'data' => $data,
  11354.                 'page_header' => 'Report',
  11355.                 'print_title' => $print_title,
  11356.                 'document_type' => 'Journal voucher',
  11357.                 'document_mark_image' => $document_mark['original'],
  11358.                 'page_header_sub' => 'Add',
  11359. //                'type_list'=>$type_list,
  11360.                 'mis_data' => $mis_data,
  11361.                 'item_data' => [],
  11362.                 'received' => 2,
  11363.                 'return' => 1,
  11364.                 'total_w_vat' => 1,
  11365.                 'total_vat' => 1,
  11366.                 'total_wo_vat' => 1,
  11367.                 'invoice_id' => 'abcd1234',
  11368.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11369.                 'created_by' => 'created by',
  11370.                 'created_at' => '',
  11371.                 'red' => 0,
  11372.                 'company_name' => $company_data->getName(),
  11373.                 'company_data' => $company_data,
  11374.                 'company_address' => $company_data->getAddress(),
  11375.                 'company_image' => $company_data->getImage(),
  11376.                 'p' => $p
  11377.             )
  11378.         );
  11379.     }
  11380.     public
  11381.     function ReplacementReportAction(Request $request)
  11382.     {
  11383.         $qry_data = array(
  11384.             'warehouseId' => [0],
  11385.             'igId' => [0],
  11386.             'brandId' => [0],
  11387.             'categoryId' => [0],
  11388.             'actionTagId' => [0],
  11389.         );
  11390.         $em $this->getDoctrine()->getManager();
  11391.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  11392.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  11393.         $data_searched = [];
  11394.         $companyId $this->getLoggedUserCompanyId($request);
  11395.         $company_data Company::getCompanyData($em$companyId);
  11396.         $data = [];
  11397.         $print_title "Inventory Report";
  11398.         $document_mark = array(
  11399.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11400.             'copy' => ''
  11401.         );
  11402.         $post_data $request->request;
  11403.         $start_date $post_data->has('start_date') ? $post_data->get('start_date') : '';
  11404.         $end_date $post_data->has('end_date') ? $post_data->get('end_date') : '';
  11405.         if ($request->isMethod('POST'))
  11406.             $method 'POST';
  11407.         else
  11408.             $method 'GET';
  11409.         {
  11410. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  11411.             $data_searched Inventory::GetReplacementReportData($this->getDoctrine()->getManager(),
  11412.                 $request->request$method,
  11413.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  11414.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  11415.                 return new JsonResponse(
  11416.                     array(
  11417.                         'page_title' => 'Inventory ',
  11418.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11419.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11420.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11421.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11422.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11423.                         'action_tag' => $warehouse_action_list,
  11424.                         'start_date' => $start_date,
  11425.                         'end_date' => $end_date,
  11426.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11427.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11428.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11429.                         'data_searched' => $data_searched,
  11430.                         'success' => empty($data_searched['query_result']) ? false true
  11431.                     )
  11432.                 );
  11433.             }
  11434.             if ($request->request->get('print_data_enabled') == 1) {
  11435.                 $print_sub_title "";
  11436.                 return $this->render('@Inventory/pages/print/print_replacement_report.html.twig',
  11437.                     array(
  11438.                         'page_title' => 'Replacement Report',
  11439.                         'page_header' => 'Report',
  11440.                         'print_title' => $print_title,
  11441.                         'document_type' => 'Journal voucher',
  11442.                         'document_mark_image' => $document_mark['original'],
  11443.                         'page_header_sub' => 'Add',
  11444.                         'item_data' => [],
  11445.                         'received' => 2,
  11446.                         'return' => 1,
  11447.                         'total_w_vat' => 1,
  11448.                         'total_vat' => 1,
  11449.                         'total_wo_vat' => 1,
  11450.                         'invoice_id' => 'abcd1234',
  11451.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  11452.                         'created_by' => 'created by',
  11453.                         'created_at' => '',
  11454.                         'red' => 0,
  11455.                         'company_name' => $company_data->getName(),
  11456.                         'company_data' => $company_data,
  11457.                         'company_address' => $company_data->getAddress(),
  11458.                         'company_image' => $company_data->getImage(),
  11459.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11460.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11461.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11462.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11463.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11464.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11465.                         'action_tag' => $warehouse_action_list,
  11466.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11467.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11468.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11469.                         'start_date' => $start_date,
  11470.                         'end_date' => $end_date,
  11471.                         'data_searched' => $data_searched
  11472.                     )
  11473.                 );
  11474.             }
  11475.         }
  11476.         return $this->render('@Inventory/pages/report/replacement_report.html.twig',
  11477.             array(
  11478.                 'page_title' => 'Replacement Report',
  11479.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11480.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11481.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11482.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11483.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11484. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11485.                 'action_tag' => $warehouse_action_list,
  11486.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11487.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11488.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11489.                 'start_date' => $start_date,
  11490.                 'end_date' => $end_date,
  11491.                 'data_searched' => $data_searched,
  11492.                 'success' => empty($data_searched['query_result']) ? false true
  11493.             )
  11494.         );
  11495.     }
  11496.     public
  11497.     function InventoryViewAction(Request $request)
  11498.     {
  11499.         $qry_data = array(
  11500.             'warehouseId' => [0],
  11501.             'igId' => [0],
  11502.             'brandId' => [0],
  11503.             'categoryId' => [0],
  11504.             'actionTagId' => [0],
  11505.         );
  11506.         $em $this->getDoctrine()->getManager();
  11507.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  11508.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  11509.         $data_searched = [];
  11510.         $companyId $this->getLoggedUserCompanyId($request);
  11511.         $company_data Company::getCompanyData($em$companyId);
  11512.         $data = [];
  11513.         $print_title "Inventory Report";
  11514.         $document_mark = array(
  11515.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11516.             'copy' => ''
  11517.         );
  11518.         if ($request->isMethod('POST'))
  11519.             $method 'POST';
  11520.         else
  11521.             $method 'GET';
  11522.         {
  11523. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  11524.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  11525.                 $request->request$method,
  11526.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  11527.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  11528.                 return new JsonResponse(
  11529.                     array(
  11530.                         'page_title' => 'Inventory ',
  11531.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11532.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11533.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11534.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11535.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11536.                         'action_tag' => $warehouse_action_list,
  11537.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11538.                         'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  11539.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11540.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11541.                         'data_searched' => $data_searched,
  11542.                         'success' => empty($data_searched['query_result']) ? false true
  11543.                     )
  11544.                 );
  11545.             }
  11546.             if ($request->request->get('print_data_enabled') == 1) {
  11547.                 $print_sub_title "";
  11548.                 return $this->render('@Inventory/pages/print/print_inventory_data.html.twig',
  11549.                     array(
  11550.                         'page_title' => 'Inventory Report',
  11551.                         'page_header' => 'Report',
  11552.                         'print_title' => $print_title,
  11553.                         'document_type' => 'Journal voucher',
  11554.                         'document_mark_image' => $document_mark['original'],
  11555.                         'page_header_sub' => 'Add',
  11556.                         'item_data' => [],
  11557.                         'received' => 2,
  11558.                         'return' => 1,
  11559.                         'total_w_vat' => 1,
  11560.                         'total_vat' => 1,
  11561.                         'total_wo_vat' => 1,
  11562.                         'invoice_id' => 'abcd1234',
  11563.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  11564.                         'created_by' => 'created by',
  11565.                         'created_at' => '',
  11566.                         'red' => 0,
  11567.                         'company_name' => $company_data->getName(),
  11568.                         'company_data' => $company_data,
  11569.                         'company_address' => $company_data->getAddress(),
  11570.                         'company_image' => $company_data->getImage(),
  11571.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11572.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11573.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11574.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11575.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11576.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11577.                         'action_tag' => $warehouse_action_list,
  11578.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11579.                         'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  11580.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11581.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11582.                         'data_searched' => $data_searched
  11583.                     )
  11584.                 );
  11585.             }
  11586.         }
  11587.         return $this->render('@Inventory/pages/report/inventory_view.html.twig',
  11588.             array(
  11589.                 'page_title' => 'Inventory',
  11590.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  11591.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  11592.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  11593.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  11594.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  11595. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  11596.                 'action_tag' => $warehouse_action_list,
  11597.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  11598.                 'spec_type' => Inventory::SpecTypeList($this->getDoctrine()->getManager()),
  11599.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  11600.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  11601.                 'data_searched' => $data_searched
  11602.             )
  11603.         );
  11604.     }
  11605.     public
  11606.     function GrnListAction(Request $request)
  11607.     {
  11608.         $q $this->getDoctrine()
  11609.             ->getRepository('ApplicationBundle\\Entity\\Grn')
  11610.             ->findBy(
  11611.                 array(
  11612.                     'status' => GeneralConstant::ACTIVE,
  11613. //                    'approved' =>  GeneralConstant::APPROVED,
  11614.                 )
  11615.             );
  11616.         $stage_list = array(
  11617.             => 'Pending',
  11618.             => 'Pending',
  11619.             => 'Complete',
  11620.             => 'Partial',
  11621.         );
  11622.         $data = [];
  11623.         foreach ($q as $entry) {
  11624.             $data[] = array(
  11625.                 'doc_date' => $entry->getGrnDate(),
  11626.                 'id' => $entry->getGrnId(),
  11627.                 'doc_hash' => $entry->getDocumentHash(),
  11628.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  11629.                 'stage' => $stage_list[$entry->getStage()]
  11630.             );
  11631.         }
  11632.         return $this->render('@Inventory/pages/views/grn_list.html.twig',
  11633.             array(
  11634.                 'page_title' => 'Grn List',
  11635.                 'data' => $data
  11636.             )
  11637.         );
  11638.     }
  11639.     public
  11640.     function ViewGrnAction(Request $request$id)
  11641.     {
  11642.         $em $this->getDoctrine()->getManager();
  11643.         $dt Inventory::GetGrnDetails($em$id);
  11644.         return $this->render(
  11645.             '@Inventory/pages/views/view_grn.html.twig',
  11646.             array(
  11647.                 'page_title' => 'View',
  11648.                 'data' => $dt,
  11649.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  11650.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11651.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11652.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11653.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  11654.                     $id,
  11655.                     $dt['created_by'],
  11656.                     $dt['edited_by'])
  11657.             )
  11658.         );
  11659.     }
  11660.     public
  11661.     function PrintGrnAction(Request $request$id)
  11662.     {
  11663.         $em $this->getDoctrine()->getManager();
  11664.         $dt Inventory::GetGrnDetails($em$id);
  11665.         $company_data Company::getCompanyData($em1);
  11666.         $document_mark = array(
  11667.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11668.             'copy' => ''
  11669.         );
  11670.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11671.             $html $this->renderView('@Inventory/pages/print/print_received_note.html.twig',
  11672.                 array(
  11673.                     //full array here
  11674.                     'pdf' => true,
  11675.                     'page_title' => 'Grn',
  11676.                     'export' => 'pdf,print',
  11677.                     'data' => $dt,
  11678.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11679.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11680.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11681.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  11682.                         $id,
  11683.                         $dt['created_by'],
  11684.                         $dt['edited_by']),
  11685.                     'document_mark_image' => $document_mark['original'],
  11686.                     'company_name' => $company_data->getName(),
  11687.                     'company_data' => $company_data,
  11688.                     'company_address' => $company_data->getAddress(),
  11689.                     'company_image' => $company_data->getImage(),
  11690.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11691.                     'red' => 0
  11692.                 )
  11693.             );
  11694.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11695. //                'orientation' => 'landscape',
  11696. //                'enable-javascript' => true,
  11697. //                'javascript-delay' => 1000,
  11698.                 'no-stop-slow-scripts' => false,
  11699.                 'no-background' => false,
  11700.                 'lowquality' => false,
  11701.                 'encoding' => 'utf-8',
  11702. //            'images' => true,
  11703. //            'cookie' => array(),
  11704.                 'dpi' => 300,
  11705.                 'image-dpi' => 300,
  11706. //                'enable-external-links' => true,
  11707. //                'enable-internal-links' => true
  11708.             ));
  11709.             return new Response(
  11710.                 $pdf_response,
  11711.                 200,
  11712.                 array(
  11713.                     'Content-Type' => 'application/pdf',
  11714.                     'Content-Disposition' => 'attachment; filename="grn.pdf"'
  11715.                 )
  11716.             );
  11717.         }
  11718.         return $this->render('@Inventory/pages/print/print_received_note.html.twig',
  11719.             array(
  11720.                 'page_title' => 'Grn',
  11721.                 'export' => 'pdf,print',
  11722.                 'data' => $dt,
  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.     }
  11740.     public
  11741.     function PrintGrnBarcodeAction(Request $request$id)
  11742.     {
  11743.         $em $this->getDoctrine()->getManager();
  11744.         $dt Inventory::GetGrnDetails($em$id);
  11745.         $company_data Company::getCompanyData($em1);
  11746.         $repeatCount 1;
  11747.         if ($request->query->has('repeatCount'))
  11748.             $repeatCount $request->query->get('repeatCount');
  11749.         $document_mark = array(
  11750.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11751.             'copy' => ''
  11752.         );
  11753.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11754.             $html $this->renderView('@Inventory/pages/print/print_grn_barcodes.html.twig',
  11755.                 array(
  11756.                     //full array here
  11757.                     'pdf' => true,
  11758.                     'page_title' => 'Grn Barcodes',
  11759.                     'export' => 'print',
  11760.                     'data' => $dt,
  11761.                     'repeatCount' => $repeatCount,
  11762.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11763.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11764.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11765.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  11766.                         $id,
  11767.                         $dt['created_by'],
  11768.                         $dt['edited_by']),
  11769.                     'document_mark_image' => $document_mark['original'],
  11770.                     'company_name' => $company_data->getName(),
  11771.                     'company_data' => $company_data,
  11772.                     'company_address' => $company_data->getAddress(),
  11773.                     'company_image' => $company_data->getImage(),
  11774.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11775.                     'red' => 0
  11776.                 )
  11777.             );
  11778.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11779. //                'orientation' => 'landscape',
  11780.                 'enable-javascript' => true,
  11781. //                'javascript-delay' => 1000,
  11782.                 'no-stop-slow-scripts' => false,
  11783.                 'no-background' => false,
  11784.                 'lowquality' => false,
  11785.                 'encoding' => 'utf-8',
  11786. //            'images' => true,
  11787. //            'cookie' => array(),
  11788.                 'dpi' => 300,
  11789.                 'image-dpi' => 300,
  11790. //                'enable-external-links' => true,
  11791. //                'enable-internal-links' => true
  11792.             ));
  11793.             return new Response(
  11794.                 $pdf_response,
  11795.                 200,
  11796.                 array(
  11797.                     'Content-Type' => 'application/pdf',
  11798.                     'Content-Disposition' => 'attachment; filename="grn_barcodes.pdf"'
  11799.                 )
  11800.             );
  11801.         }
  11802.         return $this->render('@Inventory/pages/print/print_grn_barcodes.html.twig',
  11803.             array(
  11804.                 'page_title' => 'Grn barcodes',
  11805. //                'export'=>'pdf,print',
  11806.                 'data' => $dt,
  11807.                 'repeatCount' => $repeatCount,
  11808.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  11809.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11810.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11811.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  11812.                     $id,
  11813.                     $dt['created_by'],
  11814.                     $dt['edited_by']),
  11815.                 'document_mark_image' => $document_mark['original'],
  11816.                 'company_name' => $company_data->getName(),
  11817.                 'company_data' => $company_data,
  11818.                 'company_address' => $company_data->getAddress(),
  11819.                 'company_image' => $company_data->getImage(),
  11820.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11821.                 'red' => 0
  11822.             )
  11823.         );
  11824.     }
  11825.     public function GenerateBarcodeAction(Request $request$type$id$item_id)
  11826.     {
  11827.         $em $this->getDoctrine()->getManager();
  11828.         $repeatCount 1;
  11829.         $spec_item_id 0;
  11830.         $skip_ids = [];
  11831.         $clearUnnecessaryOnly 0;
  11832.         if ($request->query->has('skipIds'))
  11833.             $skip_ids $request->query->get('skipIds');
  11834.         if ($request->query->has('clearUnnecessaryOnly'))
  11835.             $clearUnnecessaryOnly $request->query->get('clearUnnecessaryOnly');
  11836.         if ($type == 'srcv') {
  11837.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')->findOneBy(
  11838.                 array(
  11839.                     'stockReceivedNoteId' => $id
  11840.                 )
  11841.             );
  11842.             if ($item_id == '_single_') {
  11843.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findBy(
  11844.                     array(
  11845.                         'stockReceivedNoteId' => $id,
  11846. //                        'id' => $item_id
  11847.                     )
  11848.                 );
  11849.             } else {
  11850.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findBy(
  11851.                     array(
  11852.                         'stockReceivedNoteId' => $id,
  11853.                         'id' => $item_id
  11854.                     )
  11855.                 );
  11856.             }
  11857.             $inv_acc_data = [
  11858.                 'fa_amount' => 0,
  11859.                 'tg_amount' => 0,
  11860.             ];
  11861.             $inv_acc_data_by_head = [
  11862.             ];
  11863.             $new_non_delivered_sales_code_range = [];
  11864.             foreach ($doc_item_data as $entry) {
  11865.                 //adding transaction
  11866.                 $sales_code_range_ser = [];
  11867.                 if (in_array($entry->getId(), $skip_ids))
  11868.                     continue;
  11869.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  11870.                     ->findOneBy(
  11871.                         array(
  11872.                             'id' => $entry->getProductId()
  11873.                         )
  11874.                     );
  11875.                 $stitem $em->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  11876.                     ->findOneBy(
  11877.                         array(
  11878.                             'id' => $entry->getStockTransferItemId(),
  11879.                             'productId' => $entry->getProductId()
  11880.                         )
  11881.                     );
  11882.                 if ($product) {
  11883.                     if ($product->getHasSerial() == 1) {
  11884.                         //clear if exists
  11885.                         if ($clearUnnecessaryOnly == 1) {
  11886.                             $get_kids_sql "DELETE FROM product_by_code
  11887.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  11888. //                $get_kids_sql .=' ORDER BY name ASC';
  11889.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  11890.                             $em->flush();
  11891.                         } else {
  11892.                             $get_kids_sql "DELETE FROM product_by_code
  11893.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  11894. //                $get_kids_sql .=' ORDER BY name ASC';
  11895.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  11896.                             $em->flush();
  11897.                         }
  11898. //                        $check_here = $stmt;
  11899.                         //now addng product by code
  11900.                         $sales_code_range = [];
  11901.                         if ($doc_data->getType() == || $doc_data->getType() == 4) {
  11902. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  11903. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  11904.                             $product_action_tag_id $entry->getWarehouseActionId();
  11905.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getQty(),
  11906.                                 $doc_data->getStockReceivedNoteDate(), $entry->getWarrantyMon(), 0$doc_data->getCompanyId(), $entry->getWarehouseId(),
  11907.                                 $entry->getWarehouseActionId(), $entry->getPurchaseCodeRange(), nullnullnullnull$doc_data->getStockReceivedNoteId()
  11908.                             );
  11909.                             $sales_code_range $barcodeData['sales_code_range'];
  11910.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  11911.                             $em->flush();
  11912.                         }
  11913. //                        else {
  11914. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11915. //
  11916. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11917. //                            } else {
  11918. //
  11919. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11920. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  11921. //                                $sales_code_range = json_decode($json_without_bigints, true);
  11922. //                            }
  11923. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  11924. //
  11925. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  11926. //                            } else {
  11927. //
  11928. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  11929. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  11930. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  11931. //                            }
  11932. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  11933. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  11934. //                            $new_non_delivered_sales_code_range = [];
  11935. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  11936. //                                if (!(in_array($ndsc, $sales_code_range)))
  11937. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  11938. //                            }
  11939. //                            if ($sales_code_range != null) {
  11940. //                                foreach ($sales_code_range as $ind => $dt) {
  11941. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  11942. //                                        ->findOneBy(
  11943. //                                            array(
  11944. //                                                'salesCode' => [$dt],
  11945. //                                                'productId' => $entry->getProductId()
  11946. //                                            )
  11947. //                                        );
  11948. //
  11949. //                                    if ($np) {
  11950. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  11951. //                                        $np->setProductId($entry->getProductId());
  11952. //                                        $np->setWarehouseId($entry->getWarehouseId());
  11953. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  11954. //                                        $np->setPosition(1);//in warehouse
  11955. //                                        $np->setStockReceivedNoteId($id);
  11956. //
  11957. //
  11958. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  11959. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  11960. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  11961. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  11962. //                                            'direction' => 'in',
  11963. //                                            'warehouseId' => $entry->getWarehouseId(),
  11964. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  11965. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  11966. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  11967. //                                        );
  11968. //                                        $np->setTransactionHistory(json_encode(
  11969. //                                            $trans_history
  11970. //                                        ));
  11971. //
  11972. //
  11973. //                                        $em->persist($np);
  11974. //                                        $em->flush();
  11975. //                                    }
  11976. //                                }
  11977. //                            }
  11978. //                        }
  11979.                     }
  11980.                 }
  11981.                 //adding transaction
  11982.                 if ($stitem) {
  11983.                     $stitem->setNonDeliveredSalesCodeRange(json_encode($new_non_delivered_sales_code_range));
  11984.                 }
  11985.                 $spec_item_id $entry->getId();
  11986.                 if ($item_id == '_single_') {
  11987.                     break;
  11988.                 }
  11989.             }
  11990.         }
  11991.         if ($type == 'irr') {
  11992.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacement')->findOneBy(
  11993.                 array(
  11994.                     'itemReceivedAndReplacementId' => $id
  11995.                 )
  11996.             );
  11997.             if ($item_id == '_single_') {
  11998.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacementItem')->findBy(
  11999.                     array(
  12000.                         'itemReceivedAndReplacementId' => $id,
  12001. //                        'id' => $item_id
  12002.                     )
  12003.                 );
  12004.             } else {
  12005.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ItemReceivedAndReplacementItem')->findBy(
  12006.                     array(
  12007.                         'itemReceivedAndReplacementId' => $id,
  12008.                         'id' => $item_id
  12009.                     )
  12010.                 );
  12011.             }
  12012.             $inv_acc_data = [
  12013.                 'fa_amount' => 0,
  12014.                 'tg_amount' => 0,
  12015.             ];
  12016.             $inv_acc_data_by_head = [
  12017.             ];
  12018.             $new_non_delivered_sales_code_range = [];
  12019.             foreach ($doc_item_data as $entry) {
  12020.                 //adding transaction
  12021.                 $sales_code_range_ser = [];
  12022.                 if (in_array($entry->getId(), $skip_ids))
  12023.                     continue;
  12024.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12025.                     ->findOneBy(
  12026.                         array(
  12027.                             'id' => $entry->getReceivedProductId()
  12028.                         )
  12029.                     );
  12030.                 if ($product) {
  12031.                     if ($product->getHasSerial() == 1) {
  12032.                         //clear if exists
  12033. //                        if($clearUnnecessaryOnly==1) {
  12034. //                            $get_kids_sql = "DELETE FROM product_by_code
  12035. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12036. ////                $get_kids_sql .=' ORDER BY name ASC';
  12037. //
  12038. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12039. //                            
  12040. //                            $em->flush();
  12041. //                        }
  12042. //                        else{
  12043. //                            $get_kids_sql = "DELETE FROM product_by_code
  12044. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12045. ////                $get_kids_sql .=' ORDER BY name ASC';
  12046. //
  12047. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12048. //                            
  12049. //                            $em->flush();
  12050. //                        }
  12051. //                        $check_here = $stmt;
  12052.                         //now addng product by code
  12053.                         $sales_code_range = [];
  12054.                         if ($entry->getReceivedQty() > 0) {
  12055. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  12056. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  12057. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  12058.                             $barcodeData Inventory::GenerateBarcode($em$entry->getReceivedProductId(), $entry->getReceivedQty(),
  12059.                                 $doc_data->getItemReceivedAndReplacementDate(), 00$doc_data->getCompanyId(), $entry->getReceivedWarehouseId(),
  12060.                                 $entry->getReceivedWarehouseActionId(), nullnullnullnullnullnullnullnull$doc_data->getItemReceivedAndReplacementId()
  12061.                             );
  12062.                             $sales_code_range $barcodeData['sales_code_range'];
  12063.                             $entry->setReceivedCodeRange(json_encode($sales_code_range));
  12064.                             $em->flush();
  12065.                         }
  12066. //                        else {
  12067. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12068. //
  12069. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12070. //                            } else {
  12071. //
  12072. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12073. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  12074. //                                $sales_code_range = json_decode($json_without_bigints, true);
  12075. //                            }
  12076. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12077. //
  12078. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12079. //                            } else {
  12080. //
  12081. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12082. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  12083. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  12084. //                            }
  12085. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  12086. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  12087. //                            $new_non_delivered_sales_code_range = [];
  12088. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  12089. //                                if (!(in_array($ndsc, $sales_code_range)))
  12090. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  12091. //                            }
  12092. //                            if ($sales_code_range != null) {
  12093. //                                foreach ($sales_code_range as $ind => $dt) {
  12094. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12095. //                                        ->findOneBy(
  12096. //                                            array(
  12097. //                                                'salesCode' => [$dt],
  12098. //                                                'productId' => $entry->getProductId()
  12099. //                                            )
  12100. //                                        );
  12101. //
  12102. //                                    if ($np) {
  12103. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  12104. //                                        $np->setProductId($entry->getProductId());
  12105. //                                        $np->setWarehouseId($entry->getWarehouseId());
  12106. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  12107. //                                        $np->setPosition(1);//in warehouse
  12108. //                                        $np->setStockReceivedNoteId($id);
  12109. //
  12110. //
  12111. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  12112. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  12113. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  12114. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  12115. //                                            'direction' => 'in',
  12116. //                                            'warehouseId' => $entry->getWarehouseId(),
  12117. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  12118. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  12119. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  12120. //                                        );
  12121. //                                        $np->setTransactionHistory(json_encode(
  12122. //                                            $trans_history
  12123. //                                        ));
  12124. //
  12125. //
  12126. //                                        $em->persist($np);
  12127. //                                        $em->flush();
  12128. //                                    }
  12129. //                                }
  12130. //                            }
  12131. //                        }
  12132.                     }
  12133.                 }
  12134.                 //adding transaction
  12135.                 $spec_item_id $entry->getId();
  12136.                 if ($item_id == '_single_') {
  12137.                     break;
  12138.                 }
  12139.             }
  12140.         }
  12141.         if ($type == 'prdcn') {
  12142.             $doc_data $em->getRepository('ApplicationBundle\\Entity\\Production')->findOneBy(
  12143.                 array(
  12144.                     'productionId' => $id
  12145.                 )
  12146.             );
  12147.             if ($item_id == '_single_') {
  12148.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findBy(
  12149.                     array(
  12150.                         'productionId' => $id,
  12151. //                        'id' => $item_id
  12152.                     )
  12153.                 );
  12154.             } else {
  12155.                 $doc_item_data $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findBy(
  12156.                     array(
  12157.                         'productionId' => $id,
  12158.                         'id' => $item_id
  12159.                     )
  12160.                 );
  12161.             }
  12162.             $inv_acc_data = [
  12163.                 'fa_amount' => 0,
  12164.                 'tg_amount' => 0,
  12165.             ];
  12166.             $inv_acc_data_by_head = [
  12167.             ];
  12168.             $new_non_delivered_sales_code_range = [];
  12169.             foreach ($doc_item_data as $entry) {
  12170.                 //adding transaction
  12171.                 $sales_code_range_ser = [];
  12172.                 if (in_array($entry->getId(), $skip_ids))
  12173.                     continue;
  12174.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12175.                     ->findOneBy(
  12176.                         array(
  12177.                             'id' => $entry->getProductId()
  12178.                         )
  12179.                     );
  12180.                 if ($product) {
  12181.                     if ($product->getHasSerial() == 1) {
  12182.                         //clear if exists
  12183. //                        if($clearUnnecessaryOnly==1) {
  12184. //                            $get_kids_sql = "DELETE FROM product_by_code
  12185. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12186. ////                $get_kids_sql .=' ORDER BY name ASC';
  12187. //
  12188. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12189. //                            
  12190. //                            $em->flush();
  12191. //                        }
  12192. //                        else{
  12193. //                            $get_kids_sql = "DELETE FROM product_by_code
  12194. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  12195. ////                $get_kids_sql .=' ORDER BY name ASC';
  12196. //
  12197. //                            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12198. //                            
  12199. //                            $em->flush();
  12200. //                        }
  12201. //                        $check_here = $stmt;
  12202.                         //now addng product by code
  12203.                         $sales_code_range = [];
  12204.                         if ($entry->getProducedQty() > 0) {
  12205. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  12206. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  12207. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  12208.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getProducedQty(),
  12209.                                 $doc_data->getProductionDate(), 00$doc_data->getCompanyId(), $entry->getWarehouseId(),
  12210.                                 $entry->getProducedItemActionTagId(), nullnullnullnullnullnullnull$doc_data->getProductionId(), null
  12211.                             );
  12212.                             $sales_code_range $barcodeData['sales_code_range'];
  12213.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  12214.                             $em->flush();
  12215.                         }
  12216. //                        else {
  12217. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12218. //
  12219. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12220. //                            } else {
  12221. //
  12222. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12223. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  12224. //                                $sales_code_range = json_decode($json_without_bigints, true);
  12225. //                            }
  12226. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  12227. //
  12228. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  12229. //                            } else {
  12230. //
  12231. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  12232. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  12233. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  12234. //                            }
  12235. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  12236. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  12237. //                            $new_non_delivered_sales_code_range = [];
  12238. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  12239. //                                if (!(in_array($ndsc, $sales_code_range)))
  12240. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  12241. //                            }
  12242. //                            if ($sales_code_range != null) {
  12243. //                                foreach ($sales_code_range as $ind => $dt) {
  12244. //                                    $np = $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12245. //                                        ->findOneBy(
  12246. //                                            array(
  12247. //                                                'salesCode' => [$dt],
  12248. //                                                'productId' => $entry->getProductId()
  12249. //                                            )
  12250. //                                        );
  12251. //
  12252. //                                    if ($np) {
  12253. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  12254. //                                        $np->setProductId($entry->getProductId());
  12255. //                                        $np->setWarehouseId($entry->getWarehouseId());
  12256. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  12257. //                                        $np->setPosition(1);//in warehouse
  12258. //                                        $np->setStockReceivedNoteId($id);
  12259. //
  12260. //
  12261. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  12262. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  12263. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  12264. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  12265. //                                            'direction' => 'in',
  12266. //                                            'warehouseId' => $entry->getWarehouseId(),
  12267. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  12268. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  12269. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  12270. //                                        );
  12271. //                                        $np->setTransactionHistory(json_encode(
  12272. //                                            $trans_history
  12273. //                                        ));
  12274. //
  12275. //
  12276. //                                        $em->persist($np);
  12277. //                                        $em->flush();
  12278. //                                    }
  12279. //                                }
  12280. //                            }
  12281. //                        }
  12282.                     }
  12283.                 }
  12284.                 //adding transaction
  12285.                 $spec_item_id $entry->getId();
  12286.                 if ($item_id == '_single_') {
  12287.                     break;
  12288.                 }
  12289.             }
  12290.         }
  12291.         return new JsonResponse(array(
  12292.             'success' => $spec_item_id != true false,
  12293.             'skipIds' => [],
  12294.             'spec_item_id' => $spec_item_id
  12295.         ));
  12296. //        return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  12297. //            array(
  12298. //                'page_title' => 'Srcv barcodes',
  12299. ////                'export'=>'pdf,print',
  12300. //                'data' => $dt,
  12301. //                'repeatCount' => $repeatCount,
  12302. //                'item_id' => $item_id,
  12303. //                'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12304. //                    $id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12305. //                'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12306. //                    array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  12307. //                    $id,
  12308. //                    $dt['created_by'],
  12309. //                    $dt['edited_by']),
  12310. //                'document_mark_image' => $document_mark['original'],
  12311. //                                    'company_name' => $company_data->getName(),
  12312. //                    'company_data'=>$company_data,
  12313. //                'company_address' => $company_data->getAddress(),
  12314. //                'company_image' => $company_data->getImage(),
  12315. //                'invoice_footer' => $company_data->getInvoiceFooter(),
  12316. //                'red' => 0
  12317. //
  12318. //            )
  12319. //        );
  12320.     }
  12321.     public
  12322.     function PrintLabelAction(Request $request$id)
  12323.     {
  12324.         $em $this->getDoctrine()->getManager();
  12325. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12326.         $repeatCount 1;
  12327.         $assignProductId '';
  12328.         $productByCodeIds = [];
  12329.         $print_selection_type 1;
  12330.         $print_selection_string 1;
  12331.         $assignLabelFormatId 0;
  12332.         $assignColorId 0;
  12333.         $assignProductionScheduleId 0;
  12334.         $warehouseId '';
  12335.         $warehouseActionId '';
  12336.         $toAssignPosition '';
  12337.         $printFlag $request->request->has('printFlag') ? $request->request->get('printFlag') : 1;
  12338.         $returnJson $request->request->has('returnJson') ? $request->request->get('returnJson') : 0;
  12339.         if ($returnJson == 1)
  12340.             $printFlag 0;
  12341.         $companyId $this->getLoggedUserCompanyId($request);
  12342.         if ($request->query->has('repeatCount'))
  12343.             $repeatCount $request->query->get('repeatCount');
  12344.         if ($request->request->has('print_selection_type'))
  12345.             $print_selection_type $request->request->get('print_selection_type');
  12346.         if ($request->request->has('print_selection_string'))
  12347.             $print_selection_string $request->request->get('print_selection_string');
  12348.         if ($request->request->has('productByCodeIds'))
  12349.             $productByCodeIds json_decode($request->request->get('productByCodeIds'), true);
  12350.         if ($request->request->has('formatId'))
  12351.             $assignLabelFormatId $request->request->get('formatId');
  12352.         if ($printFlag == 0) {
  12353.             if ($request->request->has('productSelector'))
  12354.                 $assignProductId $request->request->get('productSelector');
  12355.             if ($request->request->has('colorId'))
  12356.                 $assignColorId $request->request->get('colorId');
  12357.             if ($request->request->has('productionScheduleId'))
  12358.                 $assignProductionScheduleId $request->request->get('productionScheduleId');
  12359.             if ($request->request->has('warehouseId'))
  12360.                 $warehouseId $request->request->get('warehouseId');
  12361.             if ($request->request->has('warehouseActionId'))
  12362.                 $warehouseActionId $request->request->get('warehouseActionId');
  12363.             if ($request->request->has('position'))
  12364.                 $toAssignPosition $request->request->get('position');
  12365.             if ($assignColorId == '')
  12366.                 $assignColorId 0;
  12367.         }
  12368.         if ($productByCodeIds == null)
  12369.             $productByCodeIds = [];
  12370.         $productByCodeData = [];
  12371.         $productList = [];
  12372.         $productIds = [];
  12373.         if ($print_selection_type == 2) {
  12374.             //range
  12375.             $productByCodeIds Inventory::getIdsFromIdSelectionStr($print_selection_string);
  12376.         }
  12377.         $labelData = [
  12378.             'formatId' => 0
  12379.         ];
  12380.         $formatId 0;
  12381.         if (!empty($productByCodeIds)) {
  12382.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12383.                 ->findBy(
  12384.                     array(
  12385.                         'productByCodeId' => $productByCodeIds
  12386.                     )
  12387.                 );
  12388.             foreach ($productByCodeData as $d) {
  12389.                 if ($d->getStage() < 10$d->setStage(11);
  12390.                 if ($assignProductId != '') {
  12391.                     $d->setProductId($assignProductId);
  12392.                 }
  12393.                 if ($assignColorId != 0) {
  12394.                     $d->setColorId($assignColorId);
  12395.                 } else {
  12396.                     $productData $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12397.                         ->findOneBy(
  12398.                             array(
  12399.                                 'id' => $assignProductId
  12400.                             )
  12401.                         );
  12402.                     if ($productData) {
  12403.                         $d->setColorId($productData->getDefaultColorId());
  12404.                     }
  12405.                 }
  12406.                 if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  12407.                     $d->setDefaultLabelFormatId($assignLabelFormatId);
  12408.                     $d->setDeviceLabelFormatId($assignLabelFormatId);
  12409.                 }
  12410.                 $toAssignPosition != '' $d->setPosition($toAssignPosition) : '';
  12411.                 $warehouseId != '' $d->setWarehouseId($warehouseId) : '';
  12412.                 $warehouseActionId != '' $d->setWarehouseActionId($warehouseActionId) : '';
  12413.                 if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  12414.                     $d->setProductionScheduleId($assignProductionScheduleId);
  12415.                     $productionSchedule $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  12416.                         ->findOneBy(
  12417.                             array(
  12418.                                 'productionScheduleId' => $assignProductionScheduleId
  12419.                             )
  12420.                         );
  12421.                     if ($productionSchedule) {
  12422.                         if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  12423.                             //becuase it will assigned at previous lines
  12424.                         } else {
  12425.                             $d->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  12426.                             $d->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  12427.                         }
  12428.                         $d->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  12429.                         $d->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  12430.                     }
  12431.                 }
  12432.                 $em->flush();
  12433.                 if ($d->getProductId() != '' || $d->getProductId() != null)
  12434.                     $productIds[] = $d->getProductId();
  12435.                 $formatId $d->getDeviceLabelFormatId();
  12436.             }
  12437.         }
  12438.         $labelFormatHere $em->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  12439.             ->findOneBy(
  12440.                 array(
  12441.                     'formatId' => $formatId,
  12442. //                        'CompanyId' => $companyId
  12443.                 )
  12444.             );
  12445.         if ($labelFormatHere) {
  12446.             $formatData json_decode($labelFormatHere->getFormatData(), true);
  12447.             if ($formatData == null$formatData = [];
  12448.             $labelData = array(
  12449.                 'id' => $labelFormatHere->getFormatId(),
  12450.                 'formatId' => $labelFormatHere->getFormatId(),
  12451.                 'labelType' => $labelFormatHere->getLabelType(),
  12452.                 'name' => $labelFormatHere->getName(),
  12453.                 'width' => $labelFormatHere->getWidth(),
  12454.                 'pageWidth' => $labelFormatHere->getPageWidth(),
  12455.                 'height' => $labelFormatHere->getheight(),
  12456.                 'pageHeight' => $labelFormatHere->getPageHeight(),
  12457.                 'formatData' => $formatData,
  12458.             );
  12459.         }
  12460.         $productList Inventory::ProductList($em$this->getLoggedUserCompanyId($request), 10''$productIds);
  12461.         $company_data Company::getCompanyData($em1);
  12462.         $document_mark = array(
  12463.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12464.             'copy' => ''
  12465.         );
  12466.         $dt $productByCodeData;
  12467.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12468.             $html $this->renderView('@Inventory/pages/print/print_label.html.twig',
  12469.                 array(
  12470.                     //full array here
  12471.                     'pdf' => true,
  12472.                     'page_title' => 'Device Labels',
  12473.                     'export' => 'print',
  12474.                     'repeatCount' => $repeatCount,
  12475.                     'labelData' => $labelData,
  12476.                     'brandList' => Inventory::GetBrandList($em$companyId),
  12477. //                    'item_id' => $item_id,
  12478.                     'data' => $dt,
  12479.                     'productList' => $productList,
  12480.                     'approval_data' => [],
  12481.                     'document_log' => [],
  12482.                     'document_mark_image' => $document_mark['original'],
  12483.                     'company_name' => $company_data->getName(),
  12484.                     'company_data' => $company_data,
  12485.                     'company_address' => $company_data->getAddress(),
  12486.                     'company_image' => $company_data->getImage(),
  12487.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12488.                     'red' => 0
  12489.                 )
  12490.             );
  12491.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12492. //                'orientation' => 'landscape',
  12493.                 'enable-javascript' => true,
  12494. //                'javascript-delay' => 1000,
  12495.                 'no-stop-slow-scripts' => false,
  12496.                 'no-background' => false,
  12497.                 'lowquality' => false,
  12498.                 'encoding' => 'utf-8',
  12499. //            'images' => true,
  12500. //            'cookie' => array(),
  12501.                 'dpi' => 300,
  12502.                 'image-dpi' => 300,
  12503. //                'enable-external-links' => true,
  12504. //                'enable-internal-links' => true
  12505.             ));
  12506.             return new Response(
  12507.                 $pdf_response,
  12508.                 200,
  12509.                 array(
  12510.                     'Content-Type' => 'application/pdf',
  12511.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  12512.                 )
  12513.             );
  12514.         }
  12515.         $url $this->generateUrl(
  12516.             'print_label'
  12517.         );
  12518.         if ($returnJson == && $printFlag == 0) {
  12519. //                    $dr = $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findBy(
  12520. //                        array(
  12521. //                            'salesOrderId' => $orderId, ///material
  12522. //
  12523. //                        )
  12524. //                    );
  12525.             return new JsonResponse(array(
  12526.                 'success' => true,
  12527. //                        'documentHash' => $order->getDocumentHash(),
  12528. //                'documentId' => $receiptId,
  12529. //                'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
  12530. //
  12531. //                'viewUrl' => $url . "/" . $receiptId,
  12532.             ));
  12533.         } else return $this->render('@Inventory/pages/print/print_label.html.twig',
  12534.             array(
  12535.                 'page_title' => 'Product Labels',
  12536. //                'export'=>'pdf,print',
  12537.                 'data' => $dt,
  12538.                 'productList' => $productList,
  12539.                 'repeatCount' => $repeatCount,
  12540. //                'item_id' => $item_id,
  12541.                 'labelData' => $labelData,
  12542.                 'brandList' => Inventory::GetBrandList($em$companyId),
  12543.                 'approval_data' => [],
  12544.                 'document_log' => [],
  12545.                 'document_mark_image' => $document_mark['original'],
  12546.                 'company_name' => $company_data->getName(),
  12547.                 'company_data' => $company_data,
  12548.                 'company_address' => $company_data->getAddress(),
  12549.                 'company_image' => $company_data->getImage(),
  12550.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12551.                 'red' => 0
  12552.             )
  12553.         );
  12554.     }
  12555.     public
  12556.     function PrintCartonLabelAction(Request $request$id)
  12557.     {
  12558.         $em $this->getDoctrine()->getManager();
  12559. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12560.         $repeatCount 1;
  12561.         $assignProductId '';
  12562.         $productByCodeIds = [];
  12563.         $cartonId 0;
  12564.         if ($id != 0)
  12565.             $cartonId $id;
  12566.         $colorText '';
  12567.         $weightText '';
  12568.         if ($request->query->has('repeatCount'))
  12569.             $repeatCount $request->query->get('repeatCount');
  12570.         if ($request->request->has('printCartonId'))
  12571.             $cartonId $request->request->get('printCartonId');
  12572.         if ($request->request->has('printCartonColorText'))
  12573.             $colorText $request->request->get('printCartonColorText');
  12574.         if ($request->request->has('printCartonWeightText'))
  12575.             $weightText $request->request->get('printCartonWeightText');
  12576.         $labelData = [
  12577.             'formatId' => 0
  12578.         ];
  12579.         if ($productByCodeIds == null)
  12580.             $productByCodeIds = [];
  12581.         $productByCodeData = [];
  12582.         $cartonData = [];
  12583.         $product = [];
  12584.         if ($cartonId != 0) {
  12585.             $cartonData $em->getRepository('ApplicationBundle\\Entity\\Carton')
  12586.                 ->findOneBy(
  12587.                     array(
  12588.                         'id' => $cartonId
  12589.                     )
  12590.                 );
  12591.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12592.                 ->findBy(
  12593.                     array(
  12594.                         'cartonId' => $cartonId
  12595.                     )
  12596.                 );
  12597. //            if(!empty($productByCodeData))
  12598. //                $product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12599. //                ->findOneBy(
  12600. //                    array(
  12601. //                        'id' => $productByCodeData[0]->getProductId()
  12602. //                    )
  12603. //                );
  12604. //            else
  12605.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  12606.                 ->findOneBy(
  12607.                     array(
  12608.                         'id' => $cartonData->getProductId()
  12609.                     )
  12610.                 );
  12611.             $formatId $cartonData->getCartonLabelFormatId();
  12612.             $labelFormatHere $em->getRepository('ApplicationBundle\\Entity\\LabelFormat')
  12613.                 ->findOneBy(
  12614.                     array(
  12615.                         'formatId' => $formatId,
  12616. //                        'CompanyId' => $companyId
  12617.                     )
  12618.                 );
  12619.             if ($labelFormatHere) {
  12620.                 $formatData json_decode($labelFormatHere->getFormatData(), true);
  12621.                 if ($formatData == null$formatData = [];
  12622.                 $labelData = array(
  12623.                     'id' => $labelFormatHere->getFormatId(),
  12624.                     'formatId' => $labelFormatHere->getFormatId(),
  12625.                     'labelType' => $labelFormatHere->getLabelType(),
  12626.                     'name' => $labelFormatHere->getName(),
  12627.                     'width' => $labelFormatHere->getWidth(),
  12628.                     'pageWidth' => $labelFormatHere->getPageWidth(),
  12629.                     'height' => $labelFormatHere->getheight(),
  12630.                     'pageHeight' => $labelFormatHere->getPageHeight(),
  12631.                     'formatData' => $formatData,
  12632.                 );
  12633.             }
  12634.         }
  12635.         $company_data Company::getCompanyData($em1);
  12636.         $document_mark = array(
  12637.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12638.             'copy' => ''
  12639.         );
  12640.         $dt $productByCodeData;
  12641.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12642.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  12643.                 array(
  12644.                     //full array here
  12645.                     'pdf' => true,
  12646.                     'page_title' => 'Carton Labels',
  12647.                     'export' => 'print',
  12648.                     'labelData' => $labelData,
  12649.                     'repeatCount' => $repeatCount,
  12650. //                    'item_id' => $item_id,
  12651.                     'data' => $dt,
  12652.                     'cartonData' => $cartonData,
  12653.                     'product' => $product,
  12654.                     'colorText' => $colorText,
  12655.                     'weightText' => $weightText,
  12656.                     'approval_data' => [],
  12657.                     'document_log' => [],
  12658.                     'document_mark_image' => $document_mark['original'],
  12659.                     'company_name' => $company_data->getName(),
  12660.                     'company_data' => $company_data,
  12661.                     'company_address' => $company_data->getAddress(),
  12662.                     'company_image' => $company_data->getImage(),
  12663.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12664.                     'red' => 0
  12665.                 )
  12666.             );
  12667.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12668. //                'orientation' => 'landscape',
  12669.                 'enable-javascript' => true,
  12670. //                'javascript-delay' => 1000,
  12671.                 'no-stop-slow-scripts' => false,
  12672.                 'no-background' => false,
  12673.                 'lowquality' => false,
  12674.                 'encoding' => 'utf-8',
  12675. //            'images' => true,
  12676. //            'cookie' => array(),
  12677.                 'dpi' => 300,
  12678.                 'image-dpi' => 300,
  12679. //                'enable-external-links' => true,
  12680. //                'enable-internal-links' => true
  12681.             ));
  12682.             return new Response(
  12683.                 $pdf_response,
  12684.                 200,
  12685.                 array(
  12686.                     'Content-Type' => 'application/pdf',
  12687.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  12688.                 )
  12689.             );
  12690.         }
  12691.         if ($request->query->has('previewOnly')) {
  12692.             $html $this->renderView('@Inventory/pages/print/print_carton_label.html.twig',
  12693.                 array(
  12694.                     'page_title' => 'Carton Labels',
  12695. //                'export'=>'pdf,print',
  12696.                     'data' => $dt,
  12697.                     'skip_parameters' => 1,
  12698.                     'labelData' => $labelData,
  12699.                     'cartonData' => $cartonData,
  12700.                     'product' => $product,
  12701.                     'colorText' => $colorText,
  12702.                     'weightText' => $weightText,
  12703.                     'repeatCount' => $repeatCount,
  12704. //                'item_id' => $item_id,
  12705.                     'approval_data' => [],
  12706.                     'document_log' => [],
  12707.                     'document_mark_image' => $document_mark['original'],
  12708.                     'company_name' => $company_data->getName(),
  12709.                     'company_data' => $company_data,
  12710.                     'company_address' => $company_data->getAddress(),
  12711.                     'company_image' => $company_data->getImage(),
  12712.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12713.                     'red' => 0
  12714.                 )
  12715.             );
  12716.             if ($request->query->has('returnJson')) {
  12717.                 return new JsonResponse(
  12718.                     array(
  12719.                         'success' => true,
  12720.                         'page_title' => 'Product Details',
  12721.                         'company_data' => $company_data,
  12722.                         'renderedHtml' => $html,
  12723. //                'productData' => $productData,
  12724. //                'currInvList' => $currInvList,
  12725. //                'productList' => Inventory::ProductList($em, $companyId),
  12726. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  12727. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  12728. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  12729. //                'unitList' => Inventory::UnitTypeList($em),
  12730. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  12731. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  12732. //                'warehouseList' => Inventory::WarehouseList($em),
  12733.                     )
  12734.                 );
  12735.             }
  12736.         }
  12737.         return $this->render('@Inventory/pages/print/print_carton_label.html.twig',
  12738.             array(
  12739.                 'page_title' => 'Carton Labels',
  12740. //                'export'=>'pdf,print',
  12741.                 'data' => $dt,
  12742.                 'cartonData' => $cartonData,
  12743.                 'product' => $product,
  12744. //                'productByCodeData' => $productByCodeData,
  12745.                 'colorText' => $colorText,
  12746.                 'weightText' => $weightText,
  12747.                 'repeatCount' => $repeatCount,
  12748.                 'labelData' => $labelData,
  12749. //                'item_id' => $item_id,
  12750.                 'approval_data' => [],
  12751.                 'document_log' => [],
  12752.                 'document_mark_image' => $document_mark['original'],
  12753.                 'company_name' => $company_data->getName(),
  12754.                 'company_data' => $company_data,
  12755.                 'company_address' => $company_data->getAddress(),
  12756.                 'company_image' => $company_data->getImage(),
  12757.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12758.                 'red' => 0
  12759.             )
  12760.         );
  12761.     }
  12762.     public function AssignInfoToProductByCodeAction(Request $request$id)
  12763.     {
  12764.         $em $this->getDoctrine()->getManager();
  12765.         $companyId $this->getLoggedUserCompanyId($request);
  12766. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  12767.         $cartonId '';
  12768.         $passStatus 5;
  12769.         $assignProductId '';
  12770.         $assignProductionId '';
  12771.         $assignProductionScheduleId '';
  12772.         $gbWeightGm '';
  12773.         $dvWeightGm '';
  12774.         $cartonWeightGm '';
  12775.         if ($request->request->has('cartonId'))
  12776.             $cartonId $request->request->get('cartonId');
  12777.         if ($request->request->has('passStatus'))
  12778.             $passStatus $request->request->get('passStatus');
  12779.         if ($request->request->has('productByCodeId'))
  12780.             $id $request->request->get('productByCodeId');
  12781.         if ($request->request->has('productId'))
  12782.             $assignProductId $request->request->get('productId');
  12783.         if ($request->request->has('productionId'))
  12784.             $assignProductionId $request->request->get('productionId');
  12785.         if ($request->request->has('productionScheduleId'))
  12786.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  12787.         if ($request->request->has('gbWeightGm'))
  12788.             $gbWeightGm $request->request->get('gbWeightGm');
  12789.         if ($request->request->has('dvWeightGm'))
  12790.             $dvWeightGm $request->request->get('dvWeightGm');
  12791.         if ($request->request->has('cartonWeightGm'))
  12792.             $cartonWeightGm $request->request->get('cartonWeightGm');
  12793.         $cartonAssignedAlready 0;
  12794.         $otherData = array(
  12795.             'currentCartonBalance' => 0,
  12796.             'currentCartonCapacity' => 0,
  12797.             'currentCartonAssigned' => 0,
  12798.             'currentCartonFull' => 0,
  12799.         );
  12800.         if ($id != && $id != '') {
  12801.             $productByCodeData $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12802.                 ->findOneBy(
  12803.                     array(
  12804.                         'productByCodeId' => $id
  12805.                     )
  12806.                 );
  12807.             if ($assignProductId != ''$productByCodeData->setProductId($assignProductId);
  12808.             if ($productByCodeData->getCartonId() != '' || $productByCodeData->getCartonId() != null)
  12809.                 $cartonAssignedAlready 1;
  12810.             else if ($cartonId != ''$productByCodeData->setCartonId($cartonId);
  12811.             if ($dvWeightGm != ''$productByCodeData->setSingleWeightGm($dvWeightGm);
  12812.             if ($gbWeightGm != '') {
  12813.                 $productByCodeData->setPackagedWeightGm($gbWeightGm);
  12814.             }
  12815.             $colorText '_NA_';
  12816.             if ($passStatus != 5$productByCodeData->setStage($passStatus);
  12817.             $productByCodeData->setCompanyId($companyId);
  12818.             if ($assignProductionId != '') {
  12819.                 $productByCodeData->setProductionId($assignProductionId);
  12820.                 $productionData $em->getRepository('ApplicationBundle\\Entity\\Production')
  12821.                     ->findOneBy(
  12822.                         array(
  12823.                             'productionId' => $assignProductionId
  12824.                         )
  12825.                     );
  12826.                 if ($assignProductId != '' && $assignProductId != null && $assignProductId != 0)
  12827.                     $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  12828.                         array(
  12829.                             'productionId' => $assignProductionId,
  12830.                             'productId' => $assignProductId,
  12831.                             'type' => 1,
  12832.                         )
  12833.                     );
  12834.                 else
  12835.                     $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  12836.                         array(
  12837.                             'productionId' => $assignProductionId,
  12838. //                            'productId' => $assignProductId,
  12839.                             'type' => 1,
  12840.                         )
  12841.                     );
  12842.                 $assignProductionScheduleId $productionData->getProductionScheduleId();
  12843.                 if ($productionItemData) {
  12844.                     $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  12845.                     $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  12846.                     $productByCodeData->setPosition(1);//in inventory
  12847.                     $productByCodeData->setSerialAssigned(1);
  12848.                     $productByCodeData->setColorId($productionItemData->getColorId());
  12849.                     $productByCodeData->setColorText($productionItemData->getColorText());
  12850.                     $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  12851.                     $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  12852.                     if ($passStatus == 1)//passed
  12853.                     {
  12854. //                    $transDate = new \DateTime();
  12855. //                    Inventory::addItemToInventoryCompact($em,
  12856. //                        $productionItemData->getProductId(),
  12857. //                        $productionItemData->getWarehouseId(),
  12858. //                        $productionItemData->getWarehouseId(),
  12859. //                        $productionData->getProducedItemActionTagId(),
  12860. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  12861. //                        $transDate,
  12862. //                        1,
  12863. //                        1,
  12864. //                        $entry['valueAdd'],
  12865. //                        $entry['valueSub'],
  12866. //                        $entry['price'],
  12867. //                        $this->getLoggedUserCompanyId($request),
  12868. //                        0,
  12869. //                        $entry['entity'],
  12870. //                        $entry['entityId'],
  12871. //                        $entry['entityDocHash']
  12872. //                    );
  12873.                     }
  12874.                     $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  12875.                     if ($transHistory == null)
  12876.                         $transHistory = [];
  12877.                     $transHistory[] = array(
  12878.                         'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  12879.                         'direction' => 'in',
  12880.                         'warehouseId' => $productionItemData->getWarehouseId(),
  12881.                         'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  12882.                         'fromWarehouseId' => 0,
  12883.                         'fromWarehouseActionId' => //stock of goods
  12884.                     );
  12885.                     $productByCodeData->setTransactionHistory(json_encode($transHistory));
  12886.                 }
  12887.             }
  12888.             if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  12889.                 $productByCodeData->setProductionScheduleId($assignProductionScheduleId);
  12890.                 $productionSchedule $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  12891.                     ->findOneBy(
  12892.                         array(
  12893.                             'productionScheduleId' => $assignProductionScheduleId
  12894.                         )
  12895.                     );
  12896.                 if ($productionSchedule) {
  12897.                     $productByCodeData->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  12898.                     $productByCodeData->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  12899.                     $productByCodeData->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  12900.                     $productByCodeData->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  12901.                     if ($productByCodeData->getProductionId() == null || $productByCodeData->getProductionId() == '' || $productByCodeData->getProductionId() == 0) {
  12902.                         $productionItemData $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')->findOneBy(
  12903.                             array(
  12904.                                 'productionScheduleId' => $assignProductionScheduleId,
  12905.                                 'productId' => $productionSchedule->getProducedProductId(),
  12906.                                 'type' => 1,
  12907.                             )
  12908.                         );
  12909. //                        $assignProductionScheduleId=$productionData->getProductionScheduleId();
  12910.                         if ($productionItemData) {
  12911.                             $productByCodeData->setProductionId($productionItemData->getProductionId());
  12912.                             $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  12913.                             $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  12914.                             $productByCodeData->setPosition(1);//in inventory
  12915.                             $productByCodeData->setSerialAssigned(1);
  12916.                             $productByCodeData->setColorId($productionItemData->getColorId());
  12917.                             $productByCodeData->setColorText($productionItemData->getColorText());
  12918.                             $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  12919.                             $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  12920.                             if ($passStatus == 1)//passed
  12921.                             {
  12922. //                    $transDate = new \DateTime();
  12923. //                    Inventory::addItemToInventoryCompact($em,
  12924. //                        $productionItemData->getProductId(),
  12925. //                        $productionItemData->getWarehouseId(),
  12926. //                        $productionItemData->getWarehouseId(),
  12927. //                        $productionData->getProducedItemActionTagId(),
  12928. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  12929. //                        $transDate,
  12930. //                        1,
  12931. //                        1,
  12932. //                        $entry['valueAdd'],
  12933. //                        $entry['valueSub'],
  12934. //                        $entry['price'],
  12935. //                        $this->getLoggedUserCompanyId($request),
  12936. //                        0,
  12937. //                        $entry['entity'],
  12938. //                        $entry['entityId'],
  12939. //                        $entry['entityDocHash']
  12940. //                    );
  12941.                             }
  12942.                             $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  12943.                             if ($transHistory == null)
  12944.                                 $transHistory = [];
  12945.                             $transHistory[] = array(
  12946.                                 'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  12947.                                 'direction' => 'in',
  12948.                                 'warehouseId' => $productionItemData->getWarehouseId(),
  12949.                                 'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  12950.                                 'fromWarehouseId' => 0,
  12951.                                 'fromWarehouseActionId' => //stock of goods
  12952.                             );
  12953.                             $productByCodeData->setTransactionHistory(json_encode($transHistory));
  12954.                         }
  12955.                     }
  12956.                 }
  12957.             }
  12958. //                $productByCodeData->setPurchaseWarrantyLastDate($new_pwld);
  12959.             $em->flush();
  12960.             //now adding carton
  12961.         }
  12962.         if ($cartonId != '') {
  12963.             $carton $em->getRepository('ApplicationBundle\\Entity\\Carton')
  12964.                 ->findOneBy(
  12965.                     array(
  12966.                         'id' => $cartonId
  12967.                     )
  12968.                 );
  12969.             if ($cartonWeightGm != ''$carton->setCartonWeightGm($cartonWeightGm);
  12970.             $otherData['currentCartonCapacity'] = $carton->getCartonCapacityCount();
  12971.             if ($cartonAssignedAlready == 0)
  12972.                 $carton->setCartonAssignedCount(($carton->getCartonAssignedCount()) + 1);
  12973.             $otherData['currentCartonAssigned'] = $carton->getCartonAssignedCount();
  12974.             $otherData['currentCartonBalance'] = $otherData['currentCartonCapacity'] - $otherData['currentCartonAssigned'];
  12975.             if ($otherData['currentCartonAssigned'] >= $otherData['currentCartonCapacity'])
  12976.                 $otherData['currentCartonFull'] = 1;
  12977.             $em->flush();
  12978.         }
  12979.         if ($cartonId != '') {
  12980. //                    if($cartonAssignedAlready==1)
  12981. //                    {
  12982.             $productByCodeDataListForThisCarton $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  12983.                 ->findBy(
  12984.                     array(
  12985.                         'cartonId' => $cartonId
  12986.                     )
  12987.                 );
  12988.             $carton $em->getRepository('ApplicationBundle\\Entity\\Carton')
  12989.                 ->findOneBy(
  12990.                     array(
  12991.                         'id' => $cartonId
  12992.                     )
  12993.                 );
  12994.             $total_carton_predicted_weight 0;
  12995.             $colorTextList = [];
  12996.             $cartonProductByCodeIds = [];
  12997.             foreach ($productByCodeDataListForThisCarton as $pikamaster) {
  12998.                 if (!in_array($pikamaster->getProductByCodeId(), $cartonProductByCodeIds))
  12999.                     $cartonProductByCodeIds[] = $pikamaster->getProductByCodeId();
  13000.                 if (!in_array($pikamaster->getColorText(), $colorTextList) && $pikamaster->getColorText() != null)
  13001.                     $colorTextList[] = $pikamaster->getColorText();
  13002.                 $total_carton_predicted_weight += ($pikamaster->getPackagedWeightGm());
  13003.                 if ($passStatus != 5)
  13004.                     if ($pikamaster->getStage() < $passStatus)
  13005.                         $pikamaster->setStage($passStatus);
  13006.             }
  13007.             if ($carton)
  13008.                 $carton->setCartonCalculatedWeightGm($total_carton_predicted_weight);
  13009.             if ($passStatus != 5)
  13010.                 $carton->setStage($passStatus);
  13011.             $carton->setColors(implode(','$colorTextList));
  13012.             $carton->setCartonProductByCodeIds(json_encode($cartonProductByCodeIds));
  13013.             $em->flush();
  13014.         }
  13015.         return new JsonResponse(array(
  13016.             'success' => true,
  13017.             'otherData' => $otherData,
  13018.         ));
  13019.     }
  13020.     public function RefreshCartonListAction(Request $request$id)
  13021.     {
  13022.         $em $this->getDoctrine()->getManager();
  13023. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  13024.         $cartonListArray = [];
  13025.         $cartonList = [];
  13026.         $assignableCartonList = [];
  13027.         $assignableCartonListArray = [];
  13028.         $assignable 0;
  13029.         $cartonId '';
  13030.         $passStatus 5;
  13031.         $assignProductId '';
  13032.         $assignProductionId '';
  13033.         $assignProductionScheduleId '';
  13034.         if ($request->request->has('productionId'))
  13035.             $assignProductionId $request->request->get('productionId');
  13036.         if ($request->request->has('productionScheduleId'))
  13037.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  13038.         if ($request->request->has('assignable'))
  13039.             $assignable $request->request->get('assignable');
  13040.         $cartonAssignedAlready 0;
  13041.         $otherData = array(
  13042.             'currentCartonBalance' => 0,
  13043.             'currentCartonCapacity' => 0,
  13044.             'currentCartonAssigned' => 0,
  13045.             'currentCartonFull' => 0,
  13046.         );
  13047.         //1st get all cartons for this production id
  13048.         $cartonList $em->getRepository('ApplicationBundle\\Entity\\Carton')
  13049.             ->findBy(
  13050.                 array(
  13051. //                    'productionId' => $assignProductionId,
  13052.                     'productionScheduleId' => $assignProductionScheduleId
  13053.                 )
  13054.             );
  13055.         $foundAssignable 0;
  13056.         $setId 0;
  13057.         $lastdmySer '';
  13058.         foreach ($cartonList as $carton) {
  13059.             $cartonData = array(
  13060.                 'id' => $carton->getId(),
  13061.                 'name' => $carton->getCartonNumber(),
  13062.                 'colors' => $carton->getColors(),
  13063.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  13064.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  13065.             );
  13066.             $cartonListArray[] = $cartonData;
  13067.             $cartonList[$cartonData['id']] = $cartonData;
  13068.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  13069.                 $foundAssignable 1;
  13070.                 $setId $cartonData['id'];
  13071.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  13072.                 $assignableCartonListArray[] = $cartonData;
  13073.             }
  13074.         }
  13075.         if ($assignable == && $foundAssignable == 0) {
  13076. //            $productionData = $em->getRepository('ApplicationBundle\\Entity\\Production')
  13077. //                ->findOneBy(
  13078. //                    array(
  13079. //                        'productionId' => $assignProductionId
  13080. //                    )
  13081. //                );
  13082.             $productionScheduleData $em->getRepository('ApplicationBundle\\Entity\\ProductionSchedule')
  13083.                 ->findOneBy(
  13084.                     array(
  13085.                         'productionScheduleId' => $assignProductionScheduleId
  13086.                     )
  13087.                 );
  13088.             $productId 0;
  13089.             $product = [];
  13090.             $productModel '';
  13091.             if ($productionScheduleData)
  13092.                 $productId $productionScheduleData->getProducedProductId();
  13093. //            $productionItem = $em->getRepository('ApplicationBundle\\Entity\\ProductionEntryItem')
  13094. //                ->findOneBy(
  13095. //                    array(
  13096. //                        'productionId' => $assignProductionId,
  13097. //                        'type' => 1
  13098. //                    )
  13099. //                );
  13100.             if ($productId != 0) {
  13101. //                    $productId = $productionItem->getProductId();
  13102.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  13103.                     ->findOneBy(
  13104.                         array(
  13105.                             'id' => $productId,
  13106.                         )
  13107.                     );
  13108.                 $productModel $product->getModelNo();
  13109.             }
  13110.             $carton = new Carton();
  13111.             $carton_capacity $productionScheduleData->getCartonCapacity();
  13112.             $carton->setProductId($productId);
  13113.             $carton->setProductionId($assignProductionId);
  13114.             $carton->setProductionScheduleId($assignProductionScheduleId);
  13115.             if ($productionScheduleData) {
  13116.                 $carton->setCartonLabelFormatId($productionScheduleData->getCartonLabelFormatId());
  13117.             }
  13118.             $carton->setCartonCapacityCount($carton_capacity == null $carton_capacity);
  13119.             $carton->setCartonAssignedCount(0);
  13120.             $carton->setCompanyId($this->getLoggedUserCompanyId($request));
  13121.             $today = new \DateTime();
  13122.             $dmy $productModel '-' . ($today->format('m')) . '-' . ($today->format('Y')) . '-' $productionScheduleData->getBatchNumber();
  13123.             $ser 0;
  13124.             $carton->setCartonNumberDmy($dmy);
  13125.             $carton->setCartonNumberLastSer(* (($today->format('h')) . '' . ($today->format('i'))));
  13126.             $carton->setCartonNumber($dmy '-' . ($today->format('h')) . '' . ($today->format('i')));
  13127.             $em->persist($carton);
  13128.             $em->flush();
  13129.             $cartonData = array(
  13130.                 'id' => $carton->getId(),
  13131.                 'name' => $carton->getCartonNumber(),
  13132.                 'colors' => $carton->getColors(),
  13133.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  13134.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  13135.             );
  13136.             $cartonListArray[] = $cartonData;
  13137.             $cartonList[$cartonData['id']] = $cartonData;
  13138.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  13139.                 $foundAssignable 1;
  13140.                 $setId $cartonData['id'];
  13141.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  13142.                 $assignableCartonListArray[] = $cartonData;
  13143.             }
  13144.         }
  13145.         return new JsonResponse(array(
  13146.             'success' => true,
  13147.             'cartonList' => $cartonList,
  13148.             'cartonListArray' => $cartonListArray,
  13149.             'assignableCartonList' => $assignableCartonList,
  13150.             'assignableCartonListArray' => $assignableCartonListArray,
  13151.             'setId' => $setId,
  13152.         ));
  13153.     }
  13154.     public
  13155.     function PrintDrBarcodeAction(Request $request$id$item_id)
  13156.     {
  13157.         $em $this->getDoctrine()->getManager();
  13158.         $dt Inventory::GetDrDetails($em$id$item_id);
  13159.         $repeatCount 1;
  13160.         if ($request->query->has('repeatCount'))
  13161.             $repeatCount $request->query->get('repeatCount');
  13162.         $company_data Company::getCompanyData($em1);
  13163.         $document_mark = array(
  13164.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13165.             'copy' => ''
  13166.         );
  13167.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13168.             $html $this->renderView('@Inventory/pages/print/print_dr_barcodes.html.twig',
  13169.                 array(
  13170.                     //full array here
  13171.                     'pdf' => true,
  13172.                     'page_title' => 'Challan Barcodes',
  13173.                     'export' => 'print',
  13174.                     'repeatCount' => $repeatCount,
  13175.                     'item_id' => $item_id,
  13176.                     'data' => $dt,
  13177.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13178.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13179.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13180.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  13181.                         $id,
  13182.                         $dt['created_by'],
  13183.                         $dt['edited_by']),
  13184.                     'document_mark_image' => $document_mark['original'],
  13185.                     'company_name' => $company_data->getName(),
  13186.                     'company_data' => $company_data,
  13187.                     'company_address' => $company_data->getAddress(),
  13188.                     'company_image' => $company_data->getImage(),
  13189.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13190.                     'red' => 0
  13191.                 )
  13192.             );
  13193.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13194. //                'orientation' => 'landscape',
  13195.                 'enable-javascript' => true,
  13196. //                'javascript-delay' => 1000,
  13197.                 'no-stop-slow-scripts' => false,
  13198.                 'no-background' => false,
  13199.                 'lowquality' => false,
  13200.                 'encoding' => 'utf-8',
  13201. //            'images' => true,
  13202. //            'cookie' => array(),
  13203.                 'dpi' => 300,
  13204.                 'image-dpi' => 300,
  13205. //                'enable-external-links' => true,
  13206. //                'enable-internal-links' => true
  13207.             ));
  13208.             return new Response(
  13209.                 $pdf_response,
  13210.                 200,
  13211.                 array(
  13212.                     'Content-Type' => 'application/pdf',
  13213.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  13214.                 )
  13215.             );
  13216.         }
  13217.         return $this->render('@Inventory/pages/print/print_dr_barcodes.html.twig',
  13218.             array(
  13219.                 'page_title' => 'Challan barcodes',
  13220. //                'export'=>'pdf,print',
  13221.                 'data' => $dt,
  13222.                 'repeatCount' => $repeatCount,
  13223.                 'item_id' => $item_id,
  13224.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13225.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13226.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13227.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  13228.                     $id,
  13229.                     $dt['created_by'],
  13230.                     $dt['edited_by']),
  13231.                 'document_mark_image' => $document_mark['original'],
  13232.                 'company_name' => $company_data->getName(),
  13233.                 'company_data' => $company_data,
  13234.                 'company_address' => $company_data->getAddress(),
  13235.                 'company_image' => $company_data->getImage(),
  13236.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13237.                 'red' => 0
  13238.             )
  13239.         );
  13240.     }
  13241.     public
  13242.     function PrintIrrBarcodeAction(Request $request$id$item_id)
  13243.     {
  13244.         $em $this->getDoctrine()->getManager();
  13245.         $dt Inventory::GetIrrDetails($em$id$item_id);
  13246.         $repeatCount 1;
  13247.         if ($request->query->has('repeatCount'))
  13248.             $repeatCount $request->query->get('repeatCount');
  13249.         $company_data Company::getCompanyData($em1);
  13250.         $document_mark = array(
  13251.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13252.             'copy' => ''
  13253.         );
  13254.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13255.             $html $this->renderView('@Inventory/pages/print/print_irr_barcodes.html.twig',
  13256.                 array(
  13257.                     //full array here
  13258.                     'pdf' => true,
  13259.                     'page_title' => 'Sales Return Barcodes',
  13260.                     'export' => 'print',
  13261.                     'repeatCount' => $repeatCount,
  13262.                     'item_id' => $item_id,
  13263.                     'data' => $dt,
  13264.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13265.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13266.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13267.                         array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13268.                         $id,
  13269.                         $dt['created_by'],
  13270.                         $dt['edited_by']),
  13271.                     'document_mark_image' => $document_mark['original'],
  13272.                     'company_name' => $company_data->getName(),
  13273.                     'company_data' => $company_data,
  13274.                     'company_address' => $company_data->getAddress(),
  13275.                     'company_image' => $company_data->getImage(),
  13276.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13277.                     'red' => 0
  13278.                 )
  13279.             );
  13280.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13281. //                'orientation' => 'landscape',
  13282.                 'enable-javascript' => true,
  13283. //                'javascript-delay' => 1000,
  13284.                 'no-stop-slow-scripts' => false,
  13285.                 'no-background' => false,
  13286.                 'lowquality' => false,
  13287.                 'encoding' => 'utf-8',
  13288. //            'images' => true,
  13289. //            'cookie' => array(),
  13290.                 'dpi' => 300,
  13291.                 'image-dpi' => 300,
  13292. //                'enable-external-links' => true,
  13293. //                'enable-internal-links' => true
  13294.             ));
  13295.             return new Response(
  13296.                 $pdf_response,
  13297.                 200,
  13298.                 array(
  13299.                     'Content-Type' => 'application/pdf',
  13300.                     'Content-Disposition' => 'attachment; filename="irr_barcodes.pdf"'
  13301.                 )
  13302.             );
  13303.         }
  13304.         return $this->render('@Inventory/pages/print/print_irr_barcodes.html.twig',
  13305.             array(
  13306.                 'page_title' => 'Sales Return barcodes',
  13307. //                'export'=>'pdf,print',
  13308.                 'data' => $dt,
  13309.                 'repeatCount' => $repeatCount,
  13310.                 'item_id' => $item_id,
  13311.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13312.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13313.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13314.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  13315.                     $id,
  13316.                     $dt['created_by'],
  13317.                     $dt['edited_by']),
  13318.                 'document_mark_image' => $document_mark['original'],
  13319.                 'company_name' => $company_data->getName(),
  13320.                 'company_data' => $company_data,
  13321.                 'company_address' => $company_data->getAddress(),
  13322.                 'company_image' => $company_data->getImage(),
  13323.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13324.                 'red' => 0
  13325.             )
  13326.         );
  13327.     }
  13328.     public
  13329.     function PrintSrcvBarcodeAction(Request $request$id$item_id)
  13330.     {
  13331.         $em $this->getDoctrine()->getManager();
  13332.         $dt Inventory::GetSrcvDetails($em$id$item_id);
  13333.         $repeatCount 1;
  13334.         if ($request->query->has('repeatCount'))
  13335.             $repeatCount $request->query->get('repeatCount');
  13336.         $company_data Company::getCompanyData($em1);
  13337.         $document_mark = array(
  13338.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13339.             'copy' => ''
  13340.         );
  13341.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13342.             $html $this->renderView('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  13343.                 array(
  13344.                     //full array here
  13345.                     'pdf' => true,
  13346.                     'page_title' => 'Grn Barcodes',
  13347.                     'export' => 'print',
  13348.                     'repeatCount' => $repeatCount,
  13349.                     'item_id' => $item_id,
  13350.                     'data' => $dt,
  13351.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13352.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13353.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13354.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13355.                         $id,
  13356.                         $dt['created_by'],
  13357.                         $dt['edited_by']),
  13358.                     'document_mark_image' => $document_mark['original'],
  13359.                     'company_name' => $company_data->getName(),
  13360.                     'company_data' => $company_data,
  13361.                     'company_address' => $company_data->getAddress(),
  13362.                     'company_image' => $company_data->getImage(),
  13363.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13364.                     'red' => 0
  13365.                 )
  13366.             );
  13367.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13368. //                'orientation' => 'landscape',
  13369.                 'enable-javascript' => true,
  13370. //                'javascript-delay' => 1000,
  13371.                 'no-stop-slow-scripts' => false,
  13372.                 'no-background' => false,
  13373.                 'lowquality' => false,
  13374.                 'encoding' => 'utf-8',
  13375. //            'images' => true,
  13376. //            'cookie' => array(),
  13377.                 'dpi' => 300,
  13378.                 'image-dpi' => 300,
  13379. //                'enable-external-links' => true,
  13380. //                'enable-internal-links' => true
  13381.             ));
  13382.             return new Response(
  13383.                 $pdf_response,
  13384.                 200,
  13385.                 array(
  13386.                     'Content-Type' => 'application/pdf',
  13387.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  13388.                 )
  13389.             );
  13390.         }
  13391.         return $this->render('@Inventory/pages/print/print_srcv_barcodes.html.twig',
  13392.             array(
  13393.                 'page_title' => 'Srcv barcodes',
  13394. //                'export'=>'pdf,print',
  13395.                 'data' => $dt,
  13396.                 'repeatCount' => $repeatCount,
  13397.                 'item_id' => $item_id,
  13398.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13399.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13400.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13401.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  13402.                     $id,
  13403.                     $dt['created_by'],
  13404.                     $dt['edited_by']),
  13405.                 'document_mark_image' => $document_mark['original'],
  13406.                 'company_name' => $company_data->getName(),
  13407.                 'company_data' => $company_data,
  13408.                 'company_address' => $company_data->getAddress(),
  13409.                 'company_image' => $company_data->getImage(),
  13410.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13411.                 'red' => 0
  13412.             )
  13413.         );
  13414.     }
  13415. //product by code
  13416.     public function ImeiListExcelUploadAction(Request $request)
  13417.     {
  13418.         $lastIndex $request->request->get('lastIndex'0);
  13419.         if ($request->isMethod('POST')) {
  13420.             $post $request->request;
  13421.             if ($request->request->has('chunkData')) {
  13422.                 //now getting the relevant checks
  13423.                 $check_list = [];
  13424.                 $csv_data $request->request->get('chunkData', []);
  13425.                 $em $this->getDoctrine()->getManager();
  13426.                 foreach ($csv_data as $ind => $data_row) {
  13427. //                    if ($ind == 1)
  13428. //                        continue;
  13429.                     $np $this->getDoctrine()
  13430.                         ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  13431.                         ->findOneBy(
  13432.                             array(
  13433.                                 'salesCode' => isset($data_row[4]) ? $data_row[4] : 0,
  13434. //                    'approved' =>  GeneralConstant::APPROVED,
  13435.                             )
  13436.                         );
  13437.                     if (!$np)
  13438.                         $np = new ProductByCode();
  13439. //                    $np = new ProductByCode();
  13440.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  13441.                     if (isset($data_row[1])) $np->setProductId($data_row[1]);
  13442.                     if (isset($data_row[0])) $np->setLcNumber($data_row[0]);
  13443.                     if (isset($data_row[2])) $np->setCartonNumber($data_row[2]);
  13444.                     if (isset($data_row[3])) $np->setSerialNo($data_row[3]);
  13445.                     $np->setSerialAssigned(isset($data_row[10]) ? $data_row[10] : 0);
  13446.                     if (isset($data_row[4])) $np->setImei1($data_row[4]);
  13447.                     if (isset($data_row[5])) $np->setImei2($data_row[5]);
  13448.                     if (isset($data_row[6])) $np->setImei3($data_row[6]);
  13449.                     if (isset($data_row[7])) $np->setImei4($data_row[7]);
  13450.                     if (isset($data_row[8])) $np->setBtMac($data_row[8]);
  13451.                     if (isset($data_row[9])) $np->setWlanMac($data_row[9]);
  13452.                     $np->setWarehouseId(isset($data_row[11]) ? $data_row[11] : 0);
  13453.                     $np->setWarehouseActionId(isset($data_row[12]) ? $data_row[12] : 0);
  13454.                     $np->setPosition(isset($data_row[13]) ? $data_row[13] : 0);//in inventory
  13455.                     $np->setPurchaseOrderId(0);
  13456.                     $np->setGrnId(0);
  13457.                     $np->setStage(0);
  13458.                     if (isset($data_row[3])) $np->setSalesCodeRange(json_encode([$data_row[3]]));
  13459. //                $np->setSalesCode($data_row[3]);
  13460.                     if (isset($data_row[4])) $np->setSalesCode($data_row[4]); //IMEI
  13461.                     $np->setSalesCodeSer(0);
  13462.                     $np->setSalesCodeDmy('');
  13463.                     $np->setPurchaseCodeRange("");
  13464.                     $np->setPurchaseReceiptDate(null);
  13465.                     $np->setLastInDate(null);
  13466.                     $np->setStatus(GeneralConstant::ACTIVE);
  13467.                     $np->setTransactionHistory(json_encode([
  13468.                         ]
  13469.                     ));
  13470.                     $np->setPurchaseWarrantyLastDate(null);
  13471.                     $em->persist($np);
  13472.                     $em->flush();
  13473.                 }
  13474.                 return new JsonResponse(array(
  13475.                     "success" => true,
  13476.                     "lastIndex" => $lastIndex,
  13477.                     "file_path" => '',
  13478.                     "csv_data" => $csv_data,
  13479.                     //                "debug_data"=>System::encryptSignature($r)
  13480.                 ));
  13481.             } else {
  13482.                 $path "";
  13483.                 $file_path "";
  13484.                 //            var_dump($request->files);
  13485.                 //        var_dump($request->getFile());
  13486.                 foreach ($request->files as $uploadedFile) {
  13487.                     //            if($uploadedFile->getImage())
  13488.                     //                var_dump($uploadedFile->getFile());
  13489.                     //                var_dump($uploadedFile);
  13490.                     if ($uploadedFile != null) {
  13491.                         $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  13492.                         $path $fileName;
  13493.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  13494.                         if (!file_exists($upl_dir)) {
  13495.                             mkdir($upl_dir0777true);
  13496.                         }
  13497.                         $file $uploadedFile->move($upl_dir$path);
  13498.                     }
  13499.                 }
  13500.                 //        print_r($file);
  13501.                 if ($path != "")
  13502.                     $file_path 'uploads/FileUploads/' $path;
  13503.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  13504.                 //
  13505.                 //            $img_file = file_get_contents($g_path);
  13506.                 //            $r=base64_encode($img_file);
  13507.                 $row 1;
  13508.                 $csv_data = [];
  13509.                 if (($handle fopen($g_path"r")) !== FALSE) {
  13510.                     while (($data fgetcsv($handle1000",")) !== FALSE) {
  13511.                         $num count($data);
  13512.                         $csv_data[$row] = $data;
  13513.                         //                    echo "<p> $num fields in line $row: <br /></p>\n";
  13514.                         $row++;
  13515.                         //                    for ($c=0; $c < $num; $c++) {
  13516.                         //                        echo $data[$c] . "<br />\n";
  13517.                         //                    }
  13518.                     }
  13519.                     fclose($handle);
  13520.                 }
  13521.                 //now getting the relevant checks
  13522.                 $check_list = [];
  13523.                 $em $this->getDoctrine()->getManager();
  13524.                 foreach ($csv_data as $ind => $data_row) {
  13525.                     if ($ind == 1)
  13526.                         continue;
  13527.                     $np = new ProductByCode();
  13528.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  13529.                     $np->setProductId($data_row[1]);
  13530.                     $np->setLcNumber($data_row[0]);
  13531.                     $np->setCartonNumber($data_row[2]);
  13532.                     $np->setSerialNo($data_row[3]);
  13533.                     $np->setSerialAssigned(0);
  13534.                     $np->setImei1($data_row[4]);
  13535.                     $np->setImei2($data_row[5]);
  13536.                     $np->setImei3($data_row[6]);
  13537.                     $np->setImei4($data_row[7]);
  13538.                     $np->setBtMac($data_row[8]);
  13539.                     $np->setWlanMac($data_row[9]);
  13540.                     $np->setWarehouseId(0);
  13541.                     $np->setWarehouseActionId(0);
  13542.                     $np->setPosition(0);//in inventory
  13543.                     $np->setPurchaseOrderId(0);
  13544.                     $np->setGrnId(0);
  13545.                     $np->setStage(0);
  13546.                     $np->setSalesCodeRange(json_encode([$data_row[3]]));
  13547. //                $np->setSalesCode($data_row[3]);
  13548.                     $np->setSalesCode($data_row[4]); //IMEI
  13549.                     $np->setSalesCodeSer(0);
  13550.                     $np->setSalesCodeDmy('');
  13551.                     $np->setPurchaseCodeRange("");
  13552.                     $np->setPurchaseReceiptDate(null);
  13553.                     $np->setLastInDate(null);
  13554.                     $np->setStatus(GeneralConstant::ACTIVE);
  13555.                     $np->setTransactionHistory(json_encode([
  13556.                         ]
  13557.                     ));
  13558.                     $np->setPurchaseWarrantyLastDate(null);
  13559.                     $em->persist($np);
  13560.                     $em->flush();
  13561.                 }
  13562.                 return new JsonResponse(array(
  13563.                     "success" => true,
  13564.                     "lastIndex" => $lastIndex,
  13565.                     "file_path" => $file_path,
  13566.                     "csv_data" => $csv_data,
  13567.                     //                "debug_data"=>System::encryptSignature($r)
  13568.                 ));
  13569.             }
  13570.         }
  13571.         return new JsonResponse(array(
  13572.             "success" => false,
  13573.             "file_path" => '',
  13574.             "csv_data" => [],
  13575.             "lastIndex" => $lastIndex,
  13576.         ));
  13577.     }
  13578.     public
  13579.     function ProductByCodeListAction(Request $request)
  13580.     {
  13581.         $em $this->getDoctrine()->getManager();
  13582.         $companyId $this->getLoggedUserCompanyId($request);
  13583.         $listData Inventory::GetProductListForProductByCodeListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  13584.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  13585.             if ($request->query->has('dataTableQry')) {
  13586.                 return new JsonResponse(
  13587.                     $listData
  13588.                 );
  13589.             }
  13590.         }
  13591.         $q = [];
  13592. //        $q = $this->getDoctrine()
  13593. //            ->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  13594. //            ->findBy(
  13595. //                array(
  13596. //                    'status' => GeneralConstant::ACTIVE,
  13597. ////                    'approved' =>  GeneralConstant::APPROVED,
  13598. //                )
  13599. //
  13600. //            );
  13601.         //temp start
  13602. //        foreach($q as $np) {
  13603. //            if($np->getPosition()==1) {   /// only starting ones or in warehouse ones
  13604. //                $temp_obj = json_decode($np->getTransactionHistory());
  13605. //                if ($temp_obj != null) {
  13606. //                    $transHistory = [];
  13607. //                    $transHistory[] = $temp_obj;
  13608. //                    $np->setTransactionHistory(json_encode($transHistory));
  13609. //                }
  13610. //            }
  13611. //            $em->flush();
  13612. //        }
  13613.         ///temp end
  13614.         $stage_list = array(
  13615.             => 'Pending',
  13616.             => 'Pending',
  13617.             => 'Complete',
  13618.             => 'Partial',
  13619.         );
  13620.         $data = [];
  13621. //        foreach($q as $entry)
  13622. //        {
  13623. //            $data[]=array(
  13624. //                'doc_date'=>$entry->getStockRequisitionDate(),
  13625. //                'id'=>$entry->getStockRequisitionId(),
  13626. //                'doc_hash'=>$entry->getDocumentHash(),
  13627. //                'approval_status'=>GeneralConstant::$approvalStatus[$entry->getApproved()],
  13628. //                'stage'=>$stage_list[$entry->getStage()]
  13629. //
  13630. //            );
  13631. //        }
  13632.         return $this->render('@Inventory/pages/views/product_by_code_list.html.twig',
  13633.             array(
  13634.                 'page_title' => 'Product List',
  13635.                 'data' => $q,
  13636. //                'listData' => $listData,
  13637.                 'products' => Inventory::ProductList($em),
  13638.                 'warehouseList' => Inventory::WarehouseList($em)
  13639.             )
  13640.         );
  13641.     }
  13642. //SR
  13643.     public
  13644.     function SrListAction(Request $request)
  13645.     {
  13646.         $q $this->getDoctrine()
  13647.             ->getRepository('ApplicationBundle\\Entity\\StockRequisition')
  13648.             ->findBy(
  13649.                 array(
  13650.                     'status' => GeneralConstant::ACTIVE,
  13651. //                    'approved' =>  GeneralConstant::APPROVED,
  13652.                 )
  13653.                 ,
  13654.                 array(
  13655.                     'stockRequisitionDate' => 'DESC'
  13656.                 )
  13657.             );
  13658.         $stage_list = array(
  13659.             => 'Pending',
  13660.             => 'Pending',
  13661.             => 'Complete',
  13662.             => 'Partial',
  13663.         );
  13664.         $data = [];
  13665.         foreach ($q as $entry) {
  13666.             $data[] = array(
  13667.                 'doc_date' => $entry->getStockRequisitionDate(),
  13668.                 'id' => $entry->getStockRequisitionId(),
  13669.                 'doc_hash' => $entry->getDocumentHash(),
  13670.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13671.                 'stage' => $stage_list[$entry->getStage()],
  13672.                 'indentTagged' => $entry->getIndentTagged(),
  13673.                 'srIds' => $entry->getSrIds(),
  13674.                 'irIds' => $entry->getIrIds(),
  13675.                 'prIds' => $entry->getPrIds(),
  13676.                 'poIds' => $entry->getPoIds(),
  13677.             );
  13678.         }
  13679.         return $this->render('@Inventory/pages/views/sr_list.html.twig',
  13680.             array(
  13681.                 'page_title' => 'Stock Requisition List',
  13682.                 'data' => $data
  13683.             )
  13684.         );
  13685.     }
  13686.     public
  13687.     function ViewSrAction(Request $request$id)
  13688.     {
  13689.         $em $this->getDoctrine()->getManager();
  13690.         $dt Inventory::GetSrDetails($em$id);
  13691.         return $this->render(
  13692.             '@Inventory/pages/views/view_stock_requisition.html.twig',
  13693.             array(
  13694.                 'page_title' => 'Stock requisition',
  13695.                 'data' => $dt,
  13696.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13697.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13698.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13699.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13700.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13701.                     $id,
  13702.                     $dt['created_by'],
  13703.                     $dt['edited_by'])
  13704.             )
  13705.         );
  13706.     }
  13707.     public
  13708.     function PrintSrAction(Request $request$id)
  13709.     {
  13710.         $em $this->getDoctrine()->getManager();
  13711.         $dt Inventory::GetSrDetails($em$id);
  13712.         $company_data Company::getCompanyData($em1);
  13713.         $document_mark = array(
  13714.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13715.             'copy' => ''
  13716.         );
  13717.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13718.             $html $this->renderView('@Inventory/pages/print/print_sr.html.twig',
  13719.                 array(
  13720.                     //full array here
  13721.                     'pdf' => true,
  13722.                     'page_title' => 'Stock Requisition',
  13723.                     'export' => 'pdf,print',
  13724.                     'data' => $dt,
  13725.                     'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13726.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13727.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13728.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13729.                         array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13730.                         $id,
  13731.                         $dt['created_by'],
  13732.                         $dt['edited_by']),
  13733.                     'document_mark_image' => $document_mark['original'],
  13734.                     'company_name' => $company_data->getName(),
  13735.                     'company_data' => $company_data,
  13736.                     'company_address' => $company_data->getAddress(),
  13737.                     'company_image' => $company_data->getImage(),
  13738.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13739.                     'red' => 0
  13740.                 )
  13741.             );
  13742.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13743.                 //     'orientation' => 'landscape',
  13744.                 //     'enable-javascript' => true,
  13745.                 //     'javascript-delay' => 1000,
  13746.                 'no-stop-slow-scripts' => false,
  13747.                 'no-background' => false,
  13748.                 'lowquality' => false,
  13749.                 'encoding' => 'utf-8',
  13750.                 //    'images' => true,
  13751.                 //    'cookie' => array(),
  13752.                 'dpi' => 300,
  13753.                 'image-dpi' => 300,
  13754.                 //    'enable-external-links' => true,
  13755.                 //    'enable-internal-links' => true
  13756.             ));
  13757.             return new Response(
  13758.                 $pdf_response,
  13759.                 200,
  13760.                 array(
  13761.                     'Content-Type' => 'application/pdf',
  13762.                     'Content-Disposition' => 'attachment; filename="stock_requisition_' $id '.pdf"'
  13763.                 )
  13764.             );
  13765.         }
  13766.         return $this->render('@Inventory/pages/print/print_sr.html.twig',
  13767.             array(
  13768.                 'page_title' => 'Stock Requisition',
  13769.                 'export' => 'pdf,print',
  13770.                 'data' => $dt,
  13771.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  13772.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13773.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13774.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13775.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  13776.                     $id,
  13777.                     $dt['created_by'],
  13778.                     $dt['edited_by']),
  13779.                 'document_mark_image' => $document_mark['original'],
  13780.                 'company_name' => $company_data->getName(),
  13781.                 'company_data' => $company_data,
  13782.                 'company_address' => $company_data->getAddress(),
  13783.                 'company_image' => $company_data->getImage(),
  13784.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13785.                 'red' => 0
  13786.             )
  13787.         );
  13788.     }
  13789. //IR
  13790.     public
  13791.     function IrListAction(Request $request)
  13792.     {
  13793.         $q $this->getDoctrine()
  13794.             ->getRepository('ApplicationBundle\\Entity\\StoreRequisition')
  13795.             ->findBy(
  13796.                 array(
  13797.                     'status' => GeneralConstant::ACTIVE,
  13798. //                    'approved' =>  GeneralConstant::APPROVED,
  13799.                 ),
  13800.                 array(
  13801.                     'storeRequisitionDate' => 'DESC'
  13802.                 )
  13803.             );
  13804.         $stage_list = array(
  13805.             => 'Pending',
  13806.             => 'Pending',
  13807.             => 'Complete',
  13808.             => 'Partial',
  13809.         );
  13810.         $data = [];
  13811.         foreach ($q as $entry) {
  13812.             $data[] = array(
  13813.                 'doc_date' => $entry->getStoreRequisitionDate(),
  13814.                 'id' => $entry->getStoreRequisitionId(),
  13815.                 'doc_hash' => $entry->getDocumentHash(),
  13816.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13817.                 'stage' => $stage_list[$entry->getStage()],
  13818.                 'prTagged' => $entry->getIndentTagged(),
  13819.                 'srIds' => $entry->getSrIds(),
  13820.                 'irIds' => $entry->getIrIds(),
  13821.                 'prIds' => $entry->getPrIds(),
  13822.                 'poIds' => $entry->getPoIds(),
  13823.             );
  13824.         }
  13825.         return $this->render('@Inventory/pages/views/ir_list.html.twig',
  13826.             array(
  13827.                 'page_title' => 'Indent Requisition List',
  13828.                 'data' => $data
  13829.             )
  13830.         );
  13831.     }
  13832.     public
  13833.     function ViewIrAction(Request $request$id)
  13834.     {
  13835.         $em $this->getDoctrine()->getManager();
  13836.         $dt Inventory::GetIrDetails($em$id);
  13837.         return $this->render(
  13838.             '@Inventory/pages/views/view_indent_requisition.html.twig',
  13839.             array(
  13840.                 'page_title' => 'Indent',
  13841.                 'data' => $dt,
  13842.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13843.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13844.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13845.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13846.                     $id,
  13847.                     $dt['created_by'],
  13848.                     $dt['edited_by'])
  13849.             )
  13850.         );
  13851.     }
  13852.     public
  13853.     function PrintIrAction(Request $request$id)
  13854.     {
  13855.         $em $this->getDoctrine()->getManager();
  13856.         $dt Inventory::GetIrDetails($em$id);
  13857.         $company_data Company::getCompanyData($em1);
  13858.         $document_mark = array(
  13859.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13860.             'copy' => ''
  13861.         );
  13862.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13863.             $html $this->renderView('@Inventory/pages/print/print_ir.html.twig',
  13864.                 array(
  13865.                     //full array here
  13866.                     'pdf' => true,
  13867.                     'page_title' => 'Indent Requisition',
  13868.                     'export' => 'pdf,print',
  13869.                     'data' => $dt,
  13870.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13871.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13872.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13873.                         array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13874.                         $id,
  13875.                         $dt['created_by'],
  13876.                         $dt['edited_by']),
  13877.                     'document_mark_image' => $document_mark['original'],
  13878.                     'company_name' => $company_data->getName(),
  13879.                     'company_data' => $company_data,
  13880.                     'company_address' => $company_data->getAddress(),
  13881.                     'company_image' => $company_data->getImage(),
  13882.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13883.                     'red' => 0
  13884.                 )
  13885.             );
  13886.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13887. //                'orientation' => 'landscape',
  13888. //                'enable-javascript' => true,
  13889. //                'javascript-delay' => 1000,
  13890.                 'no-stop-slow-scripts' => false,
  13891.                 'no-background' => false,
  13892.                 'lowquality' => false,
  13893.                 'encoding' => 'utf-8',
  13894. //            'images' => true,
  13895. //            'cookie' => array(),
  13896.                 'dpi' => 300,
  13897.                 'image-dpi' => 300,
  13898. //                'enable-external-links' => true,
  13899. //                'enable-internal-links' => true
  13900.             ));
  13901.             return new Response(
  13902.                 $pdf_response,
  13903.                 200,
  13904.                 array(
  13905.                     'Content-Type' => 'application/pdf',
  13906.                     'Content-Disposition' => 'attachment; filename="indent_' $id '.pdf"'
  13907.                 )
  13908.             );
  13909.         }
  13910.         return $this->render('@Inventory/pages/print/print_ir.html.twig',
  13911.             array(
  13912.                 'page_title' => 'Indent Requisition',
  13913.                 'export' => 'pdf,print',
  13914.                 'data' => $dt,
  13915.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13916.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  13917.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  13918.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  13919.                     $id,
  13920.                     $dt['created_by'],
  13921.                     $dt['edited_by']),
  13922.                 'document_mark_image' => $document_mark['original'],
  13923.                 'company_name' => $company_data->getName(),
  13924.                 'company_data' => $company_data,
  13925.                 'company_address' => $company_data->getAddress(),
  13926.                 'company_image' => $company_data->getImage(),
  13927.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13928.                 'red' => 0
  13929.             )
  13930.         );
  13931.     }
  13932. //PR
  13933.     public
  13934.     function PrListAction(Request $request)
  13935.     {
  13936.         $q $this->getDoctrine()
  13937.             ->getRepository('ApplicationBundle\\Entity\\PurchaseRequisition')
  13938.             ->findBy(
  13939.                 array(
  13940.                     'status' => GeneralConstant::ACTIVE,
  13941. //                    'approved' =>  GeneralConstant::APPROVED,
  13942.                 ),
  13943.                 array(
  13944.                     'purchaseRequisitionDate' => 'DESC'
  13945.                 )
  13946.             );
  13947.         $stage_list = array(
  13948.             => 'Pending',
  13949.             => 'Pending',
  13950.             => 'Complete',
  13951.             => 'Partial',
  13952.         );
  13953.         $data = [];
  13954.         foreach ($q as $entry) {
  13955.             $data[] = array(
  13956.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  13957.                 'id' => $entry->getPurchaseRequisitionId(),
  13958.                 'doc_hash' => $entry->getDocumentHash(),
  13959.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  13960.                 'acquisition_status' => $entry->getAcquisitionStatus(),
  13961.                 'acquisition_start_date' => $entry->getAcquisitionStartDate(),
  13962.                 'acquisition_end_date' => $entry->getAcquisitionEndDate(),
  13963.                 'acquisition_method' => $entry->getquotationAcquisitionMethod(),
  13964.                 'poTagged' => $entry->getPoTagged(),
  13965.                 'typeHash' => $entry->getTypehash(),
  13966.                 'srIds' => $entry->getSrIds(),
  13967.                 'irIds' => $entry->getIrIds(),
  13968.                 'prIds' => $entry->getPrIds(),
  13969.                 'poIds' => $entry->getPoIds(),
  13970.             );
  13971.         }
  13972.         return $this->render('@Inventory/pages/views/pr_list.html.twig',
  13973.             array(
  13974.                 'page_title' => 'Purchase Requisition List',
  13975.                 'data' => $data
  13976.             )
  13977.         );
  13978.     }
  13979.     public
  13980.     function ServiceRequisitionListAction(Request $request)
  13981.     {
  13982.         $q $this->getDoctrine()
  13983.             ->getRepository('ApplicationBundle\\Entity\\PurchaseRequisition')
  13984.             ->findBy(
  13985.                 array(
  13986.                     'status' => GeneralConstant::ACTIVE,
  13987. //                    'approved' =>  GeneralConstant::APPROVED,
  13988.                 ),
  13989.                 array(
  13990.                     'purchaseRequisitionDate' => 'DESC'
  13991.                 )
  13992.             );
  13993.         $stage_list = array(
  13994.             => 'Pending',
  13995.             => 'Pending',
  13996.             => 'Complete',
  13997.             => 'Partial',
  13998.         );
  13999.         $data = [];
  14000.         foreach ($q as $entry) {
  14001.             $data[] = array(
  14002.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  14003.                 'id' => $entry->getPurchaseRequisitionId(),
  14004.                 'doc_hash' => $entry->getDocumentHash(),
  14005.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  14006.                 'poTagged' => $entry->getPoTagged(),
  14007.                 'typeHash' => $entry->getTypehash(),
  14008.                 'srIds' => $entry->getSrIds(),
  14009.                 'irIds' => $entry->getIrIds(),
  14010.                 'prIds' => $entry->getPrIds(),
  14011.                 'poIds' => $entry->getPoIds(),
  14012.             );
  14013.         }
  14014.         return $this->render('@Inventory/pages/views/service_requisition_list.html.twig',
  14015.             array(
  14016.                 'page_title' => 'Service Requisition List',
  14017.                 'data' => $data
  14018.             )
  14019.         );
  14020.     }
  14021.     public
  14022.     function ViewPrAction(Request $request$id)
  14023.     {
  14024.         $em $this->getDoctrine()->getManager();
  14025.         $dt Inventory::GetPrDetails($em$id);
  14026.         $companyId $this->getLoggedUserCompanyId($request);
  14027.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  14028.             array(
  14029.                 'page_title' => 'Purchase Requisition',
  14030.                 'data' => $dt,
  14031.                 'branchList' => Client::BranchList($em$companyId),
  14032.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  14033.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14034.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14035.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14036.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14037.                     $id,
  14038.                     $dt['created_by'],
  14039.                     $dt['edited_by'])
  14040.             )
  14041.         );
  14042.     }
  14043.     public
  14044.     function ViewServiceRequisitionAction(Request $request$id)
  14045.     {
  14046.         $em $this->getDoctrine()->getManager();
  14047.         $dt Inventory::GetPrDetails($em$id);
  14048.         return $this->render('@Inventory/pages/views/view_purchase_requisition.html.twig',
  14049.             array(
  14050.                 'page_title' => 'Service Requisition',
  14051.                 'data' => $dt,
  14052.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14053.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14054.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14055.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14056.                     $id,
  14057.                     $dt['created_by'],
  14058.                     $dt['edited_by'])
  14059.             )
  14060.         );
  14061.     }
  14062.     public
  14063.     function PrintPrAction(Request $request$id)
  14064.     {
  14065.         $em $this->getDoctrine()->getManager();
  14066.         $dt Inventory::GetPrDetails($em$id);
  14067.         $companyId $this->getLoggedUserCompanyId($request);
  14068.         $company_data Company::getCompanyData($em$companyId);
  14069.         $document_mark = array(
  14070.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  14071.             'copy' => ''
  14072.         );
  14073.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  14074.             $html $this->renderView('@Inventory/pages/print/print_pr.html.twig',
  14075.                 array(
  14076.                     //full array here
  14077.                     'pdf' => true,
  14078.                     'page_title' => 'Purchase Requisition',
  14079.                     'export' => 'pdf,print',
  14080.                     'data' => $dt,
  14081.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14082.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14083.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14084.                         array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14085.                         $id,
  14086.                         $dt['created_by'],
  14087.                         $dt['edited_by']),
  14088.                     'document_mark_image' => $document_mark['original'],
  14089.                     'branchList' => Client::BranchList($em$companyId),
  14090.                     'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  14091.                     'company_name' => $company_data->getName(),
  14092.                     'company_data' => $company_data,
  14093.                     'company_address' => $company_data->getAddress(),
  14094.                     'company_image' => $company_data->getImage(),
  14095.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  14096.                     'red' => 0
  14097.                 )
  14098.             );
  14099.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  14100. //                'orientation' => 'landscape',
  14101. //                'enable-javascript' => true,
  14102. //                'javascript-delay' => 1000,
  14103.                 'no-stop-slow-scripts' => false,
  14104.                 'no-background' => false,
  14105.                 'lowquality' => false,
  14106.                 'encoding' => 'utf-8',
  14107. //            'images' => true,
  14108. //            'cookie' => array(),
  14109.                 'dpi' => 300,
  14110.                 'image-dpi' => 300,
  14111. //                'enable-external-links' => true,
  14112. //                'enable-internal-links' => true
  14113.             ));
  14114.             return new Response(
  14115.                 $pdf_response,
  14116.                 200,
  14117.                 array(
  14118.                     'Content-Type' => 'application/pdf',
  14119.                     'Content-Disposition' => 'attachment; filename="purchase_requisition_' $id '.pdf"'
  14120.                 )
  14121.             );
  14122.         }
  14123.         return $this->render('@Inventory/pages/print/print_pr.html.twig',
  14124.             array(
  14125.                 'page_title' => 'Purchase Requisition',
  14126.                 'export' => 'pdf,print',
  14127.                 'data' => $dt,
  14128.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14129.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  14130.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  14131.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  14132.                     $id,
  14133.                     $dt['created_by'],
  14134.                     $dt['edited_by']),
  14135.                 'document_mark_image' => $document_mark['original'],
  14136.                 'company_name' => $company_data->getName(),
  14137.                 'company_data' => $company_data,
  14138.                 'branchList' => Client::BranchList($em$companyId),
  14139.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  14140.                 'company_address' => $company_data->getAddress(),
  14141.                 'company_image' => $company_data->getImage(),
  14142.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  14143.                 'red' => 0
  14144.             )
  14145.         );
  14146.     }
  14147.     public
  14148.     function CreateSecondaryDeliveryReceiptAction(Request $request)
  14149.     {
  14150.         $em $this->getDoctrine()->getManager();
  14151.         $companyId $this->getLoggedUserCompanyId($request);
  14152.         $userBranchIdList $request->getSession()->get('branchIdList');
  14153.         if ($userBranchIdList == null$userBranchIdList = [];
  14154.         $userBranchId $request->getSession()->get('branchId');
  14155.         if ($request->isMethod('POST')) {
  14156.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  14157.             $dochash $request->request->get('docHash'); //change
  14158.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14159.             $approveRole 1;  //created
  14160.             $approveHash $request->request->get('approvalHash');
  14161.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  14162.                 $loginId$approveRole$approveHash)
  14163.             ) {
  14164.                 $this->addFlash(
  14165.                     'error',
  14166.                     'Sorry Couldnot insert Data.'
  14167.                 );
  14168.             } else {
  14169.                 $receiptId SalesOrderM::CreateNewSecondaryDeliveryReceipt($this->getDoctrine()->getManager(), $request->request,
  14170.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  14171.                     $this->getLoggedUserCompanyId($request));
  14172.                 //now add Approval info
  14173.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14174.                 $approveRole 1;  //created
  14175.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  14176.                     $receiptId,
  14177.                     $loginId,
  14178.                     $approveRole,
  14179.                     $request->request->get('approvalHash'));
  14180.                 $options = array(
  14181.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  14182.                     'notification_server' => $this->container->getParameter('notification_server'),
  14183.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  14184.                     'url' => $this->generateUrl(
  14185.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  14186.                         ['entity_view_route_path_name']
  14187.                     )
  14188.                 );
  14189.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  14190.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  14191.                     $receiptId,
  14192.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  14193.                 );
  14194.                 $this->addFlash(
  14195.                     'success',
  14196.                     'New Delivery Receipt Created'
  14197.                 );
  14198.                 $url $this->generateUrl(
  14199.                     'view_delivery_receipt'
  14200.                 );
  14201.                 return $this->redirect($url "/" $receiptId);
  14202.             }
  14203.         }
  14204.         $debugData = [];
  14205. //        $dr_data=$em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')->findOneBy(
  14206. //            array(
  14207. //                'deliveryReceiptId'=>$dr_id
  14208. //            )
  14209. //        );
  14210.         $new_swld = new \DateTime('2017-07-09');
  14211. //        if ($entry->getWarranty() > 0)
  14212. //            $new_swld->modify('+' . $entry->getWarranty() . ' month');
  14213.         $debugData[] = $new_swld->format('Y-m-d');
  14214.         $debugData[] = $new_swld;
  14215. //        $debugData[]=$dr_data->getDeliveryReceiptDate();
  14216.         $debugData[] = '+' '1' ' month';
  14217.         $branchList Client::BranchList($em$companyId, [], $userBranchIdList);
  14218.         $warehouseIds = [];
  14219.         foreach ($branchList as $br) {
  14220.             $warehouseIds[] = $br['warehouseId'];
  14221.         }
  14222.         return $this->render('@Inventory/pages/input_forms/secondaryDeliveryReceipt.html.twig',
  14223.             array(
  14224.                 'page_title' => 'New Delivery Receipt',
  14225.                 'ExistingClients' => Accounts::getClientLedgerHeads($em),
  14226.                 'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($em),
  14227.                 'ClientList' => SalesOrderM::GetSecondaryClientList($em),
  14228.                 'warehouse' => Inventory::WarehouseList($em$companyId$warehouseIds),
  14229.                 'salesOrders' => SalesOrderM::SecondarySalesOrderListPendingDelivery($em$warehouseIds),
  14230.                 'salesOrdersArray' => SalesOrderM::SecondarySalesOrderListPendingDeliveryArray($em$warehouseIds),
  14231.                 'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
  14232.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
  14233.                 'debugData' => $debugData,
  14234.             )
  14235.         );
  14236.     }
  14237.     public function AddUnitTypeAction(Request $request$id 0)
  14238.     {
  14239.         $em $this->getDoctrine()->getManager();
  14240.         $unitType $id != $em->getRepository(UnitType::class)->find($id) : null;
  14241.         if ($request->isMethod('POST')) {
  14242.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14243.             Inventory::CreateUnitType($em$id$request->request$loginId);
  14244.             $this->addFlash(
  14245.                 'success',
  14246.                 $id != 'Unit Type Updated' 'Unit Type Added'
  14247.             );
  14248.             $unitType $id != $em->getRepository(UnitType::class)->find($id) : null;
  14249.         }
  14250.         $unitTypeDetails $em->getRepository(UnitType::class)->findBy(array(), array('name' => 'ASC'));
  14251.         $existingConversionMap = [];
  14252.         if ($unitType && $unitType->getConversion() != '') {
  14253.             $existingConversionMap json_decode($unitType->getConversion(), true);
  14254.             if ($existingConversionMap == null) {
  14255.                 $existingConversionMap = [];
  14256.             }
  14257.         }
  14258.         return $this->render('@Inventory/pages/input_forms/addUnitType.html.twig',
  14259.             array(
  14260.                 'page_title' => $id != 'Edit Unit Type' 'Add Unit Type',
  14261.                 'ex_id' => $id,
  14262.                 'ex_det' => $unitType,
  14263.                 'existingConversionMap' => $existingConversionMap,
  14264.                 'unitTypeDetails' => $unitTypeDetails,
  14265.                 'unitTypeRecords' => $unitTypeDetails
  14266.             )
  14267.         );
  14268.     }
  14269.     public function AddCurrencyAction(Request $request$id 0)
  14270.     {
  14271.         $em $this->getDoctrine()->getManager();
  14272.         $currency $id != $em->getRepository(Currencies::class)->find($id) : null;
  14273.         if ($request->isMethod('POST')) {
  14274.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14275.             Inventory::CreateCurrency($em$id$request->request$loginId);
  14276.             $this->addFlash(
  14277.                 'success',
  14278.                 $id != 'Currency Updated' 'Currency Added'
  14279.             );
  14280.             $currency $id != $em->getRepository(Currencies::class)->find($id) : null;
  14281.         }
  14282.         $currencyDetails $em->getRepository(Currencies::class)->findBy(array(), array('code' => 'ASC'));
  14283.         $existingConversionMap = [];
  14284.         if ($currency && $currency->getConversionData() != '') {
  14285.             $existingConversionMap json_decode($currency->getConversionData(), true);
  14286.             if ($existingConversionMap == null) {
  14287.                 $existingConversionMap = [];
  14288.             }
  14289.         }
  14290.         return $this->render('@Inventory/pages/input_forms/addCurrency.html.twig',
  14291.             array(
  14292.                 'page_title' => $id != 'Edit Currency' 'Add Currency',
  14293.                 'ex_id' => $id,
  14294.                 'ex_det' => $currency,
  14295.                 'existingConversionMap' => $existingConversionMap,
  14296.                 'currencyDetails' => $currencyDetails,
  14297.                 'currencyRecords' => $currencyDetails
  14298.             )
  14299.         );
  14300.     }
  14301.     public
  14302.     function SubcategoryListAction()
  14303.     {
  14304.         return $this->render('@Inventory/pages/input_forms/subCategoryList.html.twig',
  14305.             array(
  14306.                 'page_title' => 'Sub Category List',
  14307.             )
  14308.         );
  14309.     }
  14310. //    public function getInventoryProductList(Request $request)
  14311. //    {
  14312. //        $em = $this->getDoctrine()->getManager();
  14313. //
  14314. //        $page = (int) $request->query->get('page', 1);     // Default page = 1
  14315. //        $limit = (int) $request->query->get('limit', 10);   // Default limit = 10
  14316. //        $offset = ($page - 1) * $limit;
  14317. //
  14318. //        // First, get the total count of products
  14319. //        $totalQuery = $em->createQueryBuilder()
  14320. //            ->select('COUNT(i.id)')
  14321. //            ->from('ApplicationBundle:InventoryStorage', 'i')
  14322. //            ->where('i.qty > :minQty')
  14323. //            ->setParameter('minQty', 0)
  14324. //            ->getQuery();
  14325. //
  14326. //        $totalRecords = (int) $totalQuery->getSingleScalarResult();
  14327. //        $totalPages = $limit > 0 ? (int) ceil($totalRecords / $limit) : 1;
  14328. //
  14329. //        // Then, get the paginated data
  14330. //        $qb = $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->createQueryBuilder('i')
  14331. //            ->select([
  14332. //                'i.productId AS productId',
  14333. //                'COALESCE(ig.name, \'\') AS itemGroupName',
  14334. //                'COALESCE(w.name, \'\') AS wareHouseName',
  14335. //                'i.qty AS quantity',
  14336. //                'COALESCE(b.name, \'\') AS brandName',
  14337. //                'COALESCE(u.name, \'\') AS UnitName',
  14338. //                'COALESCE(c.name, \'\') AS color',
  14339. //                'COALESCE(s.name, \'\') AS size',
  14340. //                'COALESCE(i.salesPrice, 0) AS salesPrice',
  14341. //                'COALESCE(p.name, \'\') AS productName'
  14342. //            ])
  14343. //            ->leftJoin('ApplicationBundle:InvProducts', 'p', 'WITH', 'i.productId = p.id')
  14344. //            ->leftJoin('ApplicationBundle:InvItemGroup', 'ig', 'WITH', 'i.igId = ig.id')
  14345. //            ->leftJoin('ApplicationBundle:Warehouse', 'w', 'WITH', 'i.warehouseId = w.id')
  14346. //            ->leftJoin('ApplicationBundle:BrandCompany', 'b', 'WITH', 'i.brandId = b.id')
  14347. //            ->leftJoin('ApplicationBundle:UnitType', 'u', 'WITH', 'i.unitTypeId = u.id')
  14348. //            ->leftJoin('ApplicationBundle:Colors', 'c', 'WITH', 'i.color = c.id')
  14349. //            ->leftJoin('ApplicationBundle:ProductSizes', 's', 'WITH', 'i.size = s.id')
  14350. //            ->where('i.qty > :minQty')
  14351. //            ->setParameter('minQty', 0)
  14352. //            ->setFirstResult($offset)
  14353. //            ->setMaxResults($limit);
  14354. //
  14355. //        $inventoryData = $qb->getQuery()->getResult();
  14356. //
  14357. //        return $this->json([
  14358. //            'page' => $page,
  14359. //            'limit' => $limit,
  14360. //            'totalRecords' => $totalRecords,
  14361. //            'totalPages' => $totalPages,
  14362. //            'data' => $inventoryData,
  14363. //        ]);
  14364. //    }
  14365.     public function getInventoryProductList(Request $request)
  14366.     {
  14367.         $em $this->getDoctrine()->getManager();
  14368.         $page = (int)$request->query->get('page'1);
  14369.         $limit = (int)$request->query->get('limit'10);
  14370.         $offset = ($page 1) * $limit;
  14371.         $totalQuery $em->createQueryBuilder()
  14372.             ->select('COUNT(i.id)')
  14373.             ->from('ApplicationBundle:InventoryStorage''i')
  14374.             ->where('i.qty > :minQty')
  14375.             ->setParameter('minQty'0)
  14376.             ->getQuery();
  14377.         $totalRecords = (int)$totalQuery->getSingleScalarResult();
  14378.         $totalPages $limit ? (int)ceil($totalRecords $limit) : 1;
  14379.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14380.         $qb $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->createQueryBuilder('i')
  14381.             ->select([
  14382.                 'i.productId AS productId',
  14383.                 'COALESCE(ig.name, \'\') AS itemGroupName',
  14384.                 'COALESCE(w.name, \'\') AS wareHouseName',
  14385.                 'COALESCE(wa.name, \'\') AS subWareHouseName',
  14386.                 'i.qty AS quantity',
  14387.                 'i.qty AS lastSold',
  14388.                 'i.qty AS lastPurchase',
  14389.                 'COALESCE(b.name, \'\') AS brandName',
  14390.                 'COALESCE(u.name, \'\') AS UnitName',
  14391.                 'COALESCE(c.name, \'\') AS color',
  14392.                 'COALESCE(s.name, \'\') AS size',
  14393.                 'COALESCE(i.purchasePrice, 0) AS purchasePrice',
  14394.                 'COALESCE(i.salesPrice, 0) AS salesPrice',
  14395.                 'COALESCE(p.name, \'\') AS productName',
  14396.                 'COALESCE(p.productCode, \'\') AS productCode',
  14397.                 "CASE 
  14398.                 WHEN p.images IS NOT NULL AND p.images <> '' 
  14399.                 THEN p.images 
  14400.                 ELSE '$defaultImage
  14401.             END AS image"
  14402.             ])
  14403.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  14404.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''i.igId = ig.id')
  14405.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''i.warehouseId = w.id')
  14406.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''i.actionTagId = wa.id')
  14407.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''i.brandId = b.id')
  14408.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''i.unitTypeId = u.id')
  14409.             ->leftJoin('ApplicationBundle:Colors''c''WITH''i.color = c.id')
  14410.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''i.size = s.id')
  14411.             ->where('i.qty > :minQty')
  14412.             ->setParameter('minQty'0)
  14413.             ->setFirstResult($offset)
  14414.             ->setMaxResults($limit);
  14415.         $inventoryData $qb->getQuery()->getResult();
  14416.         return $this->json([
  14417.             'page' => $page,
  14418.             'limit' => $limit,
  14419.             'totalRecords' => $totalRecords,
  14420.             'totalPages' => $totalPages,
  14421.             'data' => $inventoryData,
  14422.         ]);
  14423.     }
  14424.     public function CreateStockTransferForAppAction(Request $request)
  14425.     {
  14426.         $em $this->getDoctrine()->getManager();
  14427.         $companyId $this->getLoggedUserCompanyId($request);
  14428.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  14429.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  14430.         if ($request->isMethod('POST')) {
  14431.             $em $this->getDoctrine()->getManager();
  14432.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  14433.             $dochash $request->request->get('docHash'); //change
  14434.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14435.             $approveRole $request->request->get('approvalRole');
  14436.             $approveHash $request->request->get('approvalHash');
  14437.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  14438.                 $loginId$approveRole$approveHash)
  14439.             ) {
  14440.                 $this->addFlash(
  14441.                     'error',
  14442.                     'Sorry Couldnot insert Data.'
  14443.                 );
  14444.             } else {
  14445.                 if ($request->request->has('check_allowed'))
  14446.                     $check_allowed 1;
  14447.                 $StID Inventory::CreateNewStockTransferForAPP(
  14448.                     $this->getDoctrine()->getManager(),
  14449.                     $request->request,
  14450.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  14451.                     $this->getLoggedUserCompanyId($request)
  14452.                 );
  14453.                 //now add Approval info
  14454.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14455.                 $approveRole 1;  //created
  14456.                 $options = array(
  14457.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  14458.                     'notification_server' => $this->container->getParameter('notification_server'),
  14459.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  14460.                     'url' => $this->generateUrl(
  14461.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  14462.                         ['entity_view_route_path_name']
  14463.                     )
  14464.                 );
  14465.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  14466.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  14467.                     $StID,
  14468.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  14469.                 );
  14470.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  14471.                     $loginId,
  14472.                     $approveRole,
  14473.                     $request->request->get('approvalHash'));
  14474.                 $this->addFlash(
  14475.                     'success',
  14476.                     'Stock Transfer Added.'
  14477.                 );
  14478.                 $url $this->generateUrl(
  14479.                     'view_st'
  14480.                 );
  14481. //                return $this->redirect($url . "/" . $StID);
  14482.                 return $this->json(['success' => true]);
  14483.             }
  14484.         }
  14485.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  14486.             array(
  14487.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  14488.             )
  14489.         );
  14490.         $INVLIST = [];
  14491.         foreach ($slotList as $slot) {
  14492.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  14493.         }
  14494.         return $this->json(['success' => true]);
  14495. //       return $this->render('@Inventory/pages/input_forms/stock_transfer_note.html.twig',
  14496. //           array(
  14497. //         'page_title' => 'Stock Transfer Note',
  14498. //               'warehouseList' => Inventory::WarehouseList($em),
  14499. //        'warehouseListArray' => Inventory::WarehouseListArray($em),
  14500. //               'colorList' => Inventory::GetColorList($em),
  14501. //               'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  14502. //                'srList' => [],
  14503. //               'warehouseActionList' => $warehouse_action_list,
  14504. //                'warehouseActionListArray' => $warehouse_action_list_array,
  14505. //                'item_list' => Inventory::ItemGroupList($em),
  14506. //                'item_list_array' => Inventory::ItemGroupListArray($em),
  14507. //               'category_list_array' => Inventory::ProductCategoryListArray($em),
  14508. //              'product_list_array' => Inventory::ProductListDetailedArray($em),
  14509. ////               'product_list_array' => [],
  14510. //               'product_list' => Inventory::ProductList($em, $companyId),
  14511. ////                'product_list' => [],
  14512. //               'prefix_list' => array(
  14513. //                   [
  14514. //                       'id' => 1,
  14515. //                       'value' => 'GN',
  14516. //                        'text' => 'GN'
  14517. //
  14518. //                   ]
  14519. //              ),
  14520. //              'assoc_list' => array(
  14521. //                  [
  14522. //                       'id' => 1,
  14523. //                        'value' => 1,
  14524. //                        'text' => 'GN'
  14525. //
  14526. //                  ]
  14527. //               ),
  14528. //              'INVLIST' => $INVLIST
  14529. //           )
  14530. //      );
  14531.     }
  14532.     public function getWarehouseList(Request $request)
  14533.     {
  14534.         $em $this->getDoctrine()->getManager();
  14535.         $warehouses $em->getRepository('ApplicationBundle\\Entity\\Warehouse')
  14536.             ->createQueryBuilder('w')
  14537.             ->select('w.id''w.name')
  14538.             ->orderBy('w.name''ASC')
  14539.             ->getQuery()
  14540.             ->getResult();
  14541.         return $this->json($warehouses);
  14542.     }
  14543.     public function getSubWarehouseList(Request $request)
  14544.     {
  14545.         $em $this->getDoctrine()->getManager();
  14546.         $warehouses $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')
  14547.             ->createQueryBuilder('w')
  14548.             ->select('w.id''w.name')
  14549. //            ->orderBy('w.name', 'ASC')
  14550.             ->getQuery()
  14551.             ->getResult();
  14552.         return $this->json($warehouses);
  14553.     }
  14554.     public function getStockReceiveList(Request $request)
  14555.     {
  14556.         $list GeneralConstant::$stockReceiveType;
  14557.         return $this->json($list);
  14558.     }
  14559.     public function getOrderListByStockReceiveId(Request $request)
  14560.     {
  14561.         $em $this->getDoctrine()->getManager();
  14562.         $typeName $request->request->get('type');
  14563.         $typeId $request->request->get('id');
  14564.         $document null;
  14565.         if ($typeName == 'From Stock Transfer' || $typeId == 1) {
  14566.             $document $em->getRepository('ApplicationBundle\\Entity\\StockTransfer')->createQueryBuilder('s')->select('s.stockTransferId''s.documentHash')->where('s.approved !=1')->getQuery()->getResult();
  14567.         } else if ($typeName == 'For Stock In' || $typeId == 3) {
  14568.             $document $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->createQueryBuilder('a')->select('a.accountsHeadId''a.name')->getQuery()->getResult();
  14569.         } else if ($typeName == 'For Opening Entity' || $typeId == 4) {
  14570.             $document $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')
  14571.                 ->createQueryBuilder('w')
  14572.                 ->select('w.id''w.name')
  14573.                 ->getQuery()
  14574.                 ->getResult();
  14575.         }
  14576.         return $this->json($document);
  14577.     }
  14578.     public function GetProductFromInvStorage(Request $request)
  14579.     {
  14580.         $em $this->getDoctrine()->getManager();
  14581.         $searchTerm trim($request->get('name'));
  14582.         // Fetch all or filtered products
  14583.         if ($searchTerm) {
  14584.             $products $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  14585.                 ->createQueryBuilder('p')
  14586.                 ->where('p.name LIKE :term')
  14587.                 ->setParameter('term''%' $searchTerm '%')
  14588.                 ->getQuery()
  14589.                 ->getResult();
  14590.         } else {
  14591.             $products $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findAll();
  14592.         }
  14593.         $response = [];
  14594.         foreach ($products as $product) {
  14595.             // All InventoryStorage entries for the product
  14596.             $invStorageItems $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy([
  14597.                 'productId' => $product->getId()
  14598.             ]);
  14599.             $inventoryList = [];
  14600.             foreach ($invStorageItems as $item) {
  14601.                 $warehouse $em->getRepository('ApplicationBundle\\Entity\\Warehouse')->find($item->getWarehouseId());
  14602.                 $subWarehouse $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')->find($item->getActionTagId());
  14603.                 $inventoryList[] = [
  14604.                     'warehouse_id' => $item->getWarehouseId(),
  14605.                     'warehouse_name' => $warehouse $warehouse->getName() : '',
  14606.                     'sub_warehouse_id' => $item->getActionTagId(),
  14607.                     'sub_warehouse_name' => $subWarehouse $subWarehouse->getName() : '',
  14608.                     'quantity' => $item->getQty(),
  14609.                     'lastSold' => $item->getNonInvoicedQty(),
  14610.                     'lastPurchase' => $item->getPhysicalQty(),
  14611.                     'purchasePrice' => $item->getPurchasePrice(),
  14612.                     'salesPrice' => $item->getSalesPrice(),
  14613.                     'brandName' => $item->getBrandId(),
  14614.                     'unitName' => 'pcs'// Optional: Resolve via Unit table
  14615.                 ];
  14616.             }
  14617.             $response[] = [
  14618.                 'productId' => $product->getId(),
  14619.                 'itemGroupName' => $product->getIgId(),
  14620.                 'productName' => $product->getName(),
  14621.                 'productCode' => $product->getProductCode(),
  14622.                 'color' => $product->getColors(),
  14623.                 'size' => $product->getSizes(),
  14624.                 'image' => $product->getDefaultImage(),
  14625.                 'inventory' => $inventoryList
  14626.             ];
  14627.         }
  14628.         return new JsonResponse($response);
  14629.     }
  14630.     public function getProductByDocumentId(Request $request)
  14631.     {
  14632.         $em $this->getDoctrine()->getManager();
  14633.         $documentId $request->request->get('documentId');
  14634.         $accountsHeadId $request->request->get('accountsHeadId');
  14635.         if ($documentId) {
  14636.             $productIdRows $em->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  14637.                 ->createQueryBuilder('s')
  14638.                 ->select('s.productId')
  14639.                 ->where('s.stockTransferId = :documentId')
  14640.                 ->setParameter('documentId'$documentId)
  14641.                 ->getQuery()
  14642.                 ->getResult();
  14643.             $fromWarehouseRow $em->getRepository('ApplicationBundle\\Entity\\StockTransferItem')
  14644.                 ->createQueryBuilder('s')
  14645.                 ->select('s.warehouseId''s.toWarehouseId''s.warehouseActionId''s.toWarehouseActionId''s.qty''s.price')
  14646.                 ->where('s.stockTransferId = :documentId')
  14647.                 ->setParameter('documentId'$documentId)
  14648.                 ->setMaxResults(1)
  14649.                 ->getQuery()
  14650.                 ->getOneOrNullResult();
  14651.             $productIds array_map(function ($row) {
  14652.                 return $row['productId'];
  14653.             }, $productIdRows);
  14654.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findBy([
  14655.                 'id' => $productIds
  14656.             ]);
  14657.             $productData array_map(function ($p) {
  14658.                 return [
  14659.                     'id' => $p->getId(),
  14660.                     'name' => $p->getName(),
  14661.                     'modelNo' => $p->getModelNo(),
  14662.                     'sku' => $p->getSkuCode(),
  14663.                     'productCode' => $p->getProductCode(),
  14664.                     'purchasePrice' => $p->getPurchasePrice(),
  14665.                     'salesPrice' => $p->getSalesPrice(),
  14666.                     'purchasePriceWoExpense' => $p->getPurchasePriceWoExpense(),
  14667.                     'qty' => $p->getQty(),
  14668.                     'nonInvoicedQty' => $p->getNonInvoicedQty(),
  14669.                     'nonSalesInvoicedQty' => $p->getNonSalesInvoicedQty(),
  14670.                     'unitTypeId' => $p->getUnitTypeId(),
  14671.                     'dimension' => $p->getDimension(),
  14672.                     'dimensionUnitTypeId' => $p->getDimensionUnitTypeId(),
  14673.                     'weight' => $p->getWeight(),
  14674.                     'categoryId' => $p->getCategoryId(),
  14675.                     'subCategoryId' => $p->getSubCategoryId(),
  14676.                     'brandCompany' => $p->getBrandCompany(),
  14677.                     'warehouseId' => $p->getWarehouseId(),
  14678.                     'reorderLevel' => $p->getReorderLevel(),
  14679.                     'defaultImage' => $p->getDefaultImage(),
  14680.                     'status' => $p->getStatus()
  14681.                 ];
  14682.             }, $product);
  14683.             return $this->json([
  14684.                 'warehouseId' => $fromWarehouseRow['warehouseId'],
  14685.                 'toWarehouseId' => $fromWarehouseRow['toWarehouseId'],
  14686.                 'warehouseActionId' => $fromWarehouseRow['warehouseActionId'],
  14687.                 'toWarehouseActionId' => $fromWarehouseRow['toWarehouseActionId'],
  14688.                 'quantity' => $fromWarehouseRow['qty'],
  14689.                 'price' => $fromWarehouseRow['price'],
  14690.                 'products' => $productData
  14691.             ]);
  14692.         } else if ($accountsHeadId) {
  14693.             $products $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findAll();
  14694.             $productData array_map(function ($p) {
  14695.                 return [
  14696.                     'id' => $p->getId(),
  14697.                     'name' => $p->getName(),
  14698.                     'modelNo' => $p->getModelNo(),
  14699.                     'sku' => $p->getSkuCode(),
  14700.                     'productCode' => $p->getProductCode(),
  14701.                     'purchasePrice' => $p->getPurchasePrice(),
  14702.                     'salesPrice' => $p->getSalesPrice(),
  14703.                     'purchasePriceWoExpense' => $p->getPurchasePriceWoExpense(),
  14704.                     'qty' => $p->getQty(),
  14705.                     'nonInvoicedQty' => $p->getNonInvoicedQty(),
  14706.                     'nonSalesInvoicedQty' => $p->getNonSalesInvoicedQty(),
  14707.                     'unitTypeId' => $p->getUnitTypeId(),
  14708.                     'dimension' => $p->getDimension(),
  14709.                     'dimensionUnitTypeId' => $p->getDimensionUnitTypeId(),
  14710.                     'weight' => $p->getWeight(),
  14711.                     'categoryId' => $p->getCategoryId(),
  14712.                     'subCategoryId' => $p->getSubCategoryId(),
  14713.                     'brandCompany' => $p->getBrandCompany(),
  14714.                     'warehouseId' => $p->getWarehouseId(),
  14715.                     'reorderLevel' => $p->getReorderLevel(),
  14716.                     'defaultImage' => $p->getDefaultImage(),
  14717.                     'status' => $p->getStatus()
  14718.                 ];
  14719.             }, $products);
  14720.             return $this->json($productData);
  14721.         } else {
  14722.             return new JsonResponse([
  14723.                 "status" => false,
  14724.                 "message" => "Please insert valid documentId or accountsHead!"
  14725.             ]);
  14726.         }
  14727.     }
  14728.     public function getQuantityBasedOnSubWareHouse(Request $request)
  14729.     {
  14730.         $em $this->getDoctrine()->getManager();
  14731.         $productId $request->get('product_id');
  14732.         $productName trim($request->get('product_name'));
  14733.         $warehouseId $request->get('warehouse_id');
  14734.         $warehouseActionId $request->get('warehouse_action_id');
  14735.         if (!$productId && $productName) {
  14736.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  14737.                 ->createQueryBuilder('p')
  14738.                 ->where('p.name LIKE :name')
  14739.                 ->setParameter('name''%' $productName '%')
  14740.                 ->setMaxResults(1)
  14741.                 ->getQuery()
  14742.                 ->getOneOrNullResult();
  14743.             if ($product) {
  14744.                 $productId $product->getId();
  14745.             }
  14746.         }
  14747.         if (!$productId || !$warehouseId || !$warehouseActionId) {
  14748.             return new JsonResponse(['error' => 'Product ID, Warehouse ID, and Action Tag ID are required'], 400);
  14749.         }
  14750.         $criteria = [
  14751.             'productId' => $productId,
  14752.             'warehouseId' => $warehouseId,
  14753.             'actionTagId' => $warehouseActionId,
  14754.         ];
  14755.         $invStorageItems $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy($criteria);
  14756.         if (empty($invStorageItems)) {
  14757.             return new JsonResponse([
  14758.                 'product_id' => $productId,
  14759.                 'quantities' => []
  14760.             ]);
  14761.         }
  14762.         $totalQty 0;
  14763.         $totalNonInvoicedQty 0;
  14764.         $totalPhysicalQty 0;
  14765.         $purchasePrice null;
  14766.         $salesPrice null;
  14767.         foreach ($invStorageItems as $item) {
  14768.             $totalQty += $item->getQty();
  14769.             $totalNonInvoicedQty += $item->getNonInvoicedQty();
  14770.             $totalPhysicalQty += $item->getPhysicalQty();
  14771.             $purchasePrice $item->getPurchasePrice();
  14772.             $salesPrice $item->getSalesPrice();
  14773.         }
  14774.         $subWarehouse $em->getRepository('ApplicationBundle\\Entity\\WarehouseAction')->find($warehouseActionId);
  14775.         $quantitiesBySubWarehouse = [[
  14776.             'action_tag_id' => $warehouseActionId,
  14777.             'sub_warehouse' => $subWarehouse $subWarehouse->getName() : '',
  14778.             'qty' => $totalQty,
  14779.             'non_invoiced_qty' => $totalNonInvoicedQty,
  14780.             'physical_qty' => $totalPhysicalQty,
  14781.             'purchase_price' => $purchasePrice,
  14782.             'sales_price' => $salesPrice,
  14783.         ]];
  14784.         return new JsonResponse([
  14785.             'product_id' => $productId,
  14786.             'quantities' => $quantitiesBySubWarehouse
  14787.         ]);
  14788.     }
  14789.     public function getPriceByWareHouseId(Request $request)
  14790.     {
  14791.         $em $this->getDoctrine()->getManager();
  14792.         $warehouseId $request->request->get('warehouseId');
  14793.         $productId $request->request->get('productId');
  14794.         $actionTagId $request->request->get('actionTagId');
  14795.         $unitPrice $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->createQueryBuilder('st')
  14796.             ->select('st.purchasePrice AS purchasePrice')
  14797.             ->where('st.productId = :productId')
  14798.             ->andWhere('st.warehouseId = :warehouseId')
  14799.             ->andWhere('st.actionTagId = :actionTagId')
  14800.             ->setParameter('productId'$productId)
  14801.             ->setParameter('warehouseId'$warehouseId)
  14802.             ->setParameter('actionTagId'$actionTagId)
  14803.             ->setMaxResults(1)
  14804.             ->getQuery()
  14805.             ->getOneOrNullResult();
  14806.         return new JsonResponse([
  14807.             'purchasePrice' => $unitPrice $unitPrice['purchasePrice'] : null
  14808.         ]);
  14809.     }
  14810.     public function getStockTransferList(Request $request)
  14811.     {
  14812.         $em $this->getDoctrine()->getManager();
  14813.         $warehouses $em->getRepository('ApplicationBundle\\Entity\\StockTransfer')
  14814.             ->createQueryBuilder('s')
  14815.             ->select('s.stockTransferId''s.documentHash')
  14816. //            ->orderBy('s.name', 'ASC')
  14817.             ->getQuery()
  14818.             ->getResult();
  14819.         return $this->json($warehouses);
  14820.     }
  14821.     public function stockTransferItemList(Request $request)
  14822.     {
  14823.         $em $this->getDoctrine()->getManager();
  14824.         $stockTransferId $request->query->get('stockTransferId');
  14825.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14826.         $qb $em->createQueryBuilder();
  14827.         $qb->select(
  14828.             'sti.id AS id',
  14829.             'sti.productId AS productId',
  14830.             'sti.stockTransferId AS stockTransferId',
  14831.             'p.name AS productName',
  14832.             'sti.price AS price',
  14833.             'p.images AS images',
  14834.             'ig.name AS itemGroupName',
  14835.             'w.name AS wareHouseName',
  14836.             'sti.warehouseId AS warehouseId',
  14837.             'wa.name AS subWareHouseName',
  14838.             'sti.warehouseActionId AS warehouseActionId',
  14839.             'sti.qty AS quantity',
  14840.             'b.name AS brandName',
  14841.             'u.name AS UnitName',
  14842.             'c.name AS color',
  14843.             's.name AS size'
  14844.         )
  14845.             ->from('ApplicationBundle:StockTransferItem''sti')
  14846.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''sti.productId = p.id')
  14847.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''p.igId = ig.id')
  14848.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''sti.warehouseId = w.id')
  14849.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''sti.warehouseActionId = wa.id')
  14850.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''p.brandCompany = b.id')
  14851.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''p.unitTypeId = u.id')
  14852.             ->leftJoin('ApplicationBundle:Colors''c''WITH''sti.colorId = c.id')
  14853.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''sti.sizeId = s.id')
  14854.             ->where('sti.stockTransferId = :stockTransferId')
  14855.             ->setParameter('stockTransferId'$stockTransferId);
  14856.         $results $qb->getQuery()->getResult();
  14857.         $response = [];
  14858.         foreach ($results as $item) {
  14859.             $response[] = [
  14860.                 'id' => $item['id'],
  14861.                 'stockTransferId' => $item['stockTransferId'],
  14862.                 'productId' => (int)$item['productId'],
  14863.                 'itemGroupName' => $item['itemGroupName'] ?? '',
  14864.                 'wareHouseName' => $item['wareHouseName'] ?? '',
  14865.                 'wareHouseId' => $item['warehouseId'] ?? '',
  14866.                 'subWareHouseName' => $item['subWareHouseName'] ?? '',
  14867.                 'subWareHouseId' => $item['warehouseActionId'] ?? '',
  14868.                 'quantity' => (int)$item['quantity'],
  14869.                 'brandName' => $item['brandName'] ?? '',
  14870.                 'UnitName' => $item['UnitName'] ?? '',
  14871.                 'color' => $item['color'] ?? '',
  14872.                 'size' => $item['size'] ?? '',
  14873.                 'price' => (float)$item['price'],
  14874.                 'productName' => $item['productName'] ?? '',
  14875.                 'image' => !empty($item['images']) ? $item['images'] : $defaultImage,
  14876.             ];
  14877.         }
  14878.         return $this->json($response);
  14879.     }
  14880.     public function inventoryStorageFilter(Request $request)
  14881.     {
  14882.         $em $this->getDoctrine()->getManager();
  14883.         $qb $em->createQueryBuilder();
  14884.         $defaultImage 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14885.         $qb->select(
  14886.             'i.productId',
  14887.             'ig.name AS itemGroupName',
  14888.             'w.name AS wareHouseName',
  14889.             'wa.name AS subWareHouseName',
  14890.             'i.qty AS quantity',
  14891.             'b.name AS brandName',
  14892.             'u.name AS UnitName',
  14893.             'c.name AS color',
  14894.             's.name AS size',
  14895.             'i.purchasePrice AS price',
  14896.             'p.name AS productName',
  14897.             'p.images'
  14898.         )
  14899.             ->from('ApplicationBundle:InventoryStorage''i')
  14900.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  14901.             ->leftJoin('ApplicationBundle:InvItemGroup''ig''WITH''i.igId = ig.id')
  14902.             ->leftJoin('ApplicationBundle:Warehouse''w''WITH''i.warehouseId = w.id')
  14903.             ->leftJoin('ApplicationBundle:BrandCompany''b''WITH''i.brandId = b.id')
  14904.             ->leftJoin('ApplicationBundle:UnitType''u''WITH''i.unitTypeId = u.id')
  14905.             ->leftJoin('ApplicationBundle:Colors''c''WITH''i.color = c.id')
  14906.             ->leftJoin('ApplicationBundle:ProductSizes''s''WITH''i.size = s.id')
  14907.             ->leftJoin('ApplicationBundle:WarehouseAction''wa''WITH''i.actionTagId = wa.id');
  14908.         // Define available filters with their mappings
  14909.         $filters = [
  14910.             'itemGroup' => 'ig.id',
  14911.             'category' => 'p.categoryId',
  14912.             'warehouse' => 'w.id',
  14913.             'storageType' => 'i.actionTagId',
  14914.             'brand' => 'b.id',
  14915.             'color' => 'c.id',
  14916.             'colorCode' => 'c.hexCode',
  14917.             'size' => 's.id',
  14918.         ];
  14919.         foreach ($filters as $param => $field) {
  14920.             $value $request->query->get($param);
  14921.             if ($value !== null) {
  14922.                 $values array_map('trim'explode(','$value));
  14923.                 if (count($values) > 1) {
  14924.                     $qb->andWhere($qb->expr()->in($field":$param"))
  14925.                         ->setParameter($param$values);
  14926.                 } else {
  14927.                     $qb->andWhere("$field = :$param")
  14928.                         ->setParameter($param$values[0]);
  14929.                 }
  14930.             }
  14931.         }
  14932.         $rawResult $qb->getQuery()->getArrayResult();
  14933.         $finalResult = [];
  14934.         foreach ($rawResult as $row) {
  14935.             $finalResult[] = [
  14936.                 'productId' => $row['productId'],
  14937.                 'itemGroupName' => $row['itemGroupName'],
  14938.                 'wareHouseName' => $row['wareHouseName'],
  14939.                 'subWareHouseName' => $row['subWareHouseName'],
  14940.                 'quantity' => $row['quantity'],
  14941.                 'brandName' => $row['brandName'],
  14942.                 'UnitName' => $row['UnitName'],
  14943.                 'color' => $row['color'] ?? '',
  14944.                 'size' => $row['size'] ?? '',
  14945.                 'price' => $row['price'],
  14946.                 'productName' => $row['productName'],
  14947.                 'image' => !empty($row['images']) ? $row['images'] : $defaultImage,
  14948.             ];
  14949.         }
  14950.         // Check if finalResult is empty
  14951.         if (empty($finalResult)) {
  14952.             return $this->json([
  14953.                 'success' => false,
  14954.                 'message' => 'No inventory items found matching your criteria'
  14955.             ]);
  14956.         }
  14957.         return $this->json([
  14958.             'success' => true,
  14959.             'data' => $finalResult
  14960.         ]);
  14961.     }
  14962. //    public function inventoryStorageFilter(Request $request)
  14963. //    {
  14964. //        $em = $this->getDoctrine()->getManager();
  14965. //        $qb = $em->createQueryBuilder();
  14966. //        $defaultImage = 'https://lh4.googleusercontent.com/proxy/z44RbfM9MMdI-bVIgyw9sKy1ErMYbKCe3zqwwgNxGl-pv65QEJyRx5dURuTaS_qM1V5PVz-nGHf1cmza8pjXvTD92B5rMG0WBrI';
  14967. //
  14968. //        $qb->select(
  14969. //            'i.productId',
  14970. //            'ig.name AS itemGroupName',
  14971. //            'w.name AS wareHouseName',
  14972. //            'wa.name AS subWareHouseName',
  14973. //            'i.qty AS quantity',
  14974. //            'b.name AS brandName',
  14975. //            'u.name AS UnitName',
  14976. //            'c.name AS color',
  14977. //            's.name AS size',
  14978. //            'i.purchasePrice AS price',
  14979. //            'p.name AS productName',
  14980. //            'p.images'
  14981. //        )
  14982. //            ->from('ApplicationBundle:InventoryStorage', 'i')
  14983. //            ->leftJoin('ApplicationBundle:InvProducts', 'p', 'WITH', 'i.productId = p.id')
  14984. //            ->leftJoin('ApplicationBundle:InvItemGroup', 'ig', 'WITH', 'i.igId = ig.id')
  14985. //            ->leftJoin('ApplicationBundle:Warehouse', 'w', 'WITH', 'i.warehouseId = w.id')
  14986. //            ->leftJoin('ApplicationBundle:BrandCompany', 'b', 'WITH', 'i.brandId = b.id')
  14987. //            ->leftJoin('ApplicationBundle:UnitType', 'u', 'WITH', 'i.unitTypeId = u.id')
  14988. //            ->leftJoin('ApplicationBundle:Colors', 'c', 'WITH', 'i.color = c.id')
  14989. //            ->leftJoin('ApplicationBundle:ProductSizes', 's', 'WITH', 'i.size = s.id')
  14990. //            ->leftJoin('ApplicationBundle:WarehouseAction', 'wa', 'WITH', 'i.actionTagId = wa.id');
  14991. //
  14992. //        // Define available filters with their mappings
  14993. //        $filters = [
  14994. //            'itemGroup'    => 'ig.id',
  14995. //            'category'     => 'p.categoryId',
  14996. //            'warehouse'    => 'w.id',
  14997. //            'storageType'  => 'i.actionTagId',
  14998. //            'brand'        => 'b.id',
  14999. //            'color'        => 'c.id',
  15000. //            'colorCode'    => 'c.hexCode',
  15001. //            'size'         => 's.id',
  15002. //        ];
  15003. //
  15004. //        foreach ($filters as $param => $field) {
  15005. //            $value = $request->query->get($param);
  15006. //
  15007. //            if ($value !== null) {
  15008. //                $values = array_map('trim', explode(',', $value)); // handle multiple
  15009. //                if (count($values) > 1) {
  15010. //                    $qb->andWhere($qb->expr()->in($field, ":$param"))
  15011. //                        ->setParameter($param, $values);
  15012. //                } else {
  15013. //                    $qb->andWhere("$field = :$param")
  15014. //                        ->setParameter($param, $values[0]);
  15015. //                }
  15016. //            }
  15017. //        }
  15018. //
  15019. //        $rawResult = $qb->getQuery()->getArrayResult();
  15020. //
  15021. //        // Now process for validation (color, size, images)
  15022. //        $finalResult = [];
  15023. //
  15024. //        foreach ($rawResult as $row) {
  15025. //            $finalResult[] = [
  15026. //                'productId'     => $row['productId'],
  15027. //                'itemGroupName' => $row['itemGroupName'],
  15028. //                'wareHouseName' => $row['wareHouseName'],
  15029. //                'subWareHouseName' => $row['subWareHouseName'],
  15030. //                'quantity'      => $row['quantity'],
  15031. //                'brandName'     => $row['brandName'],
  15032. //                'UnitName'      => $row['UnitName'],
  15033. //                'color'         => $row['color'] ?? '',
  15034. //                'size'          => $row['size'] ?? '',
  15035. //                'price'         => $row['price'],
  15036. //                'productName'   => $row['productName'],
  15037. //                'image'         => !empty($row['images']) ? $row['images'] : $defaultImage,
  15038. //            ];
  15039. //        }
  15040. //
  15041. //
  15042. //
  15043. //        return $this->json($finalResult);
  15044. //    }
  15045.     public function getItemGroupList()
  15046.     {
  15047.         $em $this->getDoctrine()->getManager();
  15048.         $itemGroups $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')
  15049.             ->createQueryBuilder('ig')
  15050.             ->select('ig.id''ig.name')
  15051.             ->getQuery()
  15052.             ->getResult();
  15053.         return $this->json($itemGroups);
  15054.     }
  15055.     public function getProductCategoryList()
  15056.     {
  15057.         $em $this->getDoctrine()->getManager();
  15058.         $categories $em->getRepository('ApplicationBundle\\Entity\\InvProductCategories')
  15059.             ->createQueryBuilder('pc')
  15060.             ->select('pc.id''pc.name')
  15061.             ->getQuery()
  15062.             ->getResult();
  15063.         return $this->json($categories);
  15064.     }
  15065.     public function getBrandList()
  15066.     {
  15067.         $em $this->getDoctrine()->getManager();
  15068.         $brands $em->getRepository('ApplicationBundle\\Entity\\BrandCompany')
  15069.             ->createQueryBuilder('b')
  15070.             ->select('b.id''b.name')
  15071.             ->getQuery()
  15072.             ->getResult();
  15073.         return $this->json($brands);
  15074.     }
  15075.     public function getColorList()
  15076.     {
  15077.         $em $this->getDoctrine()->getManager();
  15078.         $colors $em->getRepository('ApplicationBundle\\Entity\\Colors')
  15079.             ->createQueryBuilder('c')
  15080.             ->select('c.id''c.name')
  15081.             ->getQuery()
  15082.             ->getResult();
  15083.         return $this->json($colors);
  15084.     }
  15085.     public function getColorCodeList()
  15086.     {
  15087.         $em $this->getDoctrine()->getManager();
  15088.         $colorCodes $em->getRepository('ApplicationBundle\\Entity\\Colors')
  15089.             ->createQueryBuilder('c')
  15090.             ->select('c.id''c.hexCode')
  15091.             ->getQuery()
  15092.             ->getResult();
  15093.         return $this->json($colorCodes);
  15094.     }
  15095.     public function getSizeList()
  15096.     {
  15097.         $em $this->getDoctrine()->getManager();
  15098.         $sizes $em->getRepository('ApplicationBundle\\Entity\\ProductSizes')
  15099.             ->createQueryBuilder('s')
  15100.             ->select('s.id''s.name')
  15101.             ->getQuery()
  15102.             ->getResult();
  15103.         if (empty($sizes)) {
  15104.             return $this->json([
  15105.                 'success' => false,
  15106.                 'message' => 'No data found'
  15107.             ]);
  15108.         }
  15109.         return $this->json($sizes);
  15110.     }
  15111.     public function productCodeList()
  15112.     {
  15113.         $em $this->getDoctrine()->getManager();
  15114.         $productCode $em->getRepository('ApplicationBundle\\Entity\\ProductByCode')
  15115.             ->createQueryBuilder('p')
  15116.             ->select('p.productByCodeId''p.productId''p.salesCode')
  15117.             ->getQuery()
  15118.             ->getResult();
  15119.         if (empty($productCode)) {
  15120.             return $this->json([
  15121.                 'success' => false,
  15122.                 'message' => 'No data found'
  15123.             ]);
  15124.         }
  15125.         return $this->json($productCode);
  15126.     }
  15127.     public function getItemInOutHistory(Request $request)
  15128.     {
  15129.         $em $this->getDoctrine()->getManager();
  15130.         $qb $em->getRepository('ApplicationBundle\\Entity\\InvItemTransaction')->createQueryBuilder('i')
  15131.             ->select([
  15132.                 'i.productId AS productId',
  15133.                 'i.transactionType AS transactionType',
  15134.                 'i.transactionDate AS transactionDate',
  15135.                 'toWarehouse.name AS toWarehouseId',
  15136.                 'toSubWarehouse.name AS toSubWarehouseId',
  15137.                 'fromWarehouse.name AS fromWarehouseId',
  15138.                 'fromSubWarehouse.name AS fromSubWarehouseId',
  15139.                 'i.qty AS quantity',
  15140.                 'i.entityDocHash AS document',
  15141.                 'i.entity AS entity',
  15142.                 'i.entityId AS entityId',
  15143.                 'p.name AS productName',
  15144.             ])
  15145.             ->leftJoin('ApplicationBundle:InvProducts''p''WITH''i.productId = p.id')
  15146.             ->leftJoin('ApplicationBundle:Warehouse''toWarehouse''WITH''i.warehouseId = toWarehouse.id')
  15147.             ->leftJoin('ApplicationBundle:WarehouseAction''toSubWarehouse''WITH''i.actionTagId = toSubWarehouse.id')
  15148.             ->leftJoin('ApplicationBundle:Warehouse''fromWarehouse''WITH''i.fromWarehouseId = fromWarehouse.id')
  15149.             ->leftJoin('ApplicationBundle:WarehouseAction''fromSubWarehouse''WITH''i.fromActionTagId = fromSubWarehouse.id');
  15150.         // Parse dd-mm-yyyy to Y-m-d
  15151.         $startDateStr $request->query->get('startDate');
  15152.         $endDateStr $request->query->get('endDate');
  15153.         if ($startDateStr && $endDateStr) {
  15154.             try {
  15155.                 $startDate = \DateTime::createFromFormat('d-m-Y'$startDateStr)->setTime(000);
  15156.                 $endDate = \DateTime::createFromFormat('d-m-Y'$endDateStr)->setTime(235959);
  15157.                 $qb->andWhere('i.transactionDate BETWEEN :startDate AND :endDate')
  15158.                     ->setParameter('startDate'$startDate)
  15159.                     ->setParameter('endDate'$endDate);
  15160.             } catch (\Exception $e) {
  15161.                 return $this->json(['error' => 'Invalid date format. Use dd-mm-yyyy.'], 400);
  15162.             }
  15163.         }
  15164.         $results $qb->getQuery()->getResult();
  15165.         $data array_map(function ($item) {
  15166.             return [
  15167.                 'productId' => $item['productId'],
  15168.                 'transactionType' => $item['transactionType'] == 'IN' 'OUT',
  15169.                 'transactionDate' => $item['transactionDate']->format('Y-m-d'),
  15170.                 'toWarehouseId' => $item['toWarehouseId'] ?? '',
  15171.                 'toSubWarehouseId' => $item['toSubWarehouseId'] ?? '',
  15172.                 'toSubWarehouseShortName' => $item['toSubWarehouseId'] ?? '',
  15173.                 'fromWarehouseId' => $item['fromWarehouseId'] ?? '',
  15174.                 'fromSubWarehouseId' => $item['fromSubWarehouseId'] ?? '',
  15175.                 'fromSubWarehouseShortName' => $item['fromSubWarehouseId'] ?? '',
  15176.                 'quantity' => $item['quantity'],
  15177.                 'document' => !empty($item['document']) ? $item['document'] : 0,
  15178.                 'entity' => !empty($item['entity']) ? $item['entity'] : 0,
  15179.                 'entityId' => !empty($item['entityId']) ? $item['entityId'] : 0,
  15180.                 'productName' => $item['productName'],
  15181.             ];
  15182.         }, $results);
  15183.         return $this->json($data);
  15184.     }
  15185.     public function CreateStockReceivedNoteForApp(Request $request$id 0)
  15186.     {
  15187.         $em $this->getDoctrine()->getManager();
  15188.         $companyId $this->getLoggedUserCompanyId($request);
  15189.         $extDocData = [];
  15190.         $userId $request->getSession()->get(UserConstants::USER_ID);
  15191.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  15192.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  15193. //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  15194.         $userBranchIdList $request->getSession()->get('branchIdList');
  15195.         if ($userBranchIdList == null$userBranchIdList = [];
  15196.         $userBranchId $request->getSession()->get('branchId');
  15197.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  15198.             $em $this->getDoctrine()->getManager();
  15199.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //change
  15200.             $dochash $request->request->get('docHash'); //change
  15201.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  15202.             $approveRole $request->request->get('approvalRole');
  15203.             $approveHash $request->request->get('approvalHash');
  15204.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  15205.                 $loginId$approveRole$approveHash$id)
  15206.             ) {
  15207.                 if ($request->request->has('returnJson')) {
  15208.                     return new JsonResponse(array(
  15209.                         'success' => false,
  15210.                         'documentHash' => 0,
  15211.                         'documentId' => 0,
  15212.                         'billIds' => [],
  15213.                         'drIds' => [],
  15214.                         'pmntTransIds' => [],
  15215.                         'viewUrl' => '',
  15216.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  15217.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  15218.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  15219.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  15220.                     ));
  15221.                 } else
  15222.                     $this->addFlash(
  15223.                         'error',
  15224.                         'Sorry Could not insert Data.'
  15225.                     );
  15226.             } else {
  15227.                 if ($request->request->has('check_allowed'))
  15228.                     $check_allowed 1;
  15229.                 $StID Inventory::CreateNewStockReceivedNoteForApp(
  15230.                     $this->getDoctrine()->getManager(),
  15231.                     $request->request,
  15232.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  15233.                     $this->getLoggedUserCompanyId($request)
  15234.                 );
  15235.                 //now add Approval info
  15236.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  15237.                 $approveRole 1;  //created
  15238.                 $options = array(
  15239.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  15240.                     'notification_server' => $this->container->getParameter('notification_server'),
  15241.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  15242.                     'url' => $this->generateUrl(
  15243.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  15244.                         ['entity_view_route_path_name']
  15245.                     )
  15246.                 );
  15247.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  15248.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  15249.                     $StID,
  15250.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  15251.                 );
  15252.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  15253.                     $loginId,
  15254.                     $approveRole,
  15255.                     $request->request->get('approvalHash'));
  15256.                 $url $this->generateUrl(
  15257.                     'view_srcv'
  15258.                 );
  15259.                 if ($request->request->has('returnJson')) {
  15260.                     return new JsonResponse(array(
  15261.                         'success' => true,
  15262.                         'documentHash' => $dochash,
  15263.                         'documentId' => $StID,
  15264. //                        'viewUrl' => $url . "/" . $StID,
  15265.                     ));
  15266.                 } else {
  15267.                     $this->addFlash(
  15268.                         'success',
  15269.                         'Stock Received Note Added.'
  15270.                     );
  15271.                     return $this->redirect($url "/" $StID);
  15272.                 }
  15273.             }
  15274.         }
  15275.         $slotList $em->getRepository('ApplicationBundle\\Entity\\InventoryStorage')->findBy(
  15276.             array(
  15277.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  15278.             )
  15279.         );
  15280.         if ($id == 0) {
  15281.         } else {
  15282.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNote')->findOneBy(
  15283.                 array(
  15284.                     'stockReceivedNoteId' => $id,
  15285.                 )
  15286.             );
  15287.             //now if its not editable, redirect to view
  15288.             if ($extDoc) {
  15289.                 if ($extDoc->getEditFlag() != 1) {
  15290.                     $url $this->generateUrl(
  15291.                         'view_srcv'
  15292.                     );
  15293.                     return $this->redirect($url "/" $id);
  15294.                 } else {
  15295.                     $extDocData $extDoc;
  15296.                     $extDocDataDetails $em->getRepository('ApplicationBundle\\Entity\\StockReceivedNoteItem')->findOneBy(
  15297.                         array(
  15298.                             'stockReceivedNoteId' => $id///material
  15299.                         )
  15300.                     );
  15301.                 }
  15302.             } else {
  15303.             }
  15304.         }
  15305.         $INVLIST = [];
  15306.         foreach ($slotList as $slot) {
  15307.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  15308.         }
  15309.         $dataArray = array(
  15310.             'page_title' => 'Stock Received Note',
  15311. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  15312.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  15313.             'users' => Users::getUserListById($em),
  15314.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  15315.             'warehouseList' => Inventory::WarehouseList($em),
  15316.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  15317.             'warehouseActionList' => $warehouse_action_list,
  15318.             'warehouseActionListArray' => $warehouse_action_list_array,
  15319.             'extDocData' => $extDocData,
  15320.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  15321.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  15322.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  15323.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  15324. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  15325. //            'product_list' => Inventory::ProductList($em, $companyId),
  15326.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  15327.             'prefix_list' => array(
  15328.                 [
  15329.                     'id' => 1,
  15330.                     'value' => 'GN',
  15331.                     'text' => 'GN'
  15332.                 ]
  15333.             ),
  15334.             'assoc_list' => array(
  15335.                 [
  15336.                     'id' => 1,
  15337.                     'value' => 1,
  15338.                     'text' => 'GN'
  15339.                 ]
  15340.             ),
  15341.             'INVLIST' => $INVLIST,
  15342.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  15343.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  15344.             'userBranchIdList' => $userBranchIdList,
  15345.             'userBranchId' => $userBranchId,
  15346. //            'headList' => Accounts::HeadList($em),
  15347.         );
  15348.         //json
  15349.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  15350.         {
  15351.             $dataArray['success'] = true;
  15352.             return new JsonResponse(
  15353.                 $dataArray
  15354.             );
  15355.         }
  15356.         return $this->render('@Inventory/pages/input_forms/stock_received_note.html.twig',
  15357.             $dataArray
  15358.         );
  15359.     }
  15360.     public function RefreshTaskOnSessionAction(Request $request)
  15361.     {
  15362.         $session $request->getSession();
  15363.         $em $this->getDoctrine()->getManager();
  15364.         $currentPlanningItemId 0;
  15365.         $currentTaskId 0;
  15366.         $taskActualStartTs 0;
  15367.         $currentTask $em->getRepository('ApplicationBundle\\Entity\\TaskLog')
  15368.             ->findOneBy(
  15369.                 array(
  15370.                     'userId' => $session->get(UserConstants::USER_ID),
  15371.                     'workingStatus' => 1
  15372.                 )
  15373.             );
  15374.         if ($currentTask) {
  15375.             $currentTaskId $currentTask->getId();
  15376.             $currentPlanningItemId $currentTask->getPlanningItemId();
  15377.             $taskActualStartTs $currentTask->getActualStartTs();
  15378.         }
  15379.         $session->set(UserConstants::USER_CURRENT_TASK_ID$currentTaskId);
  15380.         $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$currentPlanningItemId);
  15381.         return new JsonResponse(
  15382.             array(
  15383.                 'currentPlanningItemId' => $currentPlanningItemId,
  15384.                 'currentTaskId' => $currentTaskId,
  15385.                 'taskActualStartTs' => $taskActualStartTs,
  15386.             )
  15387.         );
  15388.     }
  15389.     private function getProductFormDefaults($em$companyId$loginId)
  15390.     {
  15391.         $defaults = array(
  15392.             'unitTypeId' => 0,
  15393.             'defaultTaxConfigId' => 0,
  15394.             'defaultPurchaseTaxConfigId' => 0,
  15395.             'defaultPurchaseActionTagId' => 0
  15396.         );
  15397.         if ($loginId != '' && $loginId != null) {
  15398.             $pref $em->getRepository('ApplicationBundle\\Entity\\InvProductFormPreference')->findOneBy(array(
  15399.                 'companyId' => $companyId,
  15400.                 'loginId' => $loginId
  15401.             ));
  15402.             if ($pref) {
  15403.                 $defaults['unitTypeId'] = (int) $pref->getUnitTypeId();
  15404.                 $defaults['defaultTaxConfigId'] = (int) $pref->getDefaultTaxConfigId();
  15405.                 $defaults['defaultPurchaseTaxConfigId'] = (int) $pref->getDefaultPurchaseTaxConfigId();
  15406.                 $defaults['defaultPurchaseActionTagId'] = (int) $pref->getDefaultPurchaseActionTagId();
  15407.             }
  15408.         }
  15409.         if ($defaults['unitTypeId'] == 0) {
  15410.             $defaults['unitTypeId'] = $this->resolveDefaultPcsUnitTypeId($em);
  15411.         }
  15412.         if ($defaults['defaultTaxConfigId'] == || $defaults['defaultPurchaseTaxConfigId'] == || $defaults['defaultPurchaseActionTagId'] == 0) {
  15413.             $defaultItemGroup $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(array(
  15414.                 'CompanyId' => $companyId,
  15415.                 'status' => GeneralConstant::ACTIVE
  15416.             ));
  15417.             if ($defaultItemGroup) {
  15418.                 if ($defaults['defaultTaxConfigId'] == 0) {
  15419.                     $defaults['defaultTaxConfigId'] = (int) $defaultItemGroup->getDefaultTaxConfigId();
  15420.                 }
  15421.                 if ($defaults['defaultPurchaseTaxConfigId'] == 0) {
  15422.                     $defaults['defaultPurchaseTaxConfigId'] = (int) $defaultItemGroup->getDefaultPurchaseTaxConfigId();
  15423.                 }
  15424.                 if ($defaults['defaultPurchaseActionTagId'] == 0) {
  15425.                     $defaults['defaultPurchaseActionTagId'] = (int) $defaultItemGroup->getDefaultPurchaseActionTagId();
  15426.                 }
  15427.                 if ($defaults['unitTypeId'] == 0) {
  15428.                     $defaults['unitTypeId'] = (int) $defaultItemGroup->getUnitTypeId();
  15429.                 }
  15430.             }
  15431.         }
  15432.         return $defaults;
  15433.     }
  15434.     private function resolveDefaultPcsUnitTypeId($em)
  15435.     {
  15436.         $unitTypes Inventory::UnitTypeList($em);
  15437.         foreach ($unitTypes as $unitType) {
  15438.             $name = isset($unitType['name']) ? strtoupper(trim($unitType['name'])) : '';
  15439.             $suffix = isset($unitType['classSuffix']) ? strtoupper(trim($unitType['classSuffix'])) : '';
  15440.             if ($name === 'PCS' || $suffix === 'PCS') {
  15441.                 return (int) $unitType['id'];
  15442.             }
  15443.         }
  15444.         foreach ($unitTypes as $unitType) {
  15445.             if (isset($unitType['id']) && $unitType['id'] != && $unitType['id'] != '') {
  15446.                 return (int) $unitType['id'];
  15447.             }
  15448.         }
  15449.         return 0;
  15450.     }
  15451.     private function saveProductFormDefaults($em$companyId$loginId$savedEntityRequest $request)
  15452.     {
  15453.         if ($loginId == '' || $loginId == null) {
  15454.             return;
  15455.         }
  15456.         $unitTypeId 0;
  15457.         $defaultTaxConfigId 0;
  15458.         $defaultPurchaseTaxConfigId 0;
  15459.         $defaultPurchaseActionTagId 0;
  15460.         if ($savedEntity) {
  15461.             if (method_exists($savedEntity'getUnitTypeId')) {
  15462.                 $unitTypeId = (int) $savedEntity->getUnitTypeId();
  15463.             }
  15464.             if (method_exists($savedEntity'getDefaultTaxConfigId')) {
  15465.                 $defaultTaxConfigId = (int) $savedEntity->getDefaultTaxConfigId();
  15466.             }
  15467.             if (method_exists($savedEntity'getDefaultPurchaseTaxConfigId')) {
  15468.                 $defaultPurchaseTaxConfigId = (int) $savedEntity->getDefaultPurchaseTaxConfigId();
  15469.             }
  15470.             if (method_exists($savedEntity'getDefaultPurchaseActionTagId')) {
  15471.                 $defaultPurchaseActionTagId = (int) $savedEntity->getDefaultPurchaseActionTagId();
  15472.             }
  15473.         }
  15474.         if ($unitTypeId == 0) {
  15475.             $unitTypeId = (int) $request->request->get('unitTypeId'0);
  15476.         }
  15477.         if ($defaultTaxConfigId == 0) {
  15478.             $defaultTaxConfigId = (int) $request->request->get('defaultTaxConfigId'0);
  15479.             if ($defaultTaxConfigId == 0) {
  15480.                 $taxConfigIds $request->request->get('taxConfigIds', array());
  15481.                 if (!empty($taxConfigIds)) {
  15482.                     $defaultTaxConfigId = (int) $taxConfigIds[0];
  15483.                 }
  15484.             }
  15485.         }
  15486.         if ($defaultPurchaseTaxConfigId == 0) {
  15487.             $defaultPurchaseTaxConfigId = (int) $request->request->get('defaultPurchaseTaxConfigId'0);
  15488.             if ($defaultPurchaseTaxConfigId == 0) {
  15489.                 $purchaseTaxConfigIds $request->request->get('purchaseTaxConfigIds', array());
  15490.                 if (!empty($purchaseTaxConfigIds)) {
  15491.                     $defaultPurchaseTaxConfigId = (int) $purchaseTaxConfigIds[0];
  15492.                 }
  15493.             }
  15494.         }
  15495.         if ($defaultPurchaseActionTagId == 0) {
  15496.             $defaultPurchaseActionTagId = (int) $request->request->get('defaultPurchaseActionTagId'0);
  15497.         }
  15498.         $pref $em->getRepository('ApplicationBundle\\Entity\\InvProductFormPreference')->findOneBy(array(
  15499.             'companyId' => $companyId,
  15500.             'loginId' => $loginId
  15501.         ));
  15502.         if (!$pref) {
  15503.             $pref = new \ApplicationBundle\Entity\InvProductFormPreference();
  15504.             $pref->setCompanyId($companyId);
  15505.             $pref->setLoginId($loginId);
  15506.             $em->persist($pref);
  15507.         }
  15508.         $pref->setUnitTypeId($unitTypeId);
  15509.         $pref->setDefaultTaxConfigId($defaultTaxConfigId);
  15510.         $pref->setDefaultPurchaseTaxConfigId($defaultPurchaseTaxConfigId);
  15511.         $pref->setDefaultPurchaseActionTagId($defaultPurchaseActionTagId);
  15512.         $em->flush();
  15513.     }
  15514.     // â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  15515.     // S2.2 â€” EPC Category catalog
  15516.     // â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  15517.     public function EpcCategoryListAction(Request $request)
  15518.     {
  15519.         $em $this->getDoctrine()->getManager();
  15520.         $categories $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')
  15521.             ->findBy([], ['displayOrder' => 'ASC''code' => 'ASC']);
  15522.         return $this->render('@Inventory/pages/list/list_epc_categories.html.twig', [
  15523.             'page_title'  => 'EPC Category Catalog',
  15524.             'categories'  => $categories,
  15525.         ]);
  15526.     }
  15527.     public function EpcCategoryEditAction(Request $request$id 0)
  15528.     {
  15529.         $em $this->getDoctrine()->getManager();
  15530.         $ex_id = (int)($request->request->get('ex_id'$id));
  15531.         $cat   null;
  15532.         if ($ex_id 0) {
  15533.             $cat $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')->find($ex_id);
  15534.         }
  15535.         if ($request->isMethod('POST')) {
  15536.             $entity $cat ?? new \ApplicationBundle\Entity\EpcCategory();
  15537.             $entity->setCode(strtoupper(trim($request->request->get('code'''))));
  15538.             $entity->setName(trim($request->request->get('name''')));
  15539.             $entity->setDescription(trim($request->request->get('description''')));
  15540.             $entity->setDisplayOrder((int)$request->request->get('display_order'99));
  15541.             $entity->setActive($request->request->get('active') ? 0);
  15542.             if (!$cat) {
  15543.                 $entity->setCreatedAt(new \DateTime());
  15544.                 $entity->setCreatedLoginId((int)$request->getSession()->get(UserConstants::USER_LOGIN_ID0));
  15545.             }
  15546.             $em->persist($entity);
  15547.             $em->flush();
  15548.             $this->addFlash('success''EPC Category saved.');
  15549.             return $this->redirectToRoute('epc_category_list');
  15550.         }
  15551.         return $this->render('@Inventory/pages/input_forms/edit_epc_category.html.twig', [
  15552.             'page_title' => $ex_id 'Edit EPC Category' 'New EPC Category',
  15553.             'ex_id'      => $ex_id,
  15554.             'cat'        => $cat,
  15555.         ]);
  15556.     }
  15557.     public function EpcCategoryGetAllAction(Request $request)
  15558.     {
  15559.         $em $this->getDoctrine()->getManager();
  15560.         $cats $em->getRepository('ApplicationBundle\\Entity\\EpcCategory')
  15561.             ->findBy(['active' => 1], ['displayOrder' => 'ASC']);
  15562.         $data = [];
  15563.         foreach ($cats as $c) {
  15564.             $data[] = ['code' => $c->getCode(), 'name' => $c->getName()];
  15565.         }
  15566.         return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => true'categories' => $data]);
  15567.     }
  15568.     // â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  15569.     // S2.1 â€” Article Translation endpoints
  15570.     // â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  15571.     public function SuggestProductsFromCentralAction(Request $request)
  15572.     {
  15573.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15574.         if ($systemType === '_CENTRAL_') {
  15575.             return new JsonResponse(['success' => false'message' => 'Not applicable on central'], 403);
  15576.         }
  15577.         $em        $this->getDoctrine()->getManager();
  15578.         $companyId $this->getLoggedUserCompanyId($request);
  15579.         $query     trim($request->request->get('query'''));
  15580.         $igName    trim($request->request->get('igName'''));
  15581.         $modelNo   trim($request->request->get('modelNo'''));
  15582.         if (strlen($query) < && !$modelNo) {
  15583.             return new JsonResponse(['success' => true'results' => []]);
  15584.         }
  15585.         $results Inventory::SearchProductsOnCentral($query$igName$modelNo10);
  15586.         // filter out products already local for this company
  15587.         $filtered = [];
  15588.         foreach ($results as $row) {
  15589.             $globalId = (int)($row['globalId'] ?? 0);
  15590.             if ($globalId 0) {
  15591.                 $local $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  15592.                 if ($local) continue;
  15593.             }
  15594.             $filtered[] = $row;
  15595.         }
  15596.         return new JsonResponse(['success' => true'results' => $filtered]);
  15597.     }
  15598.     public function ImportProductFromCentralAction(Request $request)
  15599.     {
  15600.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15601.         if ($systemType === '_CENTRAL_') {
  15602.             return new JsonResponse(['success' => false'message' => 'Not applicable on central'], 403);
  15603.         }
  15604.         $em        $this->getDoctrine()->getManager();
  15605.         $companyId $this->getLoggedUserCompanyId($request);
  15606.         $globalId  = (int)$request->request->get('globalId'0);
  15607.         if ($globalId <= 0) {
  15608.             return new JsonResponse(['success' => false'message' => 'globalId is required'], 400);
  15609.         }
  15610.         // check idempotency
  15611.         $existing $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  15612.         if ($existing) {
  15613.             return new JsonResponse(['success' => true'productId' => $existing->getId(), 'message' => 'already_exists']);
  15614.         }
  15615.         // fetch the full row from central by globalId
  15616.         $centralUrl = \ApplicationBundle\Constants\GeneralConstant::HONEYBEE_CENTRAL_SERVER;
  15617.         $curl curl_init();
  15618.         curl_setopt_array($curl, [
  15619.             CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  15620.             CURLOPT_URL => $centralUrl '/api/search_global_products',
  15621.             CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 12,
  15622.             CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  15623.             CURLOPT_POSTFIELDS => http_build_query(['globalId' => $globalId]),
  15624.         ]);
  15625.         $response  curl_exec($curl);
  15626.         $curlError curl_error($curl);
  15627.         curl_close($curl);
  15628.         if ($curlError || !$response) {
  15629.             return new JsonResponse(['success' => false'message' => 'Central server unreachable'], 503);
  15630.         }
  15631.         $data json_decode($responsetrue);
  15632.         if (!is_array($data) || empty($data['success']) || empty($data['results'])) {
  15633.             return new JsonResponse(['success' => false'message' => 'Product not found on central'], 404);
  15634.         }
  15635.         try {
  15636.             $productId Inventory::MaterializeProductFromCentral($em$companyId$data['results'][0]);
  15637.         } catch (\Throwable $e) {
  15638.             return new JsonResponse(['success' => false'message' => $e->getMessage()], 500);
  15639.         }
  15640.         return new JsonResponse(['success' => true'productId' => $productId'message' => 'imported']);
  15641.     }
  15642.     /**
  15643.      * Dev-admin only: proxy a central product search so the create-product form can
  15644.      * "Load from Central". Returns the central rows (igName/categoryName/specDataNamed
  15645.      * + descriptive fields) for the JS to populate the form. No DB write happens here â€”
  15646.      * the user reviews and Saves to materialize. Gated by devAdminMode.
  15647.      */
  15648.     public function SearchCentralProductsAction(Request $request)
  15649.     {
  15650.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15651.         if ($systemType === '_CENTRAL_') {
  15652.             return new JsonResponse(['success' => false'message' => 'Not applicable on central'], 403);
  15653.         }
  15654.         if ((int) $request->getSession()->get('devAdminMode'0) !== 1) {
  15655.             return new JsonResponse(['success' => false'message' => 'Requires devAdmin mode (open with ?devAdminOn=1)'], 403);
  15656.         }
  15657.         $query    trim($request->request->get('query'''));
  15658.         $globalId = (int) $request->request->get('globalId'0);
  15659.         if ($globalId <= && strlen($query) < 2) {
  15660.             return new JsonResponse(['success' => false'message' => 'query must be at least 2 characters'], 400);
  15661.         }
  15662.         $centralUrl = \ApplicationBundle\Constants\GeneralConstant::HONEYBEE_CENTRAL_SERVER;
  15663.         $curl curl_init();
  15664.         curl_setopt_array($curl, [
  15665.             CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  15666.             CURLOPT_URL => $centralUrl '/api/search_global_products',
  15667.             CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 15,
  15668.             CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  15669.             CURLOPT_POSTFIELDS => http_build_query($globalId ? ['globalId' => $globalId] : ['query' => $query'limit' => 20]),
  15670.         ]);
  15671.         $response  curl_exec($curl);
  15672.         $curlError curl_error($curl);
  15673.         curl_close($curl);
  15674.         if ($curlError || !$response) {
  15675.             return new JsonResponse(['success' => false'message' => 'Central server unreachable' . ($curlError ': ' $curlError '')], 503);
  15676.         }
  15677.         $data json_decode($responsetrue);
  15678.         if (!is_array($data)) {
  15679.             return new JsonResponse(['success' => false'message' => 'Bad response from central'], 502);
  15680.         }
  15681.         return new JsonResponse($data);
  15682.     }
  15683.     public function ArticleTranslationSaveAction(Request $request)
  15684.     {
  15685.         $em        $this->getDoctrine()->getManager();
  15686.         $articleId = (int)$request->request->get('article_id'0);
  15687.         $data      $request->request->get('translations', []);
  15688.         $loginId   = (int)$request->getSession()->get(UserConstants::USER_LOGIN_ID0);
  15689.         if ($articleId === || !is_array($data)) {
  15690.             return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => false'message' => 'Invalid input']);
  15691.         }
  15692.         Inventory::saveArticleTranslations($em$articleId$data$loginId);
  15693.         return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => true]);
  15694.     }
  15695.     public function ArticleTranslationGetAction(Request $request$articleId 0)
  15696.     {
  15697.         $em $this->getDoctrine()->getManager();
  15698.         $translations Inventory::getArticleTranslations($em, (int)$articleId);
  15699.         return new \Symfony\Component\HttpFoundation\JsonResponse(['success' => true'translations' => $translations]);
  15700.     }
  15701.     // ===== Global-product / central-product-control cluster â€” moved from the legacy
  15702.     // ApplicationBundle\Controller\InventoryController (2026-07-03 consolidation). Behavior
  15703.     // preserved verbatim; routes repointed here. =====
  15704.     public function SyncProductAction(Request $request$id)
  15705.     {
  15706.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15707.         $em_local $this->getDoctrine()->getManager();
  15708.         if ($systemType == '_ERP_') {
  15709.             $product $em_local->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($id);
  15710.             if (!$product) {
  15711.                 return new JsonResponse(['error' => 'Product not found'], 404);
  15712.             }
  15713.             // Get category details
  15714.             $category $em_local->getRepository('ApplicationBundle\\Entity\\InvProductCategories')->find($product->getCategoryId());
  15715.             $brand $em_local -> getRepository('ApplicationBundle\\Entity\\BrandCompany')->find($product->getBrandCompany());
  15716.             $productData = [];
  15717.             $categoryData = [];
  15718.             $brandData = [];
  15719.             // Get product fields
  15720.             $reflectionClass = new \ReflectionClass($product);
  15721.             foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  15722.                 if (strpos($method->getName(), 'get') === 0) {
  15723.                     $property lcfirst(str_replace('get'''$method->getName()));
  15724.                     $productData[$property] = $method->invoke($product);
  15725.                 }
  15726.             }
  15727.             // Get category fields
  15728.             if ($category) {
  15729.                 $categoryReflection = new \ReflectionClass($category);
  15730.                 foreach ($categoryReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  15731.                     if (strpos($method->getName(), 'get') === 0) {
  15732.                         $property lcfirst(str_replace('get'''$method->getName()));
  15733.                         $categoryData[$property] = $method->invoke($category);
  15734.                     }
  15735.                 }
  15736.             }
  15737.             // Brand data
  15738.             if ($brand) {
  15739.                 $brandReflection = new \ReflectionClass($brand);
  15740.                 foreach ($brandReflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  15741.                     if (strpos($method->getName(), 'get') === 0) {
  15742.                         $property lcfirst(str_replace('get'''$method->getName()));
  15743.                         $brandData[$property] = $method->invoke($brand);
  15744.                     }
  15745.                 }
  15746.             }
  15747.             // Store product data in pending_data
  15748.             $product->setPendingData(json_encode($productData));
  15749.             $em_local->flush();
  15750.             // Send  product,brand & category to central
  15751.             $syncData = [
  15752.                 'product' => $productData,
  15753.                 'category' => $categoryData,
  15754.                 'brand' => $brandData
  15755.             ];
  15756.             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/product_sync/' $id;
  15757.             $curl curl_init();
  15758.             curl_setopt_array($curl, [
  15759.                 CURLOPT_RETURNTRANSFER => true,
  15760.                 CURLOPT_POST => true,
  15761.                 CURLOPT_URL => $urlToCall,
  15762.                 CURLOPT_CONNECTTIMEOUT => 10,
  15763.                 CURLOPT_SSL_VERIFYPEER => false,
  15764.                 CURLOPT_SSL_VERIFYHOST => false,
  15765.                 CURLOPT_HTTPHEADER => [],
  15766.                 CURLOPT_POSTFIELDS => ['syncData' => json_encode($syncData)]
  15767.             ]);
  15768.             $retData curl_exec($curl);
  15769.             $errData curl_error($curl);
  15770.             curl_close($curl);
  15771.             if ($errData) {
  15772.                 return new JsonResponse(['error' => $errData], 500);
  15773.             }
  15774.             $retDataObj json_decode($retDatatrue);
  15775.             if (isset($retDataObj['globalId'])) {
  15776.                 $product->setGlobalId($retDataObj['globalId']);
  15777.                 $em_local->flush();
  15778.             }
  15779.             return new JsonResponse(['message' => 'Product (pending) and category synced to central server!']);
  15780.         }
  15781.         // CENTRAL SYSTEM PROCESSING
  15782.         else if ($systemType == '_CENTRAL_') {
  15783.             $requestData $request->get('syncData');
  15784.             if (!$requestData) {
  15785.                 return new JsonResponse(['error' => 'Invalid data received'], 400);
  15786.             }
  15787.             $requestData json_decode($requestDatatrue);
  15788.             $productData $requestData['product'] ?? null;
  15789.             $categoryData $requestData['category'] ?? null;
  15790.             $brandData $requestData['brand'] ?? null;
  15791.             if (!$productData) {
  15792.                 return new JsonResponse(['error' => 'Product data missing'], 400);
  15793.             }
  15794.             // Process product (Store in pending_data)
  15795.             $product $em_local->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($productData['id']) ?? new InvProducts();
  15796.             // Store in pending_data until approval
  15797.             $product->setPendingData(json_encode($productData));
  15798.             $this->ApproveProductAction($id);
  15799.             $em_local->persist($product);
  15800.             // Process category (Save directly)
  15801.             if ($categoryData) {
  15802.                 $category $em_local->getRepository('ApplicationBundle\\Entity\\InvProductCategories')->find($categoryData['id']) ?? new InvProductCategories();
  15803.                 foreach ($categoryData as $field => $value) {
  15804.                     if ($field === 'id') continue;
  15805.                     $setterMethod 'set' ucfirst($field);
  15806.                     if (method_exists($category$setterMethod)) {
  15807.                         $category->$setterMethod($value);
  15808.                     }
  15809.                 }
  15810.                 $em_local->persist($category);
  15811.             }
  15812.             // process brand data
  15813.             if($brandData){
  15814.                 $brand $em_local->getRepository('ApplicationBundle\\Entity\\BrandCompany')->find($brandData['id']) ?? new BrandCompany();
  15815.                 foreach ($brandData as $field => $value){
  15816.                     if($field === 'id') continue;
  15817.                     $setterMethod 'set'.ucfirst($field);
  15818.                     if(method_exists($brand,$setterMethod)){
  15819.                         $brand->$setterMethod($value);
  15820.                     }
  15821.                 }
  15822.                 $em_local->persist($brand);
  15823.             }
  15824.             $em_local->flush();
  15825.             return new JsonResponse(['globalId' => $product->getId()]);
  15826.         }
  15827.         return new JsonResponse("Product (pending) and category updated successfully in central!");
  15828.     }
  15829.     public function CheckGlobalProductAction(Request $request)
  15830.     {
  15831.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15832.         if ($systemType !== '_CENTRAL_') {
  15833.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  15834.         }
  15835.         $em $this->getDoctrine()->getManager();
  15836.         $igName      trim($request->request->get('igName'''));
  15837.         $productName trim($request->request->get('productName'''));
  15838.         $modelNo     trim($request->request->get('modelNo'''));
  15839.         if (!$igName || !$productName) {
  15840.             return new JsonResponse(['success' => false'found' => false'message' => 'igName and productName are required']);
  15841.         }
  15842.         $ig $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(['name' => $igName'type' => 1]);
  15843.         if (!$ig) {
  15844.             return new JsonResponse(['success' => true'found' => false]);
  15845.         }
  15846.         $product null;
  15847.         if ($modelNo) {
  15848.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'modelNo' => $modelNo]);
  15849.         }
  15850.         if (!$product) {
  15851.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'name' => $productName]);
  15852.         }
  15853.         if (!$product) {
  15854.             return new JsonResponse(['success' => true'found' => false]);
  15855.         }
  15856.         return new JsonResponse(['success' => true'found' => true'globalId' => $product->getGlobalId() ?: $product->getId()]);
  15857.     }
  15858.     /** Tenant-side: pull this product's canonical version from the central catalog, overwriting local drift. */
  15859.     public function ResetProductFromCentralAction(Request $request$id)
  15860.     {
  15861.         $em $this->getDoctrine()->getManager();
  15862.         $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find((int) $id);
  15863.         if (!$product) {
  15864.             return new JsonResponse(['success' => false'message' => 'Product not found.'], 404);
  15865.         }
  15866.         $res = \ApplicationBundle\Modules\Inventory\Inventory::ResetLocalProductFromCentral($em$product);
  15867.         return new JsonResponse($res, !empty($res['success']) ? 200 400);
  15868.     }
  15869.     public function SearchGlobalProductsAction(Request $request)
  15870.     {
  15871.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  15872.         if ($systemType !== '_CENTRAL_') {
  15873.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  15874.         }
  15875.         $em          $this->getDoctrine()->getManager();
  15876.         $query       trim($request->request->get('query'''));
  15877.         $igName      trim($request->request->get('igName'''));
  15878.         $modelNo     trim($request->request->get('modelNo'''));
  15879.         $globalId    = (int)$request->request->get('globalId'0);
  15880.         $limit       min((int)$request->request->get('limit'10), 25);
  15881.         if ($globalId 0) {
  15882.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  15883.             if (!$product) {
  15884.                 $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  15885.             }
  15886.             if (!$product) {
  15887.                 return new JsonResponse(['success' => true'count' => 0'results' => []]);
  15888.             }
  15889.             $ig $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->find($product->getIgId());
  15890.             return new JsonResponse(['success' => true'count' => 1'results' => [
  15891.                 $this->buildGlobalProductRow($em$product$ig),
  15892.             ]]);
  15893.         }
  15894.         if (strlen($query) < && !$modelNo) {
  15895.             return new JsonResponse(['success' => false'message' => 'query must be at least 2 characters'], 400);
  15896.         }
  15897.         $conn $em->getConnection();
  15898.         // The central catalog DB is lean â€” it may not carry the full ERP inventory schema
  15899.         // (e.g. inv_product_brand). A LEFT JOIN still hard-fails on a missing table, so only join
  15900.         // the enrichment tables that actually exist; absent ones fall back to an empty literal.
  15901.         $existingTables = [];
  15902.         $productCols = [];
  15903.         try {
  15904.             foreach ($this->dbalFetchAllAssoc(
  15905.                 $conn,
  15906.                 "SELECT table_name AS t FROM information_schema.tables WHERE table_schema = DATABASE()"
  15907.             ) as $r) {
  15908.                 $existingTables[strtolower($r['t'])] = true;
  15909.             }
  15910.             // Also detect which COLUMNS exist on inv_products â€” a lean central may be missing
  15911.             // optional columns (description, alias, model_no, global_id, sync_flag, â€¦).
  15912.             foreach ($this->dbalFetchAllAssoc(
  15913.                 $conn,
  15914.                 "SELECT column_name AS c FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'inv_products'"
  15915.             ) as $r) {
  15916.                 $productCols[strtolower($r['c'])] = true;
  15917.             }
  15918.         } catch (\Throwable $e) { /* detection failed â†’ assume everything exists (old behaviour) */ }
  15919.         $hasTable = function ($t) use ($existingTables) {
  15920.             return empty($existingTables) || isset($existingTables[strtolower($t)]);
  15921.         };
  15922.         $hasCol = function ($c) use ($productCols) {
  15923.             return empty($productCols) || isset($productCols[strtolower($c)]);
  15924.         };
  15925.         $hasModelNo $hasCol('model_no');
  15926.         $where = [];
  15927.         $params = [];
  15928.         if ($query !== '') {
  15929.             $where[] = $hasModelNo '(p.name LIKE :q OR p.model_no LIKE :q)' 'p.name LIKE :q';
  15930.             $params['q'] = '%' $query '%';
  15931.         }
  15932.         if ($modelNo !== '' && $hasModelNo) {
  15933.             $where[] = 'p.model_no LIKE :model';
  15934.             $params['model'] = '%' $modelNo '%';
  15935.         }
  15936.         if ($igName !== '' && $hasTable('inv_item_group')) {
  15937.             $where[] = 'ig.name = :igName';
  15938.             $params['igName'] = $igName;
  15939.         }
  15940.         $whereSql $where ? ('WHERE ' implode(' AND '$where)) : '';
  15941.         // Base columns on inv_products â€” include only those that exist; missing ones become ''.
  15942.         $baseColumns = [
  15943.             ['id',          'p.id'],
  15944.             ['name',        'p.name'],
  15945.             ['modelNo',     'p.model_no'],
  15946.             ['productFdm',  'p.product_fdm'],
  15947.             ['globalId',    'p.global_id'],
  15948.             ['syncFlag',    'p.sync_flag'],
  15949.             ['description''p.description'],
  15950.             ['alias',       'p.alias'],
  15951.         ];
  15952.         $selects = [];
  15953.         foreach ($baseColumns as $bc) {
  15954.             list($as$col) = $bc;
  15955.             $rawCol substr($col2); // strip "p."
  15956.             if ($hasCol($rawCol)) {
  15957.                 $selects[] = ($rawCol === $as) ? $col : ($col ' AS ' $as);
  15958.             } else {
  15959.                 $selects[] = "'' AS $as";
  15960.             }
  15961.         }
  15962.         $joins '';
  15963.         $enrich = [
  15964.             ['inv_item_group',            'ig',  'ig.id = p.ig_id',                              'ig.name',       'igName'],
  15965.             ['inv_product_categories',    'cat''cat.id = p.category_id',                       'cat.name',      'categoryName'],
  15966.             ['inv_product_sub_categories','sub''sub.id = p.sub_category_id',                   'sub.name',      'subCategoryName'],
  15967.             ['brand_company',             'br',  'br.id = p.brand_company',                      'br.name',       'brandName'],
  15968.             ['unit_type',                 'ut',  'ut.id = p.unit_type_id',                       'ut.name',       'uomName'],
  15969.             ['inv_product_images',        'img''img.product_id = p.id AND img.is_default = 1''img.file_name''image'],
  15970.         ];
  15971.         foreach ($enrich as $e) {
  15972.             list($tbl$alias$on$col$as) = $e;
  15973.             if ($hasTable($tbl)) {
  15974.                 $selects[] = "$col AS $as";
  15975.                 $joins   .= "\n                LEFT JOIN $tbl $alias ON $on";
  15976.             } else {
  15977.                 $selects[] = "'' AS $as";
  15978.             }
  15979.         }
  15980.         // ORDER BY: exact-name first; the model_no tier only when that column exists.
  15981.         $orderSql "ORDER BY CASE WHEN p.name = :exactName THEN 0 ";
  15982.         if ($hasModelNo) {
  15983.             $orderSql .= "WHEN p.model_no = :exactModel THEN 1 ";
  15984.         }
  15985.         $orderSql .= "ELSE 2 END, p.name ASC";
  15986.         $sql "SELECT " implode(', '$selects) . "
  15987.                 FROM inv_products p" $joins "
  15988.                 $whereSql
  15989.                 $orderSql
  15990.                 LIMIT :lim";
  15991.         $params['exactName']  = $query ?: '';
  15992.         if ($hasModelNo) {
  15993.             $params['exactModel'] = $modelNo ?: $query;
  15994.         }
  15995.         $params['lim']        = $limit;
  15996.         $types = [];
  15997.         foreach ($params as $key => $val) {
  15998.             $types[$key] = is_int($val) ? \PDO::PARAM_INT : \PDO::PARAM_STR;
  15999.         }
  16000.         $rows $this->dbalFetchAllAssoc($conn$sql$params$types);
  16001.         foreach ($rows as &$row) {
  16002.             $row['globalId'] = (int)($row['globalId'] ?: $row['id']);
  16003.         }
  16004.         return new JsonResponse(['success' => true'count' => count($rows), 'results' => $rows]);
  16005.     }
  16006.     /**
  16007.      * Fetch all rows as associative arrays, portable across Doctrine DBAL versions.
  16008.      * The central server runs an older DBAL where fetchAllAssociative() does not exist â€” fall
  16009.      * back to the legacy Connection::fetchAll(). Both accept ($sql, $params, $types).
  16010.      */
  16011.     private function dbalFetchAllAssoc($conn$sql, array $params = [], array $types = [])
  16012.     {
  16013.         if (method_exists($conn'fetchAllAssociative')) {
  16014.             return $conn->fetchAllAssociative($sql$params$types);
  16015.         }
  16016.         return $conn->fetchAll($sql$params$types);
  16017.     }
  16018.     private function buildGlobalProductRow($em$product$ig)
  16019.     {
  16020.         $categoryName '';
  16021.         $subCategoryName '';
  16022.         $brandName '';
  16023.         $uomName '';
  16024.         // Enrichment tables may be absent on a lean central DB â€” never let a missing one break the row.
  16025.         try {
  16026.             if ($product->getCategoryId()) {
  16027.                 $cat $em->getRepository('ApplicationBundle\\Entity\\InvProductCategories')->find($product->getCategoryId());
  16028.                 if ($cat$categoryName $cat->getName();
  16029.             }
  16030.         } catch (\Throwable $e) { /* table absent */ }
  16031.         try {
  16032.             if ($product->getSubCategoryId()) {
  16033.                 $sub $em->getRepository('ApplicationBundle\\Entity\\InvProductSubCategories')->find($product->getSubCategoryId());
  16034.                 if ($sub$subCategoryName $sub->getName();
  16035.             }
  16036.         } catch (\Throwable $e) { /* table absent */ }
  16037.         try {
  16038.             if ($product->getBrandCompany()) {
  16039.                 $br $em->getRepository('ApplicationBundle\\Entity\\BrandCompany')->find($product->getBrandCompany());
  16040.                 if ($br$brandName $br->getName();
  16041.             }
  16042.         } catch (\Throwable $e) { /* table absent */ }
  16043.         try {
  16044.             if ($product->getUnitTypeId()) {
  16045.                 $ut $em->getRepository('ApplicationBundle\\Entity\\UnitType')->find($product->getUnitTypeId());
  16046.                 if ($ut$uomName $ut->getName();
  16047.             }
  16048.         } catch (\Throwable $e) { /* table absent */ }
  16049.         $row = [
  16050.             'id'              => $product->getId(),
  16051.             'globalId'        => $product->getGlobalId() ?: $product->getId(),
  16052.             'name'            => $product->getName(),
  16053.             'modelNo'         => $product->getModelNo(),
  16054.             'productFdm'      => $product->getProductFdm(),
  16055.             'description'     => $product->getNote(),
  16056.             'alias'           => $product->getAlias(),
  16057.             'igName'          => $ig $ig->getName() : '',
  16058.             'categoryName'    => $categoryName,
  16059.             'subCategoryName' => $subCategoryName,
  16060.             'brandName'       => $brandName,
  16061.             'uomName'         => $uomName,
  16062.             'image'           => '',
  16063.         ];
  16064.         // Publish the full descriptive catalog field set (specs, sizes, weights,
  16065.         // crate data, etc.) so a synced ERP can mirror almost the entire record.
  16066.         foreach (\ApplicationBundle\Modules\Inventory\Inventory::globalCatalogFields() as $field) {
  16067.             $getter 'get' ucfirst($field);
  16068.             if (method_exists($product$getter)) {
  16069.                 $row[$field] = $product->$getter();
  16070.             }
  16071.         }
  16072.         // Publish the spec table resolved to spec-type NAMES so a synced ERP can
  16073.         // recreate any missing spec type and carry the full spec table.
  16074.         $specDataNamed = [];
  16075.         try {
  16076.             $specArr $product->getSpecData() ? json_decode($product->getSpecData(), true) : [];
  16077.             if (is_array($specArr)) {
  16078.                 foreach ($specArr as $sd) {
  16079.                     $sid = isset($sd['id']) ? $sd['id'] : null;
  16080.                     if (!$sid) continue;
  16081.                     $st $em->getRepository('ApplicationBundle\\Entity\\SpecType')->find($sid);
  16082.                     $specDataNamed[] = ['name' => $st $st->getName() : '''value' => isset($sd['value']) ? $sd['value'] : ''];
  16083.                 }
  16084.             }
  16085.         } catch (\Throwable $e) { /* spec table absent on lean central */ }
  16086.         $row['specDataNamed'] = $specDataNamed;
  16087.         return $row;
  16088.     }
  16089.     public function RegisterGlobalProductAction(Request $request)
  16090.     {
  16091.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16092.         if ($systemType !== '_CENTRAL_') {
  16093.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16094.         }
  16095.         $em $this->getDoctrine()->getManager();
  16096.         $igName      trim($request->request->get('igName'''));
  16097.         $productName trim($request->request->get('productName'''));
  16098.         $modelNo     trim($request->request->get('modelNo'''));
  16099.         $productFdm  $request->request->get('productFdm''');
  16100.         if (!$igName || !$productName) {
  16101.             return new JsonResponse(['success' => false'message' => 'igName and productName are required'], 400);
  16102.         }
  16103.         $ig $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->findOneBy(['name' => $igName'type' => 1]);
  16104.         if (!$ig) {
  16105.             $ig = new \ApplicationBundle\Entity\InvItemGroup();
  16106.             $ig->setName($igName);
  16107.             $ig->setType(1);
  16108.             $em->persist($ig);
  16109.             $em->flush();
  16110.             $ig->setGlobalId($ig->getId());
  16111.             $em->flush();
  16112.         }
  16113.         // Race-condition guard: check again after potential ig creation
  16114.         $existing null;
  16115.         if ($modelNo) {
  16116.             $existing $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'modelNo' => $modelNo]);
  16117.         }
  16118.         if (!$existing) {
  16119.             $existing $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['igId' => $ig->getId(), 'name' => $productName]);
  16120.         }
  16121.         if ($existing) {
  16122.             return new JsonResponse(['success' => true'globalId' => $existing->getGlobalId() ?: $existing->getId()]);
  16123.         }
  16124.         $product = new \ApplicationBundle\Entity\InvProducts();
  16125.         $product->setName($productName);
  16126.         $product->setModelNo($modelNo);
  16127.         $product->setProductFdm($productFdm);
  16128.         $product->setIgId($ig->getId());
  16129.         $product->setSyncFlag(2);
  16130.         $em->persist($product);
  16131.         $em->flush();
  16132.         $product->setGlobalId($product->getId());
  16133.         $em->flush();
  16134.         return new JsonResponse(['success' => true'globalId' => $product->getId()]);
  16135.     }
  16136.     public function PushGlobalProductToErpsAction(Request $request)
  16137.     {
  16138.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16139.         if ($systemType !== '_CENTRAL_') {
  16140.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16141.         }
  16142.         $globalId = (int)$request->request->get('globalId'0);
  16143.         $data     $request->request->get('data', []);
  16144.         if (!$globalId) {
  16145.             return new JsonResponse(['success' => false'message' => 'globalId is required'], 400);
  16146.         }
  16147.         // Build the full central record ONCE (descriptive fields + igName/category +
  16148.         // named spec list) so each tenant sync applies it without calling back.
  16149.         $em $this->getDoctrine()->getManager();
  16150.         $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  16151.         if (!$product$product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  16152.         if (!$product) {
  16153.             return new JsonResponse(['success' => false'message' => 'Central product not found for globalId ' $globalId], 404);
  16154.         }
  16155.         $ig  $product->getIgId() ? $em->getRepository('ApplicationBundle\\Entity\\InvItemGroup')->find($product->getIgId()) : null;
  16156.         $row $this->buildGlobalProductRow($em$product$ig);
  16157.         $em_goc $this->getDoctrine()->getManager('company_group');
  16158.         $em_goc->getConnection()->connect();
  16159.         if (!$em_goc->getConnection()->isConnected()) {
  16160.             return new JsonResponse(['success' => false'message' => 'Cannot connect to company_group DB'], 500);
  16161.         }
  16162.         $gocList $em_goc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy(['active' => 1]);
  16163.         // Tenants live on DIFFERENT servers (their DBs are localhost to THEIR server,
  16164.         // not to central). So push once to each distinct server, and let that server's
  16165.         // receiver update ALL of its own local tenants. Resolve the address from
  16166.         // company_group_server_address â€” the field that's actually populated; the old
  16167.         // loop read *_domain_full_link (NULL for everyone), which is why it collapsed
  16168.         // to "1 server" and never reached SG.
  16169.         $seen = [];
  16170.         $servers = [];
  16171.         foreach ($gocList as $entry) {
  16172.             $addr rtrim(
  16173.                 ($entry->getCompanyGroupServerAddress() ?: $entry->getCurrentServerAddress())
  16174.                 ?: ($entry->getCurrentServerDomainFullLink() ?: ($entry->getCompanyGroupServerDomainFullLink() ?: '')),
  16175.                 '/'
  16176.             );
  16177.             if (!$addr || isset($seen[$addr])) continue;
  16178.             $seen[$addr] = true;
  16179.             $servers[] = $addr;
  16180.         }
  16181.         $results = [];
  16182.         $tenantsUpdated 0;
  16183.         foreach ($servers as $addr) {
  16184.             $curl curl_init();
  16185.             curl_setopt_array($curl, [
  16186.                 CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  16187.                 CURLOPT_URL => $addr '/api/sync_product_from_central',
  16188.                 CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 90// receiver loops its tenants
  16189.                 CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  16190.                 CURLOPT_POSTFIELDS => http_build_query(['globalId' => $globalId'data' => $row'force' => 1]),
  16191.             ]);
  16192.             $response  curl_exec($curl);
  16193.             $curlError curl_error($curl);
  16194.             curl_close($curl);
  16195.             $decoded $curlError ? ['error' => $curlError] : json_decode($responsetrue);
  16196.             $results[$addr] = $decoded;
  16197.             if (is_array($decoded) && !empty($decoded['tenants_updated'])) {
  16198.                 $tenantsUpdated += (int) $decoded['tenants_updated'];
  16199.             }
  16200.         }
  16201.         return new JsonResponse([
  16202.             'success'         => true,
  16203.             'globalId'        => $globalId,
  16204.             'pushed'          => count($servers),   // UI label: "Pushed to N server(s)"
  16205.             'servers'         => count($servers),
  16206.             'tenants_updated' => $tenantsUpdated,
  16207.             'results'         => $results,
  16208.         ]);
  16209.     }
  16210.     public function SuggestProductUpdateAction(Request $request)
  16211.     {
  16212.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16213.         if ($systemType !== '_CENTRAL_') {
  16214.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16215.         }
  16216.         $em             $this->getDoctrine()->getManager();
  16217.         $globalId       = (int)$request->request->get('globalId'0);
  16218.         $suggestedFields $request->request->get('suggestedFields', []);
  16219.         $suggestedBy    = (int)$request->request->get('suggestedBy'0);
  16220.         $sourceNote     trim($request->request->get('sourceNote'''));
  16221.         if (!$globalId || empty($suggestedFields)) {
  16222.             return new JsonResponse(['success' => false'message' => 'globalId and suggestedFields are required'], 400);
  16223.         }
  16224.         // validate: igId and modelNo cannot be suggested for change
  16225.         $forbidden = ['igId''ig_id''modelNo''model_no'];
  16226.         foreach ($forbidden as $f) {
  16227.             if (isset($suggestedFields[$f])) {
  16228.                 return new JsonResponse(['success' => false'message' => "Field '{$f}' is a global identity anchor and cannot be changed"], 422);
  16229.             }
  16230.         }
  16231.         $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  16232.         if (!$product) {
  16233.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  16234.         }
  16235.         if (!$product) {
  16236.             return new JsonResponse(['success' => false'message' => 'Product not found on central'], 404);
  16237.         }
  16238.         $suggestion = new \ApplicationBundle\Entity\InvProductCentralSuggestion();
  16239.         $suggestion->setGlobalId($globalId);
  16240.         $suggestion->setSuggestedFields(json_encode($suggestedFields));
  16241.         $suggestion->setSuggestedBy($suggestedBy ?: null);
  16242.         $suggestion->setSourceNote($sourceNote ?: null);
  16243.         $suggestion->setStatus(\ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_PENDING);
  16244.         $em->persist($suggestion);
  16245.         $em->flush();
  16246.         return new JsonResponse(['success' => true'suggestionId' => $suggestion->getId()]);
  16247.     }
  16248.     public function ApproveProductAction(Request $request$id)
  16249.     {
  16250.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16251.         if ($systemType !== '_CENTRAL_') {
  16252.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16253.         }
  16254.         $em         $this->getDoctrine()->getManager();
  16255.         $approvedBy = (int)$request->request->get('approvedBy'0);
  16256.         $suggestion $em->getRepository('ApplicationBundle\\Entity\\InvProductCentralSuggestion')->find((int)$id);
  16257.         if (!$suggestion) {
  16258.             return new JsonResponse(['error' => 'Suggestion not found'], 404);
  16259.         }
  16260.         if ($suggestion->getStatus() !== \ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_PENDING) {
  16261.             return new JsonResponse(['error' => 'Suggestion already ' $suggestion->getStatus()], 409);
  16262.         }
  16263.         $globalId $suggestion->getGlobalId();
  16264.         $product  $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->findOneBy(['globalId' => $globalId]);
  16265.         if (!$product) {
  16266.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')->find($globalId);
  16267.         }
  16268.         if (!$product) {
  16269.             return new JsonResponse(['error' => 'Central product not found for globalId ' $globalId], 404);
  16270.         }
  16271.         $fields   $suggestion->getSuggestedFieldsArray();
  16272.         $locked   = ['igId''ig_id''modelNo''model_no''id''globalId'];
  16273.         $applied  = [];
  16274.         foreach ($fields as $field => $value) {
  16275.             if (in_array($field$lockedtrue)) continue;
  16276.             $setter 'set' ucfirst($field);
  16277.             if (method_exists($product$setter)) {
  16278.                 $product->$setter($value);
  16279.                 $applied[$field] = $value;
  16280.             }
  16281.         }
  16282.         $em->flush();
  16283.         // mark suggestion approved
  16284.         $suggestion->setStatus(\ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_APPROVED);
  16285.         $suggestion->setApprovedBy($approvedBy ?: null);
  16286.         $suggestion->setApprovedAt(new \DateTime());
  16287.         $em->flush();
  16288.         // propagate approved changes to all linked ERP servers
  16289.         $em_goc $this->getDoctrine()->getManager('company_group');
  16290.         $gocList = [];
  16291.         try {
  16292.             $gocList $em_goc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy(['active' => 1]);
  16293.         } catch (\Exception $e) {}
  16294.         $seenServers = [];
  16295.         $pushResults = [];
  16296.         foreach ($gocList as $entry) {
  16297.             $serverAddress rtrim(
  16298.                 $entry->getCurrentServerDomainFullLink() ?: $entry->getCompanyGroupServerDomainFullLink(),
  16299.                 '/'
  16300.             );
  16301.             if (!$serverAddress || isset($seenServers[$serverAddress])) continue;
  16302.             $seenServers[$serverAddress] = true;
  16303.             $curl curl_init();
  16304.             curl_setopt_array($curl, [
  16305.                 CURLOPT_RETURNTRANSFER => trueCURLOPT_POST => true,
  16306.                 CURLOPT_URL => $serverAddress '/api/sync_product_from_central',
  16307.                 CURLOPT_CONNECTTIMEOUT => 8CURLOPT_TIMEOUT => 15,
  16308.                 CURLOPT_SSL_VERIFYPEER => falseCURLOPT_SSL_VERIFYHOST => false,
  16309.                 CURLOPT_POSTFIELDS => http_build_query(['globalId' => $globalId'data' => $applied]),
  16310.             ]);
  16311.             $response  curl_exec($curl);
  16312.             $curlError curl_error($curl);
  16313.             curl_close($curl);
  16314.             $pushResults[$serverAddress] = $curlError
  16315.                 ? ['error' => $curlError]
  16316.                 : json_decode($responsetrue);
  16317.         }
  16318.         return new JsonResponse([
  16319.             'success'     => true,
  16320.             'globalId'    => $globalId,
  16321.             'appliedFields' => array_keys($applied),
  16322.             'pushedTo'    => count($seenServers),
  16323.             'pushResults' => $pushResults,
  16324.         ]);
  16325.     }
  16326.     public function RejectProductSuggestionAction(Request $request$id)
  16327.     {
  16328.         $systemType $this->container->getParameter('system_type') ?: '_ERP_';
  16329.         if ($systemType !== '_CENTRAL_') {
  16330.             return new JsonResponse(['success' => false'message' => 'Not a central system'], 403);
  16331.         }
  16332.         $em           $this->getDoctrine()->getManager();
  16333.         $rejectedBy   = (int)$request->request->get('rejectedBy'0);
  16334.         $rejectionNote trim($request->request->get('rejectionNote'''));
  16335.         $suggestion $em->getRepository('ApplicationBundle\\Entity\\InvProductCentralSuggestion')->find((int)$id);
  16336.         if (!$suggestion) {
  16337.             return new JsonResponse(['error' => 'Suggestion not found'], 404);
  16338.         }
  16339.         if ($suggestion->getStatus() !== \ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_PENDING) {
  16340.             return new JsonResponse(['error' => 'Suggestion already ' $suggestion->getStatus()], 409);
  16341.         }
  16342.         $suggestion->setStatus(\ApplicationBundle\Entity\InvProductCentralSuggestion::STATUS_REJECTED);
  16343.         $suggestion->setRejectedBy($rejectedBy ?: null);
  16344.         $suggestion->setRejectedAt(new \DateTime());
  16345.         $suggestion->setRejectionNote($rejectionNote ?: null);
  16346.         $em->flush();
  16347.         return new JsonResponse(['success' => true'suggestionId' => $suggestion->getId()]);
  16348.     }
  16349. }