src/ApplicationBundle/Modules/Accounts/Controller/AccountsController.php line 1913

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Modules\Accounts\Controller;
  3. use ApplicationBundle\ApplicationBundle;
  4. use ApplicationBundle\Constants\AccountsConstant;
  5. use ApplicationBundle\Constants\GeneralConstant;
  6. use ApplicationBundle\Constants\HumanResourceConstant;
  7. use ApplicationBundle\Constants\InventoryConstant;
  8. use ApplicationBundle\Modules\Sales\Constants\SalesConstant;
  9. use ApplicationBundle\Controller\GenericController;
  10. use ApplicationBundle\Controller\PHPExcel_Cell;
  11. use ApplicationBundle\Entity\AccCheck;
  12. use ApplicationBundle\Entity\AccCostCentre;
  13. use ApplicationBundle\Entity\AccSettings;
  14. use ApplicationBundle\Entity\BankAccounts;
  15. use ApplicationBundle\Entity\BankList;
  16. use ApplicationBundle\Entity\Brs;
  17. use ApplicationBundle\Entity\CheckFormat;
  18. use ApplicationBundle\Entity\ExpenseInvoice;
  19. use ApplicationBundle\Entity\FiscalClosing;
  20. use ApplicationBundle\Entity\FundRequisition;
  21. use ApplicationBundle\Entity\ReceiptCheck;
  22. use ApplicationBundle\Entity\TaxConfig;
  23. use ApplicationBundle\Helper\CountryTemplateResolver;
  24. use ApplicationBundle\Helper\TaxMarkerLookup;
  25. use ApplicationBundle\Helper\Generic;
  26. use ApplicationBundle\Interfaces\SessionCheckInterface;
  27. use ApplicationBundle\Modules\Accounts\Accounts;
  28. use ApplicationBundle\Modules\Accounts\Service\AccountHeadPermissionService;
  29. use ApplicationBundle\Modules\Accounts\Service\AccountHeadExternalMappingService;
  30. use ApplicationBundle\Modules\Authentication\Constants\UserConstants; use ApplicationBundle\Modules\Api\Constants\ApiConstants;
  31. use ApplicationBundle\Modules\FixedAsset\FixedAsset;
  32. use ApplicationBundle\Modules\Inventory\Inventory;
  33. use ApplicationBundle\Modules\Project\ProjectM;
  34. use ApplicationBundle\Modules\Document\DocumentRegistry;
  35. use ApplicationBundle\Modules\Purchase\Purchase;
  36. use ApplicationBundle\Modules\Sales\Client;
  37. use ApplicationBundle\Modules\Sales\SalesOrderM;
  38. use ApplicationBundle\Modules\System\ApprovalFunction;
  39. use ApplicationBundle\Modules\System\DeleteDocument;
  40. use ApplicationBundle\Modules\System\DocValidation;
  41. use ApplicationBundle\Modules\System\MiscActions;
  42. use ApplicationBundle\Modules\System\System;
  43. use ApplicationBundle\Modules\User\Company;
  44. use ApplicationBundle\Modules\User\Users;
  45. use CompanyGroupBundle\Entity\EntityFile;
  46. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  47. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  48. use Ps\PdfBundle\Annotation\Pdf;
  49. use Symfony\Component\HttpFoundation\JsonResponse;
  50. use Symfony\Component\HttpFoundation\RedirectResponse;
  51. use Symfony\Component\HttpFoundation\Request;
  52. use Symfony\Component\HttpFoundation\Response;
  53. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  54. use Symfony\Component\HttpFoundation\StreamedResponse;
  55. use Symfony\Component\Process\Process;
  56. use Symfony\Component\Routing\Generator\UrlGenerator;
  57. use Symfony\Component\Validator\Constraints\Json;
  58. //use Symfony\Bundle\FrameworkBundle\Console\Application;
  59. //use Symfony\Component\Console\Input\ArrayInput;
  60. //use Symfony\Component\Console\Output\NullOutput;
  61. class AccountsController extends GenericController implements SessionCheckInterface
  62. {
  63.     private function getAllocationReportFilters(Request $request)
  64.     {
  65.         return array(
  66.             'tag_type' => trim((string) $request->query->get('tag_type''')),
  67.             'tag_value' => trim((string) $request->query->get('tag_value''')),
  68.             'projectId' => (int) $request->query->get('projectId'0),
  69.             'branchId' => (int) $request->query->get('branchId'0),
  70.             'costCenterId' => (int) $request->query->get('costCenterId'0),
  71.         );
  72.     }
  73.     private function getAllocationReportSupportData($emRequest $request)
  74.     {
  75.         $companyId $this->getLoggedUserCompanyId($request);
  76.         $filters $this->getAllocationReportFilters($request);
  77.         $summaryRows $em->getRepository('ApplicationBundle\\Entity\\TransactionDetailAllocation')
  78.             ->getAllocationSummary();
  79.         $tagTypes = [];
  80.         $tagValuesByType = [];
  81.         foreach ($summaryRows as $row) {
  82.             $type strtolower(trim((string) ($row['tag_type'] ?? '')));
  83.             $value trim((string) ($row['tag_value'] ?? ''));
  84.             if ($type === '' || $value === '') {
  85.                 continue;
  86.             }
  87.             if (!isset($tagTypes[$type])) {
  88.                 $tagTypes[$type] = array(
  89.                     'id' => $type,
  90.                     'text' => ucwords(str_replace(array('_''-'), ' '$type)),
  91.                 );
  92.             }
  93.             if (!isset($tagValuesByType[$type])) {
  94.                 $tagValuesByType[$type] = array();
  95.             }
  96.             $tagValuesByType[$type][$value] = array(
  97.                 'id' => $value,
  98.                 'text' => $value,
  99.             );
  100.         }
  101.         foreach ($tagValuesByType as $type => $values) {
  102.             $tagValuesByType[$type] = array_values($values);
  103.         }
  104.         return array(
  105.             'allocation_filters' => $filters,
  106.             'allocation_tag_types' => array_values($tagTypes),
  107.             'allocation_tag_values_by_type' => $tagValuesByType,
  108.             'project_list' => ProjectM::GetProjectList($em),
  109.             'branch_list' => Client::BranchList($em$companyId),
  110.             'cost_centers' => Accounts::CostCenterList($em),
  111.         );
  112.     }
  113.     public function exportDatabase(Request $request)
  114.     {
  115.         $session $request->getSession();
  116.         $gocDbName $session->get(UserConstants::USER_DB_NAME);
  117.         $gocDbUser $session->get(UserConstants::USER_DB_USER);
  118.         $gocDbPass $session->get(UserConstants::USER_DB_PASS);
  119.         $gocDbHost $session->get(UserConstants::USER_DB_HOST);
  120.         ////                        $connector = $this->container->get('application_connector');
  121.         //        $connector = $this->applicationConnector;
  122.         //        $connector->resetConnection(
  123.         //            'default',
  124.         //            $gocDbName,
  125.         //            $gocDbUser,
  126.         //            $gocDbPass,
  127.         //            $gocDbHost,
  128.         //            $reset = false);
  129.         $process = new Process([
  130.             'mysqldump',
  131.             '-u',
  132.             $gocDbUser// Replace with your DB username
  133.             '-p' $gocDbPass// Replace with your DB password
  134.             $gocDbName // Replace with your database name
  135.         ]);
  136.         $process->setTimeout(3600); // Increase timeout if needed
  137.         $process->run();
  138.         if (!$process->isSuccessful()) {
  139.             return new Response('Database export failed: ' $process->getErrorOutput(), Response::HTTP_INTERNAL_SERVER_ERROR);
  140.         }
  141.         // Get output of the process (SQL dump)
  142.         $sqlDump $process->getOutput();
  143.         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/dbase_backup';
  144.         if (!file_exists($upl_dir)) {
  145.             mkdir($upl_dir0777true);
  146.         }
  147.         // Save to a file
  148.         $filePath $upl_dir 'database_dump.sql'// Update this path
  149.         file_put_contents($filePath$sqlDump);
  150.         return new Response('Database exported successfully to ' $filePath);
  151.     }
  152.     public function importDatabase(Request $request)
  153.     {
  154.         $uploadedFile $request->files->get('file');
  155.         if ($uploadedFile && $uploadedFile->isValid()) {
  156.             // Save uploaded file to a temporary location
  157.             $filePath '/path/to/temp/import_file.sql'// Update this path
  158.             $uploadedFile->move(dirname($filePath), basename($filePath));
  159.             $process = new Process([
  160.                 'mysql',
  161.                 '-u',
  162.                 'your_db_user'// Replace with your DB username
  163.                 '-p' 'your_db_password'// Replace with your DB password
  164.                 'your_db_name'// Replace with your database name
  165.                 '<',
  166.                 $filePath
  167.             ]);
  168.             $process->run();
  169.             if (!$process->isSuccessful()) {
  170.                 return new Response('Database import failed: ' $process->getErrorOutput(), Response::HTTP_INTERNAL_SERVER_ERROR);
  171.             }
  172.             return new Response('Database imported successfully!');
  173.         }
  174.         return new Response('Invalid file or file not uploaded'Response::HTTP_BAD_REQUEST);
  175.     }
  176.     public function prePopulateDatabaseAction(Request $request)
  177.     {
  178.         $em $this->getDoctrine()->getManager();
  179.         System::prePopulateDatabase($em);
  180.         return new JsonResponse(array(
  181.             'success' => true,
  182.         ));
  183.     }
  184.     public function selectDataAjaxAccHeadAction(Request $request$queryStr '',
  185.                                                  $version 'latest',
  186.                                                  $identifier '_default_',
  187.                                                  $apiKey '_ignore_'
  188.     )
  189.     {
  190.         $em $this->getDoctrine()->getManager();
  191.         $em_goc $this->getDoctrine()->getManager('company_group');
  192.         $companyId 0;
  193.         $skipCurrentUserIdRestriction $request->get('skipCurrentUserIdRestriction'0);
  194.         $dataOnly $request->get('dataOnly'0);
  195.         $skipCurrentEmployeeIdRestriction $request->get('skipCurrentEmployeeIdRestriction'0);
  196.         $skipCurrentUserLoginIdRestriction $request->get('skipCurrentUserLoginIdRestriction'0);
  197.         $currentUserId $request->getSession()->get(UserConstants::USER_ID0);
  198.         $currentEmployeeId $request->getSession()->get(UserConstants::USER_EMPLOYEE_ID0);
  199.         $currentUserLoginIds = [];
  200.         if ($request->request->get('entity_group'0)) {
  201.             $companyId 0;
  202.             $em $this->getDoctrine()->getManager('company_group');
  203.         } else {
  204.             if ($request->request->get('appId'0) != 0) {
  205.                 $gocEnabled 0;
  206.                 if ($this->container->hasParameter('entity_group_enabled'))
  207.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  208.                 else
  209.                     $gocEnabled 1;
  210.                 if ($gocEnabled == 1) {
  211.                     $dataToConnect System::changeDoctrineManagerByAppId(
  212.                         $this->getDoctrine()->getManager('company_group'),
  213.                         $gocEnabled,
  214.                         $request->request->get('appId'0)
  215.                     );
  216.                     if (!empty($dataToConnect)) {
  217.                         $connector $this->container->get('application_connector');
  218.                         $connector->resetConnection(
  219.                             'default',
  220.                             $dataToConnect['dbName'],
  221.                             $dataToConnect['dbUser'],
  222.                             $dataToConnect['dbPass'],
  223.                             $dataToConnect['dbHost'],
  224.                             $reset true
  225.                         );
  226.                         $em $this->getDoctrine()->getManager();
  227.                     }
  228.                 }
  229.             } else if ($request->getSession()->get(UserConstants::USER_APP_ID) != && $request->getSession()->get(UserConstants::USER_APP_ID) != null) {
  230.                 $gocEnabled 0;
  231.                 if ($this->container->hasParameter('entity_group_enabled'))
  232.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  233.                 else
  234.                     $gocEnabled 1;
  235.                 if ($gocEnabled == 1) {
  236.                     $dataToConnect System::changeDoctrineManagerByAppId(
  237.                         $this->getDoctrine()->getManager('company_group'),
  238.                         $gocEnabled,
  239.                         $request->getSession()->get(UserConstants::USER_APP_ID)
  240.                     );
  241.                     if (!empty($dataToConnect)) {
  242.                         $connector $this->container->get('application_connector');
  243.                         $connector->resetConnection(
  244.                             'default',
  245.                             $dataToConnect['dbName'],
  246.                             $dataToConnect['dbUser'],
  247.                             $dataToConnect['dbPass'],
  248.                             $dataToConnect['dbHost'],
  249.                             $reset true
  250.                         );
  251.                         $em $this->getDoctrine()->getManager();
  252.                     }
  253.                 }
  254.             }
  255.             $companyId $this->getLoggedUserCompanyId($request);
  256.         }
  257.         $configData = [];
  258.         $isSingleDataset 1;
  259.         $dataSet $request->request->has('dataset') ? $request->request->get('dataset') : [];
  260.         if (is_string($dataSet)) $dataSet json_decode($dataSettrue);
  261.         $valuePairs $request->get('valuePairs', []);
  262.         if (is_string($valuePairs)) $valuePairs json_decode($valuePairstrue);
  263.         $allResult = [];
  264.         $datasetFromConfig = [];
  265.         if ($identifier != '_default_') {
  266.             $config_file $this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' $identifier 'Config.json';
  267.             if (!file_exists($config_file)) {
  268.             } else {
  269.                 $fileText file_get_contents($config_file);
  270.                 //now replace any value pairs
  271.                 foreach ($valuePairs as $kkeeyy => $vvaalluuee) {
  272.                     if (is_array($vvaalluuee)) {
  273.                         if (isset($vvaalluuee['value']) && isset($vvaalluuee['type'])) {
  274.                             if ($vvaalluuee['type'] == 'array'$fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee['value']), $fileText);
  275.                             if ($vvaalluuee['type'] == 'value'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  276.                             if ($vvaalluuee['type'] == 'text'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  277.                         } else {
  278.                             $fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee), $fileText);
  279.                         }
  280.                     }
  281.                     $fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee$fileText);
  282.                 }
  283.                 $fileText str_ireplace('_query_'$request->get('query'$queryStr), $fileText);
  284.                 $fileText str_ireplace('_itemLimit_'$request->get('itemLimit''_all_'), $fileText);
  285.                 $fileText str_ireplace('_offset_'$request->get('offset', ($request->get('itemLimit'10))*($request->get('page'1)-1)), $fileText);
  286.                 if (!(strpos($fileText'_CURRENT_USER_LOGIN_IDS_') === false) && $skipCurrentUserLoginIdRestriction == 0) {
  287.                     $userInfo = [];
  288.                     if ($request->getSession()->get(UserConstants::USER_TYPE0) == UserConstants::USER_TYPE_APPLICANT) {
  289.                         $userInfo $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityLoginLog')->findBy(
  290.                             array('userId' => $currentUserId)
  291.                         );
  292.                     } else {
  293.                         $userInfo $em->getRepository('ApplicationBundle\\Entity\\SysLoginLog')->findBy(
  294.                             array('userId' => $currentUserId)
  295.                         );
  296.                     }
  297.                     foreach ($userInfo as $uLogininfo) {
  298.                         $currentUserLoginIds[] = $uLogininfo->getLoginId();
  299.                     }
  300.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_'json_encode($currentUserLoginIds), $fileText);
  301.                 } else {
  302.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_''_EMPTY_'$fileText);
  303.                 }
  304.                 if (!(strpos($fileText'_CURRENT_USER_ID_') === false) && $skipCurrentUserIdRestriction == 0) {
  305.                     $fileText str_ireplace('_CURRENT_USER_ID_'$currentUserId$fileText);
  306.                 } else {
  307.                     $fileText str_ireplace('_CURRENT_USER_ID_''_EMPTY_'$fileText);
  308.                 }
  309.                 if (!(strpos($fileText'_CURRENT_USER_EMPLOYEE_ID_') === false) && $skipCurrentEmployeeIdRestriction == 0) {
  310.                     if ((strpos($fileText'skipCurrentEmployeeIdRestriction') === false)) {
  311.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_'$currentEmployeeId$fileText);
  312.                     } else {
  313.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  314.                     }
  315.                 } else {
  316.                     $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  317.                 }
  318.                 if ($fileText)
  319.                     $datasetFromConfig json_decode($fileTexttrue);
  320.                 $skipCurrentUserIdRestriction = isset($datasetFromConfig['skipCurrentUserIdRestriction']) ? $datasetFromConfig['skipCurrentUserIdRestriction'] : $skipCurrentUserIdRestriction;
  321.                 $skipCurrentEmployeeIdRestriction = isset($datasetFromConfig['skipCurrentEmployeeIdRestriction']) ? $datasetFromConfig['skipCurrentEmployeeIdRestriction'] : $skipCurrentEmployeeIdRestriction;
  322.                 $skipCurrentUserLoginIdRestriction = isset($datasetFromConfig['skipCurrentUserLoginIdRestriction']) ? $datasetFromConfig['skipCurrentUserLoginIdRestriction'] : $skipCurrentUserLoginIdRestriction;
  323.             }
  324.         }
  325.         if ($dataSet == null$dataSet = [];
  326. //        return new JsonResponse(array(
  327. //            'queryStr'=>$queryStr
  328. //        ));
  329.         if (!empty($datasetFromConfig)) {
  330.             if (isset($datasetFromConfig['tableName'])) {
  331.                 $isSingleDataset 1;
  332.                 $dataSet[] = $datasetFromConfig;
  333.             } else {
  334.                 if (count($datasetFromConfig) == 1)
  335.                     $isSingleDataset 1;
  336.                 $dataSet $datasetFromConfig;
  337.             }
  338.         }
  339.         if (empty($dataSet)) {
  340.             $isSingleDataset 1;
  341.             $singleDataSet = array(
  342.                 "valueField" => $request->request->has('valueField') ? $request->request->get('valueField') : 'id',
  343.                 "query" => $request->get('query'$queryStr),
  344.                 "headMarkers" => $request->get('headMarkers'''),
  345.                 "headMarkersStrictMatch" => $request->get('headMarkersStrictMatch'0),
  346.                 "itemLimit" => $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25,
  347.                 "selectorId" => $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_',
  348.                 "textField" => $request->request->has('textField') ? $request->request->get('textField') : 'name',
  349.                 "tableName" => $request->request->has('tableName') ? $request->request->get('tableName') : '',
  350.                 "isMultiple" => $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0,
  351.                 "orConditions" => $request->request->has('orConditions') ? $request->request->get('orConditions') : [],
  352.                 "andConditions" => $request->request->has('andConditions') ? $request->request->get('andConditions') : [],
  353.                 "andOrConditions" => $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [],
  354.                 "mustConditions" => $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [],
  355.                 "joinTableData" => $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [],
  356.                 "renderTextFormat" => $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '',
  357.                 "setDataForSingle" => $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0,
  358.                 "dataId" => $request->request->has('dataId') ? $request->request->get('dataId') : 0,
  359.                 "lastChildrenOnly" => $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0,
  360.                 "parentOnly" => $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0,
  361.                 "parentIdField" => $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id',
  362.                 "skipDefaultCompanyId" => $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1,
  363.                 "offset" => $request->request->has('offset') ? $request->request->get('offset') : 0,
  364.                 "returnTotalMatchedEntriesFlag" => $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0,
  365.                 "nextOffset" => 0,
  366.                 "totalMatchedEntries" => 0,
  367.                 "convertToObject" => $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [],
  368.                 "convertDateToStringFieldList" => $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [],
  369.                 "orderByConditions" => $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [],
  370.                 "convertToUrl" => $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [],
  371.                 "fullPathList" => $request->request->has('fullPathList') ? $request->request->get('fullPathList') : [],
  372.                 "ret_data" => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  373.             );
  374.             $dataSet[] = $singleDataSet;
  375.         }
  376. //        $lastResult = [
  377. //            'identifier' => $identifier,
  378. //            'dataSet' => $dataSet,
  379. //        ];
  380. //        return new JsonResponse($lastResult);
  381.         $userId $request->getSession()->get(UserConstants::USER_ID);
  382. //        public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [],$userId=0)
  383.         foreach ($dataSet as $dsIndex => $dataConfig) {
  384.             $companyId 0;
  385.             $queryStringIndividual $queryStr;
  386.             $data = [];
  387.             $data_by_id = [];
  388.             $setValueArray = [];
  389.             $silentChangeSelectize 0;
  390.             $setValue 0;
  391.             $setValueType 0;// 0 for id , 1 for query
  392.             $selectAll 0;
  393.             if ($queryStringIndividual == '_EMPTY_')
  394.                 $queryStringIndividual '';
  395.             if (isset($dataConfig['query']))
  396.                 $queryStringIndividual $dataConfig['query'];
  397.             if ($queryStringIndividual == '_EMPTY_')
  398.                 $queryStringIndividual '';
  399.             $queryStringIndividual str_replace('_FSLASH_''/'$queryStringIndividual);
  400.             if ($queryStringIndividual === '#setValue:') {
  401.                 $queryStringIndividual '';
  402.             }
  403.             if (!(strpos($queryStringIndividual'_silent_change_') === false)) {
  404.                 $silentChangeSelectize 1;
  405.                 $queryStringIndividual str_ireplace('_silent_change_'''$queryStringIndividual);
  406.             }
  407.             if (!(strpos($queryStringIndividual'#setValue:') === false)) {
  408.                 $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStringIndividual));
  409.                 foreach ($setValueArrayBeforeFilter as $svf) {
  410.                     if ($svf == '_ALL_') {
  411.                         $selectAll 1;
  412.                         $setValueArray = [];
  413.                         continue;
  414.                     }
  415.                     if (is_numeric($svf)) {
  416.                         $setValueArray[] = ($svf 1);
  417.                         $setValue $svf 1;
  418.                     }
  419.                 }
  420.                 $queryStringIndividual '';
  421.             }
  422.             $valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
  423.             $headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''//Special Field
  424.             $headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0//Special Field
  425.             $itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
  426.             $selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
  427.             $textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
  428.             $table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
  429.             $isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
  430.             $orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
  431.             $andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
  432.             $andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
  433.             $mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
  434.             $joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
  435.             $renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
  436.             $setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
  437.             $dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
  438.             $lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
  439.             $parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
  440.             $parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
  441.             $skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
  442.             $offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
  443.             $returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
  444.             $nextOffset 0;
  445.             $totalMatchedEntries 0;
  446.             $convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
  447.             $convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
  448.             $orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
  449.             $convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
  450.             $fullPathList = isset($dataConfig['fullPathList']) ? $dataConfig['fullPathList'] : [];
  451.             if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  452.             if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  453.             if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  454.             if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  455.             if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  456.             if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  457.             if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  458.             if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  459.             if (is_string($fullPathList)) $fullPathList json_decode($fullPathListtrue);
  460. //            return new JsonResponse(array(
  461. //                'dataSet'=>$dataSet,
  462. //                'dataConfig'=>$dataConfig,
  463. //                'hi'=>$this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json',
  464. //                'hiD'=>file_get_contents($this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json')
  465. //            ));
  466.             if ($table == '') {
  467.                 $lastResult = array(
  468.                     'success' => false,
  469.                     'currentTs' => (new \Datetime())->format('U'),
  470.                     'isMultiple' => $isMultiple,
  471.                     'setValueArray' => $setValueArray,
  472.                     'setValue' => $setValue,
  473.                     'data' => $data,
  474.                     'dataId' => $dataId,
  475.                     'selectorId' => $selectorId,
  476.                     'dataById' => $data_by_id,
  477.                     'selectedId' => 0,
  478.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  479.                 );
  480.             } else {
  481.                 $restrictionData = array(
  482. //            'table'=>'relevantField in restriction'
  483.                     'warehouse_action' => 'warehouseActionIds',
  484.                     'branch' => 'branchIds',
  485.                     'warehouse' => 'warehouseIds',
  486.                     'production_process_settings' => 'productionProcessIds',
  487.                 );
  488.                 $restrictionIdList = [];
  489.                 $filterQryForCriteria "select ";
  490.                 $selectQry "";
  491. //        $selectQry=" `$table`.* ";
  492.                 $selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
  493.                 $selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
  494.                 if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  495.                 foreach ($selectFieldList as $selField) {
  496.                     if ($selectQry != '')
  497.                         $selectQry .= ", ";
  498.                     if ($selField == '*')
  499.                         $selectQry .= " `$table`.$selField ";
  500.                     else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  501.                         if ($selectPrefix == '')
  502.                             $selectQry .= " count(*)  ";
  503.                         else
  504.                             $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  505.                     } else {
  506.                         if ($selectPrefix == '')
  507.                             $selectQry .= " `$table`.`$selField` ";
  508.                         else
  509.                             $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  510.                     }
  511.                 }
  512.                 $joinQry " from $table ";
  513. //        $filterQryForCriteria = "select * from $table ";
  514.                 $joinMustString '';
  515.                 $joinOrString '';
  516.                 $joinAndString '';
  517.                 $joinAndOrString '';
  518.                 foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  519. //            $conditionStr.=' 1=1 ';
  520.                     $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  521.                     $joinTableAlias $joinTableName '_' $joinIndex;
  522.                     $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  523.                     $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  524.                     $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  525.                     $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  526.                     $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  527.                     $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  528.                     $joinMustConditions = isset($joinTableDatum['joinMustConditions']) ? $joinTableDatum['joinMustConditions'] : [];
  529.                     $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  530.                     $joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
  531.                     $joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
  532.                     if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  533.                     if (is_string($joinMustConditions)) $joinMustConditions json_decode($joinMustConditionstrue);
  534.                     if (is_string($joinAndOrConditions)) $joinAndOrConditions json_decode($joinAndOrConditionstrue);
  535.                     if (is_string($joinOrConditions)) $joinOrConditions json_decode($joinOrConditionstrue);
  536.                     foreach ($selectFieldList as $selField) {
  537.                         if ($selField == '*')
  538.                             $selectQry .= ", `$joinTableAlias`.$selField ";
  539.                         else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  540.                             if ($selectPrefix == '')
  541.                                 $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  542.                             else
  543.                                 $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  544.                         } else {
  545.                             if ($selectPrefix == '')
  546.                                 $selectQry .= ", `$joinTableAlias`.`$selField`  ";
  547.                             else
  548.                                 $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  549.                         }
  550.                     }
  551.                     $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  552. //            if($joinTablePrimaryField!='')
  553. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  554. //            $joinAndString = '';
  555.                     $joinMustString '';
  556.                     if ($joinTablePrimaryField != '')
  557.                         $joinQry .= "  `$joinTableAlias`.`$joinTableOnField$fieldJoinType `$table`.`$joinTablePrimaryField` ";
  558.                     foreach ($joinMustConditions as $mustCondition) {
  559. //            $conditionStr.=' 1=1 ';
  560.                         $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  561.                         $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  562.                         $aliasInCondition $table;
  563.                         if (!(strpos($cfield'.') === false)) {
  564.                             $fullCfieldArray explode('.'$cfield);
  565.                             $aliasInCondition $fullCfieldArray[0];
  566.                             $cfield $fullCfieldArray[1];
  567.                         }
  568.                         $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  569.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  570.                             if ($joinMustString != '')
  571.                                 $joinMustString .= " and ";
  572.                             if ($ctype == 'like') {
  573.                                 $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  574.                                 $wordsBySpaces explode(' '$cvalue);
  575.                                 foreach ($wordsBySpaces as $word) {
  576.                                     if ($joinMustString != '')
  577.                                         $joinMustString .= " and ";
  578.                                     $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  579.                                 }
  580.                             } else if ($ctype == 'not like') {
  581.                                 $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  582.                                 $wordsBySpaces explode(' '$cvalue);
  583.                                 foreach ($wordsBySpaces as $word) {
  584.                                     if ($joinMustString != '')
  585.                                         $joinMustString .= " and ";
  586.                                     $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  587.                                 }
  588.                             } else if ($ctype == 'not_in') {
  589.                                 $joinMustString .= " ( ";
  590.                                 if (in_array('null'$cvalue)) {
  591.                                     $joinMustString .= " `$joinTableAlias`.$cfield is not null";
  592.                                     $cvalue array_diff($cvalue, ['null']);
  593.                                     if (!empty($cvalue))
  594.                                         $joinMustString .= " and ";
  595.                                 }
  596.                                 if (in_array(''$cvalue)) {
  597.                                     $joinMustString .= "`$joinTableAlias`.$cfield != '' ";
  598.                                     $cvalue array_diff($cvalue, ['']);
  599.                                     if (!empty($cvalue))
  600.                                         $joinMustString .= " and ";
  601.                                 }
  602.                                 $joinMustString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  603.                             } else if ($ctype == 'in') {
  604.                                 if (in_array('null'$cvalue)) {
  605.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null";
  606.                                     $cvalue array_diff($cvalue, ['null']);
  607.                                     if (!empty($cvalue))
  608.                                         $joinMustString .= " and ";
  609.                                 }
  610.                                 if (in_array(''$cvalue)) {
  611.                                     $joinMustString .= "`$joinTableAlias`.$cfield = '' ";
  612.                                     $cvalue array_diff($cvalue, ['']);
  613.                                     if (!empty($cvalue))
  614.                                         $joinMustString .= " and ";
  615.                                 }
  616.                                 $joinMustString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  617.                             } else if ($ctype == '=') {
  618. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  619. //                            $fullCfieldArray = explode('.', $cfield);
  620. //                            $aliasInCondition = $fullCfieldArray[0];
  621. //                            $cfield = $fullCfieldArray[1];
  622. //                        }
  623.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  624.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null ";
  625.                                 else
  626.                                     $joinMustString .= "`$joinTableAlias`.$cfield = $cvalue ";
  627.                             } else if ($ctype == '!=') {
  628.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  629.                                     $joinMustString .= "`$joinTableAlias`.$cfield is not null ";
  630.                                 else
  631.                                     $joinMustString .= "`$joinTableAlias`.$cfield != $cvalue ";
  632.                             } else {
  633.                                 if (is_string($cvalue))
  634.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  635.                                 else
  636.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  637.                             }
  638.                         }
  639.                     }
  640. //            if ($joinMustString != '') {
  641. //                if ($conditionStr != '')
  642. //                    $conditionStr .= (" and (" . $joinMustString . ") ");
  643. //                else
  644. //                    $conditionStr .= ("  (" . $joinMustString . ") ");
  645. //            }
  646. //                    if ($joinMustString != '') {
  647. //                        $joinQry .= (' and ' . $joinMustString);
  648. ////                        $joinQry.=' and (';
  649. //                    }
  650.                     $mustBracketDone 0;
  651. //                    if ($joinTablePrimaryField != '')
  652. //                        $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  653.                     foreach ($joinAndConditions as $andCondition) {
  654. //            $conditionStr.=' 1=1 ';
  655.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  656.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  657.                         $aliasInCondition $table;
  658.                         if (!(strpos($cfield'.') === false)) {
  659.                             $fullCfieldArray explode('.'$cfield);
  660.                             $aliasInCondition $fullCfieldArray[0];
  661.                             $cfield $fullCfieldArray[1];
  662.                         }
  663.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  664.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  665.                             if ($joinAndString != '')
  666.                                 $joinAndString .= " and ";
  667.                             if ($ctype == 'like') {
  668.                                 $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  669.                                 $wordsBySpaces explode(' '$cvalue);
  670.                                 foreach ($wordsBySpaces as $word) {
  671.                                     if ($joinAndString != '')
  672.                                         $joinAndString .= " and ";
  673.                                     $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  674.                                 }
  675.                             } else if ($ctype == 'not like') {
  676.                                 $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  677.                                 $wordsBySpaces explode(' '$cvalue);
  678.                                 foreach ($wordsBySpaces as $word) {
  679.                                     if ($joinAndString != '')
  680.                                         $joinAndString .= " and ";
  681.                                     $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  682.                                 }
  683.                             } else if ($ctype == 'not_in') {
  684.                                 $joinAndString .= " ( ";
  685.                                 if (in_array('null'$cvalue)) {
  686.                                     $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  687.                                     $cvalue array_diff($cvalue, ['null']);
  688.                                     if (!empty($cvalue))
  689.                                         $joinAndString .= " and ";
  690.                                 }
  691.                                 if (in_array(''$cvalue)) {
  692.                                     $joinAndString .= "`$joinTableAlias`.$cfield != '' ";
  693.                                     $cvalue array_diff($cvalue, ['']);
  694.                                     if (!empty($cvalue))
  695.                                         $joinAndString .= " and ";
  696.                                 }
  697.                                 $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  698.                             } else if ($ctype == 'in') {
  699.                                 if (in_array('null'$cvalue)) {
  700.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null";
  701.                                     $cvalue array_diff($cvalue, ['null']);
  702.                                     if (!empty($cvalue))
  703.                                         $joinAndString .= " and ";
  704.                                 }
  705.                                 if (in_array(''$cvalue)) {
  706.                                     $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  707.                                     $cvalue array_diff($cvalue, ['']);
  708.                                     if (!empty($cvalue))
  709.                                         $joinAndString .= " and ";
  710.                                 }
  711.                                 $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  712.                             } else if ($ctype == '=') {
  713. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  714. //                            $fullCfieldArray = explode('.', $cfield);
  715. //                            $aliasInCondition = $fullCfieldArray[0];
  716. //                            $cfield = $fullCfieldArray[1];
  717. //                        }
  718.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  719.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  720.                                 else
  721.                                     $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  722.                             } else if ($ctype == '!=') {
  723.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  724.                                     $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  725.                                 else
  726.                                     $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  727.                             } else {
  728.                                 if (is_string($cvalue))
  729.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  730.                                 else
  731.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  732.                             }
  733.                         }
  734.                     }
  735. //            if ($joinAndString != '') {
  736. //                if ($conditionStr != '')
  737. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  738. //                else
  739. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  740. //            }
  741. //                    if ($joinAndString != '') {
  742. //                        if ($joinMustString != '' && $mustBracketDone == 0) {
  743. //                            $joinQry .= ' and (';
  744. //                            $mustBracketDone = 1;
  745. //                        }
  746. //
  747. //
  748. //                        if ($joinQry != '')
  749. //                            $joinQry .= (" and (" . $joinAndString . ") ");
  750. //                        else
  751. //                            $joinQry .= ("  (" . $joinAndString . ") ");
  752. //
  753. //                    }
  754.                     foreach ($joinAndOrConditions as $andOrCondition) {
  755. //            $conditionStr.=' 1=1 ';
  756.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  757.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  758.                         $aliasInCondition $table;
  759.                         if (!(strpos($cfield'.') === false)) {
  760.                             $fullCfieldArray explode('.'$cfield);
  761.                             $aliasInCondition $fullCfieldArray[0];
  762.                             $cfield $fullCfieldArray[1];
  763.                         }
  764.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  765.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  766.                             if ($joinAndOrString != '')
  767.                                 $joinAndOrString .= " or ";
  768.                             if ($ctype == 'like') {
  769.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  770.                                 $wordsBySpaces explode(' '$cvalue);
  771.                                 foreach ($wordsBySpaces as $word) {
  772.                                     if ($joinAndOrString != '')
  773.                                         $joinAndOrString .= " or ";
  774.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  775.                                 }
  776.                             } else if ($ctype == 'not like') {
  777.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  778.                                 $wordsBySpaces explode(' '$cvalue);
  779.                                 foreach ($wordsBySpaces as $word) {
  780.                                     if ($joinAndOrString != '')
  781.                                         $joinAndOrString .= " or ";
  782.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  783.                                 }
  784.                             } else if ($ctype == 'not_in') {
  785.                                 $joinAndOrString .= " ( ";
  786.                                 if (in_array('null'$cvalue)) {
  787.                                     $joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
  788.                                     $cvalue array_diff($cvalue, ['null']);
  789.                                     if (!empty($cvalue))
  790.                                         $joinAndOrString .= " or ";
  791.                                 }
  792.                                 if (in_array(''$cvalue)) {
  793.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != '' ";
  794.                                     $cvalue array_diff($cvalue, ['']);
  795.                                     if (!empty($cvalue))
  796.                                         $joinAndOrString .= " or ";
  797.                                 }
  798.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  799.                             } else if ($ctype == 'in') {
  800.                                 if (in_array('null'$cvalue)) {
  801.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null";
  802.                                     $cvalue array_diff($cvalue, ['null']);
  803.                                     if (!empty($cvalue))
  804.                                         $joinAndOrString .= " or ";
  805.                                 }
  806.                                 if (in_array(''$cvalue)) {
  807.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  808.                                     $cvalue array_diff($cvalue, ['']);
  809.                                     if (!empty($cvalue))
  810.                                         $joinAndOrString .= " or ";
  811.                                 }
  812.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  813.                             } else if ($ctype == '=') {
  814. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  815. //                            $fullCfieldArray = explode('.', $cfield);
  816. //                            $aliasInCondition = $fullCfieldArray[0];
  817. //                            $cfield = $fullCfieldArray[1];
  818. //                        }
  819.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  820.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
  821.                                 else
  822.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  823.                             } else if ($ctype == '!=') {
  824.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  825.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
  826.                                 else
  827.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  828.                             } else {
  829.                                 if (is_string($cvalue))
  830.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  831.                                 else
  832.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  833.                             }
  834.                         }
  835.                     }
  836. //            if ($joinAndOrString != '')
  837. //                $joinQry .= $joinAndOrString;
  838. //                    if ($joinAndOrString != '') {
  839. //                        if ($joinMustString != '' && $mustBracketDone == 0) {
  840. //                            $joinQry .= ' and (';
  841. //                            $mustBracketDone = 1;
  842. //                        }
  843. //
  844. //
  845. //                        if ($joinQry != '')
  846. //                            $joinQry .= (" and (" . $joinAndOrString . ") ");
  847. //                        else
  848. //                            $joinQry .= ("  (" . $joinAndOrString . ") ");
  849. //                    }
  850.                     //pika
  851. //                    $joinOrString = "";
  852.                     foreach ($joinOrConditions as $orCondition) {
  853. //            $conditionStr.=' 1=1 ';
  854.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  855.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  856.                         $aliasInCondition $table;
  857.                         if (!(strpos($cfield'.') === false)) {
  858.                             $fullCfieldArray explode('.'$cfield);
  859.                             $aliasInCondition $fullCfieldArray[0];
  860.                             $cfield $fullCfieldArray[1];
  861.                         }
  862.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  863.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  864.                             if ($joinOrString != '' || $joinAndString != '' || $joinMustString != '')
  865.                                 $joinOrString .= " or ";
  866.                             if ($ctype == 'like') {
  867.                                 $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  868.                                 $wordsBySpaces explode(' '$cvalue);
  869.                                 foreach ($wordsBySpaces as $word) {
  870.                                     if ($joinOrString != '')
  871.                                         $joinOrString .= " or ";
  872.                                     $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  873.                                 }
  874.                             } else if ($ctype == 'not like') {
  875.                                 $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  876.                                 $wordsBySpaces explode(' '$cvalue);
  877.                                 foreach ($wordsBySpaces as $word) {
  878.                                     if ($joinOrString != '')
  879.                                         $joinOrString .= " or ";
  880.                                     $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  881.                                 }
  882.                             } else if ($ctype == 'not_in') {
  883.                                 $joinOrString .= " ( ";
  884.                                 if (in_array('null'$cvalue)) {
  885.                                     $joinOrString .= " `$joinTableAlias`.$cfield is not null";
  886.                                     $cvalue array_diff($cvalue, ['null']);
  887.                                     if (!empty($cvalue))
  888.                                         $joinOrString .= " or ";
  889.                                 }
  890.                                 if (in_array(''$cvalue)) {
  891.                                     $joinOrString .= "`$joinTableAlias`.$cfield != '' ";
  892.                                     $cvalue array_diff($cvalue, ['']);
  893.                                     if (!empty($cvalue))
  894.                                         $joinOrString .= " or ";
  895.                                 }
  896.                                 $joinOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  897.                             } else if ($ctype == 'in') {
  898.                                 if (in_array('null'$cvalue)) {
  899.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null";
  900.                                     $cvalue array_diff($cvalue, ['null']);
  901.                                     if (!empty($cvalue))
  902.                                         $joinOrString .= " or ";
  903.                                 }
  904.                                 if (in_array(''$cvalue)) {
  905.                                     $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  906.                                     $cvalue array_diff($cvalue, ['']);
  907.                                     if (!empty($cvalue))
  908.                                         $joinOrString .= " or ";
  909.                                 }
  910.                                 $joinOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  911.                             } else if ($ctype == '=') {
  912. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  913. //                            $fullCfieldArray = explode('.', $cfield);
  914. //                            $aliasInCondition = $fullCfieldArray[0];
  915. //                            $cfield = $fullCfieldArray[1];
  916. //                        }
  917.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  918.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null ";
  919.                                 else
  920.                                     $joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  921.                             } else if ($ctype == '!=') {
  922.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  923.                                     $joinOrString .= "`$joinTableAlias`.$cfield is not null ";
  924.                                 else
  925.                                     $joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  926.                             } else {
  927.                                 if (is_string($cvalue))
  928.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  929.                                 else
  930.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  931.                             }
  932.                         }
  933.                     }
  934. //            if ($joinOrString != '')
  935. //                $joinQry .= $joinOrString;
  936. //                    if ($joinOrString != '') {
  937. //                        if ($joinMustString != '' && $mustBracketDone == 0) {
  938. //                            $joinQry .= ' and (';
  939. //                            $mustBracketDone = 1;
  940. //                        }
  941. //                        if ($joinQry != '')
  942. //                            $joinQry .= (" or (" . $joinOrString . ") ");
  943. //                        else
  944. //                            $joinQry .= ("  (" . $joinOrString . ") ");
  945. //                    }
  946. //
  947. //                    if ($joinMustString != '' && $mustBracketDone == 1) {
  948. //                        $joinQry .= ' ) ';
  949. //
  950. //                    }
  951. //
  952. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  953.                 }
  954.                 $filterQryForCriteria .= $selectQry;
  955.                 $filterQryForCriteria .= $joinQry;
  956.                 if ($skipDefaultCompanyId == && $companyId != && !isset($dataConfig['entity_group']))
  957.                     $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  958.                 else
  959.                     $filterQryForCriteria .= " where 1=1 ";
  960.                 $conditionStr "";
  961.                 $aliasInCondition $table;
  962.                 if ($headMarkers != '' && $table == 'acc_accounts_head') {
  963.                     $markerList explode(','$headMarkers);
  964.                     $spMarkerQry "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
  965.                     $markerPassedHeads = [];
  966.                     foreach ($markerList as $mrkr) {
  967.                         $spMarkerQry .= " and marker_hash like '%" $mrkr "%'";
  968.                     }
  969.                     $spStmt $em->getConnection()->fetchAllAssociative($spMarkerQry);
  970.                     
  971.                     $spStmtResults $spStmt;
  972.                     foreach ($spStmtResults as $ggres) {
  973.                         $markerPassedHeads[] = $ggres['accounts_head_id'];
  974.                     }
  975.                     if (!empty($markerPassedHeads)) {
  976.                         if ($conditionStr != '')
  977.                             $conditionStr .= " and (";
  978.                         else
  979.                             $conditionStr .= " (";
  980.                         if ($headMarkersStrictMatch != 1) {
  981.                             foreach ($markerPassedHeads as $mh) {
  982.                                 $conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" $mh "/%' or ";
  983.                             }
  984.                         }
  985.                         $conditionStr .= "  `$aliasInCondition`.`accounts_head_id` in (" implode(','$markerPassedHeads) . ") ";
  986.                         $conditionStr .= " )";
  987.                     }
  988.                 }
  989.                 if (isset($restrictionData[$table])) {
  990.                     $userRestrictionData Users::getUserApplicationAccessSettings($em$userId)['options'];
  991.                     if (isset($userRestrictionData[$restrictionData[$table]])) {
  992.                         $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  993.                         if ($restrictionIdList == null)
  994.                             $restrictionIdList = [];
  995.                     }
  996.                     if (!empty($restrictionIdList)) {
  997.                         if ($conditionStr != '')
  998.                             $conditionStr .= " and ";
  999.                         $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  1000.                     }
  1001.                 }
  1002. //        $aliasInCondition = $table;
  1003.                 if (!empty($setValueArray) || $selectAll == 1) {
  1004.                     if (!empty($setValueArray)) {
  1005.                         if ($conditionStr != '')
  1006.                             $conditionStr .= " and ";
  1007.                         $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  1008.                     }
  1009.                 } else {
  1010. //                    $andString = '';
  1011.                     $andString $joinAndString;   /////New testing
  1012.                     foreach ($andConditions as $andCondition) {
  1013. //            $conditionStr.=' 1=1 ';
  1014.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  1015.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  1016.                         $aliasInCondition $table;
  1017.                         if (!(strpos($cfield'.') === false)) {
  1018.                             $fullCfieldArray explode('.'$cfield);
  1019.                             $aliasInCondition $fullCfieldArray[0];
  1020.                             $cfield $fullCfieldArray[1];
  1021.                         }
  1022.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  1023.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  1024.                             if ($andString != '')
  1025.                                 $andString .= " and ";
  1026.                             if ($ctype == 'like') {
  1027.                                 $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  1028.                                 $wordsBySpaces explode(' '$cvalue);
  1029.                                 foreach ($wordsBySpaces as $word) {
  1030.                                     if ($andString != '')
  1031.                                         $andString .= " and ";
  1032.                                     $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  1033.                                 }
  1034.                             } else if ($ctype == 'not like') {
  1035.                                 $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  1036.                                 $wordsBySpaces explode(' '$cvalue);
  1037.                                 foreach ($wordsBySpaces as $word) {
  1038.                                     if ($andString != '')
  1039.                                         $andString .= " and ";
  1040.                                     $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  1041.                                 }
  1042.                             } else if ($ctype == 'not_in') {
  1043.                                 $andString .= " ( ";
  1044.                                 if (in_array('null'$cvalue)) {
  1045.                                     $andString .= " `$aliasInCondition`.$cfield is not null";
  1046.                                     $cvalue array_diff($cvalue, ['null']);
  1047.                                     if (!empty($cvalue))
  1048.                                         $andString .= " and ";
  1049.                                 }
  1050.                                 if (in_array(''$cvalue)) {
  1051.                                     $andString .= "`$aliasInCondition`.$cfield != '' ";
  1052.                                     $cvalue array_diff($cvalue, ['']);
  1053.                                     if (!empty($cvalue))
  1054.                                         $andString .= " and ";
  1055.                                 }
  1056.                                 $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  1057.                             } else if ($ctype == 'in') {
  1058.                                 if (in_array('null'$cvalue)) {
  1059.                                     $andString .= "`$aliasInCondition`.$cfield is null";
  1060.                                     $cvalue array_diff($cvalue, ['null']);
  1061.                                     if (!empty($cvalue))
  1062.                                         $andString .= " and ";
  1063.                                 }
  1064.                                 if (in_array(''$cvalue)) {
  1065.                                     $andString .= "`$aliasInCondition`.$cfield = '' ";
  1066.                                     $cvalue array_diff($cvalue, ['']);
  1067.                                     if (!empty($cvalue))
  1068.                                         $andString .= " and ";
  1069.                                 }
  1070.                                 $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  1071.                             } else if ($ctype == '=') {
  1072.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  1073.                                     $andString .= "`$aliasInCondition`.$cfield is null ";
  1074.                                 else
  1075.                                     $andString .= "`$aliasInCondition`.$cfield = $cvalue ";
  1076.                             } else if ($ctype == '!=') {
  1077.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  1078.                                     $andString .= "`$aliasInCondition`.$cfield is not null ";
  1079.                                 else
  1080.                                     $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  1081.                             } else {
  1082.                                 if (is_string($cvalue))
  1083.                                     $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  1084.                                 else
  1085.                                     $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  1086.                             }
  1087.                         }
  1088.                     }
  1089.                     if ($andString != '') {
  1090.                         if ($conditionStr != '')
  1091.                             $conditionStr .= (" and (" $andString ") ");
  1092.                         else
  1093.                             $conditionStr .= ("  (" $andString ") ");
  1094.                     }
  1095. //                    $orString = '';
  1096.                     $orString $joinOrString;   /////New testing
  1097.                     foreach ($orConditions as $orCondition) {
  1098.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  1099.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  1100.                         $aliasInCondition $table;
  1101.                         if (!(strpos($cfield'.') === false)) {
  1102.                             $fullCfieldArray explode('.'$cfield);
  1103.                             $aliasInCondition $fullCfieldArray[0];
  1104.                             $cfield $fullCfieldArray[1];
  1105.                         }
  1106.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  1107.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  1108.                             if ($orString != '')
  1109.                                 $orString .= " or ";
  1110.                             if ($ctype == 'like') {
  1111.                                 $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  1112.                                 $wordsBySpaces explode(' '$cvalue);
  1113.                                 foreach ($wordsBySpaces as $word) {
  1114.                                     if ($orString != '')
  1115.                                         $orString .= " or ";
  1116.                                     $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  1117.                                 }
  1118.                             } else if ($ctype == 'not like') {
  1119.                                 $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  1120.                                 $wordsBySpaces explode(' '$cvalue);
  1121.                                 foreach ($wordsBySpaces as $word) {
  1122.                                     if ($orString != '')
  1123.                                         $orString .= " or ";
  1124.                                     $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  1125.                                 }
  1126.                             } else if ($ctype == 'not_in') {
  1127.                                 $orString .= " ( ";
  1128.                                 if (in_array('null'$cvalue)) {
  1129.                                     $orString .= " `$aliasInCondition`.$cfield is not null";
  1130.                                     $cvalue array_diff($cvalue, ['null']);
  1131.                                     if (!empty($cvalue))
  1132.                                         $orString .= " or ";
  1133.                                 }
  1134.                                 if (in_array(''$cvalue)) {
  1135.                                     $orString .= "`$aliasInCondition`.$cfield != '' ";
  1136.                                     $cvalue array_diff($cvalue, ['']);
  1137.                                     if (!empty($cvalue))
  1138.                                         $orString .= " or ";
  1139.                                 }
  1140.                                 $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  1141.                             } else if ($ctype == 'in') {
  1142.                                 $orString .= " ( ";
  1143.                                 if (in_array('null'$cvalue)) {
  1144.                                     $orString .= " `$aliasInCondition`.$cfield is null";
  1145.                                     $cvalue array_diff($cvalue, ['null']);
  1146.                                     if (!empty($cvalue))
  1147.                                         $orString .= " or ";
  1148.                                 }
  1149.                                 if (in_array(''$cvalue)) {
  1150.                                     $orString .= "`$aliasInCondition`.$cfield = '' ";
  1151.                                     $cvalue array_diff($cvalue, ['']);
  1152.                                     if (!empty($cvalue))
  1153.                                         $orString .= " or ";
  1154.                                 }
  1155.                                 $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  1156.                             } else if ($ctype == '=') {
  1157.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  1158.                                     $orString .= "`$aliasInCondition`.$cfield is null ";
  1159.                                 else
  1160.                                     $orString .= "`$aliasInCondition`.$cfield = $cvalue ";
  1161.                             } else if ($ctype == '!=') {
  1162.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  1163.                                     $orString .= "`$aliasInCondition`.$cfield is not null ";
  1164.                                 else
  1165.                                     $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  1166.                             } else {
  1167.                                 if (is_string($cvalue))
  1168.                                     $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  1169.                                 else
  1170.                                     $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  1171.                             }
  1172.                         }
  1173.                     }
  1174.                     if ($orString != '') {
  1175.                         if ($conditionStr != '')
  1176.                             $conditionStr .= (" or (" $orString ") ");
  1177.                         else
  1178.                             $conditionStr .= ("  (" $orString ") ");
  1179.                     }
  1180. //                    $andOrString = '';
  1181.                     $andOrString $joinAndOrString;   /////New testing
  1182.                     foreach ($andOrConditions as $andOrCondition) {
  1183.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  1184.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  1185.                         $aliasInCondition $table;
  1186.                         if (!(strpos($cfield'.') === false)) {
  1187.                             $fullCfieldArray explode('.'$cfield);
  1188.                             $aliasInCondition $fullCfieldArray[0];
  1189.                             $cfield $fullCfieldArray[1];
  1190.                         }
  1191.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  1192.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  1193.                             if ($andOrString != '')
  1194.                                 $andOrString .= " or ";
  1195.                             if ($ctype == 'like') {
  1196.                                 $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  1197.                                 $wordsBySpaces explode(' '$cvalue);
  1198.                                 foreach ($wordsBySpaces as $word) {
  1199.                                     if ($andOrString != '')
  1200.                                         $andOrString .= " or ";
  1201.                                     $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  1202.                                 }
  1203.                             } else if ($ctype == 'not like') {
  1204.                                 $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  1205.                                 $wordsBySpaces explode(' '$cvalue);
  1206.                                 foreach ($wordsBySpaces as $word) {
  1207.                                     if ($andOrString != '')
  1208.                                         $andOrString .= " or ";
  1209.                                     $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  1210.                                 }
  1211.                             } else if ($ctype == 'in') {
  1212.                                 $andOrString .= " ( ";
  1213.                                 if (in_array('null'$cvalue)) {
  1214.                                     $andOrString .= " `$aliasInCondition`.$cfield is null";
  1215.                                     $cvalue array_diff($cvalue, ['null']);
  1216.                                     if (!empty($cvalue))
  1217.                                         $andOrString .= " or ";
  1218.                                 }
  1219.                                 if (in_array(''$cvalue)) {
  1220.                                     $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  1221.                                     $cvalue array_diff($cvalue, ['']);
  1222.                                     if (!empty($cvalue))
  1223.                                         $andOrString .= " or ";
  1224.                                 }
  1225.                                 if (!empty($cvalue))
  1226.                                     $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  1227.                                 else
  1228.                                     $andOrString .= "  ) ";
  1229.                             } else if ($ctype == 'not_in') {
  1230.                                 $andOrString .= " ( ";
  1231.                                 if (in_array('null'$cvalue)) {
  1232.                                     $andOrString .= " `$aliasInCondition`.$cfield is not null";
  1233.                                     $cvalue array_diff($cvalue, ['null']);
  1234.                                     if (!empty($cvalue))
  1235.                                         $andOrString .= " or ";
  1236.                                 }
  1237.                                 if (in_array(''$cvalue)) {
  1238.                                     $andOrString .= "`$aliasInCondition`.$cfield != '' ";
  1239.                                     $cvalue array_diff($cvalue, ['']);
  1240.                                     if (!empty($cvalue))
  1241.                                         $andOrString .= " or ";
  1242.                                 }
  1243.                                 if (!empty($cvalue))
  1244.                                     $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  1245.                                 else
  1246.                                     $andOrString .= "  ) ";
  1247.                             } else if ($ctype == '=') {
  1248.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  1249.                                     $andOrString .= "`$aliasInCondition`.$cfield is null ";
  1250.                                 else
  1251.                                     $andOrString .= "`$aliasInCondition`.$cfield = $cvalue ";
  1252.                             } else if ($ctype == '!=') {
  1253.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  1254.                                     $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  1255.                                 else
  1256.                                     $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  1257.                             } else {
  1258.                                 if (is_string($cvalue))
  1259.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  1260.                                 else
  1261.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  1262.                             }
  1263.                         }
  1264.                     }
  1265.                     if ($andOrString != '') {
  1266.                         if ($conditionStr != '')
  1267.                             $conditionStr .= (" and (" $andOrString ") ");
  1268.                         else
  1269.                             $conditionStr .= ("  (" $andOrString ") ");
  1270.                     }
  1271.                 }
  1272.                 $mustStr $joinMustString;   /////New testing
  1273. //                $mustStr = '';
  1274. ///now must conditions
  1275.                 foreach ($mustConditions as $mustCondition) {
  1276. //            $conditionStr.=' 1=1 ';
  1277.                     $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  1278.                     $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  1279.                     $aliasInCondition $table;
  1280.                     if (!(strpos($cfield'.') === false)) {
  1281.                         $fullCfieldArray explode('.'$cfield);
  1282.                         $aliasInCondition $fullCfieldArray[0];
  1283.                         $cfield $fullCfieldArray[1];
  1284.                     }
  1285.                     $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  1286.                     if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  1287.                         if ($mustStr != '')
  1288.                             $mustStr .= " and ";
  1289.                         if ($ctype == 'like') {
  1290.                             $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  1291.                             $wordsBySpaces explode(' '$cvalue);
  1292.                             foreach ($wordsBySpaces as $word) {
  1293.                                 if ($mustStr != '')
  1294.                                     $mustStr .= " or ";
  1295.                                 $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  1296.                             }
  1297.                             $mustStr .= " )";
  1298.                         } else if ($ctype == 'not like') {
  1299.                             $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  1300.                             $wordsBySpaces explode(' '$cvalue);
  1301.                             foreach ($wordsBySpaces as $word) {
  1302.                                 if ($mustStr != '')
  1303.                                     $mustStr .= " and ";
  1304.                                 $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  1305.                             }
  1306.                         } else if ($ctype == 'in') {
  1307.                             $mustStr .= " ( ";
  1308.                             if (in_array('null'$cvalue)) {
  1309.                                 $mustStr .= " `$aliasInCondition`.$cfield is null";
  1310.                                 $cvalue array_diff($cvalue, ['null']);
  1311.                                 if (!empty($cvalue))
  1312.                                     $mustStr .= " or ";
  1313.                             }
  1314.                             if (in_array(''$cvalue)) {
  1315.                                 $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  1316.                                 $cvalue array_diff($cvalue, ['']);
  1317.                                 if (!empty($cvalue))
  1318.                                     $mustStr .= " or ";
  1319.                             }
  1320.                             $mustStr .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  1321.                         } else if ($ctype == 'not_in') {
  1322.                             $mustStr .= " ( ";
  1323.                             if (in_array('null'$cvalue)) {
  1324.                                 $mustStr .= " `$aliasInCondition`.$cfield is not null";
  1325.                                 $cvalue array_diff($cvalue, ['null']);
  1326.                                 if (!empty($cvalue))
  1327.                                     $mustStr .= " and ";
  1328.                             }
  1329.                             if (in_array(''$cvalue)) {
  1330.                                 $mustStr .= "`$aliasInCondition`.$cfield != '' ";
  1331.                                 $cvalue array_diff($cvalue, ['']);
  1332.                                 if (!empty($cvalue))
  1333.                                     $mustStr .= " and ";
  1334.                             }
  1335.                             $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  1336.                         } else if ($ctype == '=') {
  1337.                             if ($cvalue == 'null' || $cvalue == 'Null')
  1338.                                 $mustStr .= "`$aliasInCondition`.$cfield is null ";
  1339.                             else
  1340.                                 $mustStr .= "`$aliasInCondition`.$cfield = $cvalue ";
  1341.                         } else if ($ctype == '!=') {
  1342.                             if ($cvalue == 'null' || $cvalue == 'Null')
  1343.                                 $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  1344.                             else
  1345.                                 $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  1346.                         } else {
  1347.                             if (is_string($cvalue))
  1348.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  1349.                             else
  1350.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  1351.                         }
  1352.                     }
  1353.                 }
  1354.                 if ($mustStr != '') {
  1355.                     if ($conditionStr != '')
  1356.                         $conditionStr .= (" and (" $mustStr ") ");
  1357.                     else
  1358.                         $conditionStr .= ("  (" $mustStr ") ");
  1359.                 }
  1360.                 if ($conditionStr != '')
  1361.                     $filterQryForCriteria .= (" and (" $conditionStr ") ");
  1362.                 if ($lastChildrenOnly == 1) {
  1363.                     if ($filterQryForCriteria != '')
  1364.                         $filterQryForCriteria .= ' and ';
  1365.                     $filterQryForCriteria .= " `$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  1366.                 } else if ($parentOnly == 1) {
  1367.                     if ($filterQryForCriteria != '')
  1368.                         $filterQryForCriteria .= ' and ';
  1369.                     $filterQryForCriteria .= " `$table`.`$valueField`  in ( select distinct $parentIdField from  $table)";
  1370.                 }
  1371.                 if (!empty($orderByConditions)) {
  1372.                     $filterQryForCriteria .= "  order by ";
  1373.                     $fone 1;
  1374.                     foreach ($orderByConditions as $orderByCondition) {
  1375.                         if ($fone != 1) {
  1376.                             $filterQryForCriteria .= " , ";
  1377.                         }
  1378.                         if (isset($orderByCondition['valueList'])) {
  1379.                             if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  1380.                             if ($orderByCondition['valueList'] == null)
  1381.                                 $orderByCondition['valueList'] = [];
  1382.                             $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  1383.                         } else
  1384.                             $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  1385.                         $fone 0;
  1386.                     }
  1387.                 }
  1388.                 if ($returnTotalMatchedEntriesFlag == 1) {
  1389. //            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1390. //            
  1391. //            $get_kids = $stmt;
  1392.                 }
  1393.                 if ($filterQryForCriteria != '')
  1394.                     if (!empty($setValueArray) || $selectAll == 1) {
  1395.                     } else {
  1396.                         if ($itemLimit != '_ALL_')
  1397.                             $filterQryForCriteria .= "  limit $offset$itemLimit ";
  1398.                         else
  1399.                             $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  1400.                     }
  1401.                 $get_kids_sql $filterQryForCriteria;
  1402.                 $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1403.                 
  1404.                 $get_kids $stmt;
  1405.                 $selectedId 0;
  1406.                 if ($table == 'warehouse_action') {
  1407.                     if (empty($get_kids)) {
  1408.                         $get_kids_sql_2 "select * from warehouse_action";
  1409.                         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql_2);
  1410.                         
  1411.                         $get_kids2 $stmt;
  1412.                         if (empty($get_kids2))
  1413.                             $get_kids GeneralConstant::$warehouse_action_list;
  1414.                     }
  1415.                 }
  1416.                 if (!empty($get_kids)) {
  1417.                     $nextOffset $offset count($get_kids);
  1418.                     $nextOffset++;
  1419.                     foreach ($get_kids as $pa) {
  1420.                         if (!empty($setValueArray) && $selectAll == 0) {
  1421.                             if (!in_array($pa[$valueField], $setValueArray))
  1422.                                 continue;
  1423.                         }
  1424.                         if (!empty($restrictionIdList)) {
  1425.                             if (!in_array($pa[$valueField], $restrictionIdList))
  1426.                                 continue;
  1427.                         }
  1428.                         if ($selectAll == 1) {
  1429.                             $setValueArray[] = $pa[$valueField];
  1430.                             $setValue $pa[$valueField];
  1431.                         } else if (count($get_kids) == && $setDataForSingle == 1) {
  1432.                             $setValueArray[] = $pa[$valueField];
  1433.                             $setValue $pa[$valueField];
  1434.                         }
  1435.                         if ($valueField != '')
  1436.                             $pa['value'] = $pa[$valueField];
  1437.                         $renderedText $renderTextFormat;
  1438.                         $compare_array = [];
  1439.                         if ($renderTextFormat != '') {
  1440.                             $renderedText $renderTextFormat;
  1441.                             $compare_arrayFull = [];
  1442.                             $compare_array = [];
  1443.                             $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  1444.                             );
  1445.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  1446.                             if (isset($compare_arrayFull[0]))
  1447.                                 $compare_array $compare_arrayFull[0];
  1448. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  1449.                             foreach ($compare_array as $cmpdt) {
  1450.                                 $tbr str_replace("__"""$cmpdt);
  1451.                                 if ($tbr != '') {
  1452.                                     if (isset($pa[$tbr])) {
  1453.                                         if ($pa[$tbr] == null)
  1454.                                             $renderedText str_replace($cmpdt''$renderedText);
  1455.                                         else
  1456.                                             $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  1457.                                     } else {
  1458.                                         $renderedText str_replace($cmpdt''$renderedText);
  1459.                                     }
  1460.                                 }
  1461.                             }
  1462.                         }
  1463.                         $pa['rendered_text'] = $renderedText;
  1464.                         $pa['text'] = ($textField != '' $pa[$textField] : '');
  1465. //                $pa['compare_array'] = $compare_array;
  1466.                         foreach ($convertToObjectFieldList as $convField) {
  1467.                             if (isset($pa[$convField])) {
  1468.                                 $taA json_decode($pa[$convField], true);
  1469.                                 if ($taA == null$taA = [];
  1470.                                 $pa[$convField] = $taA;
  1471.                             } else {
  1472.                                 $pa[$convField] = [];
  1473.                             }
  1474.                         }
  1475.                         foreach ($convertDateToStringFieldList as $convField) {
  1476.                             if (is_array($convField)) {
  1477.                                 $fld $convField['field'];
  1478.                                 $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  1479.                             } else {
  1480.                                 $fld $convField;
  1481.                                 $frmt 'Y-m-d H:i:s';
  1482.                             }
  1483.                             if (isset($pa[$fld])) {
  1484.                                 $taA = new \DateTime($pa[$fld]);
  1485.                                 $pa[$fld] = $taA->format($frmt);
  1486.                             }
  1487.                         }
  1488.                         foreach ($convertToUrl as $convField) {
  1489. //
  1490. //                            $fld = $convField;
  1491. //
  1492. //
  1493. //                            if (isset($pa[$fld])) {
  1494. //
  1495. //
  1496. //                                $pa[$fld] =
  1497. //                                    $this->generateUrl(
  1498. //                                        'dashboard', [
  1499. //
  1500. //                                    ], UrlGenerator::ABSOLUTE_URL
  1501. //                                    ).'/'.$pa[$fld];
  1502. //
  1503. //                            }
  1504.                         }
  1505.                         foreach ($fullPathList as $pathField) {
  1506.                             $fld $pathField;
  1507.                             if (isset($pa[$fld])) {
  1508.                                 if ($pa[$fld] !='' && $pa[$fld] !=null) {
  1509.                                     $pa[$fld]=($this->generateUrl(
  1510.                                             'dashboard', [
  1511.                                         ], UrlGenerator::ABSOLUTE_URL
  1512.                                         ).$pa[$fld]);
  1513.                                 }
  1514.                             }
  1515.                         }
  1516.                         $pa['currentTs'] = (new \Datetime())->format('U');
  1517.                         $data[] = $pa;
  1518.                         if ($valueField != '') {
  1519.                             $data_by_id[$pa[$valueField]] = $pa;
  1520.                             $selectedId $pa[$valueField];
  1521.                         }
  1522.                     }
  1523.                 }
  1524.                 if ($dataOnly == 1)
  1525.                     $lastResult = array(
  1526.                         'success' => true,
  1527.                         'data' => $data,
  1528.                         'currentTs' => (new \Datetime())->format('U'),
  1529.                         'restrictionIdList' => $restrictionIdList,
  1530.                         'nextOffset' => $nextOffset,
  1531.                         'totalMatchedEntries' => $totalMatchedEntries,
  1532.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  1533.                     );
  1534.                 else
  1535.                     $lastResult = array(
  1536.                         'success' => true,
  1537.                         'data' => $data,
  1538.                         'tableName' => $table,
  1539.                         'setValue' => $setValue,
  1540.                         'currentTs' => (new \Datetime())->format('U'),
  1541.                         'restrictionIdList' => $restrictionIdList,
  1542.                         'andConditions' => $andConditions,
  1543.                         'queryStr' => $queryStringIndividual,
  1544.                         'isMultiple' => $isMultiple,
  1545.                         'nextOffset' => $nextOffset,
  1546.                         'totalMatchedEntries' => $totalMatchedEntries,
  1547.                         'selectorId' => $selectorId,
  1548.                         'setValueArray' => $setValueArray,
  1549.                         'silentChangeSelectize' => $silentChangeSelectize,
  1550.                         'convertToObjectFieldList' => $convertToObjectFieldList,
  1551.                         'conditionStr' => $conditionStr,
  1552. //                    'andStr' => $andString,
  1553. //                    'andOrStr' => $andOrString,
  1554.                         'dataById' => $data_by_id,
  1555.                         'selectedId' => $selectedId,
  1556.                         'dataId' => $dataId,
  1557.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  1558.                     );
  1559.             }
  1560.             $allResult[] = $lastResult;
  1561.         }
  1562.         if ($isSingleDataset == 1)
  1563.             return new JsonResponse($lastResult);
  1564.         else
  1565.             return new JsonResponse($allResult);
  1566.     }
  1567.     public function GenericDataTableAjax(Request $request)
  1568.     {
  1569.         $em $this->getDoctrine()->getManager();
  1570.         $companyId $this->getLoggedUserCompanyId($request);
  1571.         $listData MiscActions::GetDtDataAjax($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId$this->container->getParameter('kernel.root_dir'));
  1572.         if (isset($listData['data']['encryptedData'])) {
  1573.             foreach ($listData['data']['encryptedData'] as $k => $d) {
  1574.                 foreach ($d as $l => $f) {
  1575.                     $d[$l] = $this->get('url_encryptor')->encrypt($f);
  1576.                 }
  1577.                 $listData['data']['encryptedData'][$k] = $d;
  1578.             }
  1579.         }
  1580.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  1581.             if ($request->query->has('dataTableQry')) {
  1582.                 return new JsonResponse(
  1583.                     $listData
  1584.                 );
  1585.             }
  1586.         }
  1587.         $data = [];
  1588.         return new JsonResponse(
  1589.             $listData
  1590.         );
  1591.         //        return $this->render('@Inventory/pages/views/delivery_receipts.html.twig',
  1592.         //            array(
  1593.         //                'page_title' => 'Delivery Receipts',
  1594.         //                'data' => $data,
  1595.         //
  1596.         //            )
  1597.         //        );
  1598.     }
  1599.     public function RefreshApprovalStatusIfPending(Request $request)
  1600.     {
  1601.         $em $this->getDoctrine()->getManager();
  1602.         $Entity_list GeneralConstant::$Entity_list;
  1603.         $skipEntities $request->request->has('skipEntities') ? $request->request->get('skipEntities') : [427142627282931];
  1604.         $skipEntitiesById $request->request->has('skipEntitiesById') ? $request->request->get('skipEntitiesById') : [];
  1605.         $debugData = array(
  1606.             'skipEntities' => $skipEntities,
  1607.             'skipEntitiesById' => $skipEntitiesById,
  1608.             'allDone' => 1,
  1609.             'actedOnDoc' => ''
  1610.         );
  1611.         $didAct 0;
  1612.         $foundAtleastOne 0;
  1613.         $lastEntity 0;
  1614.         foreach ($Entity_list as $entity => $entityName) {
  1615.             if (in_array($entity$skipEntities))
  1616.                 continue;
  1617.             $lastEntity $entity;
  1618.             $debugData['allDone'] = 0;
  1619.             $doc null;
  1620.             //            if (class_exists('ApplicationBundle\\Entity\\' . $entityName))
  1621.             {
  1622.                 $docs $em->getRepository('ApplicationBundle\\Entity\\' $entityName)
  1623.                     ->findBy(
  1624.                         array(
  1625.                             'approved' => GeneralConstant::APPROVAL_STATUS_PENDING
  1626.                         )
  1627.                     );
  1628.             }
  1629.             $entityFieldGetFunction GeneralConstant::$Entity_id_get_method_list[$entity];
  1630.             if (!isset($skipEntitiesById[$entity]))
  1631.                 $skipEntitiesById[$entity] = [];
  1632.             foreach ($docs as $doc) {
  1633.                 if (in_array($doc->$entityFieldGetFunction(), $skipEntitiesById[$entity]))
  1634.                     continue;
  1635.                 $foundAtleastOne 1;
  1636.                 if ($doc) {
  1637.                     $fully_approved System::fullyApproved($em$entity$doc->$entityFieldGetFunction(), 0$this->get('mail_module'));
  1638.                     if ($fully_approved == 1)
  1639.                         $debugData['actedOnDoc'] = $doc->getDocumentHash();
  1640.                     $didAct 1;
  1641.                     $skipEntitiesById[$entity][] = $doc->$entityFieldGetFunction();
  1642.                 } else {
  1643.                 }
  1644.                 if ($didAct == 1)
  1645.                     break;
  1646.             }
  1647.             if ($didAct == 1)
  1648.                 break;
  1649.         }
  1650.         if ($foundAtleastOne == 0)
  1651.             $debugData['skipEntities'][] = $lastEntity;
  1652.         $debugData['skipEntitiesById'] = $skipEntitiesById;
  1653.         return new JsonResponse(
  1654.             $debugData
  1655.         );
  1656.     }
  1657.     public function CreateDummyRows(Request $request$startFrom 0)
  1658.     {
  1659.         //function start
  1660.         ///function end
  1661.         $em $this->getDoctrine()->getManager();
  1662.         //        for($i=0;$i<10000;$i++) {
  1663.         //            $startFrom++;
  1664.         //            $get_kids_sql = "INSERT INTO `acc_loan` ( `name`, `type`, `company_id`, `branch_id`, `bank_id`, `accounts_head_id`, `head_nature`, `payment_head_id`, `interest_expense_head_id`, `interest_head_id`, `life_year`, `interest_type`, `interest_rate`, `payment_type`, `payment_rate`, `account_number`, `card_number`, `card_type`, `create_individual_head`, `rentable`, `hit_ledger_on_action`, `parent_id`, `balance`, `bank`, `cash`, `sales`, `asset`, `liability`, `expense`, `revenue`, `payable`, `receivable`, `net_worth`, `monthly_growth`, `status`, `edit_flag`, `delete_flag`, `lock_flag`, `refresh_flag`, `disabled_flag`, `create_login_id`, `edit_login_id`, `created_at`, `updated_at`) VALUES ( 'a', 'a', $startFrom, '1', '1', '1', 'cr', '1', '1', '1', 'adsad', '1', '1', '1', '1', 'ssadada', 'adadad', 'ada', '1', '1', '1', '1', '900', '06868', '6866', '8686', '86868', '6868', '686', '6868', '686', '6868', '686', '6868', '3', '1', '1', '1', '1', '1', '1', '1', '2021-01-11 16:40:20', '2019-09-18 19:29:55');";
  1665.         //            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1666.         //            
  1667.         //            
  1668.         //        }
  1669.         for ($i 0$i 50000$i++) {
  1670.             $startFrom++;
  1671.             $get_kids_sql "INSERT INTO `employee_attendance_log` ( `attendance_id`, `current_lat`, `current_lng`, `is_from_assigned_area`, `log`, `popup_init`, `popup_response`, `delay_response_count`, `last_start_time`, `last_end_time`, `total_work_time_sec`, `current_work_status`, `current_address`, `employee_id`, `is_present`, `count_as_absent`, `presence_required`, `is_holiday`, `is_weekend`, `is_approved_leave`) VALUES ( $startFrom, '121', '1212121', '1', '" '[{\\"date\\":\\"2021 - 01 - 11 15:47:47\\",\\"type\\":1,\\"lat\\":124567,\\"lng\\":56888},{\\"date\\":\\"2021 - 01 - 11 15:47:47\\",\\"type\\":1,\\"lat\\":124567,\\"lng\\":56888},{\\"date\\":\\"2021 - 01 - 11 15:47:47\\",\\"type\\":1,\\"lat\\":124567,\\"lng\\":56888},{\\"date\\":\\"2021 - 01 - 11 15:47:47\\",\\"type\\":1,\\"lat\\":124567,\\"lng\\":56888}]' "', '2021-01-11 20:11:06', '2021-01-29 20:11:21', NULL, '2020-12-10 01:56:00', '2021-01-29 20:11:32', '36000', '1', 'sdsdsdssssssssssssss', '3', '1', '1', '1', '1', '1', '1');";
  1672.             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  1673.             
  1674.             
  1675.         }
  1676.         $url $this->generateUrl(
  1677.             'test_insert_lot_of_rows'
  1678.         );
  1679.         if ($startFrom 1000000)
  1680.             return $this->redirect($url "/" $startFrom);
  1681.         else
  1682.             return new Response(1);
  1683.     }
  1684.     public function CreateSalesInvoice(Request $request)
  1685.     {
  1686.         //function start
  1687.         ///function end
  1688.         $em $this->getDoctrine()->getManager();
  1689.         return new JsonResponse(Accounts::GetBalanceOnDateByMarkerHash($em'2021-01-21', [], [], 1));
  1690.         $childEm $this->getDoctrine()->getManager('company_group');
  1691.         ob_start();
  1692.         phpinfo();
  1693.         $phpinfo ob_get_contents();
  1694.         ob_end_clean();
  1695.         $em $this->getDoctrine()->getManager();
  1696.         return $this->render(
  1697.             '@Accounts/pages/input_forms/sales_invoice.html.twig',
  1698.             array(
  1699.                 'page_title' => 'Create Sales Invoice',
  1700.                 'phpinfo' => $phpinfo,
  1701.                 'debug_data' => $this->getDoctrine()->getManager('company_group'),
  1702.                 'debug_data_2' => Company::getMonthlyDataForDashboard($this->getDoctrine()->getManager(), 1)
  1703.             )
  1704.         );
  1705.         //refreshing/ assigning invoice/order/challan/grn/stock requisition etc id to voucher as entity id
  1706.         $tocheckEntityList = array(
  1707.             => 'Grn',
  1708.             => 'PurchaseInvoice',
  1709.             10 => 'ExpenseInvoice',
  1710.             16 => 'DeliveryReceipt',
  1711.             18 => 'SalesInvoice',
  1712.             20 => 'StockTransfer',
  1713.             21 => 'StockReceivedNote',
  1714.             30 => 'ServiceChallan',
  1715.             41 => 'ItemReceivedAndReplacement',
  1716.             44 => 'StockConsumptionNote',
  1717.             47 => 'FixedAssetConversionNote',
  1718.             48 => 'FixedAssetDisposalNote',
  1719.             53 => 'Production',
  1720.         );
  1721.         foreach ($tocheckEntityList as $entity => $entityName) {
  1722.             $entityList $em->getRepository('ApplicationBundle\\Entity\\' $entityName)->findBy(
  1723.                 array()
  1724.             );
  1725.             foreach ($entityList as $entry) {
  1726.                 $voucherIds method_exists($entry'getVoucherIds') ? json_decode($entry->getVoucherIds(), true) : [];
  1727.                 $getMethod GeneralConstant::$Entity_id_get_method_list[$entity];
  1728.                 if ($voucherIds == null)
  1729.                     $voucherIds = [];
  1730.                 if (!empty($voucherIds)) {
  1731.                     $transactions $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findBy(
  1732.                         array(
  1733.                             'transactionId' => $voucherIds
  1734.                         )
  1735.                     );
  1736.                     foreach ($transactions as $transaction) {
  1737.                         $transaction->setEntityId($entry->$getMethod());
  1738.                         $transaction->setEntity($entity);
  1739.                         $transaction->setEntityDocHash($entry->getDocumentHash());
  1740.                         $em->flush();
  1741.                     }
  1742.                 }
  1743.             }
  1744.         }
  1745.         //        return $this->render('phpinfo.html.twig', array(
  1746.         //            'phpinfo'=>$phpinfo,
  1747.         //        ));
  1748.         //If we want to change the childEm to a different database:
  1749.         /**
  1750.          * IMPORTANT: The $reset parameter is used to clear all Units of Work fro
  1751.          * the EntityManager, this means anything that was not previously flushed
  1752.          * will be lost if you do $reset = true.
  1753.          *
  1754.          * Separately, $reset is necessary if you want to apply changes across
  1755.          * multiple EntityManagers in one Controller. Make sure you flush, then
  1756.          * $reset, and you will be good to go.
  1757.          */
  1758.         /**
  1759.          * get your new database parameters here..
  1760.          */
  1761.         //        $connector = $this->container->get('application_connector');
  1762.         //        $connector->resetConnection('company_group', 'bengal_v2', "root", "", "localhost", $reset = true);
  1763.         $soList $em->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findBy(
  1764.             array()
  1765.         );
  1766.         foreach ($soList as $so) {
  1767.             //            SalesOrderM::checkIfSalesOrderComplete($em, $so->getSalesOrderId());
  1768.         }
  1769.         //childEM is now connected to the new database.
  1770.         //        $childEm = $this->getDoctrine()->getManager('company_group')
  1771.         //            ->getRepository("ApplicationBundle\\Entity\\AccSuppliers")
  1772.         //        ->findAll();
  1773.         return $this->render(
  1774.             '@Accounts/pages/input_forms/sales_invoice.html.twig',
  1775.             array(
  1776.                 'page_title' => 'Create Sales Invoice',
  1777.                 'phpinfo' => $phpinfo,
  1778.                 'debug_data' => $this->getDoctrine()->getManager('company_group'),
  1779.                 'debug_data_2' => Company::getMonthlyDataForDashboard($this->getDoctrine()->getManager(), 1)
  1780.             )
  1781.         );
  1782.     }
  1783.     public function GetFilteredCostCentres(Request $request$headId 0)
  1784.     {
  1785.         $em $this->getDoctrine()->getManager();
  1786.         $companyId $this->getLoggedUserCompanyId($request);
  1787.         $asArray $request->query->has('asArray') ? $request->query->get('asArray') : 0;
  1788.         return new JsonResponse(array(
  1789.             'costCentreList' => Accounts::CostCenterListFilteredByHeadId($em$companyId$headId$asArray)
  1790.         ));
  1791.     }
  1792.     public function GetAllocationRules(Request $request)
  1793.     {
  1794.         $em $this->getDoctrine()->getManager();
  1795.         $accountId = (int) $request->query->get('account_id'0);
  1796.         if ($accountId <= 0) {
  1797.             return new JsonResponse([
  1798.                 'success' => true,
  1799.                 'data' => [],
  1800.             ]);
  1801.         }
  1802.         $rules $em->getRepository('ApplicationBundle\\Entity\\AllocationRule')->findByAccountId($accountId);
  1803.         $data = [];
  1804.         foreach ($rules as $rule) {
  1805.             $data[] = [
  1806.                 'id' => $rule->getId(),
  1807.                 'account_id' => $rule->getAccountId(),
  1808.                 'tag_type' => $rule->getTagType(),
  1809.                 'tag_value' => $rule->getTagValue(),
  1810.                 'percentage' => (float) $rule->getPercentage(),
  1811.             ];
  1812.         }
  1813.         return new JsonResponse([
  1814.             'success' => true,
  1815.             'data' => $data,
  1816.         ]);
  1817.     }
  1818.     public function RefreshFunction(Request $request)
  1819.     {
  1820.         $em $this->getDoctrine()->getManager();
  1821.         //
  1822.         //        UPDATE `acc_accounts_head` SET `head_nature`='dr' WHERE path_tree like '%/1/%' or path_tree like '%/5/%';
  1823.         //UPDATE `acc_accounts_head` SET `head_nature`='cr' WHERE path_tree like '%/3/%' or path_tree like '%/4/%';
  1824.         $dataList2 $em->getRepository('ApplicationBundle\\Entity\\StoreRequisitionItem')->findBy(
  1825.             array()
  1826.         );
  1827.         foreach ($dataList2 as $dt2) {
  1828.             if ($dt2->getNote() == "" || $dt2->getNote() == null) {
  1829.                 //find tagged data
  1830.                 $tagData = [];
  1831.                 $note "";
  1832.                 $tagData json_decode($dt2->getTagData(), true);
  1833.                 if ($tagData) {
  1834.                     foreach ($tagData as $tg) {
  1835.                         $data1 $em->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')->findOneBy(
  1836.                             array(
  1837.                                 'id' => $tg['detailsId']
  1838.                             )
  1839.                         );
  1840.                         if ($data1) {
  1841.                             if ($data1->getNote() == "" || $data1->getNote() == null) {
  1842.                                 $note .= ", ";
  1843.                                 $note .= $data1->getNote();
  1844.                             }
  1845.                         }
  1846.                     }
  1847.                 }
  1848.                 $dt2->setNote($note);
  1849.             }
  1850.         }
  1851.         $em->flush();
  1852.         $dataList2 $em->getRepository('ApplicationBundle\\Entity\\PurchaseRequisitionItem')->findBy(
  1853.             array()
  1854.         );
  1855.         foreach ($dataList2 as $dt2) {
  1856.             if ($dt2->getNote() == "" || $dt2->getNote() == null) {
  1857.                 //find tagged data
  1858.                 $tagData = [];
  1859.                 $note "";
  1860.                 $tagData json_decode($dt2->getTagData(), true);
  1861.                 if ($tagData) {
  1862.                     foreach ($tagData as $tg) {
  1863.                         $data1 $em->getRepository('ApplicationBundle\\Entity\\StoreRequisitionItem')->findOneBy(
  1864.                             array(
  1865.                                 'id' => $tg['detailsId']
  1866.                             )
  1867.                         );
  1868.                         if ($data1) {
  1869.                             if ($data1->getNote() == "" || $data1->getNote() == null) {
  1870.                                 $note .= ", ";
  1871.                                 $note .= $data1->getNote();
  1872.                             }
  1873.                         }
  1874.                     }
  1875.                 }
  1876.                 $dt2->setNote($note);
  1877.             }
  1878.         }
  1879.         $em->flush();
  1880.         return new Response(1);
  1881.         //        $query_here=$em->getRepository('ApplicationBundle\\Entity\\EncryptedSignature')
  1882.         //            ->findOneBy(
  1883.         //                array(
  1884.         //                    'userId'=>4
  1885.         //                )
  1886.         //            );
  1887.         //             if($query_here)
  1888.         //        {
  1889.         //            $dt=$query_here->getData();
  1890.         //        }
  1891.         //        else
  1892.         //        {
  1893.         //            return false;
  1894.         //        }
  1895.         //
  1896.         //
  1897.         //
  1898.         //        $iv = '1234567812345678';
  1899.         //        $data=openssl_encrypt('ki koro miavai', "AES-128-CBC", 'monada', OPENSSL_RAW_DATA, $iv);
  1900.         ////        $decrypted = openssl_decrypt(base64_decode(base64_encode($data)), "AES-128-CBC", 'monada', OPENSSL_RAW_DATA, $iv);
  1901.         //        $decrypted = openssl_decrypt(base64_decode($dt), "AES-128-CBC", 'monada', OPENSSL_RAW_DATA, $iv);
  1902.         //
  1903.         //        return new JsonResponse(array("success"=>false,'decoded_data'=>$decrypted,'data'=>base64_encode($data)));
  1904.         //1st remove any category that is not assigned to remove redundancy
  1905.         //now
  1906.     }
  1907.     public function RefreshHeadCode(Request $request)
  1908.     {
  1909.         $head_list = [];
  1910.         $digits = [];
  1911.         //first get max level
  1912.         $em $this->getDoctrine()->getManager();
  1913.         $max_level 0;
  1914.         $query "SELECT max(head_level) max_level from  acc_accounts_head   where company_id=" $this->getLoggedUserCompanyId($request);
  1915.         $stmt $em->getConnection()->fetchAllAssociative($query);
  1916.         
  1917.         $results $stmt;
  1918.         if ($results) {
  1919.             $max_level $results[0]['max_level'];
  1920.         }
  1921.         //now create multipliers
  1922.         for ($i 1$i <= $max_level$i++) {
  1923.             $query "SELECT count(accounts_head_id) count_of_level from  acc_accounts_head   where head_level=$i and company_id=" $this->getLoggedUserCompanyId($request);
  1924.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1925.             
  1926.             $res $stmt;
  1927.             if ($res) {
  1928.                 $c $res[0]['count_of_level'];
  1929.                 $m 1;
  1930.                 $t 1;
  1931.                 for ($m 1$t <= $c$m++) {
  1932.                     $t $t 10;
  1933.                 }
  1934.                 //                while($c/10>0)
  1935.                 //                {
  1936.                 //                    $m+=1;
  1937.                 //                    $c = $c % 10;
  1938.                 //                }
  1939.                 $digits[$i] = $m;
  1940.             } else
  1941.                 $digits[$i] = 0;
  1942.         }
  1943.         //now get all acc heads and serialize them based on parent id
  1944.         $query "SELECT * from  acc_accounts_head  where company_id=" $this->getLoggedUserCompanyId($request) . " ORDER BY parent_id ASC";
  1945.         //        $query="SELECT accounts_head_id, type_hash, prefix_hash, assoc_hash, number_hash from  acc_transactions  where status=".GeneralConstant::ACTIVE;
  1946.         $stmt $em->getConnection()->fetchAllAssociative($query);
  1947.         
  1948.         $results $stmt;
  1949.         $update_qry "";
  1950.         foreach ($results as $entry) {
  1951.             $new_code '';
  1952.             $path explode('/'$entry['path_tree']);
  1953.             $path_string '';
  1954.             $new_ser 1;
  1955.             foreach ($path as $head_id) {
  1956.                 if ($head_id != '' && $head_id != 0) {
  1957.                     if ($head_id == $entry['parent_id']) {
  1958.                         $new_ser $head_list[$head_id]['last_serial'] + 1;
  1959.                         $head_list[$head_id]['last_serial'] + $new_ser;
  1960.                     }
  1961.                     $new_code $new_code $head_list[$head_id]['code'] * 1;
  1962.                 }
  1963.             }
  1964.             //now this oneonly
  1965.             for ($k 0$k $digits[$entry['head_level']]; $k++)
  1966.                 $new_code 10 $new_code;
  1967.             //now last zeroes
  1968.             for ($j $entry['head_level']; $j <= $max_level$j++) {
  1969.                 for ($k 0$k $digits[$j]; $k++)
  1970.                     $new_code 10 $new_code;
  1971.             }
  1972.             $head_list[$entry['accounts_head_id']] = array(
  1973.                 'code' => $new_code,
  1974.                 'last_serial' => 0
  1975.             );
  1976.             $update_qry .= "UPDATE acc_accounts_head set ledger_head_code=$new_code
  1977.                       where accounts_head_id=" $entry['accounts_head_id'] . "; ";
  1978.         }
  1979.         $stmt $em->getConnection()->fetchAllAssociative($update_qry);
  1980.         
  1981.         return $this->redirectToRoute('dashboard');
  1982.     }
  1983.     public function RefreshHeadLevel(Request $request)
  1984.     {
  1985.         $em $this->getDoctrine()->getManager();
  1986.         $assign_list = array();
  1987.         //        $new_cc = $em
  1988.         //            ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  1989.         //            ->findOneBy(
  1990.         //                array(
  1991.         //                    'name' => 'accounting_year_start',
  1992.         //                )
  1993.         //            );
  1994.         $heads = [];
  1995.         $query "SELECT * from  acc_accounts_head  where company_id=" $this->getLoggedUserCompanyId($request) . " ORDER BY parent_id ASC";
  1996.         //        $query="SELECT accounts_head_id, type_hash, prefix_hash, assoc_hash, number_hash from  acc_transactions  where status=".GeneralConstant::ACTIVE;
  1997.         $stmt $em->getConnection()->fetchAllAssociative($query);
  1998.         
  1999.         $results $stmt;
  2000.         $update_qry "";
  2001.         $head_list_by_id = [];
  2002.         $child_list_by_parent_id = [];
  2003.         $zero_parent_head_ids = [];
  2004.         foreach ($results as $entry) {
  2005.             $head_list_by_id[$entry['accounts_head_id']] = $entry;
  2006.             $parent_id $entry['parent_id'];
  2007.             if ($parent_id == null || $parent_id == '' || $parent_id == 0) {
  2008.                 $zero_parent_head_ids[] = $entry['accounts_head_id'];
  2009.                 $parent_id 0;
  2010.             }
  2011.             if (!isset($child_list_by_parent_id[$parent_id]))
  2012.                 $child_list_by_parent_id[$parent_id] = array();
  2013.             $child_list_by_parent_id[$parent_id][] = $entry['accounts_head_id'];
  2014.         }
  2015.         foreach ($zero_parent_head_ids as $parId) {
  2016.             $heads[$parId] = array(
  2017.                 'level' => 1
  2018.             );
  2019.             $next_ids $child_list_by_parent_id[$parId];
  2020.             $cur_level 1;
  2021.             $infLoopBreaker 0;
  2022.             while (!empty($next_ids) && $infLoopBreaker 100) {
  2023.                 $cur_level $cur_level 1;
  2024.                 $new_next_ids = [];
  2025.                 foreach ($next_ids as $childId) {
  2026.                     $entry $head_list_by_id[$childId];
  2027.                     if ($cur_level == $entry['head_level']) {
  2028.                     } else {
  2029.                         $update_qry .= "UPDATE acc_accounts_head set head_level=$cur_level
  2030.                                 where accounts_head_id=" $entry['accounts_head_id'] . "; ";
  2031.                     }
  2032.                     if (isset($child_list_by_parent_id[$childId]))
  2033.                         array_merge($new_next_idsarray_diff($new_next_ids$child_list_by_parent_id[$childId]));
  2034.                     $heads[$entry['accounts_head_id']] = array(
  2035.                         'level' => $cur_level
  2036.                     );
  2037.                 }
  2038.                 $next_ids $new_next_ids;
  2039.                 $infLoopBreaker++;
  2040.             }
  2041.         }
  2042.         //        System::log_it($this->container->getParameter('kernel.root_dir'), json_encode($zero_parent_head_ids), 'head_level_test');
  2043.         //
  2044.         //        foreach ($results as $entry) {
  2045.         //            if ($entry['parent_id'] == 0 || $entry['parent_id'] == '') {
  2046.         //                //top parent
  2047.         //                $heads[$entry['accounts_head_id']] = array(
  2048.         //                    'level' => 1
  2049.         //                );
  2050.         //            } else {
  2051.         //                $cur_level = 1 + $heads[$entry['parent_id']]['level'];
  2052.         //                if ($cur_level == $entry['head_level']) {
  2053.         //                } else {
  2054.         //                    $update_qry .= "UPDATE acc_accounts_head set head_level=$cur_level
  2055.         //                     where accounts_head_id=" . $entry['accounts_head_id'] . "; ";
  2056.         //                }
  2057.         //
  2058.         //
  2059.         //                $heads[$entry['accounts_head_id']] = array(
  2060.         //                    'level' => $cur_level
  2061.         //                );
  2062.         //            }
  2063.         //        }
  2064.         if ($update_qry != '') {
  2065.             $stmt $em->getConnection()->fetchAllAssociative($update_qry);
  2066.             
  2067.         }
  2068.         //        $Transactions=$stmt;
  2069.         return $this->redirectToRoute('opening_head_balance_assign');
  2070.     }
  2071.     public function PrintCheckRegister(Request $request)
  2072.     {
  2073.         $em $this->getDoctrine()->getManager();
  2074.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  2075.         $head_list Accounts::HeadList($em);
  2076.         $voucher_list Accounts::VoucherListForCheckRegister($em);
  2077.         $find_array = array(
  2078.             'type' => 1
  2079.         );
  2080.         if ($request->query->has('viewOption')) {
  2081.             if ($request->query->get('viewOption') == 1)
  2082.                 $find_array = ['active' => GeneralConstant::ACTIVE];
  2083.             if ($request->query->get('viewOption') == 2)
  2084.                 $find_array = ['active' => GeneralConstant::INACTIVE];
  2085.         }
  2086.         $assignedflag $request->query->has('assign_flag') ? $request->query->get('assign_flag') : 0;
  2087.         if ($assignedflag == 1)
  2088.             $find_array['assigned'] = 1;
  2089.         $check_query $this->getDoctrine()
  2090.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2091.             ->findBy(
  2092.                 $find_array,
  2093.                 array(
  2094.                     'checkNumber' => 'ASC',
  2095.                 )
  2096.             );
  2097.         $check_data = [];
  2098.         $check_data_by_bank = [];
  2099.         $start_date $request->query->has('start_date') ? (new \DateTime($request->query->get('start_date'))) : '';
  2100.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : '';
  2101.         //            if($end_date!='')
  2102.         //                $end_date->modify('+1 day');
  2103.         $book_list_by_bank = [];
  2104.         foreach ($check_query as $entry) {
  2105.             $checkTransDate $entry->getTransactionDate();
  2106.             if ($checkTransDate == null)
  2107.                 continue;
  2108.             if ($start_date != '' && ($checkTransDate instanceof \DateTime) && ($start_date $checkTransDate))
  2109.                 continue;
  2110.             if ($end_date != '' && ($checkTransDate instanceof \DateTime) && ($end_date $checkTransDate))
  2111.                 continue;
  2112.             $v_date = isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['date'] : '';
  2113.             //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2114.             if ($start_date != '' && ($v_date instanceof \DateTime) && ($start_date $v_date))
  2115.                 continue;
  2116.             //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2117.             if ($end_date != '' && ($v_date instanceof \DateTime) && ($end_date $v_date))
  2118.                 continue;
  2119.             //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2120.             //                    continue;
  2121.             //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2122.             //                    continue;
  2123.             $checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
  2124.             $assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
  2125.             if (!isset($book_list_by_bank[$entry->getAccountsHeadId()])) $book_list_by_bank[$entry->getAccountsHeadId()] = [];
  2126.             if (!in_array($entry->getBookNumber(), $book_list_by_bank[$entry->getAccountsHeadId()])) {
  2127.                 $book_list_by_bank[$entry->getAccountsHeadId()][] = $entry->getBookNumber();
  2128.             }
  2129.             $check_data_by_bank[$entry->getAccountsHeadId()][] = array(
  2130.                 'checkId' => $entry->getCheckId(),
  2131.                 'checkNumber' => sprintf("%07d"$entry->getCheckNumber()),
  2132.                 'checkNarration' => $entry->getCheckNarration(),
  2133.                 'voucherNarration' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['desc'] : '',
  2134.                 'voucherDate' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['date']->format('m/d/Y') : '',
  2135.                 'accountNumber' => $entry->getAccountNumber(),
  2136.                 'checkDate' => $checkDate,
  2137.                 'head' => $head_list[$entry->getAccountsHeadId()]['name'],
  2138.                 'head_id' => $entry->getAccountsHeadId(),
  2139.                 'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
  2140.                 'received_head_id' => $entry->getRecAccountsHeadId(),
  2141.                 'received_head_id_list' => $entry->getRecAccountsHeadIdList(),
  2142.                 'assignedDate' => $assignedDate,
  2143.                 'checkAmount' => $entry->getCheckAmount(),
  2144.                 'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
  2145.                 'voucher_id' => $entry->getVoucherId(),
  2146.             );
  2147.         }
  2148.         $count_details_by_bank = [];
  2149.         if ($request->query->has('countDetails')) {
  2150.             $check_query $this->getDoctrine()
  2151.                 ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2152.                 ->findAll();
  2153.             $count_details_by_bank = [];
  2154.             $assigned_books = [];
  2155.             foreach ($check_query as $entry) {
  2156.                 if (isset($count_details_by_bank[$entry->getAccountsHeadId()])) {
  2157.                     $count_details_by_bank[$entry->getAccountsHeadId()]['total_chk'] += 1;
  2158.                     if ($entry->getAssigned() == 1)
  2159.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] += 1;
  2160.                     else
  2161.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] += 1;
  2162.                     if (!in_array($entry->getBookNumber(), $assigned_books)) {
  2163.                         $count_details_by_bank[$entry->getAccountsHeadId()]['books'] .= (', ' $entry->getBookNumber());
  2164.                         array_push($assigned_books$entry->getBookNumber());
  2165.                     }
  2166.                 } else {
  2167.                     $count_details_by_bank[$entry->getAccountsHeadId()]['total_chk'] = 1;
  2168.                     $count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] = 0;
  2169.                     $count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] = 0;
  2170.                     if ($entry->getAssigned() == 1)
  2171.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] = 1;
  2172.                     else
  2173.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] = 1;
  2174.                     array_push($assigned_books$entry->getBookNumber());
  2175.                     $count_details_by_bank[$entry->getAccountsHeadId()]['books'] = (' ' $entry->getBookNumber());
  2176.                 }
  2177.             }
  2178.         }
  2179.         foreach ($voucher_list as $key => $entry) {
  2180.             $v_date $entry['date'];
  2181.             //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2182.             if ($start_date != '' && ($v_date instanceof \DateTime) && ($start_date $v_date))
  2183.                 continue;
  2184.             //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2185.             if ($end_date != '' && ($v_date instanceof \DateTime) && ($end_date $v_date))
  2186.                 continue;
  2187.             if (!in_array($entry['prMethod'], [34]))
  2188.                 continue;
  2189.             //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2190.             //                    continue;
  2191.             //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2192.             //                    continue;
  2193.             $trans_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  2194.                 array(
  2195.                     'transactionId' => $key,
  2196.                     'position' => 'cr'
  2197.                 )
  2198.             );
  2199.             foreach ($trans_details as $value) {
  2200.                 $checkDate $entry['date']->format('m/d/Y');
  2201.                 $assignedDate $entry['date']->format('m/d/Y');
  2202.                 $dr_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  2203.                     array(
  2204.                         'transactionId' => $key,
  2205.                         'position' => 'dr'
  2206.                     )
  2207.                 );
  2208.                 $rec_id_list = [];
  2209.                 $rec_narr "";
  2210.                 foreach ($dr_details as $dt) {
  2211.                     $rec_id_list[] = $dt->getAccountsHeadId();
  2212.                     $rec_narr .= $head_list[$dt->getAccountsHeadId()]['name'];
  2213.                     $rec_narr .= ", ";
  2214.                 }
  2215.                 $check_data_by_bank[$value->getAccountsHeadId()][] = array(
  2216.                     'checkId' => 0,
  2217.                     'checkNumber' => $entry['prReference'],
  2218.                     'checkNarration' => $rec_narr,
  2219.                     'voucherNarration' => $entry['desc'],
  2220.                     'voucherDate' => $entry['date']->format('m/d/Y'),
  2221.                     'accountNumber' => '',
  2222.                     'checkDate' => $checkDate,
  2223.                     'head' => $head_list[$value->getAccountsHeadId()]['name'],
  2224.                     'head_id' => $value->getAccountsHeadId(),
  2225.                     'received_head' => $rec_narr,
  2226.                     'received_head_id' => 0,
  2227.                     'received_head_id_list' => json_encode($rec_id_list),
  2228.                     'assignedDate' => $assignedDate,
  2229.                     'checkAmount' => $value->getAmount(),
  2230.                     'voucher_number' => $entry['doc_hash'],
  2231.                     'voucher_id' => $key,
  2232.                 );
  2233.             }
  2234.         }
  2235.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  2236.             $html $this->renderView(
  2237.                 '@Accounts/pages/print/check_register_print.html.twig',
  2238.                 array(
  2239.                     //full array here
  2240.                     'pdf' => true,
  2241.                     'page_title' => 'Cheque Register ',
  2242.                     //                'ledger_data'=>$ledger_det,
  2243.                     'export' => "pdf,print",
  2244.                     'check_data' => $check_data_by_bank,
  2245.                     'count_details_by_bank' => $count_details_by_bank,
  2246.                     'page_header' => 'Cheque Register',
  2247.                     'document_type' => 'Cheque Register',
  2248.                     //                'document_mark_image'=>$document_mark['original'],
  2249.                     'page_header_sub' => 'Add',
  2250.                     'start_date' => $start_date,
  2251.                     'end_date' => $end_date,
  2252.                     'head_list' => Accounts::HeadList($em),
  2253.                     //                'provisional'=>$provisional_option,
  2254.                     //                'type_list'=>$type_list,
  2255.                     //            'child_list'=>$child_list,
  2256.                     //                'trans_data_by_closing'=>$trans_data_by_closing,
  2257.                     'item_data' => [],
  2258.                     'received' => 2,
  2259.                     'return' => 1,
  2260.                     'total_w_vat' => 1,
  2261.                     'total_vat' => 1,
  2262.                     'total_wo_vat' => 1,
  2263.                     'invoice_id' => 'abcd1234',
  2264.                     'book_list_by_bank' => $book_list_by_bank,
  2265.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  2266.                     'created_by' => 'created by',
  2267.                     'created_at' => '',
  2268.                     'red' => 0,
  2269.                     //                'desc_head_list'=>$desc_tree_list,
  2270.                     'company_name' => $company_data->getName(),
  2271.                     'company_data' => $company_data,
  2272.                     'company_address' => $company_data->getAddress(),
  2273.                     'company_image' => $company_data->getImage(),
  2274.                     //
  2275.                 )
  2276.             );
  2277.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  2278.                 //                'orientation' => 'landscape',
  2279.                 //                'enable-javascript' => true,
  2280.                 //                'javascript-delay' => 1000,
  2281.                 'no-stop-slow-scripts' => false,
  2282.                 'no-background' => false,
  2283.                 'lowquality' => false,
  2284.                 'encoding' => 'utf-8',
  2285.                 //            'images' => true,
  2286.                 //            'cookie' => array(),
  2287.                 'dpi' => 300,
  2288.                 'image-dpi' => 300,
  2289.                 //                'enable-external-links' => true,
  2290.                 //                'enable-internal-links' => true
  2291.             ));
  2292.             return new Response(
  2293.                 $pdf_response,
  2294.                 200,
  2295.                 array(
  2296.                     'Content-Type' => 'application/pdf',
  2297.                     'Content-Disposition' => 'attachment; filename="Cheque_Register.pdf"'
  2298.                 )
  2299.             );
  2300.         }
  2301.         return $this->render(
  2302.             '@Accounts/pages/print/check_register_print.html.twig',
  2303.             array(
  2304.                 'page_title' => 'Cheque Register ',
  2305.                 //                'ledger_data'=>$ledger_det,
  2306.                 'export' => "pdf,print",
  2307.                 'check_data' => $check_data_by_bank,
  2308.                 'count_details_by_bank' => $count_details_by_bank,
  2309.                 'page_header' => 'Cheque Register',
  2310.                 'document_type' => 'Cheque Register',
  2311.                 //                'document_mark_image'=>$document_mark['original'],
  2312.                 'page_header_sub' => 'Add',
  2313.                 'start_date' => $start_date,
  2314.                 'end_date' => $end_date,
  2315.                 'head_list' => Accounts::HeadList($em),
  2316.                 //                'provisional'=>$provisional_option,
  2317.                 //                'type_list'=>$type_list,
  2318.                 //            'child_list'=>$child_list,
  2319.                 //                'trans_data_by_closing'=>$trans_data_by_closing,
  2320.                 'item_data' => [],
  2321.                 'received' => 2,
  2322.                 'return' => 1,
  2323.                 'total_w_vat' => 1,
  2324.                 'total_vat' => 1,
  2325.                 'total_wo_vat' => 1,
  2326.                 'invoice_id' => 'abcd1234',
  2327.                 'book_list_by_bank' => $book_list_by_bank,
  2328.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  2329.                 'created_by' => 'created by',
  2330.                 'created_at' => '',
  2331.                 'red' => 0,
  2332.                 //                'desc_head_list'=>$desc_tree_list,
  2333.                 'company_name' => $company_data->getName(),
  2334.                 'company_data' => $company_data,
  2335.                 'company_address' => $company_data->getAddress(),
  2336.                 'company_image' => $company_data->getImage(),
  2337.                 //                'p'=>$p
  2338.             )
  2339.         );
  2340.     }
  2341.     public function CheckRegister(Request $request)
  2342.     {
  2343.         $em $this->getDoctrine()->getManager();
  2344.         if ($request->isMethod('POST')) {
  2345.             $startCheckRaw trim((string)$request->request->get('checkNumberStart'));
  2346.             $endCheckRaw trim((string)$request->request->get('checkNumberEnd'));
  2347.             $accountNumber trim((string)$request->request->get('accountNumber'));
  2348.             $bookNumber trim((string)$request->request->get('bookNumber'));
  2349.             $accountsHeadId = (int)$request->request->get('accountsHeadId');
  2350.             $formatId = (int)$request->request->get('formatId');
  2351.             $errors = [];
  2352.             if ($accountsHeadId <= 0) {
  2353.                 $errors[] = 'Please select account.';
  2354.             }
  2355.             if ($accountNumber === '') {
  2356.                 $errors[] = 'Please enter account number.';
  2357.             }
  2358.             if ($bookNumber === '') {
  2359.                 $errors[] = 'Please enter cheque book number.';
  2360.             }
  2361.             if ($startCheckRaw === '' || !ctype_digit($startCheckRaw)) {
  2362.                 $errors[] = 'Please enter a valid starting cheque number.';
  2363.             }
  2364.             if ($endCheckRaw !== '' && !ctype_digit($endCheckRaw)) {
  2365.                 $errors[] = 'Please enter a valid ending cheque number.';
  2366.             }
  2367.             if ($formatId <= 0) {
  2368.                 $errors[] = 'Please select cheque layout format.';
  2369.             }
  2370.             if (empty($errors)) {
  2371.                 $startCheck = (int)$startCheckRaw;
  2372.                 $endCheck $endCheckRaw === '' $startCheck : (int)$endCheckRaw;
  2373.                 if ($startCheck <= 0) {
  2374.                     $errors[] = 'Please enter a valid starting cheque number.';
  2375.                 } elseif ($endCheck $startCheck) {
  2376.                     $errors[] = 'Ending cheque number cannot be smaller than starting cheque number.';
  2377.                 } else {
  2378.                     for ($p $startCheck$p <= $endCheck$p++) {
  2379.                         $duplicate $em->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2380.                             ->createQueryBuilder('c')
  2381.                             ->where('c.accountsHeadId = :headId')
  2382.                             ->andWhere('c.checkNumber = :checkNumber')
  2383.                             ->setParameter('headId'$accountsHeadId)
  2384.                             ->setParameter('checkNumber'$p)
  2385.                             ->getQuery()
  2386.                             ->getOneOrNullResult();
  2387.                         if ($duplicate) {
  2388.                             $errors[] = 'Cheque number ' $p ' already exists for this account head.';
  2389.                             break;
  2390.                         }
  2391.                     }
  2392.                 }
  2393.             }
  2394.             if (!empty($errors)) {
  2395.                 $this->addFlash('error'implode(' '$errors));
  2396.             } else {
  2397.                 for ($p $startCheck$p <= $endCheck$p++) {
  2398.                     $new = new AccCheck();
  2399.                     $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2400.                     $new->setCheckNumber($p);
  2401.                     $new->setAccountsHeadId($accountsHeadId);
  2402.                     $new->setAccountNumber($accountNumber);
  2403.                     $new->setBookNumber($bookNumber);
  2404.                     $new->setActive(GeneralConstant::ACTIVE);
  2405.                     $new->setAssigned(0);
  2406.                     $new->setStatus(3); // pending. will stay like that till its bounced or confirmed transation physically
  2407.                     $new->setFormatId($formatId);
  2408.                     $new->setType(1);
  2409.                     $new->setDetails(1);
  2410.                     $em->persist($new);
  2411.                 }
  2412.                 $em->flush();
  2413.                 $this->addFlash('success''Cheque range added.');
  2414.             }
  2415.         }
  2416.         return $this->render(
  2417.             '@Accounts/pages/views/check_register.html.twig',
  2418.             array(
  2419.                 'page_title' => 'Cheque Register',
  2420.                 'head_list' => Accounts::HeadList($em),
  2421.                 'format_list' => Accounts::CheckFormatList($em),
  2422.             )
  2423.         );
  2424.     }
  2425.     public function BankGuaranteeList(Request $request)
  2426.     {
  2427.         $em $this->getDoctrine()->getManager();
  2428.         return $this->render(
  2429.             '@Application/pages/accounts/settings/bank_guarantee_list.html.twig',
  2430.             array(
  2431.                 'page_title' => 'Bank Guarantees',
  2432.                 'bgTypes' => AccountsConstant::$BankGuarnteeTypes,
  2433.             )
  2434.         );
  2435.     }
  2436.     public function BankGuaranteeView(Request $request$id 0)
  2437.     {
  2438.         $em $this->getDoctrine()->getManager();
  2439.         $check_here $this->getDoctrine()
  2440.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2441.             ->findOneBy(
  2442.                 array(
  2443.                     'CheckId' => $request->request->get('checkId'$id),
  2444.                     //                    'approved' =>  GeneralConstant::APPROVED,
  2445.                 )
  2446.             );
  2447.         $existingBidData null;
  2448.         if ($check_here->getOpportunityId()) {
  2449.             $lead $this->getDoctrine()
  2450.                 ->getRepository('ApplicationBundle\\Entity\\Opportunity')
  2451.                 ->findOneBy(
  2452.                     array(
  2453.                         'opportunityId' => $check_here->getOpportunityId(),
  2454.                         //                    'approved' =>  GeneralConstant::APPROVED,
  2455.                     )
  2456.                 );
  2457.             if ($lead)
  2458.                 $existingBidData json_decode($lead->getBidInformation(), true);
  2459.         }
  2460.         if ($existingBidData == null)
  2461.             $existingBidData = [];
  2462. //        return new JsonResponse($check_here);
  2463.         return $this->render(
  2464.             '@Application/pages/accounts/settings/view_bank_guarantee.html.twig',
  2465.             array(
  2466.                 'page_title' => 'Bank Guarantee',
  2467.                 'data' => $check_here,
  2468.                 'bgTypes' => AccountsConstant::$BankGuarnteeTypes,
  2469.                 'bidDataList' => SalesConstant::$bidDataList,
  2470.                 'existingBidData' => $existingBidData,
  2471.                 'head_list' => Accounts::getParentLedgerHeads($em),
  2472.             )
  2473.         );
  2474.     }
  2475.     public function ApproveBankGuarantee(Request $request$id 0)
  2476.     {
  2477.         $em $this->getDoctrine()->getManager();
  2478.         $success ProjectM::PaymentReceivedInstrumentApproveAction($em$id);
  2479.         return new JsonResponse(array('success' => $success));
  2480.     }
  2481.     public function CheckManagement(Request $request)
  2482.     {
  2483.         $em $this->getDoctrine()->getManager();
  2484.         if ($request->isMethod('POST')) {
  2485.             if ($request->request->has('carryForwardCheck')) {
  2486.                 $rows $request->request->get('checkNumber');
  2487.                 $accountsHeadIds $request->request->get('accountsHeadId', []);
  2488.                 $accountNumbers $request->request->get('accountNumber', []);
  2489.                 $bookNumbers $request->request->get('bookNumber', []);
  2490.                 $checkTypes $request->request->get('checkType', []);
  2491.                 $checkAmounts $request->request->get('checkAmount', []);
  2492.                 $checkDates $request->request->get('checkDate', []);
  2493.                 $checkNarrations $request->request->get('checkNarration', []);
  2494.                 $receivedHeads $request->request->get('receivedHead', []);
  2495.                 $errors = [];
  2496.                 $submittedKeys = [];
  2497.                 $parsedRows = [];
  2498.                 if (!is_array($rows) || count($rows) < 1) {
  2499.                     $errors[] = 'Please add at least one cheque row.';
  2500.                 } else {
  2501.                     foreach ($rows as $key => $value) {
  2502.                         $rowNo $key 1;
  2503.                         $checkNumber trim((string)$value);
  2504.                         $accountsHeadId = isset($accountsHeadIds[$key]) ? (int)$accountsHeadIds[$key] : 0;
  2505.                         $accountNumber = isset($accountNumbers[$key]) ? trim((string)$accountNumbers[$key]) : '';
  2506.                         $bookNumber = isset($bookNumbers[$key]) ? trim((string)$bookNumbers[$key]) : '';
  2507.                         $checkType = isset($checkTypes[$key]) ? trim((string)$checkTypes[$key]) : '';
  2508.                         $checkAmount = isset($checkAmounts[$key]) ? trim((string)$checkAmounts[$key]) : '';
  2509.                         $checkDateRaw = isset($checkDates[$key]) ? trim((string)$checkDates[$key]) : '';
  2510.                         $checkNarration = isset($checkNarrations[$key]) ? trim((string)$checkNarrations[$key]) : '';
  2511.                         $receivedHead = isset($receivedHeads[$key]) ? (int)$receivedHeads[$key] : 0;
  2512.                         if ($accountsHeadId <= 0) {
  2513.                             $errors[] = 'Please select bank account in row ' $rowNo '.';
  2514.                         }
  2515.                         if ($accountNumber === '') {
  2516.                             $errors[] = 'Please enter account number in row ' $rowNo '.';
  2517.                         }
  2518.                         if ($bookNumber === '') {
  2519.                             $errors[] = 'Please enter book number in row ' $rowNo '.';
  2520.                         }
  2521.                         if ($checkNumber === '' || !ctype_digit($checkNumber)) {
  2522.                             $errors[] = 'Please enter a valid cheque number in row ' $rowNo '.';
  2523.                         }
  2524.                         if ($checkType === '' || !in_array((int)$checkType, array(12), true)) {
  2525.                             $errors[] = 'Please select cheque type in row ' $rowNo '.';
  2526.                         }
  2527.                         if ($checkAmount === '' || !is_numeric($checkAmount) || (float)$checkAmount <= 0) {
  2528.                             $errors[] = 'Please enter a valid amount in row ' $rowNo '.';
  2529.                         }
  2530.                         if ($checkDateRaw === '') {
  2531.                             $errors[] = 'Please enter cheque date in row ' $rowNo '.';
  2532.                         }
  2533.                         if ($receivedHead <= 0) {
  2534.                             $errors[] = 'Please select assigned account in row ' $rowNo '.';
  2535.                         }
  2536.                         $duplicateKey $accountsHeadId '|' $checkNumber;
  2537.                         if ($checkNumber !== '' && isset($submittedKeys[$duplicateKey])) {
  2538.                             $errors[] = 'Cheque number ' $checkNumber ' is duplicated in the submitted rows.';
  2539.                         }
  2540.                         $submittedKeys[$duplicateKey] = 1;
  2541.                         if ($accountsHeadId && $checkNumber !== '' && ctype_digit($checkNumber)) {
  2542.                             $duplicate $em->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2543.                                 ->createQueryBuilder('c')
  2544.                                 ->where('c.accountsHeadId = :headId')
  2545.                                 ->andWhere('c.checkNumber = :checkNumber')
  2546.                                 ->setParameter('headId'$accountsHeadId)
  2547.                                 ->setParameter('checkNumber', (int)$checkNumber)
  2548.                                 ->getQuery()
  2549.                                 ->getOneOrNullResult();
  2550.                             if ($duplicate) {
  2551.                                 $errors[] = 'Cheque number ' $checkNumber ' already exists for this account head.';
  2552.                             }
  2553.                         }
  2554.                         try {
  2555.                             $checkDate = new \DateTime($checkDateRaw);
  2556.                         } catch (\Exception $e) {
  2557.                             $errors[] = 'Please enter a valid cheque date in row ' $rowNo '.';
  2558.                             $checkDate null;
  2559.                         }
  2560.                         $parsedRows[] = array(
  2561.                             'accountsHeadId' => $accountsHeadId,
  2562.                             'accountNumber' => $accountNumber,
  2563.                             'bookNumber' => $bookNumber,
  2564.                             'checkNumber' => $checkNumber,
  2565.                             'checkType' => $checkType,
  2566.                             'checkAmount' => $checkAmount,
  2567.                             'checkDate' => $checkDate,
  2568.                             'checkNarration' => $checkNarration,
  2569.                             'receivedHead' => $receivedHead,
  2570.                         );
  2571.                     }
  2572.                 }
  2573.                 if (empty($errors)) {
  2574.                     foreach ($parsedRows as $row) {
  2575.                         $new = new AccCheck();
  2576.                         $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2577.                         $new->setCheckNumber($row['checkNumber']);
  2578.                         $new->setAccountsHeadId($row['accountsHeadId']);
  2579.                         $new->setAccountNumber($row['accountNumber']);
  2580.                         $new->setBookNumber($row['bookNumber']);
  2581.                         $new->setActive(GeneralConstant::ACTIVE);
  2582.                         $new->setAssigned(1);
  2583.                         $new_id_list = [$row['receivedHead']];
  2584.                         $new->setRecAccountsHeadId($row['receivedHead']);
  2585.                         $new->setRecAccountsHeadIdList(json_encode($new_id_list));
  2586.                         $new->setCheckNarration($row['checkNarration']);
  2587.                         $new->setCheckAmount($row['checkAmount']);
  2588.                         $checkDate $row['checkDate'];
  2589.                         $new->setCheckDate($checkDate);
  2590.                         $new->setTransactionDate($checkDate);
  2591.                         $new->setLedgerHitDate($checkDate);
  2592.                         $new->setVoucherId(0);
  2593.                         $new->setStatus(3);
  2594.                         $new->setFormatId(0);
  2595.                         $new->setType($row['checkType']);
  2596.                         $new->setDetails(1);
  2597.                         $em->persist($new);
  2598.                     }
  2599.                     $em->flush();
  2600.                     $this->addFlash('success''Carry forward cheques added.');
  2601.                 } else {
  2602.                     $this->addFlash('error'implode(' 'array_unique($errors)));
  2603.                 }
  2604.             } else {
  2605.                 $startCheckRaw trim((string)$request->request->get('checkNumberStart'));
  2606.                 $endCheckRaw trim((string)$request->request->get('checkNumberEnd'));
  2607.                 $accountNumber trim((string)$request->request->get('accountNumber'));
  2608.                 $bookNumber trim((string)$request->request->get('bookNumber'));
  2609.                 $accountsHeadId = (int)$request->request->get('accountsHeadId');
  2610.                 $formatId = (int)$request->request->get('formatId');
  2611.                 $errors = [];
  2612.                 if ($accountsHeadId <= 0) {
  2613.                     $errors[] = 'Please select account.';
  2614.                 }
  2615.                 if ($accountNumber === '') {
  2616.                     $errors[] = 'Please enter account number.';
  2617.                 }
  2618.                 if ($bookNumber === '') {
  2619.                     $errors[] = 'Please enter cheque book number.';
  2620.                 }
  2621.                 if ($startCheckRaw === '' || !ctype_digit($startCheckRaw)) {
  2622.                     $errors[] = 'Please enter a valid starting cheque number.';
  2623.                 }
  2624.                 if ($endCheckRaw !== '' && !ctype_digit($endCheckRaw)) {
  2625.                     $errors[] = 'Please enter a valid ending cheque number.';
  2626.                 }
  2627.                 if ($formatId <= 0) {
  2628.                     $errors[] = 'Please select cheque layout format.';
  2629.                 }
  2630.                 if (empty($errors)) {
  2631.                     $startCheck = (int)$startCheckRaw;
  2632.                     $endCheck $endCheckRaw === '' $startCheck : (int)$endCheckRaw;
  2633.                     if ($startCheck <= 0) {
  2634.                         $errors[] = 'Please enter a valid starting cheque number.';
  2635.                     } elseif ($endCheck $startCheck) {
  2636.                         $errors[] = 'Ending cheque number cannot be smaller than starting cheque number.';
  2637.                     } else {
  2638.                         for ($p $startCheck$p <= $endCheck$p++) {
  2639.                             $duplicate $em->getRepository('ApplicationBundle\\Entity\\AccCheck')->findOneBy(array(
  2640.                                 'accountsHeadId' => $accountsHeadId,
  2641.                                 'accountNumber' => $accountNumber,
  2642.                                 'bookNumber' => $bookNumber,
  2643.                                 'checkNumber' => $p,
  2644.                                 'destroyed' => [0null],
  2645.                             ));
  2646.                             if ($duplicate) {
  2647.                                 $errors[] = 'Cheque number ' $p ' already exists for this account and book.';
  2648.                                 break;
  2649.                             }
  2650.                         }
  2651.                     }
  2652.                 }
  2653.                 if (empty($errors)) {
  2654.                     for ($p $startCheck$p <= $endCheck$p++) {
  2655.                         $new = new AccCheck();
  2656.                         $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2657.                         $new->setCheckNumber($p);
  2658.                         $new->setAccountsHeadId($accountsHeadId);
  2659.                         $new->setAccountNumber($accountNumber);
  2660.                         $new->setBookNumber($bookNumber);
  2661.                         $new->setActive(GeneralConstant::ACTIVE);
  2662.                         $new->setAssigned(0);
  2663.                         $new->setStatus(3);
  2664.                         $new->setFormatId($formatId);
  2665.                         $new->setType(1);
  2666.                         $new->setDetails(1);
  2667.                         $em->persist($new);
  2668.                     }
  2669.                     $em->flush();
  2670.                     $this->addFlash('success''Cheque range added.');
  2671.                 } else {
  2672.                     $this->addFlash('error'implode(' 'array_unique($errors)));
  2673.                 }
  2674.             }
  2675.         }
  2676.         return $this->render(
  2677.             '@Application/pages/accounts/settings/check_management.html.twig',
  2678.             array(
  2679.                 'page_title' => 'Cheque Management',
  2680.                 'head_list' => Accounts::getParentLedgerHeads($em),
  2681.                 'format_list' => Accounts::CheckFormatList($em),
  2682.             )
  2683.         );
  2684.     }
  2685.     public function CheckManagementEntryForApp(Request $request)
  2686.     {
  2687.         $em $this->getDoctrine()->getManager();
  2688.         if ($request->isMethod('POST')) {
  2689.             $check_number_list = [];
  2690.             if ($request->request->has('carryForwardCheck')) {
  2691.                 foreach ($request->request->get('checkNumber') as $key => $value) {
  2692.                     $new = new AccCheck();
  2693.                     $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2694.                     $new->setCheckNumber($value);
  2695.                     $new->setAccountsHeadId($request->request->get('accountsHeadId')[$key]);
  2696.                     $new->setAccountNumber($request->request->get('accountNumber')[$key]);
  2697.                     $new->setBookNumber($request->request->get('bookNumber')[$key]);
  2698.                     $new->setActive(GeneralConstant::ACTIVE);
  2699.                     $new->setAssigned(1);
  2700.                     $new_id_list = [$request->request->get('receivedHead')[$key]];
  2701.                     $new->setRecAccountsHeadId($request->request->get('receivedHead')[$key]);
  2702.                     $new->setRecAccountsHeadIdList(json_encode($new_id_list));
  2703.                     $new->setCheckNarration($request->request->get('checkNarration')[$key]);
  2704.                     $new->setCheckAmount($request->request->get('checkAmount')[$key]);
  2705.                     $new->setCheckDate(new \DateTime($request->request->get('checkDate')[$key]));
  2706.                     $new->setTransactionDate(new \DateTime($request->request->get('checkDate')[$key]));
  2707.                     $new->setLedgerHitDate(new \DateTime($request->request->get('checkDate')[$key]));
  2708.                     $new->setVoucherId(0);
  2709.                     $new->setStatus(3); // pending. will stay like that till its bounced or confirmed transation physically
  2710.                     $new->setFormatId(0);
  2711.                     $new->setType($request->request->get('checkType')[$key]);
  2712.                     $new->setDetails(1);
  2713.                     $em->persist($new);
  2714.                     $em->flush();
  2715.                 }
  2716.             } else if ($request->request->get('checkNumberEnd') != '')
  2717.                 for ($p $request->request->get('checkNumberStart'); $p <= $request->request->get('checkNumberEnd'); $p++) {
  2718.                     $new = new AccCheck();
  2719.                     $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2720.                     $new->setCheckNumber($p);
  2721.                     $new->setAccountsHeadId($request->request->get('accountsHeadId'));
  2722.                     $new->setAccountNumber($request->request->get('accountNumber'));
  2723.                     $new->setBookNumber($request->request->get('bookNumber'));
  2724.                     $new->setActive(GeneralConstant::ACTIVE);
  2725.                     $new->setAssigned(0);
  2726.                     $new->setStatus(3); // pending. will stay like that till its bounced or confirmed transation physically
  2727.                     $new->setFormatId($request->request->get('formatId'));
  2728.                     $new->setType(1);
  2729.                     $new->setDetails(1);
  2730.                     $em->persist($new);
  2731.                     $em->flush();
  2732.                 }
  2733.         }
  2734. //        return $this->render(
  2735. //            'ApplicationBundle:pages/accounts/settings:check_management.html.twig',
  2736. //            array(
  2737. //                'page_title' => 'Cheque Management',
  2738. //                'head_list' => Accounts::getParentLedgerHeads($em),
  2739. //                'format_list' => Accounts::CheckFormatList($em),
  2740. //            )
  2741. //        );
  2742.         return new JsonResponse([
  2743.             'success' => true,
  2744.         ]);
  2745.     }
  2746.     public function SecurityCheckManagement(Request $request)
  2747.     {
  2748.         $em $this->getDoctrine()->getManager();
  2749.         if ($request->isMethod('POST')) {
  2750.             $check_here $this->getDoctrine()
  2751.                 ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2752.                 ->findOneBy(
  2753.                     array(
  2754.                         'CheckId' => $request->request->get('checkId'),
  2755.                         //                    'approved' =>  GeneralConstant::APPROVED,
  2756.                     )
  2757.                 );
  2758.             if ($check_here) {
  2759.                 $ind_head_id_list $request->request->get('recAccountsHeadId');
  2760.                 $new_id_list = [];
  2761.                 foreach ($ind_head_id_list as $ind_head_id) {
  2762.                     $new_id_list[] = $ind_head_id;
  2763.                 }
  2764.                 $check_here->setRecAccountsHeadId(null);
  2765.                 $check_here->setRecAccountsHeadIdList(json_encode($new_id_list));
  2766.                 $check_here->setCheckNarration($request->request->get('check_narration'));
  2767.                 $check_here->setCheckAmount($request->request->get('check_assigned_amount'));
  2768.                 //                $check_here->setCheckDate(new \DateTime($request->request->get('checkDate')[$k]));
  2769.                 //                        $check_here->setCheckDate(new \DateTime($request->request->get('date')));
  2770.                 $check_here->setAssigned(1);
  2771.                 $check_here->setStatus(1); // pending. will stay like that till its bounced or confirmed transation physically
  2772.                 $check_here->setFormatId($request->request->get('formatId'));
  2773.                 $check_here->setType(1);
  2774.                 $check_here->setSecurityCheck(1);
  2775.                 $check_here->setDetails(1);
  2776.                 //                    $em->persist($new);
  2777.                 $em->flush();
  2778.             }
  2779.         }
  2780.         $sec_check $this->getDoctrine()
  2781.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2782.             ->findBy(
  2783.                 array(
  2784.                     'active' => GeneralConstant::ACTIVE,
  2785.                     'assigned' => [0null],
  2786.                     'destroyed' => [0null],
  2787.                     'securityCheck' => [0null],
  2788.                     'type' => 1,
  2789.                     //                    'approved' =>  GeneralConstant::APPROVED,
  2790.                 )
  2791.             );
  2792.         $assignable_check_list = [];
  2793.         foreach ($sec_check as $s) {
  2794.             $assignable_check_list[] = array(
  2795.                 'checkId' => $s->getCheckId(),
  2796.                 'id' => $s->getCheckId(),
  2797.                 'value' => $s->getCheckId(),
  2798.                 'accountsHeadId' => $s->getAccountsHeadId(),
  2799.                 'text' => $s->getAccountNumber() . "-" sprintf("%07d"$s->getCheckNumber()),
  2800.                 'name' => $s->getAccountNumber() . "-" sprintf("%07d"$s->getCheckNumber())
  2801.             );
  2802.         }
  2803.         return $this->render(
  2804.             '@Application/pages/accounts/settings/security_check.html.twig',
  2805.             array(
  2806.                 'page_title' => 'Security Cheque Management',
  2807.                 'assignableCheckList' => $assignable_check_list,
  2808.                 'heads' => Accounts::getLedgerHeadsWithParents($em),
  2809.                 'format_list' => Accounts::CheckFormatList($em),
  2810.             )
  2811.         );
  2812.     }
  2813.     public function ChequeListAjax(Request $request)
  2814.     {
  2815.         $em $this->getDoctrine()->getManager();
  2816.         $allowed_ids = [];
  2817.         $companyId $this->getLoggedUserCompanyId($request);
  2818.         $viewOption 1;
  2819.         if ($request->query->has('viewOption'))
  2820.             $viewOption $request->query->get('viewOption');
  2821.         $listData Accounts::GetChequetListForChequeListAjax($em$viewOption$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  2822.         //        if ($request->isMethod('POST'))
  2823.         {
  2824.             if ($request->query->has('dataTableQry')) {
  2825.                 return new JsonResponse(
  2826.                     $listData
  2827.                 );
  2828.             }
  2829.         }
  2830.         return $this->render(
  2831.             '@Sales/pages/list_tables/client_list.html.twig',
  2832.             //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  2833.             array(
  2834.                 'page_title' => 'Cheque List',
  2835.             )
  2836.         );
  2837.     }
  2838.     public function GetCheckList(Request $request)
  2839.     {
  2840.         $em $this->getDoctrine()->getManager();
  2841.         if ($request->isMethod('POST')) {
  2842.             $head_list Accounts::HeadList($em);
  2843.             $voucher_list Accounts::VoucherListForCheckRegister($em);
  2844.             $find_array = array(
  2845.                 'type' => 1
  2846.             );
  2847.             if ($request->request->has('viewOption')) {
  2848.                 if ($request->request->get('viewOption') == 1)
  2849.                     $find_array = ['active' => GeneralConstant::ACTIVE];
  2850.                 if ($request->request->get('viewOption') == 2)
  2851.                     $find_array = ['active' => GeneralConstant::INACTIVE];
  2852.             }
  2853.             $assignedflag $request->request->has('assign_flag') ? $request->request->get('assign_flag') : 0;
  2854.             $unassignedflag $request->request->has('unassign_flag') ? $request->request->get('unassign_flag') : 0;
  2855.             $securityCheckFlag $request->request->has('security_check_flag') ? $request->request->get('security_check_flag') : 0;
  2856.             if ($assignedflag == 1)
  2857.                 $find_array['assigned'] = 1;
  2858.             if ($unassignedflag == 1)
  2859.                 $find_array['assigned'] = [0null];
  2860.             if ($securityCheckFlag == 1)
  2861.                 $find_array['securityCheck'] = 1;
  2862.             $check_query $this->getDoctrine()
  2863.                 ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2864.                 ->findBy(
  2865.                     $find_array,
  2866.                     array(
  2867.                         //                        'checkNumber'=>'ASC'
  2868.                         'CheckId' => 'ASC'
  2869.                     )
  2870.                 );
  2871.             $check_data = [];
  2872.             $start_date $request->request->has('start_date') ? (new \DateTime($request->request->get('start_date'))) : '';
  2873.             $end_date $request->request->has('end_date') ? (new \DateTime($request->request->get('end_date') . ' ' ' 23:59:59.999')) : '';
  2874.             //            if($end_date!='')
  2875.             //                $end_date->modify('+1 day');
  2876.             $book_list_by_bank = [];
  2877.             foreach ($check_query as $entry) {
  2878.                 if ($assignedflag == 1) {
  2879.                     if ($securityCheckFlag == 0) {
  2880.                         $checkTransDate $entry->getTransactionDate();
  2881.                         if ($checkTransDate == null)
  2882.                             continue;
  2883.                         if ($start_date != '' && ($checkTransDate instanceof \DateTime) && ($start_date $checkTransDate))
  2884.                             continue;
  2885.                         if ($end_date != '' && ($checkTransDate instanceof \DateTime) && ($end_date $checkTransDate))
  2886.                             continue;
  2887.                     }
  2888.                 }
  2889.                 $v_date = isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['date'] : '';
  2890.                 //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2891.                 if ($start_date != '' && ($v_date instanceof \DateTime) && ($start_date $v_date))
  2892.                     continue;
  2893.                 //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2894.                 if ($end_date != '' && ($v_date instanceof \DateTime) && ($end_date $v_date))
  2895.                     continue;
  2896.                 $checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
  2897.                 $assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
  2898.                 if (!isset($book_list_by_bank[$entry->getAccountsHeadId()])) $book_list_by_bank[$entry->getAccountsHeadId()] = [];
  2899.                 if (!in_array($entry->getBookNumber(), $book_list_by_bank[$entry->getAccountsHeadId()])) {
  2900.                     $book_list_by_bank[$entry->getAccountsHeadId()][] = $entry->getBookNumber();
  2901.                 }
  2902.                 $check_data[] = array(
  2903.                     'checkId' => $entry->getCheckId(),
  2904.                     //                    'checkNumber'=>$entry->getCheckNumber(),
  2905.                     'checkNumber' => sprintf("%07d"$entry->getCheckNumber()),
  2906.                     'checkNarration' => $entry->getCheckNarration(),
  2907.                     'voucherNarration' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['desc'] : '',
  2908.                     'voucherDate' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['date']->format('m/d/Y') : '',
  2909.                     'accountNumber' => $entry->getAccountNumber(),
  2910.                     'checkDate' => $checkDate,
  2911.                     'active' => $entry->getActive(),
  2912.                     'head' => isset($head_list[$entry->getAccountsHeadId()]) ? $head_list[$entry->getAccountsHeadId()]['name'] : '',
  2913.                     'head_id' => $entry->getAccountsHeadId(),
  2914.                     'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
  2915.                     'received_head_id' => $entry->getRecAccountsHeadId(),
  2916.                     'received_head_id_list' => $entry->getRecAccountsHeadIdList(),
  2917.                     'assignedDate' => $assignedDate,
  2918.                     'checkAmount' => $entry->getCheckAmount(),
  2919.                     'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
  2920.                     'voucher_id' => $entry->getVoucherId(),
  2921.                     'printed' => $entry->getPrinted(),
  2922.                 );
  2923.             }
  2924.             $count_details_by_bank = [];
  2925.             if ($request->request->has('countDetails')) {
  2926.                 $check_query $this->getDoctrine()
  2927.                     ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2928.                     ->findAll();
  2929.                 $count_details_by_bank = [];
  2930.                 $assigned_books = [];
  2931.                 foreach ($check_query as $entry) {
  2932.                     if (isset($count_details_by_bank[$entry->getAccountsHeadId()])) {
  2933.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_chk'] += 1;
  2934.                         if ($entry->getAssigned() == 1)
  2935.                             $count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] += 1;
  2936.                         else
  2937.                             $count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] += 1;
  2938.                         if (!in_array($entry->getBookNumber(), $assigned_books)) {
  2939.                             $count_details_by_bank[$entry->getAccountsHeadId()]['books'] .= (', ' $entry->getBookNumber());
  2940.                             array_push($assigned_books$entry->getBookNumber());
  2941.                         }
  2942.                     } else {
  2943.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_chk'] = 1;
  2944.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] = 0;
  2945.                         $count_details_by_bank[$entry->getAccountsHeadId()]['books'] = '';
  2946.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] = 0;
  2947.                         if ($entry->getAssigned() == 1)
  2948.                             $count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] = 1;
  2949.                         else
  2950.                             $count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] = 1;
  2951.                         if (!in_array($entry->getBookNumber(), $assigned_books)) {
  2952.                             $count_details_by_bank[$entry->getAccountsHeadId()]['books'] = (' ' $entry->getBookNumber());
  2953.                             array_push($assigned_books$entry->getBookNumber());
  2954.                         }
  2955.                     }
  2956.                 }
  2957.             }
  2958.             if ($securityCheckFlag == 0) {
  2959.                 foreach ($voucher_list as $key => $entry) {
  2960.                     $v_date $entry['date'];
  2961.                     //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2962.                     if ($start_date != '' && ($v_date instanceof \DateTime) && ($start_date $v_date))
  2963.                         continue;
  2964.                     //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2965.                     if ($end_date != '' && ($v_date instanceof \DateTime) && ($end_date $v_date))
  2966.                         continue;
  2967.                     if (!in_array($entry['prMethod'], [34]))
  2968.                         continue;
  2969.                     //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2970.                     //                    continue;
  2971.                     //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2972.                     //                    continue;
  2973.                     $trans_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  2974.                         array(
  2975.                             'transactionId' => $key,
  2976.                             'position' => 'cr'
  2977.                         )
  2978.                     );
  2979.                     foreach ($trans_details as $value) {
  2980.                         $checkDate $entry['date']->format('m/d/Y');
  2981.                         $assignedDate $entry['date']->format('m/d/Y');
  2982.                         $dr_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  2983.                             array(
  2984.                                 'transactionId' => $key,
  2985.                                 'position' => 'dr'
  2986.                             )
  2987.                         );
  2988.                         $rec_id_list = [];
  2989.                         $rec_narr "";
  2990.                         foreach ($dr_details as $dt) {
  2991.                             $rec_id_list[] = $dt->getAccountsHeadId();
  2992.                             $rec_narr .= $head_list[$dt->getAccountsHeadId()]['name'];
  2993.                             $rec_narr .= ", ";
  2994.                         }
  2995.                         $check_data[] = array(
  2996.                             'checkId' => 0,
  2997.                             'checkNumber' => $entry['prReference'],
  2998.                             'checkNarration' => $rec_narr,
  2999.                             'voucherNarration' => $entry['desc'],
  3000.                             'voucherDate' => $entry['date']->format('m/d/Y'),
  3001.                             'accountNumber' => '',
  3002.                             'checkDate' => $checkDate,
  3003.                             'head' => $head_list[$value->getAccountsHeadId()]['name'],
  3004.                             'head_id' => $value->getAccountsHeadId(),
  3005.                             'received_head' => $rec_narr,
  3006.                             'received_head_id' => 0,
  3007.                             'received_head_id_list' => json_encode($rec_id_list),
  3008.                             'assignedDate' => $assignedDate,
  3009.                             'checkAmount' => $value->getAmount(),
  3010.                             'voucher_number' => $entry['doc_hash'],
  3011.                             'voucher_id' => $key,
  3012.                             'printed' => 1,
  3013.                         );
  3014.                     }
  3015.                 }
  3016.             }
  3017.             if ($check_data) {
  3018.                 return new JsonResponse(array("success" => true"content" => $check_data'book_list_by_bank' => $book_list_by_bank'c_d_b_b' => $count_details_by_bank'head_list' => $head_list));
  3019.             }
  3020.             return new JsonResponse(array("success" => false'start_date' => $start_date'end_date' => $end_date,));
  3021.         }
  3022.         return new JsonResponse(array("success" => false));
  3023.     }
  3024.     public function GetCheckListForVoucher(Request $request)
  3025.     {
  3026.         $em $this->getDoctrine()->getManager();
  3027.         if ($request->isMethod('POST')) {
  3028.             $cr_table_heads $request->request->get('cr_table_heads', []);
  3029.             $dr_table_heads $request->request->get('dr_table_heads', []);
  3030.             $voucher_heads = [];
  3031.             $v_id $request->request->get('v_id'0);
  3032.             $voucher_list Accounts::VoucherList($em$v_id1);
  3033.             foreach ($voucher_list as $t) {
  3034.                 foreach ($t['det'] as $td)
  3035.                     $voucher_heads[] = $td['head_id'];
  3036.             }
  3037.             $head_list Accounts::HeadList($emarray_merge($cr_table_heads$dr_table_heads$voucher_heads));
  3038.             $checkAssignType $request->request->get('checkAssignType');
  3039.             $cr_table_heads_amount $request->request->get('cr_table_heads_amount');
  3040.             $check_list = [];
  3041.             $check_list_array = [];
  3042.             $check_list_by_ac_head = [];
  3043.             if ($request->request->get('checkModalType') == 'edit') {
  3044.                 //first check if the voucher is already tagged ( usually for edit)
  3045.                 if ($v_id != 0) {
  3046.                     $check_query $this->getDoctrine()
  3047.                         ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  3048.                         ->findBy(
  3049.                             array(
  3050.                                 'voucherId' => $v_id,
  3051.                                 'active' => GeneralConstant::ACTIVE,
  3052.                                 'destroyed' => [0null],
  3053.                                 'securityCheck' => [0null],
  3054.                             ),
  3055.                             array(
  3056.                                 //                            'checkNumber'=>'ASC'
  3057.                                 'CheckId' => 'ASC'
  3058.                             )
  3059.                         );
  3060.                     foreach ($check_query as $entry) {
  3061.                         $checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
  3062.                         $assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
  3063.                         $chk = array(
  3064.                             'checkId' => $entry->getCheckId(),
  3065.                             'checkNumber' => sprintf("%07d"$entry->getCheckNumber()),
  3066.                             'accountNumber' => $entry->getAccountNumber(),
  3067.                             'checkDate' => $checkDate,
  3068.                             'head' => $head_list[$entry->getAccountsHeadId()]['name'],
  3069.                             'head_id' => $entry->getAccountsHeadId(),
  3070.                             'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
  3071.                             'received_head_id' => $entry->getRecAccountsHeadId(),
  3072.                             'received_head_id_list' => $entry->getRecAccountsHeadIdList(),
  3073.                             'assignedDate' => $assignedDate,
  3074.                             'checkAmount' => $entry->getCheckAmount(),
  3075.                             'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
  3076.                             'voucher_id' => $entry->getVoucherId(),
  3077.                         );
  3078.                         $check_list_by_ac_head[$entry->getAccountsHeadId()][] = $chk;
  3079.                         $check_list[$entry->getCheckId()] = $chk;
  3080.                     }
  3081.                 }
  3082.                 //now getting un assigned checks for the same heads
  3083.                 $check_query $this->getDoctrine()
  3084.                     ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  3085.                     ->findBy(
  3086.                         array(
  3087.                             'accountsHeadId' => $cr_table_heads,
  3088.                             'active' => GeneralConstant::ACTIVE,
  3089.                             'assigned' => [0null],
  3090.                             'destroyed' => [0null],
  3091.                             'securityCheck' => [0null],
  3092.                         ),
  3093.                         array(
  3094.                             //                            'checkNumber'=>'ASC'
  3095.                             'CheckId' => 'ASC'
  3096.                         )
  3097.                     );
  3098.                 foreach ($check_query as $entry) {
  3099.                     $checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
  3100.                     $assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
  3101.                     $chk = array(
  3102.                         'checkId' => $entry->getCheckId(),
  3103.                         'checkNumber' => sprintf("%07d"$entry->getCheckNumber()),
  3104.                         'accountNumber' => $entry->getAccountNumber(),
  3105.                         'checkDate' => $checkDate,
  3106.                         'head' => $head_list[$entry->getAccountsHeadId()]['name'],
  3107.                         'head_id' => $entry->getAccountsHeadId(),
  3108.                         'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
  3109.                         'received_head_id' => $entry->getRecAccountsHeadId(),
  3110.                         'assignedDate' => $assignedDate,
  3111.                         'checkAmount' => $entry->getCheckAmount(),
  3112.                         'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
  3113.                         'voucher_id' => $entry->getVoucherId(),
  3114.                     );
  3115.                     $check_list_by_ac_head[$entry->getAccountsHeadId()][] = $chk;
  3116.                     $check_list[$entry->getCheckId()] = $chk;
  3117.                 }
  3118.                 //                if(empty($check_query))
  3119.                 if ($check_list) {
  3120.                     return new JsonResponse(array(
  3121.                         "success" => true,
  3122.                         "content" => $check_list,
  3123.                         "check_list_by_ac_head" => $check_list_by_ac_head,
  3124.                         "check_list" => $check_list,
  3125.                         'head_list' => $head_list
  3126.                     ));
  3127.                 }
  3128.             }
  3129.             if ($request->request->get('checkModalType') == 'view') {
  3130.                 $check_query $this->getDoctrine()
  3131.                     ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  3132.                     ->findBy(
  3133.                         array(
  3134.                             'voucherId' => $v_id
  3135.                         )
  3136.                     );
  3137.                 foreach ($check_query as $entry) {
  3138.                     $checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
  3139.                     $assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
  3140.                     $chk = array(
  3141.                         'checkId' => $entry->getCheckId(),
  3142.                         'checkNumber' => sprintf("%07d"$entry->getCheckNumber()),
  3143.                         'accountNumber' => $entry->getAccountNumber(),
  3144.                         'checkDate' => $checkDate,
  3145.                         'checkNarration' => $entry->getCheckNarration(),
  3146.                         'head' => $head_list[$entry->getAccountsHeadId()]['name'],
  3147.                         'head_id' => $entry->getAccountsHeadId(),
  3148.                         'printed' => $entry->getPrinted(),
  3149.                         'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
  3150.                         'received_head_id' => $entry->getRecAccountsHeadId(),
  3151.                         'received_head_id_list' => $entry->getRecAccountsHeadIdList(),
  3152.                         'assignedDate' => $assignedDate,
  3153.                         'checkAmount' => $entry->getCheckAmount(),
  3154.                         'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
  3155.                         'voucher_id' => $entry->getVoucherId(),
  3156.                     );
  3157.                     $check_list_by_ac_head[$entry->getAccountsHeadId()][] = $chk;
  3158.                     $check_list[$entry->getCheckId()] = $chk;
  3159.                     $check_list_array[] = $chk;
  3160.                 }
  3161.                 if (!empty($check_list)) {
  3162.                     return new JsonResponse(array(
  3163.                         "success" => true,
  3164.                         "content" => $check_list,
  3165.                         //                        "check_list_by_ac_head"=>$check_list_by_ac_head,
  3166.                         "check_list" => $check_list_array,
  3167.                         'head_list' => $head_list
  3168.                     ));
  3169.                 }
  3170.             }
  3171.             return new JsonResponse(array("success" => false));
  3172.         }
  3173.         return new JsonResponse(array("success" => false));
  3174.     }
  3175.     public function GetCheckListForBrs(Request $request)
  3176.     {
  3177.         $em $this->getDoctrine()->getManager();
  3178.         if ($request->isMethod('POST')) {
  3179.             $bank_head $request->request->get('bank_head');
  3180.             $statement_date $request->request->get('statement_date');
  3181.             $statement_date_dt = new \DateTime($statement_date);
  3182.             $statement_date_str $statement_date_dt->format('Y-m-d');
  3183.             $head_list Accounts::HeadList($em);
  3184.             //            $voucher_list=Accounts::VoucherList($em);
  3185.             $voucher_list Accounts::VoucherListForBrs($em$bank_head);
  3186.             $check_list = [];
  3187.             $check_list_array = [];
  3188.             $check_list_by_ac_head = [];
  3189.             $get_kids_sql "SELECT * FROM acc_check ";
  3190.             //            $get_kids_sql.="  Where status=3 and check_date <='".$statement_date_str." 00:00:00' and ( rec_accounts_head_id=".$bank_head;
  3191.             $get_kids_sql .= "  Where status=3 and ledger_hit_date <='" $statement_date_str " 00:00:00' and ( rec_accounts_head_id=" $bank_head;
  3192.             //            $get_kids_sql.="  Where status=3 and transaction_date <='".$statement_date_str." 00:00:00' and ( rec_accounts_head_id=".$bank_head;
  3193.             $get_kids_sql .= "  or accounts_head_id=" $bank_head ") ";
  3194.             $get_kids_sql .= ' ORDER BY check_id ASC';
  3195.             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  3196.             
  3197.             $query_output $stmt;
  3198.             if (!empty($query_output)) {
  3199.                 foreach ($query_output as $entry) {
  3200.                     //                    if($entry['type']==1)
  3201.                     //                    {
  3202.                     //                        $sub=($entry['rec_accounts_head_id']==$bank_head?0:$entry['check_amount']);
  3203.                     //                        $add=($entry['rec_accounts_head_id']==$bank_head?$entry['check_amount']:0);
  3204.                     //                    }
  3205.                     //                    if($entry['type']==2)
  3206.                     //                    {
  3207.                     $sub = ($entry['rec_accounts_head_id'] == $bank_head $entry['check_amount']);
  3208.                     $add = ($entry['rec_accounts_head_id'] == $bank_head $entry['check_amount'] : 0);
  3209.                     //                    }
  3210.                     $checkDate = ($entry['check_date'] instanceof \DateTime) ? $entry['check_date']->format('m-d-Y') : (new \DateTime($entry['check_date']))->format('m-d-Y');
  3211.                     $assignedDate = ($entry['assigned_date'] instanceof \DateTime) ? $entry['assigned_date']->format('m-d-Y') : '';
  3212.                     $chk = array(
  3213.                         'checkId' => $entry['check_id'],
  3214.                         'checkNumber' => $entry['check_number'],
  3215.                         'accountNumber' => $entry['acc_number'],
  3216.                         'checkDate' => $checkDate,
  3217.                         'head' => $head_list[$entry['accounts_head_id']]['name'],
  3218.                         'head_id' => $entry['accounts_head_id'],
  3219.                         'check_type' => $entry['type'],
  3220.                         'received_head' => isset($head_list[$entry['rec_accounts_head_id']]) ? $head_list[$entry['rec_accounts_head_id']]['name'] : '',
  3221.                         'received_head_id' => $entry['rec_accounts_head_id'],
  3222.                         'assignedDate' => $assignedDate,
  3223.                         'checkAmount' => $entry['check_amount'],
  3224.                         'sub' => $sub,
  3225.                         'add' => $add,
  3226.                         'received_head_id_list' => ($entry['rec_accounts_head_id_list'] == null) ? [] : json_decode($entry['rec_accounts_head_id_list'], true),
  3227.                         'voucherNumber' => isset($voucher_list[$entry['voucher_id']]) ? $voucher_list[$entry['voucher_id']]['doc_hash'] : '',
  3228.                         'voucherDate' => isset($voucher_list[$entry['voucher_id']]) ? $voucher_list[$entry['voucher_id']]['date']->format('m-d-Y') : '',
  3229.                         'transactionDate' => isset($voucher_list[$entry['voucher_id']]) ? $voucher_list[$entry['voucher_id']]['date']->format('m-d-Y') : '',
  3230.                         'voucher_id' => $entry['voucher_id'],
  3231.                     );
  3232.                     //                    $check_list_by_ac_head[$entry->getAccountsHeadId()][]=$chk;
  3233.                     $check_list[$entry['check_id']] = $chk;
  3234.                     $check_list_array[] = $chk;
  3235.                 }
  3236.             }
  3237.             foreach ($voucher_list as $key => $entry) {
  3238.                 $v_date $entry['date'];
  3239.                 $l_date $entry['ledgerHitDate'];
  3240.                 if ($l_date == null)
  3241.                     $l_date $v_date;
  3242.                 //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  3243.                 //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  3244.                 if ($entry['ledgerHit'] != 1)
  3245.                     continue;
  3246.                 if ($statement_date_dt != '' && ($l_date instanceof \DateTime) && ($statement_date_dt $l_date))
  3247.                     continue;
  3248.                 if ($entry['document_type'] != 6) {
  3249.                     if (!in_array($entry['prMethod'], [34]))
  3250.                         continue;
  3251.                 }
  3252.                 if ($entry['document_type'] == 6) {
  3253.                     if (!in_array($entry['prMethod'], [1]))
  3254.                         continue;
  3255.                 }
  3256.                 if ($entry['provisional'] != 1)
  3257.                     continue;
  3258.                 if (!in_array($bank_head$entry['pendReconIdList']))
  3259.                     continue;
  3260.                 //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  3261.                 //                    continue;
  3262.                 //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  3263.                 //                    continue;
  3264.                 if ($entry['document_type'] == || $entry['document_type'] == 6)
  3265.                     $trans_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  3266.                         array(
  3267.                             'transactionId' => $key,
  3268.                             'position' => 'cr',
  3269.                             //                        'accountsHeadId'=>$bank_head
  3270.                         )
  3271.                     );
  3272.                 else
  3273.                     $trans_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  3274.                         array(
  3275.                             'transactionId' => $key,
  3276.                             'position' => 'cr',
  3277.                             'accountsHeadId' => $bank_head
  3278.                         )
  3279.                     );
  3280.                 if (!empty($trans_details)) {
  3281.                     foreach ($trans_details as $k2 => $value) {
  3282.                         $checkDate $entry['date']->format('m/d/Y');
  3283.                         if ($l_date != null)
  3284.                             $ledgerHitDate $entry['ledgerHitDate']->format('m/d/Y');
  3285.                         else
  3286.                             $ledgerHitDate $entry['date']->format('m/d/Y');
  3287.                         $assignedDate $entry['date']->format('m/d/Y');
  3288.                         $dr_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  3289.                             array(
  3290.                                 'transactionId' => $key,
  3291.                                 'position' => 'dr'
  3292.                             )
  3293.                         );
  3294.                         $rec_id_list = [];
  3295.                         $rec_narr "";
  3296.                         foreach ($dr_details as $dt) {
  3297.                             $rec_id_list[] = $dt->getAccountsHeadId();
  3298.                             $rec_narr .= $head_list[$dt->getAccountsHeadId()]['name'];
  3299.                             $rec_narr .= ", ";
  3300.                         }
  3301.                         $chk = array(
  3302.                             'checkId' => 'v' $key "_" $value->getTransactionDetailsId(),
  3303.                             'checkNumber' => $entry['prReference'],
  3304.                             'prRef' => $entry['earlyPrReference'],
  3305.                             'accountNumber' => '',
  3306.                             'sub' => ($value->getAccountsHeadId() == $bank_head) ? $value->getAmount() : 0,
  3307.                             'add' => ($value->getAccountsHeadId() != $bank_head) ? $value->getAmount() : 0,
  3308.                             'checkDate' => $ledgerHitDate,
  3309.                             'head' => $head_list[$value->getAccountsHeadId()]['name'],
  3310.                             'head_id' => $value->getAccountsHeadId(),
  3311.                             'check_type' => 1,
  3312.                             'received_head' => $rec_narr,
  3313.                             'received_head_id' => 0,
  3314.                             'received_head_id_list' => $rec_id_list,
  3315.                             //                            'received_head_id_list' => json_encode($rec_id_list),
  3316.                             'assignedDate' => $assignedDate,
  3317.                             'checkAmount' => $value->getAmount(),
  3318.                             'voucherNumber' => $entry['doc_hash'],
  3319.                             'voucherDate' => $v_date->format('m-d-Y'),
  3320.                             'transactionDate' => $v_date->format('m-d-Y'),
  3321.                             'voucher_id' => $key,
  3322.                         );
  3323.                         //                    $check_list_by_ac_head[$entry->getAccountsHeadId()][]=$chk;
  3324.                         $check_list['v' $key "_" $value->getTransactionDetailsId()] = $chk;
  3325.                         $check_list_array[] = $chk;
  3326.                     }
  3327.                 }
  3328.             }
  3329.             ///old
  3330.             //            $get_kids_sql="select acc_closing_balance.balance, acc_closing_balance.opening, acc_closing_balance.date,
  3331.             //                        acc_accounts_head.path_tree,
  3332.             //                        acc_accounts_head.head_nature
  3333.             //                        from acc_closing_balance
  3334.             //                        join acc_accounts_head on acc_accounts_head.accounts_head_id=acc_closing_balance.accounts_head_id ";
  3335.             ////        $get_kids_sql.=" Where parent_id in(".implode(",", $path_array).")";
  3336.             //            $get_kids_sql.=" where  acc_accounts_head.accounts_head_id=".$bank_head;
  3337.             //
  3338.             //                $get_kids_sql .=" AND acc_closing_balance.date <='".$statement_date_str." 00:00:00' ";
  3339.             //
  3340.             //
  3341.             //
  3342.             //            $get_kids_sql.=" Order by acc_closing_balance.date desc LIMIT 1";
  3343.             //            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  3344.             //            
  3345.             //            $query_output = $stmt;
  3346.             ///old end
  3347.             $head_last_balance_data = [];
  3348.             $head_last_balance 0;
  3349.             //new method
  3350.             $balance_data Accounts::GetBalanceOnDate($em$statement_date_str, []);
  3351.             $head_last_balance $balance_data[$bank_head]['end_balance']['balance'];
  3352.             //new end
  3353.             //            if(!empty($query_output))
  3354.             //            {
  3355.             //                $head_last_balance_data=$query_output[0]   ;
  3356.             //                $head_last_balance=$query_output[0]['balance']   ;
  3357.             //            }
  3358.             //            else
  3359.             //            {
  3360.             //                $head_last_balance_data=array()   ;
  3361.             //                $head_last_balance=$head_list[$bank_head]['opening_balance']   ;
  3362.             //            }
  3363.             //                if($check_list){
  3364.             if ($check_list || $head_last_balance != 0) {
  3365.                 return new JsonResponse(array(
  3366.                     "success" => true,
  3367.                     "content" => $check_list,
  3368.                     //                        "check_list_by_ac_head"=>$check_list_by_ac_head,
  3369.                     'def_date' => $statement_date_dt->format('F d, Y'),
  3370.                     "check_list" => $check_list,
  3371.                     "check_list_array" => $check_list_array,
  3372.                     'head_list' => $head_list,
  3373.                     'head_last_balance_data' => $head_last_balance_data,
  3374.                     'head_last_balance' => $head_last_balance,
  3375.                 ));
  3376.             }
  3377.             return new JsonResponse(array("success" => false));
  3378.         }
  3379.         return new JsonResponse(array("success" => false));
  3380.     }
  3381.     public function CreatePurchaseInvoice(Request $request$id 0)
  3382.     {
  3383.         $em $this->getDoctrine()->getManager();
  3384.         if ($request->isMethod('POST')) {
  3385.             $data $request->request;
  3386.             $entity_id array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice']; //change
  3387.             $dochash $request->request->get('docHash'); //change
  3388.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3389.             $approveRole $request->request->get('approvalRole');
  3390.             $approveHash $request->request->get('approvalHash');
  3391.             if (!DocValidation::isInsertable(
  3392.                 $em,
  3393.                 $entity_id,
  3394.                 $dochash,
  3395.                 $loginId,
  3396.                 $approveRole,
  3397.                 $approveHash,
  3398.                 $id
  3399.             )) {
  3400.                 $this->addFlash(
  3401.                     'error',
  3402.                     'Sorry Couldnot insert Data.'
  3403.                 );
  3404.             } else {
  3405.                 $funcname 'PurchaseInvoice';
  3406.                 $doc_id $id;
  3407.                 DeleteDocument::$funcname($em$doc_id0);
  3408.                 $create_new_pi Accounts::CreatePurchaseInvoice($id$this->getDoctrine()->getManager(), $data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3409.                 //now add Approval info
  3410.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3411.                 $approveRole $request->request->get('approvalRole');
  3412.                 $options = array(
  3413.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3414.                     'notification_server' => $this->container->getParameter('notification_server'),
  3415.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3416.                     'url' => $this->generateUrl(
  3417.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice']]['entity_view_route_path_name']
  3418.                     )
  3419.                 );
  3420.                 System::setApprovalInfo(
  3421.                     $this->getDoctrine()->getManager(),
  3422.                     $options,
  3423.                     array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
  3424.                     $create_new_pi['pi_id'],
  3425.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3426.                 );
  3427.                 System::createEditSignatureHash(
  3428.                     $this->getDoctrine()->getManager(),
  3429.                     array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
  3430.                     $create_new_pi['pi_id'],
  3431.                     $loginId,
  3432.                     $approveRole,
  3433.                     $request->request->get('approvalHash')
  3434.                 );
  3435.                 $this->addFlash(
  3436.                     'success',
  3437.                     'New Invoice Added.'
  3438.                 );
  3439.                 $url $this->generateUrl(
  3440.                     'view_purchase_invoice'
  3441.                 );
  3442.                 System::AddNewNotification(
  3443.                     $this->container->getParameter('notification_enabled'),
  3444.                     $this->container->getParameter('notification_server'),
  3445.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  3446.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  3447.                     "Purchase Invoice : " $dochash " Has Been Created And is Under Processing",
  3448.                     'pos',
  3449.                     System::getPositionIdsByDepartment($em, [GeneralConstant::ACCOUNTS_DEPARTMENTGeneralConstant::PURCHASE_DEPARTMENT]),
  3450.                     'success',
  3451.                     $url "/" $create_new_pi['pi_id'],
  3452.                     "Purchase Bill"
  3453.                 );
  3454.                 return $this->redirect($url "/" $create_new_pi['pi_id']);
  3455.             }
  3456.         }
  3457.         $extData = [];
  3458.         $extDetailsData = [];
  3459.         if ($id == 0) {
  3460.         } else {
  3461.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')->findOneBy(
  3462.                 array(
  3463.                     'purchaseInvoiceId' => $id///material
  3464.                 )
  3465.             );
  3466.             //now if its not editable, redirect to view
  3467.             if ($extTrans) {
  3468.                 if ($extTrans->getEditFlag() != 1) {
  3469.                     $url $this->generateUrl(
  3470.                         'view_purchase_invoice'
  3471.                     );
  3472.                     return $this->redirect($url "/" $id);
  3473.                 } else {
  3474.                     $extData $extTrans;
  3475.                     $extDetailsData $em->getRepository('ApplicationBundle\\Entity\\PurchaseInvoiceItem')->findBy(
  3476.                         array(
  3477.                             'purchaseInvoiceId' => $id///material
  3478.                         )
  3479.                     );
  3480.                 }
  3481.             } else {
  3482.             }
  3483.         }
  3484.         return $this->render(
  3485.             '@Accounts/pages/input_forms/purchase_invoice.html.twig',
  3486.             array(
  3487.                 'page_title' => 'Purchase Invoice',
  3488.                 'extData' => $extData,
  3489.                 'extDetailsData' => $extDetailsData,
  3490.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  3491.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  3492.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  3493.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  3494.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  3495.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  3496.                 'grn_list' => Inventory::GrnListForPi($this->getDoctrine()->getManager()),
  3497.                 'grn_list_array' => Inventory::GrnListForPiArray($this->getDoctrine()->getManager()),
  3498.                 'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '')
  3499.                 //                'dt_debug'=>$data
  3500.                 //                'po'=>Inventory::getPurchaseOrderList
  3501.             )
  3502.         );
  3503.     }
  3504.     public function CreateServicePurchaseInvoice(Request $request$id 0)
  3505.     {
  3506.         $em $this->getDoctrine()->getManager();
  3507.         if ($request->isMethod('POST')) {
  3508.             $data $request->request;
  3509.             $entity_id array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice']; //change
  3510.             $dochash $request->request->get('docHash'); //change
  3511.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3512.             $approveRole $request->request->get('approvalRole');
  3513.             $approveHash $request->request->get('approvalHash');
  3514.             if (!DocValidation::isInsertable(
  3515.                 $em,
  3516.                 $entity_id,
  3517.                 $dochash,
  3518.                 $loginId,
  3519.                 $approveRole,
  3520.                 $approveHash,
  3521.                 $id
  3522.             )) {
  3523.                 $this->addFlash(
  3524.                     'error',
  3525.                     'Sorry Couldnot insert Data.'
  3526.                 );
  3527.             } else {
  3528.                 $funcname 'PurchaseInvoice';
  3529.                 $doc_id $id;
  3530.                 DeleteDocument::$funcname($em$doc_id0);
  3531.                 $create_new_pi Accounts::CreatePurchaseInvoice($id$this->getDoctrine()->getManager(), $data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3532.                 //now add Approval info
  3533.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3534.                 $approveRole $request->request->get('approvalRole');
  3535.                 $options = array(
  3536.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3537.                     'notification_server' => $this->container->getParameter('notification_server'),
  3538.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3539.                     'url' => $this->generateUrl(
  3540.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice']]['entity_view_route_path_name']
  3541.                     )
  3542.                 );
  3543.                 System::setApprovalInfo(
  3544.                     $this->getDoctrine()->getManager(),
  3545.                     $options,
  3546.                     array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
  3547.                     $create_new_pi['pi_id'],
  3548.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3549.                 );
  3550.                 System::createEditSignatureHash(
  3551.                     $this->getDoctrine()->getManager(),
  3552.                     array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
  3553.                     $create_new_pi['pi_id'],
  3554.                     $loginId,
  3555.                     $approveRole,
  3556.                     $request->request->get('approvalHash')
  3557.                 );
  3558.                 $this->addFlash(
  3559.                     'success',
  3560.                     'New Invoice Added.'
  3561.                 );
  3562.                 $url $this->generateUrl(
  3563.                     'view_purchase_invoice'
  3564.                 );
  3565.                 System::AddNewNotification(
  3566.                     $this->container->getParameter('notification_enabled'),
  3567.                     $this->container->getParameter('notification_server'),
  3568.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  3569.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  3570.                     "Purchase Invoice : " $dochash " Has Been Created And is Under Processing",
  3571.                     'pos',
  3572.                     System::getPositionIdsByDepartment($em, [GeneralConstant::ACCOUNTS_DEPARTMENTGeneralConstant::PURCHASE_DEPARTMENT]),
  3573.                     'success',
  3574.                     $url "/" $create_new_pi['pi_id'],
  3575.                     "Purchase Bill"
  3576.                 );
  3577.                 return $this->redirect($url "/" $create_new_pi['pi_id']);
  3578.             }
  3579.         }
  3580.         $extData = [];
  3581.         $extDetailsData = [];
  3582.         if ($id == 0) {
  3583.         } else {
  3584.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')->findOneBy(
  3585.                 array(
  3586.                     'purchaseInvoiceId' => $id///material
  3587.                 )
  3588.             );
  3589.             //now if its not editable, redirect to view
  3590.             if ($extTrans) {
  3591.                 if ($extTrans->getEditFlag() != 1) {
  3592.                     $url $this->generateUrl(
  3593.                         'view_purchase_invoice'
  3594.                     );
  3595.                     return $this->redirect($url "/" $id);
  3596.                 } else {
  3597.                     $extData $extTrans;
  3598.                     $extDetailsData $em->getRepository('ApplicationBundle\\Entity\\PurchaseInvoiceItem')->findBy(
  3599.                         array(
  3600.                             'purchaseInvoiceId' => $id///material
  3601.                         )
  3602.                     );
  3603.                 }
  3604.             } else {
  3605.             }
  3606.         }
  3607.         return $this->render(
  3608.             '@Accounts/pages/input_forms/service_purchase_invoice.html.twig',
  3609.             array(
  3610.                 'page_title' => 'Service Purchase Invoice',
  3611.                 'extData' => $extData,
  3612.                 'extDetailsData' => $extDetailsData,
  3613.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  3614.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  3615.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  3616.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  3617.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  3618.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  3619.                 'grn_list' => Inventory::GrnListForPi($this->getDoctrine()->getManager()),
  3620.                 'grn_list_array' => Inventory::GrnListForPiArray($this->getDoctrine()->getManager()),
  3621.                 'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '')
  3622.                 //                'dt_debug'=>$data
  3623.                 //                'po'=>Inventory::getPurchaseOrderList
  3624.             )
  3625.         );
  3626.     }
  3627.     //=========================================================================
  3628.     //  Previous CreateExpenseInvoice
  3629.     //=========================================================================
  3630.     /*
  3631.         public function CreateExpenseInvoice(Request $request, $id = 0)
  3632.         {
  3633.             $em = $this->getDoctrine()->getManager();
  3634.             if ($request->isMethod('POST')) {
  3635.                 $data = $request->request;
  3636.                 $expBillType = $data->get('expenseTypeId');
  3637.                 foreach ($data->get('expBillCheckMarkedExpense') as $row) {
  3638.                     $entity_id = array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice']; //change
  3639.                     $result = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')
  3640.                         ->findBy(
  3641.                             array(
  3642.                                 'typeHash' => 'EI',
  3643.                                 'prefixHash' => $data->get('expBillTypeId')[$row],
  3644.                                 'assocHash' => $data->get('expBillPartyHeadId')[$row],
  3645.                             )
  3646.                         );
  3647.                     $count = count($result);
  3648.                     $count++;
  3649.                     $dochash = 'EI/' . $data->get('expBillTypeId')[$row] . '/' . $data->get('expBillPartyHeadId')[$row] . '/' . $count; //change
  3650.                     $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3651.                     $approveRole = $request->request->get('approvalRole');
  3652.                     $approveHash = $request->request->get('approvalHash');
  3653.                     if (!DocValidation::isInsertable(
  3654.                         $em,
  3655.                         $entity_id,
  3656.                         $dochash,
  3657.                         $loginId,
  3658.                         $approveRole,
  3659.                         $approveHash,
  3660.                         $id
  3661.                     )) {
  3662.                         $this->addFlash(
  3663.                             'error',
  3664.                             'Sorry Couldnot insert Data.'
  3665.                         );
  3666.                     } else {
  3667.                         $new_ei = Accounts::CreateExpenseInvoice(
  3668.                             $this->getDoctrine()->getManager(),
  3669.                             $data,
  3670.                             $row,
  3671.                             $expBillType,
  3672.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3673.                         );
  3674.                         //now add Approval info
  3675.                         $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3676.                         $approveRole = $request->request->get('approvalRole');
  3677.                         $options = array(
  3678.                             'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3679.                             'notification_server' => $this->container->getParameter('notification_server'),
  3680.                             'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3681.                             'url' => $this->generateUrl(
  3682.                                 GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice']]['entity_view_route_path_name']
  3683.                             )
  3684.                         );
  3685.                         System::setApprovalInfo(
  3686.                             $this->getDoctrine()->getManager(),
  3687.                             $options,
  3688.                             array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  3689.                             $new_ei['ei_id'],
  3690.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3691.                         );
  3692.                         System::createEditSignatureHash(
  3693.                             $this->getDoctrine()->getManager(),
  3694.                             array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  3695.                             $new_ei['ei_id'],
  3696.                             $loginId,
  3697.                             $approveRole,
  3698.                             $request->request->get('approvalHash')
  3699.                         );
  3700.                     }
  3701.                 }
  3702.             }
  3703.             $extData = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')
  3704.                 ->findOneBy(
  3705.                     array(
  3706.                         'expenseInvoiceId' => $id,
  3707.                     )
  3708.                 );
  3709.             if (!$extData)
  3710.                 $extData = [];
  3711.             return $this->render(
  3712.                 '@Accounts/pages/input_forms/expense_bill.html.twig',
  3713.                 array(
  3714.                     'page_title' => 'Expense Bills',
  3715.                     'extData' => $extData,
  3716.                     'party_list' => Accounts::getParentLedgerHeads($this->getDoctrine()->getManager(), 'ep'),
  3717.                     'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  3718.                     'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  3719.                     'supplier_list_by_ac_head' => Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
  3720.                     'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  3721.                     'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  3722.                     'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  3723.                     'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  3724.                     'grn_list' => Inventory::GrnListForEi($this->getDoctrine()->getManager(), 1),
  3725.                     'grn_list_array' => Inventory::GrnListForEiArray($this->getDoctrine()->getManager(), 1),
  3726.                     //                'po'=>Inventory::getPurchaseOrderList
  3727.                 )
  3728.             );
  3729.         }
  3730.     */
  3731.     public function CreateExpenseInvoice(Request $request$id 0)
  3732.     {
  3733.         $em     $this->getDoctrine()->getManager();
  3734.         $em_goc $this->getDoctrine()->getManager('company_group');
  3735.         // ====================================================================
  3736.         // POST – Create or Edit
  3737.         // ====================================================================
  3738.         if ($request->isMethod('POST')) {
  3739.             $loginId     $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3740.             $approveRole $request->request->get('approvalRole');
  3741.             $approveHash $request->request->get('approvalHash');
  3742.             // Verify approval signature before doing anything
  3743.             if (!DocValidation::isSignatureOk($em$loginId$approveHash)) {
  3744.                 return new JsonResponse([
  3745.                     'success'   => false,
  3746.                     'errorText' => 'Approval Hash Mismatch',
  3747.                     'errorStr'  => 'Approval Hash Mismatch',
  3748.                 ]);
  3749.             }
  3750.             // Build cost-distribution map from parallel arrays
  3751.             $exp_distribution_poitemId $request->request->get('exp_distribution_poitemId', []);
  3752.             $exp_distribution_amount   $request->request->get('exp_distribution_amount', []);
  3753.             $costDistributionData = [];
  3754.             foreach ($exp_distribution_poitemId as $k => $poItemId) {
  3755.                 $costDistributionData[$poItemId] = [
  3756.                     'poItemId' => $poItemId,
  3757.                     'amount'   => $exp_distribution_amount[$k],
  3758.                 ];
  3759.             }
  3760.             // Normalise any date string to Y-m-d, defaulting to today
  3761.             $normaliseDate = static function (string $raw): string {
  3762.                 if ($raw === '') return date('Y-m-d');
  3763.                 $ts strtotime($raw);
  3764.                 return ($ts !== false) ? date('Y-m-d'$ts) : date('Y-m-d');
  3765.             };
  3766.             // ----------------------------------------------------------------
  3767.             // Build $expenseDataList from whichever input path was used.
  3768.             // Every row is treated as a fully independent invoice (no parent/child).
  3769.             //
  3770.             // PATH A – flat arrays from the Twig form  (expenseDate[], …)
  3771.             // PATH B – JSON blob in `expenseData`       (mobile / API)
  3772.             // PATH C – classic single-field POST        (legacy fallback)
  3773.             // ----------------------------------------------------------------
  3774.             $expenseDataList = [];
  3775.             $flatDates $request->request->get('expenseDate', []);
  3776.             if (!empty($flatDates) && is_array($flatDates)) {
  3777.                 // PATH A
  3778.                 $flatTypes            $request->request->get('expenseType', []);
  3779.                 $flatSubTypes         $request->request->get('expenseSubType', []);
  3780.                 $flatDocIds           $request->request->get('docId', []);
  3781.                 $flatAmounts          $request->request->get('expenseAmount', []);
  3782.                 $flatExpenseIds       $request->request->get('expenseId', []);
  3783.                 $flatCcIds            $request->request->get('ccId', []);
  3784.                 $flatToBePaidTo       $request->request->get('expenseToBePaidTo', []);
  3785.                 $flatCurrencyIds      $request->request->get('currencyId', []);
  3786.                 $flatCurrRates        $request->request->get('currencyMultiplyRate', []);
  3787.                 $flatFroms            $request->request->get('expenseFrom', []);
  3788.                 $flatFromNotes        $request->request->get('expenseFromNote', []);
  3789.                 $flatTos              $request->request->get('expenseTo', []);
  3790.                 $flatToNotes          $request->request->get('expenseToNote', []);
  3791.                 $flatDescs            $request->request->get('description', []);
  3792.                 $flatMarkers          $request->request->get('expenseMarkerHash', []);
  3793.                 $flatWbsCodes         $request->request->get('wbsCode', []);
  3794.                 $flatWbsActivityNames $request->request->get('wbsActivityName', []);
  3795.                 $flatUploaded         $request->request->get('uploadedFile', []);
  3796.                 $flatInvoiceIds       $request->request->get('invoiceId', []);
  3797.                 $flatInvoiceBalancing $request->request->get('invoiceBalancing', []);
  3798.                 $rowCount count($flatDates);
  3799.                 for ($i 0$i $rowCount$i++) {
  3800.                     $toNote = (string)($flatToNotes[$i] ?? '');
  3801.                     $toNote trim($toNote) === '0' '' $toNote;
  3802.                     $expenseDataList[] = [
  3803.                         'expenseType'                    => (int)($flatTypes[$i]        ?? 0),
  3804.                         'expenseSubType'                 => (int)($flatSubTypes[$i]     ?? 0),
  3805.                         'expenseId'                      => (int)($flatExpenseIds[$i]   ?? 0),
  3806.                         'ccId'                           => (int)($flatCcIds[$i]        ?? 0),
  3807.                         'currencyId'                     => (int)($flatCurrencyIds[$i]  ?? 0),
  3808.                         'currencyMultiply'               => 1,
  3809.                         'currencyMultiplyRate'           => (float)($flatCurrRates[$i]  ?? 1),
  3810.                         'docId'                          => (int)($flatDocIds[$i]       ?? 0),
  3811.                         'expenseToBePaidTo'              => $flatToBePaidTo[$i]         ?? 0,
  3812.                         'expenseFrom'                    => (int)($flatFroms[$i]        ?? 0),
  3813.                         'expenseFromNote'                => (string)($flatFromNotes[$i] ?? ''),
  3814.                         'expenseTo'                      => (int)($flatTos[$i]          ?? 0),
  3815.                         'expenseToNote'                  => $toNote,
  3816.                         'expenseAmount'                  => (float)($flatAmounts[$i]    ?? 0),
  3817.                         'previousAdvanceAmount'          => 0,
  3818.                         'checkDate'                      => '',
  3819.                         'checkNumber'                    => '',
  3820.                         'checkNarration'                 => '',
  3821.                         'checkId'                        => 0,
  3822.                         'description'                    => (string)($flatDescs[$i]     ?? ''),
  3823.                         'expenseMarkerHash'              => (string)($flatMarkers[$i]   ?? ''),
  3824.                         'markerHash'                     => (string)($flatMarkers[$i]   ?? ''),
  3825.                         'wbsCode'                        => (string)($flatWbsCodes[$i] ?? ''),
  3826.                         'wbsActivityName'                => (string)($flatWbsActivityNames[$i] ?? ''),
  3827.                         'expenseDate'                    => $normaliseDate((string)($flatDates[$i] ?? '')),
  3828.                         'invoiceBalancing'               => (int)($flatInvoiceBalancing[$i] ?? 0),
  3829.                         'attachedFile'                   => [],
  3830.                         'uploadedFile'                   => (string)($flatUploaded[$i]  ?? ''),
  3831.                         'expenseInvocationStrategyOnGrn' => null,
  3832.                         'expenseInvocationTypeOnItems'   => null,
  3833.                         'isChildInvoice'                 => 0,
  3834.                         'costDistributionData'           => $costDistributionData,
  3835.                         'expenseDistributionOnProduct'   => 0,
  3836.                         'expenseSubCategory'             => 0,
  3837.                         'expenseSubCategoryOption'       => 0,
  3838.                         'expense_sub_category'           => 0,
  3839.                         'expense_sub_category_option'    => 0,
  3840.                         'invoiceId'                      => (int)($flatInvoiceIds[$i]   ?? 0),
  3841.                     ];
  3842.                 }
  3843.             } else {
  3844.                 $expense_data $request->request->get('expenseData', []);
  3845.                 $expense_type $request->request->get('expense_type'0);
  3846.                 if (is_string($expense_data)) {
  3847.                     $expense_data json_decode($expense_datatrue);
  3848.                 }
  3849.                 if (!empty($expense_data)) {
  3850.                     // PATH B – JSON / mobile
  3851.                     $currTs = (new \DateTime())->format('U');
  3852.                     foreach ($expense_data as $idx => $expData) {
  3853.                         // Save embedded base64 image to disk
  3854.                         if (isset($expData['imageBase64'])) {
  3855.                             $imgData   base64_decode(
  3856.                                 preg_replace('#^data:image/\w+;base64,#i'''$expData['imageBase64'])
  3857.                             );
  3858.                             $fileName  $currTs md5(uniqid()) . '.png';
  3859.                             $storePath 'uploads/ExpenseInvoice/';
  3860.                             MiscActions::RemoveExpiredFiles($em_goc);
  3861.                             $uplDir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  3862.                             if (!file_exists($uplDir)) {
  3863.                                 mkdir($uplDir0777true);
  3864.                             }
  3865.                             $fp $uplDir $fileName;
  3866.                             if (file_exists($fp)) { chmod($fp0755); unlink($fp); }
  3867.                             file_put_contents(
  3868.                                 $this->container->getParameter('kernel.root_dir')
  3869.                                     . '/../web/uploads/ExpenseInvoice/' $fileName,
  3870.                                 $imgData
  3871.                             );
  3872.                             $expense_data[$idx]['uploadedFile'] = $storePath $fileName;
  3873.                         }
  3874.                         if (!isset($expData['attachedFile'])) {
  3875.                             $expense_data[$idx]['attachedFile'] = [];
  3876.                         }
  3877.                         $expense_data[$idx]['expenseDate']    = $normaliseDate((string)($expData['expenseDate'] ?? ''));
  3878.                         $expense_data[$idx]['isChildInvoice'] = 0;
  3879.                         $expenseDataList[] = $expense_data[$idx];
  3880.                     }
  3881.                 } else {
  3882.                     // PATH C – legacy single-field POST
  3883.                     $expenseDataList[] = [
  3884.                         'expenseType'                    => $expense_type,
  3885.                         'currencyId'                     => $request->request->get('expense_currency_id'0),
  3886.                         'currencyMultiply'               => $request->request->get('expense_currency_multiply'1),
  3887.                         'currencyMultiplyRate'           => $request->request->get('expense_currency_multiply_rate'1),
  3888.                         'expenseSubType'                 => $request->request->get('expense_sub_type'0),
  3889.                         'expenseId'                      => $request->request->get('expense_id'0),
  3890.                         'ccId'                           => $request->request->get('ccId'0),
  3891.                         'docId'                          => $expense_type == $request->request->get('poId')
  3892.                             : ($expense_type == $request->request->get('soId')
  3893.                                 : ($expense_type == $request->request->get('opportunityId'$request->request->get('leadId'))
  3894.                                     : ($expense_type == $request->request->get('tour_id') : 0))),
  3895.                         'expenseToBePaidTo'              => $request->request->get('expense_to_be_paid_to'0),
  3896.                         'expenseFrom'                    => $request->request->get('expense_from'0),
  3897.                         'checkDate'                      => $request->request->get('check_date'''),
  3898.                         'checkNumber'                    => $request->request->get('check_number'''),
  3899.                         'checkNarration'                 => $request->request->get('check_narration'''),
  3900.                         'checkId'                        => $request->request->get('check_id'0),
  3901.                         'expenseFromNote'                => $request->request->get('expense_from_note'''),
  3902.                         'expenseTo'                      => $request->request->get('expense_to_' $expense_type0),
  3903.                         'expenseToNote'                  => $request->request->get('expense_to_note_' $expense_type''),
  3904.                         'expenseAmount'                  => $request->request->get('expense_amount'''),
  3905.                         'previousAdvanceAmount'          => $request->request->get('prev_advance_amount'0),
  3906.                         'description'                    => $request->request->get('description'''),
  3907.                         'expenseMarkerHash'              => $request->request->get('markerHash'''),
  3908.                         'markerHash'                     => $request->request->get('markerHash'''),
  3909.                         'wbsCode'                        => $request->request->get('wbsCode'''),
  3910.                         'wbsActivityName'                => $request->request->get('wbsActivityName'''),
  3911.                         'expenseDate'                    => $normaliseDate((string)$request->request->get('expense_date''')),
  3912.                         'expenseInvocationStrategyOnGrn' => $request->request->get('expenseInvocationStrategyOnGrn'null),
  3913.                         'expenseInvocationTypeOnItems'   => $request->request->get('expenseInvocationTypeOnItems'null),
  3914.                         'invoiceBalancing'               => $request->request->has('auto_balance' $expense_type)
  3915.                             ? $request->request->get('auto_balance' $expense_type) : 0,
  3916.                         'attachedFile'                   => $request->files->get('file', []),
  3917.                         'expenseSubCategory'             => $request->request->get('expense_sub_category'0),
  3918.                         'expenseSubCategoryOption'       => $request->request->get('expense_sub_category_option'0),
  3919.                         'uploadedFile'                   => $request->request->get('uploadedFile'''),
  3920.                         'expenseDistributionOnProduct'   => $request->request->get('exp_check_expense_distribution_on_product'0),
  3921.                         'isChildInvoice'                 => 0,
  3922.                         'costDistributionData'           => $costDistributionData,
  3923.                         'expense_sub_category'           => $request->request->get('expense_sub_category'0),
  3924.                         'expense_sub_category_option'    => $request->request->get('expense_sub_category_option'0),
  3925.                     ];
  3926.                 }
  3927.             }
  3928.             $isEdit = ($id 0);
  3929.             // Resolves _OWN_ / _OWN_ADVANCE_ to the employee's ledger head
  3930.             $resolveOwnHead = function (string $headField, array $expData, array &$data) use ($em$request): ?JsonResponse {
  3931.                 $sql  "SELECT accounts_head_id, advance_head_id, employee_id, user_id
  3932.                         FROM employee
  3933.                         WHERE user_id = " . (int)$request->getSession()->get(UserConstants::USER_ID) . "
  3934.                         LIMIT 1";
  3935.                 $rows $em->getConnection()->fetchAllAssociative($sql);
  3936.                 if (empty($rows)) {
  3937.                     return new JsonResponse(['success' => false'errorText' => 'You are not listed as Employee''errorStr' => 'You are not listed as Employee']);
  3938.                 }
  3939.                 if (empty($rows[0][$headField]) || $rows[0][$headField] == 0) {
  3940.                     $label = ($headField === 'advance_head_id') ? 'Employee Advance Head' 'Employee Head';
  3941.                     return new JsonResponse(['success' => false'errorText' => "Could not Find $label"'errorStr' => "Could not Find $label"]);
  3942.                 }
  3943.                 $data['party_head_id']          = $rows[0][$headField];
  3944.                 $data['description']            = $expData['expenseToNote'];
  3945.                 $data['personal_expense_flag']  = 1;
  3946.                 $data['expense_of_user_id']     = $rows[0]['user_id'];
  3947.                 $data['expense_of_employee_id'] = $rows[0]['employee_id'];
  3948.                 return null;
  3949.             };
  3950.             // ----------------------------------------------------------------
  3951.             // Save each row as its own independent invoice.
  3952.             // All tracking arrays are declared OUTSIDE the loop so they
  3953.             // accumulate entries across all iterations.
  3954.             // ----------------------------------------------------------------
  3955.             $new_ei            = [];
  3956.             $lastSavedEiId     0;
  3957.             $lastSavedEiResult = [];
  3958.             $firstSavedEiId    0;
  3959.             $allSavedIds       = [];   
  3960.             $allDocAmounts     = [];   
  3961.             $allDocHash        = [];
  3962.             foreach ($expenseDataList as $expData) {
  3963.                 $expBillType = (int)($expData['expenseType'] ?? 0);
  3964.                 // For edit: use each row's own invoiceId; fall back to $id for single-row edits
  3965.                 $currentEiId = ($isEdit && !empty($expData['invoiceId']))
  3966.                     ? (int)$expData['invoiceId']
  3967.                     : ($isEdit $id 0);
  3968.                 $data = [
  3969.                     'doc_id'                         => $expData['docId']               ?? 0,
  3970.                     'expense_id'                     => $expData['expenseId']           ?? 0,
  3971.                     'party_id'                       => '',
  3972.                     'party_head_id'                  => $expData['expenseToBePaidTo']   ?? 0,
  3973.                     'advance_amount_to_assign'       => (float)($expData['previousAdvanceAmount'] ?? 0),
  3974.                     'invoice_amount'                 => (float)($expData['expenseAmount'] ?? 0),
  3975.                     'description'                    => $expData['description']         ?? '',
  3976.                     'expense_to_note'                => $expData['expenseToNote']       ?? '',
  3977.                     'expense_from_note'              => $expData['expenseFromNote']     ?? '',
  3978.                     'wbsCode'                        => $expData['wbsCode']             ?? '',
  3979.                     'wbsActivityName'                => $expData['wbsActivityName']     ?? '',
  3980.                     'currencyId'                     => $expData['currencyId']          ?? 0,
  3981.                     'currencyMultiply'               => $expData['currencyMultiply']    ?? 1,
  3982.                     'currencyMultiplyRate'           => $expData['currencyMultiplyRate'] ?? 1,
  3983.                     'date'                           => $expData['expenseDate'],
  3984.                     'file'                           => $expData['attachedFile']        ?? [],
  3985.                     'uploadedFile'                   => $expData['uploadedFile']        ?? '',
  3986.                     'expense_from'                   => $expData['expenseFrom']         ?? 0,
  3987.                     'check_date'                     => $expData['checkDate']           ?? '',
  3988.                     'check_number'                   => $expData['checkNumber']         ?? '',
  3989.                     'check_narration'                => $expData['checkNarration']      ?? '',
  3990.                     'check_id'                       => $expData['checkId']             ?? 0,
  3991.                     'expenseMarkerHash'              => $expData['markerHash']          ?? '',
  3992.                     'expenseSubCategory'             => $expData['expense_sub_category']        ?? 0,
  3993.                     'expenseSubCategoryOption'       => $expData['expense_sub_category_option'] ?? 0,
  3994.                     'invoiceBalancing'               => $expData['invoiceBalancing']    ?? 0,
  3995.                     'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'] ?? null,
  3996.                     'expenseInvocationTypeOnItems'   => $expData['expenseInvocationTypeOnItems']   ?? null,
  3997.                     'expenseDistributionOnProduct'   => $expData['expenseDistributionOnProduct']   ?? 0,
  3998.                     'costDistributionData'           => $expData['costDistributionData'] ?? [],
  3999.                 ];
  4000.                 if ($request->request->has('latitude')) {
  4001.                     $data['latitude']  = $request->request->get('latitude');
  4002.                     $data['longitude'] = $request->request->get('longitude');
  4003.                 }
  4004.                 // Resolve marker hash → accounts_head_id
  4005.                 if (!empty($expData['expenseMarkerHash'])) {
  4006.                     $sql  "SELECT accounts_head_id FROM acc_accounts_head
  4007.                             WHERE marker_hash LIKE '%" $expData['expenseMarkerHash'] . "%'
  4008.                             LIMIT 1";
  4009.                     $rows $em->getConnection()->fetchAllAssociative($sql);
  4010.                     if (empty($rows)) {
  4011.                         return new JsonResponse(['success' => false'errorText' => 'Could not find relevant Expense Head']);
  4012.                     }
  4013.                     $data['expense_id'] = $rows[0]['accounts_head_id'];
  4014.                 }
  4015.                 // Resolve _OWN_ / _OWN_ADVANCE_ to employee ledger head
  4016.                 $paidTo $expData['expenseToBePaidTo'] ?? 0;
  4017.                 if ($paidTo == '_OWN_' || $paidTo == -1) {
  4018.                     $err $resolveOwnHead('accounts_head_id'$expData$data);
  4019.                     if ($err) return $err;
  4020.                 }
  4021.                 if ($paidTo == '_OWN_ADVANCE_' || $paidTo == -2) {
  4022.                     $err $resolveOwnHead('advance_head_id'$expData$data);
  4023.                     if ($err) return $err;
  4024.                 }
  4025.                 $new_ei = [];
  4026.                 switch ($expBillType) {
  4027.                     case 0// General
  4028.                     case 1// PO-linked
  4029.                     case 2// SO-linked
  4030.                     case 3// Lead-linked
  4031.                     case 5// Tour/travel
  4032.                         if ($isEdit) {
  4033.                             $new_ei Accounts::EditExpenseInvoiceFromAddExpense(
  4034.                                 $this->getDoctrine()->getManager(),
  4035.                                 $data''$expBillType$loginId,
  4036.                                 000,
  4037.                                 (int)($expData['ccId'] ?? 0),
  4038.                                 000,
  4039.                                 $currentEiId
  4040.                             );
  4041.                         } else {
  4042.                             $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  4043.                                 $this->getDoctrine()->getManager(),
  4044.                                 $data''$expBillType$loginId,
  4045.                                 000,
  4046.                                 (int)($expData['ccId'] ?? 0),
  4047.                                 00
  4048.                             );
  4049.                         }
  4050.                         break;
  4051.                     default:
  4052.                         continue 2;
  4053.                 }
  4054.                 // Register each successfully saved invoice
  4055.                 if (!empty($new_ei['ei_id'])) {
  4056.                     $savedEiId = (int)$new_ei['ei_id'];
  4057.                     $allSavedIds[]             = $savedEiId;
  4058.                     $allDocAmounts[$savedEiId] = (float)($expData['expenseAmount'] ?? 0);
  4059.                     $allDocHash[$savedEiId]     = $new_ei['ei_doc_hash'] ?? '';
  4060.                     $eiEntityId array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'];
  4061.                     $options = [
  4062.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4063.                         'notification_server'  => $this->container->getParameter('notification_server'),
  4064.                         'appId'                => $request->getSession()->get(UserConstants::USER_APP_ID),
  4065.                         'url'                  => $this->generateUrl(
  4066.                             GeneralConstant::$Entity_list_details[$eiEntityId]['entity_view_route_path_name']
  4067.                         ),
  4068.                     ];
  4069.                     System::setApprovalInfo(
  4070.                         $this->getDoctrine()->getManager(),
  4071.                         $options$eiEntityId$savedEiId$loginId
  4072.                     );
  4073.                     System::createEditSignatureHash(
  4074.                         $this->getDoctrine()->getManager(),
  4075.                         $eiEntityId$savedEiId$loginId$approveRole$approveHash
  4076.                     );
  4077.                     if ($firstSavedEiId === 0) {
  4078.                         $firstSavedEiId $savedEiId;
  4079.                     }
  4080.                     $lastSavedEiId     $savedEiId;
  4081.                     $lastSavedEiResult $new_ei;
  4082.                 }
  4083.             }
  4084.             // END foreach
  4085.             // Use the last saved invoice for response URLs
  4086.             $responseEi = !empty($lastSavedEiResult) ? $lastSavedEiResult : [];
  4087.             $eiEntityId      array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'];
  4088.             $eiEntityDetails GeneralConstant::$Entity_list_details[$eiEntityId];
  4089.             $viewUrl  $this->generateUrl(
  4090.                 $eiEntityDetails['entity_view_route_path_name'],
  4091.                 ['id' => $responseEi['ei_id'] ?? 0]
  4092.             );
  4093.             $printUrl = isset($eiEntityDetails['entity_print_route_path_name'])
  4094.                 ? $this->generateUrl(
  4095.                     $eiEntityDetails['entity_print_route_path_name'],
  4096.                     ['id' => $responseEi['ei_id'] ?? 0]
  4097.                 )
  4098.                 : $viewUrl;
  4099.             return new JsonResponse([
  4100.                 'success'         => true,
  4101.                 'docId'           => $responseEi['ei_id']      ?? '',
  4102.                 'docHash'         => $responseEi['ei_doc_hash'] ?? '',
  4103.                 'documentId'      => $responseEi['ei_id']      ?? '',
  4104.                 'documentHash'    => $responseEi['ei_doc_hash'] ?? '',
  4105.                 'documentAmount'  => (float)($expenseDataList[0]['expenseAmount'] ?? 0),
  4106.                 'allDocIds'       => $allSavedIds,     
  4107.                 'allDocAmounts'   => $allDocAmounts,  
  4108.                 'allDocHashes'    => $allDocHash
  4109.                 'viewUrl'         => $viewUrl,
  4110.                 'docPrintMainUrl' => $printUrl,
  4111.                 'isEdit'          => $isEdit,
  4112.             ]);
  4113.         }
  4114.         // ====================================================================
  4115.         // GET – Render form; pre-fill when $id > 0 (edit mode)
  4116.         // ====================================================================
  4117.         $extData      = [];
  4118.         $existingRows = [];
  4119.         if ($id 0) {
  4120.             $extData $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')
  4121.                 ->findOneBy(['expenseInvoiceId' => $id]);
  4122.             if ($extData) {
  4123.                 $existingRows[] = [
  4124.                     'id'                             => $extData->getExpenseInvoiceId(),
  4125.                     'expenseType'                    => $extData->getExpenseTypeId(),
  4126.                     'expenseSubType'                 => $extData->getExpenseSubcategory()   ?? 0,
  4127.                     'expenseId'                      => $extData->getPartyId(),
  4128.                     'ccId'                           => $extData->getCostCenterId()         ?? 0,
  4129.                     'currencyId'                     => $extData->getCurrency()             ?? 0,
  4130.                     'currencyMultiply'               => $extData->getCurrencyMultiply()     ?? 1,
  4131.                     'currencyMultiplyRate'           => $extData->getCurrencyMultiplyRate() ?? 1,
  4132.                     'docId'                          => $extData->getPurchaseOrderId()      ?? 0,
  4133.                     'docIdtext'                      => '',
  4134.                     'expenseToBePaidTo'              => $extData->getPartyHeadId()          ?? 0,
  4135.                     'expenseFrom'                    => $extData->getExpenseFrom()           ?? 0,
  4136.                     'expenseFromNote'                => $extData->getExpenseFromNote()       ?? '',
  4137.                     'expenseTo'                      => 0,
  4138.                     'expenseToNote'                  => $extData->getExpenseToNote()         ?? '',
  4139.                     'expenseAmount'                  => $extData->getInvoiceAmount()         ?? 0,
  4140.                     'previousAdvanceAmount'          => $extData->getAdvanceAmount()         ?? 0,
  4141.                     'checkDate'                      => '',
  4142.                     'checkNumber'                    => '',
  4143.                     'checkNarration'                 => '',
  4144.                     'checkId'                        => 0,
  4145.                     'description'                    => $extData->getDescription()           ?? '',
  4146.                     'expenseMarkerHash'              => $extData->getMarkerHash()            ?? '',
  4147.                     'wbsCode'                        => $extData->getWbsCode()              ?? '',
  4148.                     'wbsActivityName'                => $extData->getWbsActivityName()      ?? '',
  4149.                     'expenseDate'                    => $extData->getExpenseInvoiceDate()
  4150.                         ? $extData->getExpenseInvoiceDate()->format('F d, Y')
  4151.                         : date('F d, Y'),
  4152.                     'invoiceBalancing'               => 0,
  4153.                     'uploadedFile'                   => $extData->getFiles()                 ?? '',
  4154.                     'attachedFile'                   => [],
  4155.                     'expenseInvocationStrategyOnGrn' => $extData->getExpenseInvocationStrategyOnGrn(),
  4156.                     'expenseInvocationTypeOnItems'   => $extData->getExpenseInvocationTypeOnItems(),
  4157.                     'isChildInvoice'                 => 0,
  4158.                     'refId'                          => 0,
  4159.                     'invoiceId'                      => $extData->getExpenseInvoiceId(),
  4160.                 ];
  4161.             } else {
  4162.                 $extData = [];
  4163.             }
  4164.         }
  4165.         return $this->render(
  4166.             '@Accounts/pages/input_forms/expense_bill.html.twig',
  4167.             [
  4168.                 'page_title'               => $id 'Edit Expense Bill' 'Create Expense Bill',
  4169.                 'isEdit'                   => ($id 0),
  4170.                 'editId'                   => $id,
  4171.                 'extData'                  => $extData,
  4172.                 'existingRows'             => $existingRows,
  4173.                 'party_list'               => Accounts::getParentLedgerHeads($em'ep'),
  4174.                 'warehouse'                => Inventory::WarehouseListArray($em),
  4175.                 'supplier'                 => Inventory::ProductSupplierList($em),
  4176.                 'supplier_list_by_ac_head' => Accounts::SupplierListByAcHead($em),
  4177.                 'supplier_list_array'      => Inventory::ProductSupplierListArray($em),
  4178.                 'po_list_array'            => Purchase::PurchaseOrderListArray($em),
  4179.                 'po_list'                  => Purchase::PurchaseOrderList($em),
  4180.                 'product_list'             => Inventory::ProductList($em),
  4181.                 'grn_list'                 => Inventory::GrnListForEi($em1),
  4182.                 'grn_list_array'           => Inventory::GrnListForEiArray($em1),
  4183.             ]
  4184.         );
  4185.     }
  4186.   public function PendingInvoiceList(Request $request)
  4187.     {
  4188.         return $this->render(
  4189.             '@Accounts/pages/list/pending_list.html.twig',
  4190.             array(
  4191.                 'page_title' => 'Pending Invoices'
  4192.             )
  4193.         );
  4194.     }
  4195.     public function SalesInvoiceList(Request $request)
  4196.     {
  4197.         $em $this->getDoctrine()->getManager();
  4198.         $session $request->getSession();
  4199.         $companyId $this->getLoggedUserCompanyId($request);
  4200.         $userRestrictions = [];
  4201.         $selectiveDocumentsFlag 0;
  4202.         $allowedLoginIds = [];
  4203.         $canSeeAllSo 1;
  4204.         $allowedSpIds 'all';
  4205.         $allowedClientIds 'all';
  4206.         $allowedLoginIds 'all';
  4207.         $salesPersonList Client::SalesPersonList($this->getDoctrine()->getManager());
  4208.         $clientList SalesOrderM::GetClientList($em, [], $companyId);
  4209.         $userType $session->get(UserConstants::USER_TYPE);
  4210.         $userId $session->get(UserConstants::USER_ID);
  4211.         $selectiveQryArray = array('status' => GeneralConstant::ACTIVE);
  4212.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  4213.             $selectiveQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  4214.             $allowedClientIds = [$session->get(UserConstants::CLIENT_ID)];
  4215.         }
  4216.         if ($userType == UserConstants::USER_TYPE_GENERAL) {
  4217.             $userRestrictions Users::getUserApplicationAccessSettings($em$userId)['options'];
  4218.             $selectiveDocumentsFlag 1//by default will show only selective
  4219.             if (isset($userRestrictions['canSeeAllSo'])) {
  4220.                 if ($userRestrictions['canSeeAllSo'] == 1) {
  4221.                     $selectiveDocumentsFlag 0;
  4222.                     $canSeeAllSo 1;
  4223.                 }
  4224.             }
  4225.             if ($selectiveDocumentsFlag == 1) {
  4226.                 $allowedLoginIds MiscActions::getLoginIdsByUserId($em$session->get(UserConstants::USER_ID));
  4227.             }
  4228.         }
  4229.         $q $this->getDoctrine()
  4230.             ->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
  4231.             ->findBy(
  4232.                 $selectiveQryArray
  4233.             );
  4234.         $stage_list = array(
  4235.             => 'Pending',
  4236.             => 'Complete',
  4237.             => 'Pending Payment',
  4238.         );
  4239.         $data = [];
  4240.         $salesOrders SalesOrderM::SalesOrderList($em);
  4241.         foreach ($q as $entry) {
  4242.             $clientId $entry->getClientId();
  4243.             $spId $clientList[$entry->getClientId()]['sales_person_id'];
  4244.             //            $client=$em->getRepository('ApplicationBundle\\Entity\\AccClients')
  4245.             //                ->findOneBy(
  4246.             //                    array(
  4247.             //                        'clientId'=>$clientId
  4248.             //                    )
  4249.             //                );
  4250.             if ($selectiveDocumentsFlag == 1) {
  4251.                 //1st check by sales person
  4252.                 $spCheckFailed 1;
  4253.                 if (isset($salesPersonList[$spId])) {
  4254.                     if ($salesPersonList[$spId]['userId'] == $userId) {
  4255.                         $spCheckFailed 0;
  4256.                     }
  4257.                 }
  4258.                 if ($spCheckFailed == 0) {
  4259.                 } else if (in_array($entry->getCreatedLoginId(), $allowedLoginIds) || in_array($entry->getEditedLoginId(), $allowedLoginIds)) {
  4260.                 } else {
  4261.                     continue;
  4262.                 }
  4263.             }
  4264.             $data[] = array(
  4265.                 'doc_date' => $entry->getSalesInvoiceDate(),
  4266.                 'doc_date_str' => $entry->getSalesInvoiceDate()->format('F d, Y'),
  4267.                 'id' => $entry->getSalesInvoiceId(),
  4268.                 'doc_hash' => $entry->getDocumentHash(),
  4269.                 'invoice_amount' => $entry->getInvoiceAmount(),
  4270.                 'sales_order_id' => $entry->getSalesOrderId(),
  4271.                 'sales_person_id' => $spId,
  4272.                 'sales_person_name' => isset($salesPersonList[$spId]) ? $salesPersonList[$spId]['name'] : '',
  4273.                 'so_amount' => $entry->getSoAmount(),
  4274.                 'client_name' => $clientList[$clientId]['client_name'],
  4275.                 'client_code' => $clientList[$clientId]['client_code'],
  4276.                 'client_contact_number' => $clientList[$clientId]['contact_number'],
  4277.                 'sales_order_name' => isset($salesOrders[$entry->getSalesOrderId()]) ? $salesOrders[$entry->getSalesOrderId()]['name'] : '',
  4278.                 'sales_or_service' => $entry->getSalesOrService(),
  4279.                 'stage' => $stage_list[$entry->getStage()]
  4280.             );
  4281.         }
  4282.         if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  4283.             return new JsonResponse(
  4284.                 array(
  4285.                     'page_title' => 'Sales Invoices',
  4286.                     'data' => $data,
  4287.                     'userType' => $userType,
  4288.                     'orderConfirmationPendingFlag' => 0,
  4289.                     'users' => Users::getUserListById($em),
  4290.                     'canSeeAllSo' => $canSeeAllSo,
  4291.                     'allowedSpIds' => $allowedSpIds,
  4292.                     'allowedClientIds' => $allowedClientIds,
  4293.                     'allowedLoginIds' => $allowedLoginIds,
  4294.                     'sales_person_list' => $salesPersonList,
  4295.                     'success' => empty($data) ? false true
  4296.                 )
  4297.             );
  4298.         }
  4299.         return $this->render(
  4300.             '@Accounts/pages/list/sales_invoices.html.twig',
  4301.             array(
  4302.                 'page_title' => 'Sales Invoices',
  4303.                 'data' => $data,
  4304.                 'canSeeAllSo' => $canSeeAllSo,
  4305.                 'allowedSpIds' => $allowedSpIds,
  4306.                 'allowedClientIds' => $allowedClientIds,
  4307.                 'allowedLoginIds' => $allowedLoginIds,
  4308.             )
  4309.         );
  4310.     }
  4311.     public function PurchaseInvoiceList(Request $request)
  4312.     {
  4313.         $q $this->getDoctrine()
  4314.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  4315.             ->findBy(
  4316.                 array(
  4317.                     'status' => GeneralConstant::ACTIVE,
  4318.                 )
  4319.             );
  4320.         $stage_list = array(
  4321.             => 'Pending',
  4322.             => 'Complete',
  4323.             => 'Pending Payment',
  4324.         );
  4325.         $data = [];
  4326.         foreach ($q as $entry) {
  4327.             $data[] = array(
  4328.                 'doc_date' => $entry->getPurchaseInvoiceDate(),
  4329.                 'id' => $entry->getPurchaseInvoiceId(),
  4330.                 'doc_hash' => $entry->getDocumentHash(),
  4331.                 'invoice_amount' => $entry->getInvoiceAmount(),
  4332.                 'stage' => $stage_list[$entry->getStage()]
  4333.             );
  4334.         }
  4335. //        return new JsonResponse($data);
  4336.         return $this->render(
  4337.             '@Accounts/pages/list/purchase_invoices.html.twig',
  4338.             array(
  4339.                 'page_title' => 'Purchase Invoices',
  4340.                 'data' => $data
  4341.             )
  4342.         );
  4343.     }
  4344.     public function ViewSalesInvoice(Request $request$id)
  4345.     {
  4346.         $em $this->getDoctrine()->getManager();
  4347.         $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  4348.         $dt SalesOrderM::GetSalesInvoiceDetails($em$id);
  4349.         return $this->render(
  4350. //            '@Accounts/pages/views/view_sales_invoice.html.twig',
  4351.             '@Accounts/pages/views/view_sales_invoice_demo.html.twig',
  4352.             array(
  4353.                 'page_title' => 'View',
  4354.                 'data' => $dt,
  4355.                 'absoluteUrl' => $absoluteUrl,
  4356.                 'auto_created' => $dt['auto_created'],
  4357.                 'approval_data' => System::checkIfApprovalExists(
  4358.                     $em,
  4359.                     array_flip(GeneralConstant::$Entity_list)['SalesInvoice'],
  4360.                     $id,
  4361.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4362.                 ),
  4363.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  4364.                     $this->getDoctrine()->getManager(),
  4365.                     array_flip(GeneralConstant::$Entity_list)['SalesInvoice'],
  4366.                     $id,
  4367.                     $dt['created_by'],
  4368.                     $dt['edited_by']
  4369.                 ) : []
  4370.             )
  4371.         );
  4372.     }
  4373.     public function CorrectCheckProblem(Request $request)
  4374.     {
  4375.         $em $this->getDoctrine()->getManager();
  4376.         $check_list_in_brs = array();
  4377.         $docData $em->getRepository('ApplicationBundle\\Entity\\Brs')->findBy(
  4378.             array(
  4379.                 //                'brsId'=>$id
  4380.                 //            'approved'=>1
  4381.             )
  4382.         );
  4383.         foreach ($docData as $doc) {
  4384.             $details_data json_decode($doc->getData(), true);
  4385.             if ($details_data) {
  4386.                 $pending_check_no_list = [];
  4387.                 if (isset($details_data["pending_cn"])) {
  4388.                     foreach ($details_data["pending_cn"] as $key => $value) {
  4389.                         if (!isset($check_list_in_brs[$value])) {
  4390.                             $check_list_in_brs[$value] = array(
  4391.                                 'check_amount' => 0,
  4392.                                 'narration' => ""
  4393.                             );
  4394.                         }
  4395.                         if (isset($details_data["pending_check_amount"])) {
  4396.                             if ($check_list_in_brs[$value]['check_amount'] == 0)
  4397.                                 $check_list_in_brs[$value]['check_amount'] = $details_data["pending_check_amount"][$key];
  4398.                         }
  4399.                     }
  4400.                 }
  4401.                 if (isset($details_data["cleared_cn"])) {
  4402.                     foreach ($details_data["cleared_cn"] as $key => $value) {
  4403.                         if (!isset($check_list_in_brs[$value])) {
  4404.                             $check_list_in_brs[$value] = array(
  4405.                                 'check_amount' => 0,
  4406.                                 'narration' => ""
  4407.                             );
  4408.                         }
  4409.                         if (isset($details_data["cleared_check_amount"])) {
  4410.                             if ($check_list_in_brs[$value]['check_amount'] == 0)
  4411.                                 $check_list_in_brs[$value]['check_amount'] = $details_data["cleared_check_amount"][$key];
  4412.                         }
  4413.                     }
  4414.                 }
  4415.             }
  4416.         }
  4417.         foreach ($check_list_in_brs as $key => $value) {
  4418.             $ck $em->getRepository('ApplicationBundle\\Entity\\AccCheck')->findOneBy(
  4419.                 array(
  4420.                     //                'brsId'=>$id
  4421.                     'checkNumber' => $key
  4422.                 )
  4423.             );
  4424.             if ($ck) {
  4425.                 $ck->setCheckAmount($value['check_amount']);
  4426.                 $ck->setAssigned(1);
  4427.                 if ($ck->getCheckDate() == null)
  4428.                     $ck->setCheckDate($ck->getLedgerHitDate());
  4429.                 if ($ck->getVoucherId() == null)
  4430.                     $ck->setVoucherId(0);
  4431.                 $em->flush();
  4432.             }
  4433.         }
  4434.         //        $dt=Accounts::GetBrsDetails($em,$id);
  4435.         return new JsonResponse($check_list_in_brs);
  4436.     }
  4437.     public function ViewBrs(Request $request$id)
  4438.     {
  4439.         $em $this->getDoctrine()->getManager();
  4440.         $dt Accounts::GetBrsDetails($em$id);
  4441.         return $this->render(
  4442.             '@Accounts/pages/views/brs_view.html.twig',
  4443.             array(
  4444.                 'page_title' => 'BRS',
  4445.                 'data' => $dt,
  4446.                 'auto_created' => $dt['auto_created'],
  4447.                 'approval_data' => System::checkIfApprovalExists(
  4448.                     $em,
  4449.                     array_flip(GeneralConstant::$Entity_list)['Brs'],
  4450.                     $id,
  4451.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4452.                 ),
  4453.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  4454.                     $this->getDoctrine()->getManager(),
  4455.                     array_flip(GeneralConstant::$Entity_list)['Brs'],
  4456.                     $id,
  4457.                     $dt['created_by'],
  4458.                     $dt['edited_by']
  4459.                 ) : []
  4460.             )
  4461.         );
  4462.     }
  4463.     public function PrintBrs(Request $request$id)
  4464.     {
  4465.         $em $this->getDoctrine()->getManager();
  4466.         $data Accounts::GetBrsDetails($em$id);
  4467.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  4468.         $document_mark = array(
  4469.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4470.             'copy' => ''
  4471.         );
  4472.         return $this->render(
  4473.             '@Accounts/pages/print/print_brs.html.twig',
  4474.             array(
  4475.                 'export' => 'print',
  4476.                 'page_title' => 'BRS' $data['doc_hash'],
  4477.                 'data' => $data,
  4478.                 'document_mark_image' => $document_mark['original'],
  4479.                 'company_name' => $company_data->getName(),
  4480.                 'company_data' => $company_data,
  4481.                 'company_address' => $company_data->getAddress(),
  4482.                 'company_image' => $company_data->getImage(),
  4483.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  4484.                 'page_header' => 'BRS',
  4485.                 'document_type' => 'Sales Bill',
  4486.                 'page_header_sub' => 'Add',
  4487.                 //                'type_list'=>$type_list,
  4488.                 //                'mis_data'=>$mis_data,
  4489.                 //                'mis_print'=>$mis_print,
  4490.                 'item_data' => [],
  4491.                 'received' => 2,
  4492.                 'return' => 1,
  4493.                 'total_w_vat' => 1,
  4494.                 'total_vat' => 1,
  4495.                 'total_wo_vat' => 1,
  4496.                 'invoice_id' => 'abcd1234',
  4497.                 'created_by' => 'created by',
  4498.                 'created_at' => '',
  4499.                 'red' => 0,
  4500.             )
  4501.         );
  4502.     }
  4503.     public function ViewFinancialBudget(Request $request$id)
  4504.     {
  4505.         $em $this->getDoctrine()->getManager();
  4506.         $dt Accounts::GetFinancialBudgetDetails($em$id);
  4507.         return $this->render(
  4508.             '@Accounts/pages/views/financial_budget.html.twig',
  4509.             array(
  4510.                 'page_title' => 'Financial Budget',
  4511.                 'data' => $dt,
  4512.                 'auto_created' => $dt['auto_created'],
  4513.                 'approval_data' => System::checkIfApprovalExists(
  4514.                     $em,
  4515.                     array_flip(GeneralConstant::$Entity_list)['FinancialBudget'],
  4516.                     $id,
  4517.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4518.                 ),
  4519.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  4520.                     $this->getDoctrine()->getManager(),
  4521.                     array_flip(GeneralConstant::$Entity_list)['FinancialBudget'],
  4522.                     $id,
  4523.                     $dt['created_by'],
  4524.                     $dt['edited_by']
  4525.                 ) : []
  4526.             )
  4527.         );
  4528.     }
  4529.     public function PrintFinancialBudget(Request $request$id)
  4530.     {
  4531.         $em $this->getDoctrine()->getManager();
  4532.         $data Accounts::GetFinancialBudgetDetails($em$id);
  4533.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  4534.         $document_mark = array(
  4535.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4536.             'copy' => ''
  4537.         );
  4538.         return $this->render(
  4539.             '@Accounts/pages/print/financial_budget.html.twig',
  4540.             array(
  4541.                 'export' => 'print',
  4542.                 'page_title' => 'Financial Budget' $data['doc_hash'],
  4543.                 'data' => $data,
  4544.                 'document_mark_image' => $document_mark['original'],
  4545.                 'company_name' => $company_data->getName(),
  4546.                 'company_data' => $company_data,
  4547.                 'company_address' => $company_data->getAddress(),
  4548.                 'company_image' => $company_data->getImage(),
  4549.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  4550.                 'page_header' => 'BRS',
  4551.                 'document_type' => 'Sales Bill',
  4552.                 'page_header_sub' => 'Add',
  4553.                 //                'type_list'=>$type_list,
  4554.                 //                'mis_data'=>$mis_data,
  4555.                 //                'mis_print'=>$mis_print,
  4556.                 'item_data' => [],
  4557.                 'received' => 2,
  4558.                 'return' => 1,
  4559.                 'total_w_vat' => 1,
  4560.                 'total_vat' => 1,
  4561.                 'total_wo_vat' => 1,
  4562.                 'invoice_id' => 'abcd1234',
  4563.                 'created_by' => 'created by',
  4564.                 'created_at' => '',
  4565.                 'red' => 0,
  4566.             )
  4567.         );
  4568.     }
  4569.     public function PrintSalesInvoice(Request $request$id)
  4570.     {
  4571.         $em $this->getDoctrine()->getManager();
  4572.         if ($id != 0)
  4573.             $data SalesOrderM::GetSalesInvoiceDetails($em$id);
  4574.         else if ($request->query->has('printType'))
  4575.             $data SalesOrderM::GetSalesInvoiceDetails(
  4576.                 $em,
  4577.                 $id,
  4578.                 $request->query->get('printType'),
  4579.                 $request->query->get('invoiceIds', []),
  4580.                 $request->query->get('soId'0)
  4581.             );
  4582.         // S2.3 — register in Document Variant Engine (additive, non-blocking)
  4583.         if (!empty($data['si_data'])) {
  4584.             try {
  4585.                 $invoiceVariant $request->query->get('invoiceVariant''final');
  4586.                 DocumentRegistry::register(
  4587.                     $em,
  4588.                     in_array($invoiceVariant, ['commercial','customs','lc','import','credit_note','proforma']) ? $invoiceVariant 'final',
  4589.                     'SalesInvoice',
  4590.                     (int)$id,
  4591.                     [
  4592.                         'tenantId'       => $data['si_data']->getCompanyId(),
  4593.                         'customerId'     => $data['si_data']->getClientId(),
  4594.                         'projectId'      => $data['si_data']->getProjectId(),
  4595.                         'documentNumber' => isset($data['doc_hash']) ? $data['doc_hash'] : null,
  4596.                         'currency'       => $data['si_data']->getCurrency(),
  4597.                         'createdBy'      => $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  4598.                     ]
  4599.                 );
  4600.             } catch (\Exception $e) { /* registry is non-blocking */ }
  4601.         }
  4602.         //        $company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
  4603.         $company_data Company::getCompanyData($em$data['si_data']->getCompanyId());
  4604.         $document_mark = array(
  4605.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4606.             'copy' => ''
  4607.         );
  4608.         $printTemplate CountryTemplateResolver::resolve(
  4609.             $this->get('twig'),
  4610.             $em,
  4611.             $data['si_data']->getCompanyId(),
  4612.             '@Accounts/pages/print/print_sales_invoice.html.twig'
  4613.         );
  4614.         $taxMarkers TaxMarkerLookup::forCompany($em$data['si_data']->getCompanyId());
  4615.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  4616.             $html $this->renderView(
  4617.                 $printTemplate,
  4618.                 array(
  4619.                     //full array here
  4620.                     'pdf' => true,
  4621.                     'page_title' => 'Sales Bill ' $data['doc_hash'],
  4622.                     'data' => $data,
  4623.                     'export' => 'pdf,print',
  4624.                     'document_mark_image' => $document_mark['original'],
  4625.                     'company_name' => $company_data->getName(),
  4626.                     'company_data' => $company_data,
  4627.                     'company_address' => $company_data->getAddress(),
  4628.                     'company_image' => $company_data->getImage(),
  4629.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  4630.                     'page_header' => 'New Product',
  4631.                     'document_type' => 'Sales Bill',
  4632.                     'page_header_sub' => 'Add',
  4633.                     //                'type_list'=>$type_list,
  4634.                     //                'mis_data'=>$mis_data,
  4635.                     //                'mis_print'=>$mis_print,
  4636.                     'item_data' => [],
  4637.                     'received' => 2,
  4638.                     'return' => 1,
  4639.                     'total_w_vat' => 1,
  4640.                     'total_vat' => 1,
  4641.                     'total_wo_vat' => 1,
  4642.                     'invoice_id' => 'abcd1234',
  4643.                     'created_by' => 'created by',
  4644.                     'created_at' => '',
  4645.                     'red' => 0,
  4646.                     'taxMarkers' => $taxMarkers,
  4647.                 )
  4648.             );
  4649.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  4650.                 //                'orientation' => 'landscape',
  4651.                 //                'enable-javascript' => true,
  4652.                 //                'javascript-delay' => 1000,
  4653.                 'no-stop-slow-scripts' => false,
  4654.                 'no-background' => false,
  4655.                 'lowquality' => false,
  4656.                 'encoding' => 'utf-8',
  4657.                 //            'images' => true,
  4658.                 //            'cookie' => array(),
  4659.                 'dpi' => 300,
  4660.                 'image-dpi' => 300,
  4661.                 //                'enable-external-links' => true,
  4662.                 //                'enable-internal-links' => true
  4663.             ));
  4664.             return new Response(
  4665.                 $pdf_response,
  4666.                 200,
  4667.                 array(
  4668.                     'Content-Type' => 'application/pdf',
  4669.                     'Content-Disposition' => 'attachment; filename="sales_invoice_' $id '.pdf"'
  4670.                 )
  4671.             );
  4672.         }
  4673.         return $this->render(
  4674.             $printTemplate,
  4675.             array(
  4676.                 'page_title' => 'Sales Bill ' $data['doc_hash'],
  4677.                 'data' => $data,
  4678.                 'export' => 'pdf,print',
  4679.                 'document_mark_image' => $document_mark['original'],
  4680.                 'company_name' => $company_data->getName(),
  4681.                 'company_data' => $company_data,
  4682.                 'company_address' => $company_data->getAddress(),
  4683.                 'company_image' => $company_data->getImage(),
  4684.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  4685.                 'page_header' => 'New Product',
  4686.                 'document_type' => 'Sales Bill',
  4687.                 'page_header_sub' => 'Add',
  4688.                 //                'type_list'=>$type_list,
  4689.                 //                'mis_data'=>$mis_data,
  4690.                 //                'mis_print'=>$mis_print,
  4691.                 'item_data' => [],
  4692.                 'received' => 2,
  4693.                 'return' => 1,
  4694.                 'total_w_vat' => 1,
  4695.                 'total_vat' => 1,
  4696.                 'total_wo_vat' => 1,
  4697.                 'invoice_id' => 'abcd1234',
  4698.                 'created_by' => 'created by',
  4699.                 'created_at' => '',
  4700.                 'red' => 0,
  4701.                 'taxMarkers' => $taxMarkers,
  4702.             )
  4703.         );
  4704.     }
  4705.     public function GetPurchaseInvoiceBalancingData(Request $request)
  4706.     {
  4707.         $heads $request->request->get('heads');
  4708.         $ids $request->request->get('ids');
  4709.         $em $this->getDoctrine()->getManager();
  4710.         return new JsonResponse(array(
  4711.             "success" => false,
  4712.             "content" => Accounts::GetPurchaseInvoiceBalancingData($em$heads$ids)
  4713.         ));
  4714.     }
  4715.     public function GetSalesInvoiceBalancingData(Request $request)
  4716.     {
  4717.         $heads $request->request->get('heads');
  4718.         $ids $request->request->get('ids');
  4719.         $em $this->getDoctrine()->getManager();
  4720.         return new JsonResponse(array(
  4721.             "success" => false,
  4722.             "content" => Accounts::GetSalesInvoiceBalancingData($em$heads$ids)
  4723.         ));
  4724.     }
  4725.     public function GetSelectedHeadsHistory(Request $request$mis_start_date ''$mis_end_date '')
  4726.     {
  4727.         $em $this->getDoctrine()->getManager();
  4728.         $start_date "";
  4729.         $end_date "";
  4730.         //        $em=$this->getDoctrine()->getManager();
  4731.         if ($mis_start_date != '' && $mis_start_date != 0)
  4732.             $start_date $mis_start_date;
  4733.         if ($mis_end_date != '' && $mis_start_date != 0)
  4734.             $end_date $mis_start_date;
  4735.         $engine $this->container->get('twig');
  4736.         $pids array_unique(explode("::"$_POST["pids"]));
  4737.         $Content $engine->render(
  4738.             '@Accounts/pages/report/selected_head_details.html.twig',
  4739.             Accounts::GetVoucherMisDetails($em$pids$start_date$end_date)
  4740.         );
  4741.         //        $stockPosition=$engine->render('@Sales/pages/report/selected_products_stock_position.html.twig', array('pSalesDetails'=>$ProductSales));
  4742.         return new JsonResponse(array("success" => false"content" => $Content));
  4743.         //        return new JsonResponse(array("success"=>false,"content"=>$Content, "stockPosition"=>$stockPosition));
  4744.     }
  4745.     public function EditVoucher(Request $request$id)
  4746.     {
  4747.         $em $this->getDoctrine()->getManager();
  4748.         $Transaction $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  4749.             'transactionId' => $id,
  4750.             'editFlag' => 1,
  4751.             'lockFlag' => [0null],
  4752.             'disabledFlag' => [0null],
  4753.         ));
  4754.         if ($Transaction) {
  4755.             if ($Transaction->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  4756.                 return $this->redirectToRoute('edit_journal_voucher', array('id' => $id));
  4757.             }
  4758.         } else {
  4759.             //            $this->container->get("session")->setFlash("error", "Pikachu is not allowed");
  4760.             $this->addFlash(
  4761.                 'error',
  4762.                 'The Action was not allowed.'
  4763.             );
  4764.             $url $request->headers->get("referer");
  4765.             //            return $this->render('@Purchase/pages/list_tables/quotation.html.twig',
  4766.             //                array(
  4767.             //                    'page_title'=>'Quotation Calculator'
  4768.             //
  4769.             //                )
  4770.             //            );
  4771.             return new RedirectResponse($url);
  4772.         }
  4773.         //
  4774.         //
  4775.         //        return $this->render('@Accounts/pages/input_forms/journal_voucher.html.twig',
  4776.         //            array(
  4777.         //                'page_title'=>'Create Journal Voucher'
  4778.         //            )
  4779.         //        );
  4780.     }
  4781.     public function RefreshDocHash(Request $request$entity_id)
  4782.     {
  4783.         //        $response = new StreamedResponse();
  4784.         //        $response->setCallback(function () {
  4785.         $em $this->getDoctrine()->getManager();
  4786.         $assign_list = array();
  4787.         $new_cc $em
  4788.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  4789.             ->findOneBy(
  4790.                 array(
  4791.                     'name' => 'accounting_year_start',
  4792.                 )
  4793.             );
  4794.         $query "SELECT transaction_id, type_hash, prefix_hash, assoc_hash, number_hash from  acc_transactions  where status=" GeneralConstant::ACTIVE;
  4795.         $date_start "";
  4796.         $date_start_str "";
  4797.         if ($new_cc) {
  4798.             $date_start = new \DateTime($new_cc->getData());
  4799.             $date_start_str $date_start->format('Y-m-d');
  4800.         }
  4801.         if ($new_cc)
  4802.             $query .= " AND transaction_date>= '" $date_start_str " 00:00:00' ";
  4803.         $query .= " ORDER BY transaction_date ASC";
  4804.         $stmt $em->getConnection()->fetchAllAssociative($query);
  4805.         
  4806.         $Transactions $stmt;
  4807.         $update_qry "";
  4808.         foreach ($Transactions as $entry) {
  4809.             if (isset($assign_list[$entry['type_hash'] . '_' $entry['prefix_hash'] . '_' $entry['assoc_hash']])) {
  4810.                 $to_be_assigned $assign_list[$entry['type_hash'] . '_' $entry['prefix_hash'] . '_' $entry['assoc_hash']]['last_no_hash'] + 1;
  4811.                 if ($to_be_assigned == $entry['number_hash']) {
  4812.                 } else {
  4813.                     $update_qry .= "UPDATE acc_transactions set number_hash=$to_be_assigned, document_hash='" $entry['type_hash'] . '/' $entry['prefix_hash'] . '/' $entry['assoc_hash'] . "/$to_be_assigned'
  4814.                     where transaction_id=" $entry['transaction_id'] . "; ";
  4815.                 }
  4816.                 $assign_list[$entry['type_hash'] . '_' $entry['prefix_hash'] . '_' $entry['assoc_hash']]['last_no_hash'] = $to_be_assigned;
  4817.             } else {
  4818.                 $assign_list[$entry['type_hash'] . '_' $entry['prefix_hash'] . '_' $entry['assoc_hash']]['last_no_hash'] = $entry['number_hash'];
  4819.             }
  4820.         }
  4821.         $stmt $em->getConnection()->fetchAllAssociative($update_qry);
  4822.         
  4823.         //        $Transactions=$stmt;
  4824.         return $this->redirectToRoute('dashboard');
  4825.     }
  4826.     public function RefreshTransactions(Request $request)
  4827.     {
  4828.         //        $response = new StreamedResponse();
  4829.         //        $response->setCallback(function () {
  4830.         $em $this->getDoctrine()->getManager();
  4831.         //1st get all brscleared vids for heads
  4832.         $brs_cleared_vids_by_head = [];
  4833.         $Transaction $em->getRepository('ApplicationBundle\\Entity\\Brs')->findBy(
  4834.             array(
  4835.                 //                'approved'=>GeneralConstant::APPROVED,
  4836.                 //                'transactionId'=>$tids
  4837.                 //            'ledgerHit'=>1,
  4838.             )
  4839.         );
  4840.         foreach ($Transaction as $doc) {
  4841.             $data json_decode($doc->getData(), true);
  4842.             if (isset($data['cleared_check_id'])) {
  4843.                 $check_ids $data['cleared_check_id'];
  4844.                 //                $recon_dates=$data['recon_date'];
  4845.                 $v_ids $data['cleared_vid'];
  4846.                 foreach ($v_ids as $vid) {
  4847.                     if (isset($brs_cleared_vids_by_head[$doc->getAccountsHeadId()])) {
  4848.                         $brs_cleared_vids_by_head[$doc->getAccountsHeadId()][] = $vid;
  4849.                     } else {
  4850.                         $brs_cleared_vids_by_head[$doc->getAccountsHeadId()] = [$vid];
  4851.                     }
  4852.                 }
  4853.             }
  4854.             //            $tids[]=$d->getTransactionId();
  4855.         }
  4856.         $bank_settings $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  4857.             'name' => 'bank_parents'
  4858.         ));
  4859.         $bank_id_list = [];
  4860.         if ($bank_settings)
  4861.             $bank_id_list json_decode($bank_settings->getData());
  4862.         $head_list Accounts::HeadListFullPath($em);
  4863.         $bank_head_list = [];
  4864.         $bank_head_list_array = [];
  4865.         foreach ($head_list as $k => $v) {
  4866.             //            if($k==210)
  4867.             //                continue;
  4868.             foreach ($bank_id_list as $bid) {
  4869.                 $q_str '/' $bid '/';
  4870.                 $path_string $v['path'];
  4871.                 $debug_it[] = [$q_str$path_stringstrpos($path_string$q_str)];
  4872.                 if (strpos($path_string$q_str) !== false) {
  4873.                     $bank_head_list[$k] = $v;
  4874.                     $bank_head_list_array[] = $k;
  4875.                 } else {
  4876.                 }
  4877.             }
  4878.         }
  4879.         ///temporarily adding pending reconlist for vouchers
  4880.         $Transaction $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findBy(
  4881.             array(
  4882.                 'approved' => GeneralConstant::APPROVED,
  4883.                 //                'transactionId'=>$tids
  4884.                 //            'ledgerHit'=>1,
  4885.             )
  4886.         );
  4887.         foreach ($Transaction as $d) {
  4888.             $tids[] = $d->getTransactionId();
  4889.         }
  4890.         $TransactionDetails $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  4891.             array(
  4892.                 'accountsHeadId' => $tids,
  4893.                 //            'ledgerHit'=>1,
  4894.             )
  4895.         );
  4896.         $det_by_trans_id = [];
  4897.         foreach ($TransactionDetails as $d) {
  4898.             if (in_array($d->getAccountsHeadId(), $bank_head_list_array)) {
  4899.                 if (isset($brs_cleared_vids_by_head[$d->getAccountsHeadId()])) {
  4900.                     if (in_array($d->getTransactionId(), $brs_cleared_vids_by_head[$d->getAccountsHeadId()])) {
  4901.                         continue;
  4902.                     }
  4903.                 }
  4904.                 if (isset($det_by_trans_id[$d->getTransactionId()])) {
  4905.                     $det_by_trans_id[$d->getTransactionId()]['pendReconIdList'][] = $d->getAccountsHeadId();
  4906.                 } else {
  4907.                     $det_by_trans_id[$d->getTransactionId()] = array(
  4908.                         'pendReconIdList' => [$d->getAccountsHeadId()]
  4909.                     );
  4910.                 }
  4911.             }
  4912.         }
  4913.         foreach ($det_by_trans_id as $tid => $d) {
  4914.             $Transaction $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  4915.                 array(
  4916.                     'approved' => GeneralConstant::APPROVED,
  4917.                     'transactionId' => $tid
  4918.                     //            'ledgerHit'=>1,
  4919.                 )
  4920.             );
  4921.             if ($Transaction) {
  4922.                 if (empty($d['pendReconIdList'])) {
  4923.                     $Transaction->setProvisional(0);
  4924.                     $Transaction->setPendingReconciliationIdList(json_encode([]));
  4925.                 } else {
  4926.                     $Transaction->setPendingReconciliationIdList(json_encode($d['pendReconIdList']));
  4927.                     $Transaction->setProvisional(1);
  4928.                 }
  4929.                 $em->flush();
  4930.             }
  4931.         }
  4932.         //            echo 'Refreshing  Transactions\n';
  4933.         //            flush();
  4934.         //
  4935.         //            $new_cc = $em
  4936.         //                ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  4937.         //                ->findOneBy(
  4938.         //                    array(
  4939.         //                        'name' => 'accounting_year_start',
  4940.         //                    )
  4941.         //                );
  4942.         //
  4943.         //            $query="UPDATE  acc_transactions set ledger_hit=0  ";
  4944.         //            $date_start="";
  4945.         //            $date_start_str="";
  4946.         //            if($new_cc) {
  4947.         //                $date_start = new \DateTime($new_cc->getData());
  4948.         //                $date_start_str=$date_start->format('Y-m-d');
  4949.         //            }
  4950.         //            if($new_cc)
  4951.         //                $query.=" where transaction_date>= '".$date_start_str." 00:00:00' ";
  4952.         //
  4953.         //
  4954.         //            $stmt = $em->getConnection()->fetchAllAssociative($query);
  4955.         //            
  4956.         //            echo 'Refreshing  Transactions\n';
  4957.         //            flush();
  4958.         //            sleep(2);
  4959.         //
  4960.         //            $Transactions=$em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  4961.         //                    'approved'=>1,
  4962.         //                    'ledgerHit'=>0
  4963.         //                )
  4964.         //                ,array(
  4965.         //                    'transactionDate'=>'ASC'
  4966.         //                ));
  4967.         ////            foreach($Transactions as $test)
  4968.         ////            {
  4969.         ////                echo 'processing v_id'.$test->getTransactionId().'\n';
  4970.         ////                flush();
  4971.         //        if($Transactions) {
  4972.         //            ApprovalFunction::AccTransactions($em, $Transactions->getTransactionId());
  4973.         //            return $this->redirectToRoute('refresh_transactions');
  4974.         //        }
  4975.         //        else
  4976.         //            return $this->redirectToRoute('dashboard');
  4977.         //
  4978.         //
  4979.         //                sleep(2);
  4980.         //
  4981.         ////                return $this->redirectToRoute('refresh_transactions');
  4982.         //
  4983.         //            }
  4984.         ////            echo 'Hello World';
  4985.         ////            flush();
  4986.         ////            sleep(2);
  4987.         ////            echo 'Hello World';
  4988.         ////            flush();
  4989.         //        });
  4990.         //        $response->send();
  4991.         //        $httpKernel->terminate($request, $response);
  4992.         //        ApprovalFunction::AccTransactions($em,$id);
  4993.         //        $done=MiscActions::refreshTransactions($em);
  4994.         //
  4995.         //        $this->addFlash(
  4996.         //            'success',
  4997.         //            'The Action was Successful.'
  4998.         //        );
  4999.         //
  5000.         //
  5001.         //
  5002.         return $this->redirectToRoute('dashboard');
  5003.     }
  5004.     public function RefreshDatabase(Request $request$refdate '')
  5005.     {
  5006.         $em $this->getDoctrine()->getManager();
  5007.         if ($refdate == '')
  5008.             $refdate '2018-11-10';
  5009.         ////starting correcting the delivery confirmations
  5010.         //1st get the required delivery confirmation list
  5011.         $get_kids_sql " SELECT *  FROM `delivery_confirmation` WHERE `delivery_confirmation_date` >= '" $refdate " 00:00:00'
  5012. ORDER BY `delivery_confirmation`.`delivery_confirmation_id` ASC";
  5013.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5014.         
  5015.         $get_kids $stmt;
  5016.         $dc_id_list = [];
  5017.         $dc_det_by_id = [];
  5018.         foreach ($get_kids as $kid) {
  5019.             $dc_id_list[] = $kid['delivery_confirmation_id'];
  5020.             $dc_det_by_id[$kid['delivery_confirmation_id']] = $kid;
  5021.         }
  5022.         //now
  5023.         foreach ($dc_id_list as $k => $dc_id) {
  5024.             //1st get delivery receipt date
  5025.             $dr $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  5026.                 ->findOneBy(
  5027.                     array(
  5028.                         'deliveryReceiptId' => $dc_det_by_id[$dc_id]['delivery_receipt_id'],
  5029.                     )
  5030.                 );
  5031.             if ($dr) {
  5032.                 $todate = new \Datetime();
  5033.                 $next_one_date $todate->format('Y-m-d') . ' 23:59:59';
  5034.                 if (isset($dc_id_list[$k 1]))
  5035.                     $next_one_date $dc_det_by_id[$dc_id_list[$k 1]]['created_at'];
  5036.                 $qry "select * from sales_invoice where sales_invoice_date>='" $dc_det_by_id[$dc_id]['created_at'] .
  5037.                     "' and sales_invoice_date< '" $next_one_date "' ORDER BY `sales_invoice`.`sales_invoice_date` ASC limit 1";
  5038.                 $stmt $em->getConnection()->fetchAllAssociative($qry);
  5039.                 
  5040.                 $get_kids $stmt;
  5041.                 if (!empty($get_kids)) {
  5042.                     $voucher_list json_decode($get_kids[0]['voucher_ids'], true);
  5043.                     $qry1 "update sales_invoice set
  5044.                    sales_invoice_date='" $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "' ,
  5045.                    receipt_id_list='" json_encode([$dr->getDeliveryReceiptId()]) . "'
  5046.                    where sales_invoice_id=" $get_kids[0]['sales_invoice_id'];
  5047.                     $stmt $em->getConnection()->executeStatement($qry1);
  5048.                     
  5049.                     $qry1 "update  acc_transactions set
  5050.                     transaction_date='" $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "' ,
  5051.                     ledger_hit_date='" $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "'
  5052.                     where transaction_id in (" implode(', '$voucher_list) . ")";
  5053.                     $stmt $em->getConnection()->executeStatement($qry1);
  5054.                     
  5055.                     $qry1 "update  acc_transaction_details set
  5056.                     transaction_date='" $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "' ,
  5057.                     ledger_hit_date='" $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "'
  5058.                     where transaction_id in (" implode(', '$voucher_list) . ")";
  5059.                     $stmt $em->getConnection()->executeStatement($qry1);
  5060.                     
  5061.                     //            $get_kids=$stmt;
  5062.                 }
  5063.             }
  5064.         }
  5065.         //            MiscActions::refreshDatabase($em);
  5066.         $this->addFlash(
  5067.             'success',
  5068.             'The Action was Successful.'
  5069.         );
  5070.         return $this->redirectToRoute('dashboard');
  5071.     }
  5072.     public function RefreshClosing(Request $request)
  5073.     {
  5074.         $em $this->getDoctrine()->getManager();
  5075.         $debug_data = [];
  5076.         $autoStartFixedAssetDepreciation 0;
  5077.         $autoStartLedgerHit 0;
  5078.         $autoStartInventoryRefresh 0;
  5079.         $inventoryRefreshed 0;
  5080.         $modifyAccTransFlag 0;
  5081.         $lastRefreshDate '';
  5082.         if ($request->query->has('rectifyGrnExpIdTag')) {
  5083.             $pos $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findBy(array(
  5084.                 'approved' => 1,
  5085.                 //                            'ledgerHit' => 0
  5086.             ));
  5087.             foreach ($pos as $po) {
  5088.                 $Grns $em->getRepository('ApplicationBundle\\Entity\\Grn')->findBy(
  5089.                     array(
  5090.                         'purchaseOrderId' => $po->getPurchaseOrderId(),
  5091.                         'approved' => 1,
  5092.                         //                            'ledgerHit' => 0
  5093.                     ),
  5094.                     array(
  5095.                         'grnDate' => 'asc'
  5096.                     )
  5097.                 );
  5098.                 $eis $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->findBy(
  5099.                     array(
  5100.                         'purchaseOrderId' => $po->getPurchaseOrderId(),
  5101.                         'approved' => 1,
  5102.                         //                            'ledgerHit' => 0
  5103.                     ),
  5104.                     array(
  5105.                         'expenseInvoiceDate' => 'asc'
  5106.                     )
  5107.                 );
  5108.                 $first_grn_found 0;
  5109.                 foreach ($Grns as $grn) {
  5110.                     $grn->setExpenseAmount(0);
  5111.                     $grn->setExpensePendingBalanceAmount(0);
  5112.                     $em->flush();
  5113.                     if ($first_grn_found == 1) continue;
  5114.                     //                    if ($grn->getExpenseAmount() == 0 || $grn->getExpenseAmount() == null || $grn->getExpenseAmount() == '')
  5115.                     //                        continue;
  5116.                     $grnExpAmount $grn->getExpenseAmount();
  5117.                     $conditionFailed 1;
  5118.                     $chkAmount 0;
  5119.                     $total_price_value 0;
  5120.                     $tot_expense 0;
  5121.                     $eisObjList = [];
  5122.                     $passedEiIds = [];
  5123.                     $eiIds = [];
  5124.                     $passedEis = [];
  5125.                     $eiAmounts = [];
  5126.                     $grnItems $em->getRepository('ApplicationBundle\\Entity\\GrnItem')
  5127.                         ->findBy(
  5128.                             array(
  5129.                                 'grnId' => $grn->getGrnId()
  5130.                             )
  5131.                         );
  5132.                     foreach ($grnItems as $key => $entry) {
  5133.                         $total_price_value += $entry->getLocalPrice() * $entry->getQty();
  5134.                     }
  5135.                     foreach ($eis as $ei) {
  5136.                         $ei->setGrnIds(json_encode([]));
  5137.                         $em->flush();
  5138.                         $eiAmounts[$ei->getExpenseInvoiceId()] = $ei->getInvoiceAmount();
  5139.                         $eisObjList[$ei->getExpenseInvoiceId()] = $ei;
  5140.                         $eiIds[] = $ei->getExpenseInvoiceId();
  5141.                         if ($ei->getExpenseInvoiceDate() <= $grn->getGrnDate()) {
  5142.                             $passedEiIds[] = $ei->getExpenseInvoiceId();
  5143.                             $passedEis[$ei->getExpenseInvoiceId()] = $ei;
  5144.                             $tot_expense += ($ei->getInvoiceAmount());
  5145.                         }
  5146.                     }
  5147.                     //adding frm po ended
  5148.                     $expense_mult = ($total_price_value != ? (($total_price_value $tot_expense) / $total_price_value) : 0);
  5149.                     foreach ($grnItems as $key => $entry) {
  5150.                         $entry->setPriceWithExpense($entry->getLocalPrice() * $expense_mult);
  5151.                     }
  5152.                     $grn->setExpenseAmount($tot_expense);
  5153.                     $grn->setExpensePendingBalanceAmount($tot_expense);
  5154.                     //                    if ($conditionFailed == 0) {
  5155.                     foreach ($passedEis as $ei) {
  5156.                         $ei->setGrnIds(json_encode([$grn->getGrnId()]));
  5157.                         $em->flush();
  5158.                     }
  5159.                     //                    }
  5160.                     $first_grn_found 1;
  5161.                 }
  5162.             }
  5163.         }
  5164.         if ($request->query->has('autoStartLedgerHit'))
  5165.             $autoStartLedgerHit 1;
  5166.         if ($request->query->has('autoStartInventoryRefresh'))
  5167.             $autoStartInventoryRefresh $request->query->get('autoStartInventoryRefresh');
  5168.         if ($request->query->has('modifyAccTransFlag'))
  5169.             $modifyAccTransFlag $request->query->get('modifyAccTransFlag');
  5170.         if ($request->query->has('inventoryRefreshed'))
  5171.             $inventoryRefreshed $request->query->get('inventoryRefreshed');
  5172.         if ($request->query->has('lastRefreshDate'))
  5173.             $lastRefreshDate $request->query->get('lastRefreshDate');
  5174.         if ($request->query->has('autoStartFixedAssetDepreciation'))
  5175.             $autoStartFixedAssetDepreciation 1;
  5176.         if ($request->isMethod('POST')) {
  5177.             //            $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  5178.             //                'approved' => 1,
  5179.             //                'ledgerHit' => 0
  5180.             //            ));
  5181.             if ($request->request->has('fixedAssetDep')) {
  5182.                 $apData FixedAsset::TakeDepreciationActionBook($em, [], $this->getLoggedUserCompanyId($request));
  5183.                 $ap $apData['continueFlag'];
  5184.                 if ($ap == 1) {
  5185.                     //                        $skip_ids[] = $get_kids[0]['transaction_id'];
  5186.                     return new JsonResponse(array(
  5187.                         "success" => true,
  5188.                         'workData' => $apData
  5189.                     ));
  5190.                 } else {
  5191.                     return new JsonResponse(array(
  5192.                         "success" => false,
  5193.                         'workData' => $apData
  5194.                     ));
  5195.                 }
  5196.             } else {
  5197.                 $skip_ids = [];
  5198.                 if ($request->request->has('skipIds'))
  5199.                     $skip_ids $request->request->get('skipIds');
  5200.                 $get_kids_sql 'select transaction_id, document_hash from acc_transactions where approved=1 and ledger_hit=0 and transaction_id not in (' implode(','$skip_ids) . ')   limit 1';
  5201.                 //                $get_kids_sql = 'select transaction_id, document_hash from acc_transactions where transaction_id=3236 and approved=1 and ledger_hit=0 and transaction_id not in (' . implode(',', $skip_ids) . ')  order by transaction_amount desc limit 1';
  5202.                 $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5203.                 
  5204.                 $get_kids $stmt;
  5205.                 $vid 0;
  5206.                 $vname '';
  5207.                 if (!empty($get_kids)) {
  5208.                     $ap ApprovalFunction::AccTransactions($em$get_kids[0]['transaction_id']);
  5209.                     if ($ap == 0)
  5210.                         $skip_ids[] = $get_kids[0]['transaction_id'];
  5211.                     return new JsonResponse(array(
  5212.                         "success" => true,
  5213.                         "debugData" => $ap,
  5214.                         "v_id" => $get_kids[0]['transaction_id'],
  5215.                         "v_name" => $get_kids[0]['document_hash'],
  5216.                         "skip_ids" => $skip_ids,
  5217.                     ));
  5218.                 } else {
  5219.                     return new JsonResponse(array(
  5220.                         "success" => false,
  5221.                         "v_id" => 0,
  5222.                         "v_name" => "",
  5223.                         "skip_ids" => $skip_ids,
  5224.                     ));
  5225.                 }
  5226.             }
  5227.         }
  5228.         //        MiscActions::refreshDatabase($em);
  5229.         return $this->render(
  5230.             '@Application/pages/accounts/settings/refresh_combo_action.html.twig',
  5231.             array(
  5232.                 'page_title' => 'Debug',
  5233.                 'debug_data' => $debug_data,
  5234.                 'autoStartLedgerHit' => $autoStartLedgerHit,
  5235.                 'autoStartInventoryRefresh' => $autoStartInventoryRefresh,
  5236.                 'inventoryRefreshed' => $inventoryRefreshed,
  5237.                 'modifyAccTransFlag' => $modifyAccTransFlag,
  5238.                 'lastRefreshDate' => $lastRefreshDate,
  5239.                 'autoStartFixedAssetDepreciation' => $autoStartFixedAssetDepreciation,
  5240.                 //                'voucherDetails'=>$v_details,
  5241.                 //                'heads'=>Accounts::HeadList($em),
  5242.                 //                'transaction'=>$Transaction
  5243.             )
  5244.         );
  5245.         //        return $this->redirectToRoute('dashboard');
  5246.     }
  5247.     public function ResetClosing(Request $request)
  5248.     {
  5249.         $em $this->getDoctrine()->getManager();
  5250.         $debug_data = [];
  5251.         if ($request->isMethod('POST')) {
  5252.             //            $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  5253.             //                'approved' => 1,
  5254.             //                'ledgerHit' => 0
  5255.             //            ));
  5256.             $skip_ids = [];
  5257.             if ($request->request->has('skipIds'))
  5258.                 $skip_ids $request->request->get('skipIds');
  5259.             $get_kids_sql '     UPDATE `acc_accounts_head` SET `current_balance`=opening_balance,`current_balance_reconciled`=opening_balance WHERE 1;
  5260.     UPDATE `acc_transactions` SET `ledger_hit`=0 WHERE 1;
  5261.     UPDATE `acc_transaction_details` SET `ledger_hit`=0 WHERE 1;
  5262.     UPDATE `acc_clients` SET `client_due`=(select opening_balance from acc_accounts_head
  5263.     where acc_accounts_head.accounts_head_id=acc_clients.accounts_head_id  LIMIT 1) WHERE acc_clients.accounts_head_id=acc_clients.advance_head_id;
  5264.     UPDATE `acc_clients` SET `initial_opening_balance`=(select opening_balance from acc_accounts_head
  5265.     where acc_accounts_head.accounts_head_id=acc_clients.accounts_head_id  LIMIT 1) WHERE acc_clients.accounts_head_id=acc_clients.advance_head_id;
  5266.     UPDATE `acc_clients` SET `client_due`=(select sum(opening_balance) from acc_accounts_head
  5267.     where acc_accounts_head.accounts_head_id=acc_clients.accounts_head_id OR acc_accounts_head.accounts_head_id=acc_clients.advance_head_id ) WHERE acc_clients.accounts_head_id!=acc_clients.advance_head_id;
  5268.      UPDATE `acc_clients` SET `initial_opening_balance`=(select sum(opening_balance) from acc_accounts_head
  5269.     where acc_accounts_head.accounts_head_id=acc_clients.accounts_head_id OR acc_accounts_head.accounts_head_id=acc_clients.advance_head_id ) WHERE acc_clients.accounts_head_id!=acc_clients.advance_head_id;
  5270.     UPDATE `acc_clients` SET `client_received`=0 where 1;
  5271.     UPDATE `acc_suppliers` SET `supplier_due`=(select opening_balance from acc_accounts_head
  5272.     where acc_accounts_head.accounts_head_id=acc_suppliers.accounts_head_id  LIMIT 1) WHERE acc_suppliers.accounts_head_id=acc_suppliers.advance_head_id;
  5273.     UPDATE `acc_suppliers` SET `supplier_due`=(select sum(opening_balance) from acc_accounts_head
  5274.     where acc_accounts_head.accounts_head_id=acc_suppliers.accounts_head_id OR acc_accounts_head.accounts_head_id=acc_suppliers.advance_head_id ) WHERE acc_suppliers.accounts_head_id!=acc_suppliers.advance_head_id;
  5275.     UPDATE `acc_suppliers` SET `supplier_paid`=0 where 1;
  5276.     truncate `acc_closing_balance`;
  5277.     truncate `acc_actual_closing_balance`;
  5278.     truncate `monthly_summary`;
  5279. UPDATE company SET revenue=0, asset=0, liability=0, expense=0, payable=0 , receivable=0, net_worth=0, monthly_growth=0 WHERE 1;';
  5280.             //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5281.             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  5282.             
  5283.             //            $get_kids=$stmt;
  5284.             $vid 0;
  5285.             $vname '';
  5286.             $head_list = [];
  5287.             $headDataList = [];
  5288.             //            $curr_id = $head_id;
  5289.             $get_kids_sql 'select * from acc_accounts_head where accounts_head_id not in (select distinct parent_id from acc_accounts_head) ;';
  5290.             //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5291.             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5292.             
  5293.             $query $stmt;
  5294.             if (!empty($query)) ///exists so lets edit rather than creating new
  5295.             {
  5296.                 foreach ($query as $entry) {
  5297.                     if (!isset($headDataList[$entry['company_id']]))
  5298.                         $headDataList[$entry['company_id']] = array();
  5299.                     $primary_head_data = array();
  5300.                     $primary_head_data['id'] = $entry['accounts_head_id'];
  5301.                     $primary_head_data['addition'] = $entry['current_balance'];
  5302.                     $primary_head_data['headNature'] = $entry['head_nature'];
  5303.                     $primary_head_data['headType'] = $entry['type'];
  5304.                     $primary_head_data['pathTree'] = $entry['path_tree'];
  5305.                     $headDataList[$entry['company_id']][] = $primary_head_data;
  5306.                 }
  5307.             }
  5308.             foreach ($headDataList as $companyId => $headDataDetails) {
  5309.                 Company::updateMonthlySummary($em$headDataDetails$companyId'_opening_date_''_ALL_');
  5310.             }
  5311.             return new JsonResponse(array(
  5312.                 "success" => true,
  5313.                 "skip_ids" => $skip_ids,
  5314.             ));
  5315.         }
  5316.         //        MiscActions::refreshDatabase($em);
  5317.         //        return $this->redirectToRoute('dashboard');
  5318.     }
  5319.     public function GetNonLedgerHitVoucherCount(Request $request)
  5320.     {
  5321.         $em $this->getDoctrine()->getManager();
  5322.         $debug_data = [];
  5323.         //            $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  5324.         //                'approved' => 1,
  5325.         //                'ledgerHit' => 0
  5326.         //            ));
  5327.         $skip_ids = [];
  5328.         $v_count 0;
  5329.         if ($request->request->has('skipIds'))
  5330.             $skip_ids $request->request->get('skipIds');
  5331.         $get_kids_sql 'select count(transaction_id) v_count from acc_transactions where approved=1 and ledger_hit=0 ';
  5332.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5333.         
  5334.         $get_kids $stmt;
  5335.         if (!empty($get_kids))
  5336.             $v_count = ($get_kids[0]['v_count']);
  5337.         $vid 0;
  5338.         $vname '';
  5339.         return new JsonResponse(array(
  5340.             "success" => true,
  5341.             "v_count" => $v_count,
  5342.             "skip_ids" => $skip_ids,
  5343.         ));
  5344.         //        MiscActions::refreshDatabase($em);
  5345.         //        return $this->redirectToRoute('dashboard');
  5346.     }
  5347.     public function RefreshPath(Request $request$id 0)
  5348.     {
  5349.         $em $this->getDoctrine()->getManager();
  5350.         $head_id $id;
  5351.         $get_kids_sql " SELECT accounts_head_id FROM acc_accounts_head
  5352.                             WHERE acc_accounts_head.accounts_head_id >" $head_id " limit 1";
  5353.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5354.         
  5355.         $head $stmt;
  5356.         if (!empty($head)) {
  5357.             Accounts::AddHeadPath($em$head[0]['accounts_head_id']);
  5358.             return new JsonResponse(array(
  5359.                 "success" => true,
  5360.                 "last_id" => $head[0]['accounts_head_id'],
  5361.                 //                "r"=>$r,
  5362.                 //                "debug_data"=>System::encryptSignature($r)
  5363.             ));
  5364.         } else {
  5365.             return new JsonResponse(array(
  5366.                 "success" => false,
  5367.                 "last_id" => $head_id,
  5368.                 //                "r"=>$r,
  5369.                 //                "debug_data"=>System::encryptSignature($r)
  5370.             ));
  5371.         }
  5372.         //        return $this->redirectToRoute('dashboard');
  5373.     }
  5374.     public function RefreshHeadNature(Request $request$id 0)
  5375.     {
  5376.         $em $this->getDoctrine()->getManager();
  5377.         $head_id $id;
  5378.         $assetParentHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
  5379.             'type' => AccountsConstant::ASSET,
  5380.             'head_level' => 1
  5381.         ));
  5382.         $libParentHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
  5383.             'type' => AccountsConstant::LIABILITY,
  5384.             'head_level' => 1
  5385.         ));
  5386.         $incParentHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
  5387.             'type' => AccountsConstant::INCOME,
  5388.             'head_level' => 1
  5389.         ));
  5390.         $expParentHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
  5391.             'type' => AccountsConstant::EXPENSE,
  5392.             'head_level' => 1
  5393.         ));
  5394.         if ($assetParentHead) {
  5395.             $stmt $em->getConnection()->executeStatement("update acc_accounts_head set head_nature='dr' , `type`='ast' where path_tree like '%/" $assetParentHead->getAccountsHeadId() . "/%' ");
  5396.             
  5397.             //            $head=$stmt;
  5398.         }
  5399.         if ($expParentHead) {
  5400.             $stmt $em->getConnection()->executeStatement("update acc_accounts_head set head_nature='dr' , `type`='exp' where path_tree like '%/" $expParentHead->getAccountsHeadId() . "/%' ");
  5401.             
  5402.             //            $head=$stmt;
  5403.         }
  5404.         if ($incParentHead) {
  5405.             $stmt $em->getConnection()->executeStatement("update acc_accounts_head set head_nature='cr' , `type`='inc' where path_tree like '%/" $incParentHead->getAccountsHeadId() . "/%' ");
  5406.             
  5407.             //            $head=$stmt;
  5408.         }
  5409.         if ($libParentHead) {
  5410.             $stmt $em->getConnection()->executeStatement("update acc_accounts_head set head_nature='cr' , `type`='lib' where path_tree like '%/" $libParentHead->getAccountsHeadId() . "/%' ");
  5411.             
  5412.             //            $head=$stmt;
  5413.         }
  5414.         if (!empty($head)) {
  5415.             return new JsonResponse(array(
  5416.                 "success" => true,
  5417.                 "last_id" => $head[0]['accounts_head_id'],
  5418.                 //                "r"=>$r,
  5419.                 //                "debug_data"=>System::encryptSignature($r)
  5420.             ));
  5421.         } else {
  5422.             return new JsonResponse(array(
  5423.                 "success" => false,
  5424.                 "last_id" => $head_id,
  5425.                 //                "r"=>$r,
  5426.                 //                "debug_data"=>System::encryptSignature($r)
  5427.             ));
  5428.         }
  5429.         //        return $this->redirectToRoute('dashboard');
  5430.     }
  5431.     public function RefreshCombo(Request $request)
  5432.     {
  5433.         $em $this->getDoctrine()->getManager();
  5434.         $debug_data = [];
  5435.         //test
  5436.         $wrong_voucher_list = [];
  5437.         $ind_voucherAmounts = [];
  5438.         $ind_voucherIds = [];
  5439.         //        $ind_voucherAmounts=[];
  5440.         $transactions $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  5441.             ->findBy(
  5442.                 array(
  5443.                     'approved' => 1,
  5444.                     'ledgerHit' => 1,
  5445.                 )
  5446.             );
  5447.         foreach ($transactions as $d) {
  5448.             $ind_voucherAmounts[$d->getTransactionId()] = 0;
  5449.             $ind_voucherIds[] = $d->getTransactionId();
  5450.         }
  5451.         $transactions $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
  5452.             ->findBy(
  5453.                 array(
  5454.                     'transactionId' => $ind_voucherIds,
  5455.                 )
  5456.             );
  5457.         foreach ($transactions as $d) {
  5458.             if ($d->getPosition() == 'cr')
  5459.                 $ind_voucherAmounts[$d->getTransactionId()] += $d->getAmount();
  5460.             elseif ($d->getPosition() == 'dr')
  5461.                 $ind_voucherAmounts[$d->getTransactionId()] -= $d->getAmount();
  5462.         }
  5463.         foreach ($ind_voucherAmounts as $k => $d) {
  5464.             if ($d >= || $d <= -1)
  5465.                 $wrong_voucher_list[$k] = $d;
  5466.         }
  5467.         $debug_data $wrong_voucher_list;
  5468.         //test ends
  5469.         return new JsonResponse(
  5470.             $debug_data
  5471.         );
  5472.         //        return $this->render(
  5473.         //            'ApplicationBundle:pages/accounts/settings:refresh_combo_action.html.twig',
  5474.         //            array(
  5475.         //                'page_title' => 'Refresh',
  5476.         //                'debug_data' => $debug_data,
  5477.         //                'autoStartLedgerHit' => 0,
  5478.         //                'autoStartInventoryRefresh' => 0,
  5479.         //                'inventoryRefreshed' => 0,
  5480.         //                'lastRefreshDate' => '',
  5481.         //                'autoStartFixedAssetDepreciation' => 0,
  5482.         //
  5483.         //                //                'voucherDetails'=>$v_details,
  5484.         //                //                'heads'=>Accounts::HeadList($em),
  5485.         //                //                'transaction'=>$Transaction
  5486.         //            )
  5487.         //        );
  5488.         //        return $this->redirectToRoute('dashboard');
  5489.     }
  5490.     /**
  5491.      * Core A — recompute acc_accounts_head.current_balance from the ledger.
  5492.      *
  5493.      * Two modes:
  5494.      *   - per-voucher: POST/GET transaction id (?id= or ?transaction_id=) → rebuilds
  5495.      *     only the heads that voucher touches (+ their subtree/ancestor chains).
  5496.      *     This is the on-page "Recompute balances" fix for the voucher view and the
  5497.      *     hook for the inline amount editor (so editing an amount can no longer
  5498.      *     leave current_balance stale, as it did on the NETZE tenant).
  5499.      *   - full: ?all=1 → rebuilds every ledger-backed head in the tenant.
  5500.      *
  5501.      * Dry-run unless ?apply=1. Unbacked heads (no ledger rows behind them, e.g.
  5502.      * unposted opening balances) are reported but never written unless
  5503.      * ?include_unbacked=1.
  5504.      */
  5505.     public function RebuildVoucherBalances(Request $request)
  5506.     {
  5507.         $em $this->getDoctrine()->getManager();
  5508.         $apply           = (int) $request->get('apply'0) === 1;
  5509.         $includeUnbacked = (int) $request->get('include_unbacked'0) === 1;
  5510.         $all             = (int) $request->get('all'0) === 1;
  5511.         $txId            $request->get('id'$request->get('transaction_id'null));
  5512.         $headIds = [];
  5513.         if (!$all) {
  5514.             if ($txId === null || $txId === '') {
  5515.                 return new JsonResponse(['ok' => 0'error' => 'Provide a transaction id, or all=1 for a full rebuild.'], 400);
  5516.             }
  5517.             $details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
  5518.                 ->findBy(array('transactionId' => (int) $txId));
  5519.             foreach ($details as $d) {
  5520.                 $headIds[] = (int) $d->getAccountsHeadId();
  5521.             }
  5522.             if (empty($headIds)) {
  5523.                 return new JsonResponse(['ok' => 0'error' => 'No ledger lines found for transaction ' $txId '.'], 404);
  5524.             }
  5525.         }
  5526.         try {
  5527.             $result = \ApplicationBundle\Modules\Accounts\Service\LedgerRebuildService::recompute($em, [
  5528.                 'headIds'         => $headIds,
  5529.                 'apply'           => $apply,
  5530.                 'includeUnbacked' => $includeUnbacked,
  5531.             ]);
  5532.         } catch (\Throwable $e) {
  5533.             return new JsonResponse(['ok' => 0'error' => $e->getMessage()], 500);
  5534.         }
  5535.         return new JsonResponse(array_merge(
  5536.             ['ok' => 1'scope' => $all 'all' : ('transaction:' $txId)],
  5537.             $result['summary'],
  5538.             ['rows' => array_slice($result['rows'], 0100)]
  5539.         ));
  5540.     }
  5541.     public function OpeningHeadBalanceForce(Request $request)
  5542.     {
  5543.         $em $this->getDoctrine()->getManager();
  5544.         $new_cc $this->getDoctrine()
  5545.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  5546.             ->findOneBy(
  5547.                 array(
  5548.                     'name' => 'accounting_year_start',
  5549.                 )
  5550.             );
  5551.         $start_date_str $new_cc $new_cc->getData() : "";
  5552.         $start_date = new \DateTime($start_date_str);
  5553.         $query_head_list = [];
  5554.         $head_list = [];
  5555.         $debug_data = [];
  5556.         $customer_heads = [];
  5557.         $get_kids_sql '     select distinct  `accounts_head_id` from acc_clients where 1;';
  5558.         //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5559.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5560.         
  5561.         $get_kids $stmt;
  5562.         foreach ($get_kids as $kid)
  5563.             $customer_heads[] = $kid['accounts_head_id'];
  5564.         $get_kids_sql '     select distinct  `advance_head_id` from acc_clients where 1;';
  5565.         //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5566.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5567.         
  5568.         $get_kids $stmt;
  5569.         foreach ($get_kids as $kid)
  5570.             $customer_heads[] = $kid['advance_head_id'];
  5571.         if ($request->isMethod('POST')) {
  5572.             $data = [];
  5573.             if ($request->request->has('dataHere'))
  5574.                 $data json_decode($request->request->get('dataHere'), true);
  5575.             if (!empty($data)) {
  5576.                 if (isset($data['head_id'])) {
  5577.                     //1st get all head data
  5578.                     $get_kids_sql '     UPDATE `acc_accounts_head` SET opening_balance=0 WHERE 1;';
  5579.                     //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5580.                     $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5581.                     
  5582.                     $em->flush();
  5583.                     $get_kids_sql "SELECT acc_accounts_head.name,
  5584. acc_accounts_head.opening_balance,
  5585. acc_accounts_head.current_balance,
  5586. acc_accounts_head.current_balance_reconciled,
  5587. acc_accounts_head.path_tree,
  5588. acc_accounts_head.head_nature,
  5589.  acc_accounts_head.cc_enabled, acc_accounts_head.accounts_head_id, acc_accounts_head.parent_id, acc_accounts_head.type, acc_accounts_head.advance_of, b.name  parent_name FROM acc_accounts_head left join acc_accounts_head as b
  5590. on acc_accounts_head.parent_id=b.accounts_head_id WHERE  acc_accounts_head.company_id=" .
  5591.                         $this->getLoggedUserCompanyId($request) . "  ORDER BY name ASC";
  5592.                     $get_kids_sql .= '';
  5593.                     $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5594.                     
  5595.                     $get_kids $stmt;
  5596.                     foreach ($get_kids as $kid) {
  5597.                         $m = array();
  5598.                         $par_list array_filter(explode('/'$kid["path_tree"]));
  5599.                         $m["id"] = $kid["accounts_head_id"];
  5600.                         $m["value"] = $kid["accounts_head_id"];
  5601.                         $m["text"] = $kid["name"] . (($kid["advance_of"] == null || $kid["advance_of"] == 0) ? '' ' (Advance)');
  5602.                         $m["parent_name"] = $kid["parent_name"];
  5603.                         $m["type"] = $kid["type"];
  5604.                         $m["head_nature"] = $kid["head_nature"];
  5605.                         $m["opening"] = $kid["opening_balance"];
  5606.                         //                        $m["opening"] = 0;
  5607.                         $m["newOpening"] = 0;
  5608.                         $m["newCurrentBalance"] = 0;
  5609.                         $m["newCurrentBalanceReconciled"] = 0;
  5610.                         $m["current_balance"] = $kid["current_balance"];
  5611.                         $m["reconciled_balance"] = $kid["current_balance_reconciled"];
  5612.                         $m["parent_id"] = $kid["parent_id"];
  5613.                         $m["allParents"] = $par_list;
  5614.                         $m["cc_enabled"] = $kid["cc_enabled"];
  5615.                         $m["child_total_balance"] = 0;
  5616.                         $head_list[$kid["accounts_head_id"]] = $m;
  5617.                     }
  5618.                     //next check the change in opening
  5619.                     foreach ($data['head_id'] as $k => $h) {
  5620.                         if (isset($head_list[$h])) {
  5621.                             $to_add 0;
  5622.                             //                            $to_add=(1*$data['head_opening'][$k])-(1*$head_list[$h]['opening']);
  5623.                             $child_nature $head_list[$h]['head_nature'];
  5624.                             //                            if(!isset($head_list[$h]['to_add']))
  5625.                             //                            {
  5626.                             //                                $head_list[$h]['to_add']=$to_add;
  5627.                             //                            }
  5628.                             //                            $head_list[$h]['opening']=$head_list[$h]['opening']+$to_add;
  5629.                             //                            $head_list[$h]['current_balance']=$head_list[$h]['current_balance']+$to_add;
  5630.                             //                            $head_list[$h]['reconciled_balance']=$head_list[$h]['reconciled_balance']+$to_add;
  5631.                             $to_add_cb = (str_replace(","""$data['head_opening'][$k]));
  5632.                             $head_list[$h]['newOpening'] = $head_list[$h]['newOpening'] + $to_add_cb;
  5633.                             $head_list[$h]['newCurrentBalance'] = $head_list[$h]['newCurrentBalance'] + $to_add_cb;
  5634.                             $head_list[$h]['newCurrentBalanceReconciled'] = $head_list[$h]['newCurrentBalanceReconciled'] + $to_add_cb;
  5635.                             $head_list[$h]['child_total_balance'] = $head_list[$h]['child_total_balance'] + $to_add_cb;
  5636.                             //                            if($to_add!=0)
  5637.                             {
  5638.                                 foreach ($head_list[$h]['allParents'] as $par) {
  5639.                                     if (isset($head_list[$par])) {
  5640.                                         $to_add_par 0;
  5641.                                         $to_add_cb = ($child_nature == $head_list[$par]['head_nature']) ? ($to_add_cb) : ((-1) * $to_add_cb);
  5642.                                         if (!isset($head_list[$par]['child_total_balance'])) {
  5643.                                             $head_list[$par]['child_total_balance'] = $to_add_cb;
  5644.                                         } else {
  5645.                                             $head_list[$par]['child_total_balance'] = $head_list[$par]['child_total_balance'] + $to_add_cb;
  5646.                                         }
  5647.                                         $head_list[$par]['newOpening'] = $head_list[$par]['newOpening'] + $to_add_cb;
  5648.                                         $head_list[$par]['newCurrentBalance'] = $head_list[$par]['newCurrentBalance'] + $to_add_cb;
  5649.                                         $head_list[$par]['newCurrentBalanceReconciled'] = $head_list[$par]['newCurrentBalanceReconciled'] + $to_add_cb;
  5650.                                     }
  5651.                                 }
  5652.                             }
  5653.                         }
  5654.                     }
  5655.                     foreach ($head_list as $k => $head) {
  5656.                         //                        if (isset($head['to_add']) && $head['to_add'] != 0) {
  5657.                         //                        $query_head_list[]=$k;
  5658.                         //                        }
  5659.                         if (isset($head['child_total_balance'])) {
  5660.                             if ($head['newOpening'] != $head['opening']) {
  5661.                                 $to_add $head['newOpening'] - $head['opening'];
  5662.                                 $head_list[$k]['to_add'] = $head['newOpening'] - $head['opening'];
  5663.                                 $head_list[$k]['opening'] = $head['opening'] + $to_add;
  5664.                                 $head_list[$k]['current_balance'] = $head['current_balance'] + $to_add;
  5665.                                 $head_list[$k]['reconciled_balance'] = $head['reconciled_balance'] + $to_add;
  5666.                                 $query_head_list[] = $k;
  5667.                             }
  5668.                         }
  5669.                     }
  5670.                     //if no change then dont use  that
  5671.                     //add teh change to all the closings found in that criteria be ware of the head natures
  5672.                     $closings $em->getRepository('ApplicationBundle\\Entity\\AccClosingBalance')->findBy(
  5673.                         array(
  5674.                             'accountsHeadId' => $query_head_list
  5675.                         )
  5676.                     );
  5677.                     foreach ($closings as $closing) {
  5678.                         //check if the date is >= to start_date
  5679.                         if ($closing->getDate() >= $start_date) {
  5680.                             $to_add = isset($head_list[$closing->getAccountsHeadId()]['to_add']) ? $head_list[$closing->getAccountsHeadId()]['to_add'] : 0;
  5681.                             if ($to_add != 0) {
  5682.                                 $closing->setOpening($closing->getOpening() + $to_add);
  5683.                                 $closing->setBalance($closing->getBalance() + $to_add);
  5684.                                 //                                            $closing->setAddition($closing->getAddition() + $to_add);
  5685.                             }
  5686.                         }
  5687.                     }
  5688.                     $em->flush();
  5689.                     //add teh change to all the actual closings found in that criteria be ware of the head natures
  5690.                     $closings $em->getRepository('ApplicationBundle\\Entity\\AccActualClosingBalance')->findBy(
  5691.                         array(
  5692.                             'accountsHeadId' => $query_head_list
  5693.                         )
  5694.                     );
  5695.                     foreach ($closings as $closing) {
  5696.                         //check if the date is >= to start_date
  5697.                         if ($closing->getDate() >= $start_date) {
  5698.                             $to_add = isset($head_list[$closing->getAccountsHeadId()]['to_add']) ? $head_list[$closing->getAccountsHeadId()]['to_add'] : 0;
  5699.                             if ($to_add != 0) {
  5700.                                 $closing->setOpening($closing->getOpening() + $to_add);
  5701.                                 $closing->setBalance($closing->getBalance() + $to_add);
  5702.                                 //                                            $closing->setAddition($closing->getAddition() + $to_add);
  5703.                             }
  5704.                         }
  5705.                     }
  5706.                     $em->flush();
  5707.                     //add teh change to all the Heads found in that criteria be ware of the head natures
  5708.                     $heads $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findBy(
  5709.                         array(
  5710.                             'accountsHeadId' => $query_head_list
  5711.                         )
  5712.                     );
  5713.                     foreach ($heads as $head) {
  5714.                         $to_add = isset($head_list[$head->getAccountsHeadId()]['to_add']) ? $head_list[$head->getAccountsHeadId()]['to_add'] : 0;
  5715.                         if ($to_add != 0) {
  5716.                             $head->setOpeningBalance($head_list[$head->getAccountsHeadId()]['opening']);
  5717.                             $head->setCurrentBalance($head_list[$head->getAccountsHeadId()]['current_balance']);
  5718.                             $head->setCurrentBalanceReconciled($head_list[$head->getAccountsHeadId()]['reconciled_balance']);
  5719.                         }
  5720.                     }
  5721.                     $em->flush();
  5722.                 }
  5723.             }
  5724.             $this->addFlash(
  5725.                 'success',
  5726.                 'The Action was Successful.'
  5727.             );
  5728.             //            MiscActions::refreshTransactions($em);
  5729.             //            return $this->redirectToRoute('dashboard');
  5730.             $debug_data $head_list;
  5731.         }
  5732.         $child_head_list Accounts::getParentLedgerHeads($em'''', []);
  5733.         return $this->render(
  5734.             '@Accounts/pages/input_forms/opening_head_balance_assign.html.twig',
  5735.             array(
  5736.                 'page_title' => 'Assign Head Opening',
  5737.                 'head_list' => $child_head_list,
  5738.                 'customer_heads' => $customer_heads,
  5739.                 'start_date' => $start_date,
  5740.                 'mod_head_list' => $head_list,
  5741.                 'query_head_list' => $query_head_list,
  5742.                 'debug_data' => $debug_data
  5743.                 //                'voucherDetails'=>$v_details,
  5744.                 //                'heads'=>Accounts::HeadList($em),
  5745.                 //                'transaction'=>$Transaction
  5746.             )
  5747.         );
  5748.     }
  5749.     public function OpeningHeadBalance(Request $request)
  5750.     {
  5751.         $em $this->getDoctrine()->getManager();
  5752.         $new_cc $this->getDoctrine()
  5753.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  5754.             ->findOneBy(
  5755.                 array(
  5756.                     'name' => 'accounting_year_start',
  5757.                 )
  5758.             );
  5759.         $start_date_str $new_cc $new_cc->getData() : "";
  5760.         $start_date = new \DateTime($start_date_str);
  5761.         $query_head_list = [];
  5762.         $head_list = [];
  5763.         $debug_data = [];
  5764.         $customer_heads = [];
  5765.         $get_kids_sql '     select distinct  `accounts_head_id` from acc_clients where 1;';
  5766.         //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5767.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5768.         
  5769.         $get_kids $stmt;
  5770.         foreach ($get_kids as $kid)
  5771.             $customer_heads[] = $kid['accounts_head_id'];
  5772.         $get_kids_sql '     select distinct  `advance_head_id` from acc_clients where 1;';
  5773.         //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5774.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5775.         
  5776.         $get_kids $stmt;
  5777.         foreach ($get_kids as $kid)
  5778.             $customer_heads[] = $kid['advance_head_id'];
  5779.         if ($request->isMethod('POST')) {
  5780.             $data = [];
  5781.             if ($request->request->has('dataHere'))
  5782.                 $data json_decode($request->request->get('dataHere'), true);
  5783.             if (!empty($data)) {
  5784.                 if (isset($data['head_id'])) {
  5785.                     //1st get all head data
  5786.                     $get_kids_sql "SELECT acc_accounts_head.name,
  5787. acc_accounts_head.opening_balance,
  5788. acc_accounts_head.current_balance,
  5789. acc_accounts_head.current_balance_reconciled,
  5790. acc_accounts_head.path_tree,
  5791. acc_accounts_head.head_nature,
  5792.  acc_accounts_head.cc_enabled, acc_accounts_head.accounts_head_id, acc_accounts_head.parent_id, acc_accounts_head.type, acc_accounts_head.advance_of, b.name  parent_name FROM acc_accounts_head left join acc_accounts_head as b
  5793. on acc_accounts_head.parent_id=b.accounts_head_id WHERE  acc_accounts_head.company_id=" .
  5794.                         $this->getLoggedUserCompanyId($request) . "  ORDER BY name ASC";
  5795.                     $get_kids_sql .= '';
  5796.                     $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5797.                     
  5798.                     $get_kids $stmt;
  5799.                     foreach ($get_kids as $kid) {
  5800.                         $m = array();
  5801.                         $par_list array_filter(explode('/'$kid["path_tree"]));
  5802.                         $m["id"] = $kid["accounts_head_id"];
  5803.                         $m["value"] = $kid["accounts_head_id"];
  5804.                         $m["text"] = $kid["name"] . (($kid["advance_of"] == null || $kid["advance_of"] == 0) ? '' ' (Advance)');
  5805.                         $m["parent_name"] = $kid["parent_name"];
  5806.                         $m["type"] = $kid["type"];
  5807.                         $m["head_nature"] = $kid["head_nature"];
  5808.                         $m["opening"] = $kid["opening_balance"];
  5809.                         $m["newOpening"] = 0;
  5810.                         $m["newCurrentBalance"] = 0;
  5811.                         $m["newCurrentBalanceReconciled"] = 0;
  5812.                         $m["current_balance"] = $kid["current_balance"];
  5813.                         $m["reconciled_balance"] = $kid["current_balance_reconciled"];
  5814.                         $m["parent_id"] = $kid["parent_id"];
  5815.                         $m["allParents"] = $par_list;
  5816.                         $m["cc_enabled"] = $kid["cc_enabled"];
  5817.                         $m["child_total_balance"] = 0;
  5818.                         $head_list[$kid["accounts_head_id"]] = $m;
  5819.                     }
  5820.                     //next check the change in opening
  5821.                     foreach ($data['head_id'] as $k => $h) {
  5822.                         if (isset($head_list[$h])) {
  5823.                             $to_add 0;
  5824.                             //                            $to_add=(1*$data['head_opening'][$k])-(1*$head_list[$h]['opening']);
  5825.                             $child_nature $head_list[$h]['head_nature'];
  5826.                             //                            if(!isset($head_list[$h]['to_add']))
  5827.                             //                            {
  5828.                             //                                $head_list[$h]['to_add']=$to_add;
  5829.                             //                            }
  5830.                             //                            $head_list[$h]['opening']=$head_list[$h]['opening']+$to_add;
  5831.                             //                            $head_list[$h]['current_balance']=$head_list[$h]['current_balance']+$to_add;
  5832.                             //                            $head_list[$h]['reconciled_balance']=$head_list[$h]['reconciled_balance']+$to_add;
  5833.                             $to_add_cb = (str_replace(","""$data['head_opening'][$k]));
  5834.                             $head_list[$h]['newOpening'] = $head_list[$h]['newOpening'] + $to_add_cb;
  5835.                             $head_list[$h]['newCurrentBalance'] = $head_list[$h]['newCurrentBalance'] + $to_add_cb;
  5836.                             $head_list[$h]['newCurrentBalanceReconciled'] = $head_list[$h]['newCurrentBalanceReconciled'] + $to_add_cb;
  5837.                             $head_list[$h]['child_total_balance'] = $head_list[$h]['child_total_balance'] + $to_add_cb;
  5838.                             //                            if($to_add!=0)
  5839.                             {
  5840.                                 foreach ($head_list[$h]['allParents'] as $par) {
  5841.                                     if (isset($head_list[$par])) {
  5842.                                         $to_add_par 0;
  5843.                                         $to_add_cb = ($child_nature == $head_list[$par]['head_nature']) ? ($to_add_cb) : ((-1) * $to_add_cb);
  5844.                                         if (!isset($head_list[$par]['child_total_balance'])) {
  5845.                                             $head_list[$par]['child_total_balance'] = $to_add_cb;
  5846.                                         } else {
  5847.                                             $head_list[$par]['child_total_balance'] = $head_list[$par]['child_total_balance'] + $to_add_cb;
  5848.                                         }
  5849.                                         $head_list[$par]['newOpening'] = $head_list[$par]['newOpening'] + $to_add_cb;
  5850.                                         $head_list[$par]['newCurrentBalance'] = $head_list[$par]['newCurrentBalance'] + $to_add_cb;
  5851.                                         $head_list[$par]['newCurrentBalanceReconciled'] = $head_list[$par]['newCurrentBalanceReconciled'] + $to_add_cb;
  5852.                                     }
  5853.                                 }
  5854.                             }
  5855.                         }
  5856.                     }
  5857.                     foreach ($head_list as $k => $head) {
  5858.                         //                        if (isset($head['to_add']) && $head['to_add'] != 0) {
  5859.                         //                        $query_head_list[]=$k;
  5860.                         //                        }
  5861.                         if (isset($head['child_total_balance'])) {
  5862.                             if ($head['newOpening'] != $head['opening']) {
  5863.                                 $to_add $head['newOpening'] - $head['opening'];
  5864.                                 $head_list[$k]['to_add'] = $head['newOpening'] - $head['opening'];
  5865.                                 $head_list[$k]['opening'] = $head['opening'] + $to_add;
  5866.                                 $head_list[$k]['current_balance'] = $head['current_balance'] + $to_add;
  5867.                                 $head_list[$k]['reconciled_balance'] = $head['reconciled_balance'] + $to_add;
  5868.                                 $query_head_list[] = $k;
  5869.                             }
  5870.                         }
  5871.                     }
  5872.                     //if no change then dont use  that
  5873.                     //add teh change to all the closings found in that criteria be ware of the head natures
  5874.                     $closings $em->getRepository('ApplicationBundle\\Entity\\AccClosingBalance')->findBy(
  5875.                         array(
  5876.                             'accountsHeadId' => $query_head_list
  5877.                         )
  5878.                     );
  5879.                     foreach ($closings as $closing) {
  5880.                         //check if the date is >= to start_date
  5881.                         if ($closing->getDate() >= $start_date) {
  5882.                             $to_add = isset($head_list[$closing->getAccountsHeadId()]['to_add']) ? $head_list[$closing->getAccountsHeadId()]['to_add'] : 0;
  5883.                             if ($to_add != 0) {
  5884.                                 $closing->setOpening($closing->getOpening() + $to_add);
  5885.                                 $closing->setBalance($closing->getBalance() + $to_add);
  5886.                                 //                                            $closing->setAddition($closing->getAddition() + $to_add);
  5887.                             }
  5888.                         }
  5889.                     }
  5890.                     $em->flush();
  5891.                     //add teh change to all the actual closings found in that criteria be ware of the head natures
  5892.                     $closings $em->getRepository('ApplicationBundle\\Entity\\AccActualClosingBalance')->findBy(
  5893.                         array(
  5894.                             'accountsHeadId' => $query_head_list
  5895.                         )
  5896.                     );
  5897.                     foreach ($closings as $closing) {
  5898.                         //check if the date is >= to start_date
  5899.                         if ($closing->getDate() >= $start_date) {
  5900.                             $to_add = isset($head_list[$closing->getAccountsHeadId()]['to_add']) ? $head_list[$closing->getAccountsHeadId()]['to_add'] : 0;
  5901.                             if ($to_add != 0) {
  5902.                                 $closing->setOpening($closing->getOpening() + $to_add);
  5903.                                 $closing->setBalance($closing->getBalance() + $to_add);
  5904.                                 //                                            $closing->setAddition($closing->getAddition() + $to_add);
  5905.                             }
  5906.                         }
  5907.                     }
  5908.                     $em->flush();
  5909.                     //add teh change to all the Heads found in that criteria be ware of the head natures
  5910.                     $heads $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findBy(
  5911.                         array(
  5912.                             'accountsHeadId' => $query_head_list
  5913.                         )
  5914.                     );
  5915.                     foreach ($heads as $head) {
  5916.                         $to_add = isset($head_list[$head->getAccountsHeadId()]['to_add']) ? $head_list[$head->getAccountsHeadId()]['to_add'] : 0;
  5917.                         if ($to_add != 0) {
  5918.                             $head->setOpeningBalance($head_list[$head->getAccountsHeadId()]['opening']);
  5919.                             $head->setCurrentBalance($head_list[$head->getAccountsHeadId()]['current_balance']);
  5920.                             $head->setCurrentBalanceReconciled($head_list[$head->getAccountsHeadId()]['reconciled_balance']);
  5921.                         }
  5922.                     }
  5923.                     $em->flush();
  5924.                 }
  5925.             }
  5926.             $this->addFlash(
  5927.                 'success',
  5928.                 'The Action was Successful.'
  5929.             );
  5930.             //            MiscActions::refreshTransactions($em);
  5931.             //            return $this->redirectToRoute('dashboard');
  5932.             $debug_data $head_list;
  5933.         }
  5934.         $child_head_list Accounts::getParentLedgerHeads($em'''', []);
  5935.         return $this->render(
  5936.             '@Accounts/pages/input_forms/opening_head_balance_assign.html.twig',
  5937.             array(
  5938.                 'page_title' => 'Assign Head Opening',
  5939.                 'head_list' => $child_head_list,
  5940.                 'start_date' => $start_date,
  5941.                 'mod_head_list' => $head_list,
  5942.                 'query_head_list' => $query_head_list,
  5943.                 'customer_heads' => $customer_heads,
  5944.                 'debug_data' => $debug_data
  5945.                 //                'voucherDetails'=>$v_details,
  5946.                 //                'heads'=>Accounts::HeadList($em),
  5947.                 //                'transaction'=>$Transaction
  5948.             )
  5949.         );
  5950.     }
  5951.     public function EditJournalVoucher(Request $request$id)
  5952.     {
  5953.         $v_details = [];
  5954.         $Transaction = [];
  5955.         if ($id != 0) {
  5956.             $em $this->getDoctrine()->getManager();
  5957.             $Transaction $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  5958.                 'transactionId' => $id,
  5959.                 'editFlag' => 1,
  5960.                 'lockFlag' => [0null],
  5961.                 'disabledFlag' => [0null],
  5962.             ));
  5963.             if ($Transaction) {
  5964.                 $v_details Accounts::GetVoucherDetails($em$id);
  5965.             } else {
  5966.                 //            $this->container->get("session")->setFlash("error", "Pikachu is not allowed");
  5967.                 $this->addFlash(
  5968.                     'error',
  5969.                     'The Action was not allowed.'
  5970.                 );
  5971.             }
  5972.         }
  5973.         if ($request->isMethod('POST')) {
  5974.             //            Generic::debugMessage($_POST);
  5975.             $em $this->getDoctrine()->getManager();
  5976.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  5977.             $dochash $request->request->get('voucherNumber'); //change
  5978.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5979.             $approveRole $request->request->get('approvalRole');
  5980.             $approveHash $request->request->get('approvalHash');
  5981.             if (!DocValidation::isEditable(
  5982.                 $em,
  5983.                 $entity_id,
  5984.                 $dochash,
  5985.                 $loginId,
  5986.                 $approveRole,
  5987.                 $approveHash
  5988.             )) {
  5989.                 $this->addFlash(
  5990.                     'error',
  5991.                     'Sorry Couldnot insert Data.'
  5992.                 );
  5993.             } else {
  5994.                 //1st delete the doc
  5995.                 $funcname 'AccTransactions';
  5996.                 $doc_id $request->request->get('extTransId');
  5997.                 DeleteDocument::$funcname($em$doc_id0);
  5998.                 $ledgerHeads $request->request->get('ledgerHeads');
  5999.                 $notes $request->request->get('trNote');
  6000.                 $costCenters $request->request->get('costCenters');
  6001.                 $drAmount $request->request->get('drAmount');
  6002.                 $crAmount $request->request->get('crAmount');
  6003.                 $check_allowed 0;
  6004.                 if ($request->request->has('check_allowed'))
  6005.                     $check_allowed 1;
  6006.                 $em_goc $this->getDoctrine()->getManager('company_group');
  6007.                 $post_data $request->request;
  6008.                 $TransID Accounts::EditExistingTrans(
  6009.                     $this->getDoctrine()->getManager(),
  6010.                     $doc_id,
  6011.                     $request->request->get('date'),
  6012.                     array_sum($request->request->get('drAmount')),
  6013.                     AccountsConstant::VOUCHER_JOURNAL,
  6014.                     $request->request->get('description'),
  6015.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  6016.                     $request->request->get('type_hash'),
  6017.                     $request->request->get('prefix_hash'),
  6018.                     $request->request->get('assoc_hash'),
  6019.                     $request->request->get('number_hash'),
  6020.                     $check_allowed,
  6021.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6022.                     $this->getLoggedUserCompanyId($request)
  6023.                 );
  6024.                 for ($i 0$i count($ledgerHeads); $i++) {
  6025.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  6026.                         Accounts::CreateNewTransactionDetails(
  6027.                             $this->getDoctrine()->getManager(),
  6028.                             $request->request->get('date'),
  6029.                             $TransID,
  6030.                             Generic::CurrToInt($drAmount[$i]),
  6031.                             $ledgerHeads[$i],
  6032.                             $notes[$i],
  6033.                             AccountsConstant::DEBIT,
  6034.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6035.                             [],
  6036.                             [],
  6037.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6038.                         );
  6039.                     }
  6040.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  6041.                         Accounts::CreateNewTransactionDetails(
  6042.                             $this->getDoctrine()->getManager(),
  6043.                             $request->request->get('date'),
  6044.                             $TransID,
  6045.                             Generic::CurrToInt($crAmount[$i]),
  6046.                             $ledgerHeads[$i],
  6047.                             $notes[$i],
  6048.                             AccountsConstant::CREDIT,
  6049.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6050.                             [],
  6051.                             [],
  6052.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6053.                         );
  6054.                     }
  6055.                 }
  6056.                 //now add Approval info
  6057.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6058.                 $approveRole 2;  //created
  6059.                 $options = array(
  6060.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6061.                     'notification_server' => $this->container->getParameter('notification_server'),
  6062.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6063.                     'url' => $this->generateUrl(
  6064.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  6065.                     )
  6066.                 );
  6067.                 System::setApprovalInfo(
  6068.                     $this->getDoctrine()->getManager(),
  6069.                     $options,
  6070.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  6071.                     $TransID,
  6072.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6073.                     3    //journal voucher
  6074.                 );
  6075.                 System::createEditSignatureHash(
  6076.                     $this->getDoctrine()->getManager(),
  6077.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  6078.                     $TransID,
  6079.                     $loginId,
  6080.                     $approveRole,
  6081.                     $request->request->get('approvalHash')
  6082.                 );
  6083.                 $trans_here $this->getDoctrine()
  6084.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  6085.                     ->findOneBy(
  6086.                         array(
  6087.                             'transactionId' => $TransID
  6088.                         )
  6089.                     );
  6090.                 //notify
  6091.                 System::AddNewNotification(
  6092.                     $this->container->getParameter('notification_enabled'),
  6093.                     $this->container->getParameter('notification_server'),
  6094.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  6095.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  6096.                     "Journal Voucher : " $trans_here->getDocumentHash() . " is Created Right Now",
  6097.                     'all',
  6098.                     "",
  6099.                     'success',
  6100.                     "",
  6101.                     "Journal"
  6102.                 );
  6103.                 $this->addFlash(
  6104.                     'success',
  6105.                     'New Transaction Added.'
  6106.                 );
  6107.             }
  6108.         }
  6109.         return $this->render(
  6110.             '@Accounts/pages/input_forms/journal_voucher.html.twig',
  6111.             array(
  6112.                 'page_title' => 'Edit Journal Voucher',
  6113.                 'voucherDetails' => $v_details,
  6114.                 //                'heads'=>Accounts::HeadList($em),
  6115.                 'transaction' => $Transaction
  6116.             )
  6117.         );
  6118.     }
  6119.     public function CancelCheck(Request $request$voucherId 0)
  6120.     {
  6121.         $em $this->getDoctrine()->getManager();
  6122.         if ($request->isMethod('POST')) {
  6123.             //            Generic::debugMessage($_POST);
  6124.             $em $this->getDoctrine()->getManager();
  6125.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  6126.             $dochash $request->request->get('voucherNumber'); //change
  6127.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6128.             $approveRole $request->request->get('approvalRole');
  6129.             $approveHash $request->request->get('approvalHash');
  6130.             if (!DocValidation::isInsertable(
  6131.                 $em,
  6132.                 $entity_id,
  6133.                 $dochash,
  6134.                 $loginId,
  6135.                 $approveRole,
  6136.                 $approveHash,
  6137.                 $voucherId
  6138.             )) {
  6139.                 $this->addFlash(
  6140.                     'error',
  6141.                     'Sorry Couldnot insert Data.'
  6142.                 );
  6143.             } else {
  6144.                 $funcname 'AccTransactions';
  6145.                 $doc_id $voucherId;
  6146.                 DeleteDocument::$funcname($em$doc_id0);
  6147.                 $ledgerHeads $request->request->get('ledgerHeads');
  6148.                 $notes $request->request->get('trNote');
  6149.                 $costCenters $request->request->get('costCenters');
  6150.                 $drAmount $request->request->get('drAmount');
  6151.                 $crAmount $request->request->get('crAmount');
  6152.                 $check_allowed 0;
  6153.                 if ($request->request->has('check_allowed'))
  6154.                     $check_allowed 1;
  6155.                 $TransID Accounts::CreateNewTransaction(
  6156.                     $voucherId,
  6157.                     $this->getDoctrine()->getManager(),
  6158.                     $request->request->get('date'),
  6159.                     array_sum($request->request->get('drAmount')),
  6160.                     AccountsConstant::VOUCHER_JOURNAL,
  6161.                     $request->request->get('description'),
  6162.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  6163.                     $request->request->get('type_hash'),
  6164.                     $request->request->get('prefix_hash'),
  6165.                     $request->request->get('assoc_hash'),
  6166.                     $request->request->get('number_hash'),
  6167.                     $check_allowed,
  6168.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6169.                     $this->getLoggedUserCompanyId($request)
  6170.                 );
  6171.                 for ($i 0$i count($ledgerHeads); $i++) {
  6172.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  6173.                         Accounts::CreateNewTransactionDetails(
  6174.                             $this->getDoctrine()->getManager(),
  6175.                             $request->request->get('date'),
  6176.                             $TransID,
  6177.                             Generic::CurrToInt($drAmount[$i]),
  6178.                             $ledgerHeads[$i],
  6179.                             $notes[$i],
  6180.                             AccountsConstant::DEBIT,
  6181.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6182.                             [],
  6183.                             [],
  6184.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6185.                         );
  6186.                     }
  6187.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  6188.                         Accounts::CreateNewTransactionDetails(
  6189.                             $this->getDoctrine()->getManager(),
  6190.                             $request->request->get('date'),
  6191.                             $TransID,
  6192.                             Generic::CurrToInt($crAmount[$i]),
  6193.                             $ledgerHeads[$i],
  6194.                             $notes[$i],
  6195.                             AccountsConstant::CREDIT,
  6196.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6197.                             [],
  6198.                             [],
  6199.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6200.                         );
  6201.                     }
  6202.                 }
  6203.                 //now add Approval info
  6204.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6205.                 $approveRole $request->request->get('approvalRole');
  6206.                 $options = array(
  6207.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6208.                     'notification_server' => $this->container->getParameter('notification_server'),
  6209.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6210.                     'url' => $this->generateUrl(
  6211.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  6212.                     )
  6213.                 );
  6214.                 System::setApprovalInfo(
  6215.                     $this->getDoctrine()->getManager(),
  6216.                     $options,
  6217.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  6218.                     $TransID,
  6219.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6220.                     3    //journal voucher
  6221.                 );
  6222.                 System::createEditSignatureHash(
  6223.                     $this->getDoctrine()->getManager(),
  6224.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  6225.                     $TransID,
  6226.                     $loginId,
  6227.                     $approveRole,
  6228.                     $request->request->get('approvalHash')
  6229.                 );
  6230.                 $trans_here $this->getDoctrine()
  6231.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  6232.                     ->findOneBy(
  6233.                         array(
  6234.                             'transactionId' => $TransID
  6235.                         )
  6236.                     );
  6237.                 //notify
  6238.                 $this->addFlash(
  6239.                     'success',
  6240.                     'New Transaction Added.'
  6241.                 );
  6242.                 $url $this->generateUrl(
  6243.                     'view_voucher'
  6244.                 );
  6245.                 System::AddNewNotification(
  6246.                     $this->container->getParameter('notification_enabled'),
  6247.                     $this->container->getParameter('notification_server'),
  6248.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  6249.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  6250.                     "Journal Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  6251.                     'pos',
  6252.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  6253.                     'success',
  6254.                     $url "/" $TransID,
  6255.                     "Journal"
  6256.                 );
  6257.                 return $this->redirect($url "/" $TransID);
  6258.             }
  6259.         }
  6260.         //for edits
  6261.         $extVoucherData = [];
  6262.         $extVoucherDetailsData = [];
  6263.         if ($voucherId == 0) {
  6264.         } else {
  6265.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  6266.                 array(
  6267.                     'transactionId' => $voucherId///material
  6268.                 )
  6269.             );
  6270.             //now if its not editable, redirect to view
  6271.             if ($extTrans) {
  6272.                 if ($extTrans->getEditFlag() != 1) {
  6273.                     $url $this->generateUrl(
  6274.                         'view_voucher'
  6275.                     );
  6276.                     return $this->redirect($url "/" $voucherId);
  6277.                 } else {
  6278.                     $extVoucherData $extTrans;
  6279.                     $extVoucherDetailsData Accounts::GetVoucherDataForEdit($em$voucherId);
  6280.                 }
  6281.             } else {
  6282.             }
  6283.         }
  6284.         return $this->render(
  6285.             '@Accounts/pages/input_forms/journal_voucher.html.twig',
  6286.             array(
  6287.                 'page_title' => 'Create Journal Voucher',
  6288.                 'transaction' => [],
  6289.                 'extVoucherData' => $extVoucherData,
  6290.                 'extVoucherDetailsData' => $extVoucherDetailsData
  6291.             )
  6292.         );
  6293.     }
  6294.     public function ToggleActiveCheck(Request $request$id 0)
  6295.     {
  6296.         $em $this->getDoctrine()->getManager();
  6297.         $chk $em->getRepository("ApplicationBundle\\Entity\\AccCheck")->findOneBy(array(
  6298.             'CheckId' => $id
  6299.         ));
  6300.         if ($chk) {
  6301.             if ($chk->getActive() == GeneralConstant::ACTIVE) {
  6302.                 $chk->setActive(GeneralConstant::INACTIVE);
  6303.                 $chk->setAssigned(null);
  6304.                 $chk->setVoucherId(null);
  6305.                 $chk->setCheckAmount(null);
  6306.                 $chk->setTransactionDate(null);
  6307.                 $chk->setCheckDate(null);
  6308.                 $chk->setReconDate(null);
  6309.                 $chk->setLedgerHitDate(null);
  6310.                 $chk->setRecAccountsHeadIdList(null);
  6311.                 $chk->setRecAccountsHeadId(null);
  6312.             } else
  6313.                 $chk->setActive(GeneralConstant::ACTIVE);
  6314.             $em->flush();
  6315.         }
  6316.         //            $chk->setActive(GeneralConstant::INACTIVE);
  6317.         $em->flush();
  6318.         //for edits
  6319.         $extVoucherData = [];
  6320.         $extVoucherDetailsData = [];
  6321.         //        if($voucherId==0)
  6322.         //        {
  6323.         //
  6324.         //        }
  6325.         //        else
  6326.         //        {
  6327.         //
  6328.         //            $extTrans=$em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  6329.         //                array(
  6330.         //                    'transactionId'=>$voucherId, ///material
  6331.         //
  6332.         //                )
  6333.         //            );
  6334.         //
  6335.         //
  6336.         //            //now if its not editable, redirect to view
  6337.         //            if($extTrans) {
  6338.         //                if ($extTrans->getEditFlag() != 1) {
  6339.         //                    $url = $this->generateUrl(
  6340.         //                        'view_voucher'
  6341.         //                    );
  6342.         //                    return $this->redirect($url . "/" . $voucherId);
  6343.         //                }
  6344.         //                else
  6345.         //                {
  6346.         //                    $extVoucherData=$extTrans;
  6347.         //                    $extVoucherDetailsData=Accounts::GetVoucherDataForEdit($em,$voucherId);
  6348.         //                }
  6349.         //            }
  6350.         //            else
  6351.         //            {
  6352.         //
  6353.         //            }
  6354.         //
  6355.         //        }
  6356.         //
  6357.         //
  6358.         //        return $this->render('@Accounts/pages/input_forms/journal_voucher.html.twig',
  6359.         //            array(
  6360.         //                'page_title'=>'Create Journal Voucher',
  6361.         //                'transaction'=>[],
  6362.         //                'extVoucherData'=>$extVoucherData,
  6363.         //                'extVoucherDetailsData'=>$extVoucherDetailsData
  6364.         //            )
  6365.         //        );
  6366.         return new JsonResponse(array(
  6367.             "success" => $chk true false,
  6368.             "id" => $id,
  6369.             "currStatus" => $chk $chk->getActive() : ''
  6370.             //            "file_path"=>$file_path,
  6371.             //                "r"=>$r,
  6372.             //                "debug_data"=>System::encryptSignature($r)
  6373.         ));
  6374.         //        $url = $this->generateUrl(
  6375.         //            'check_management'
  6376.         //        );
  6377.         //        return $this->redirect($url);
  6378.     }
  6379.     public function CreateFundTransfer(Request $request$id 0)
  6380.     {
  6381.         $em $this->getDoctrine()->getManager();
  6382.         $voucherId $id;
  6383.         if ($request->isMethod('POST')) {
  6384.             //            Generic::debugMessage($_POST);
  6385.             $em $this->getDoctrine()->getManager();
  6386.             MiscActions::RemoveExpiredDocs($em);
  6387.             $numberHash MiscActions::GetNumberHash($em'JV'"GN"$request->request->get('projectId') ?: 0''1);
  6388.             $dochash 'JV' '/' "GN" '/' $request->request->get('projectId') ?: '/' $numberHash;
  6389.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  6390.             //            $dochash = $request->request->get('voucherNumber'); //change
  6391.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6392.             $approveRole $request->request->get('approvalRole');
  6393.             $approveHash $request->request->get('approvalHash');
  6394.             if (!DocValidation::isInsertable(
  6395.                 $em,
  6396.                 $entity_id,
  6397.                 $dochash,
  6398.                 $loginId,
  6399.                 $approveRole,
  6400.                 $approveHash,
  6401.                 $id
  6402.             )) {
  6403.                 $this->addFlash(
  6404.                     'error',
  6405.                     'Sorry Couldnot insert Data.'
  6406.                 );
  6407.             } else {
  6408.                 $funcname 'AccTransactions';
  6409.                 $doc_id $voucherId;
  6410.                 DeleteDocument::$funcname($em$doc_id0);
  6411.                 $ledgerHeads $request->request->get('ledgerHeads');
  6412.                 $notes $request->request->get('trNote');
  6413.                 $costCenters $request->request->get('costCenters');
  6414.                 $drAmount $request->request->get('drAmount');
  6415.                 $crAmount $request->request->get('crAmount');
  6416.                 $check_allowed 0;
  6417.                 if ($request->request->has('check_allowed'))
  6418.                     $check_allowed 1;
  6419.                 $em_goc $this->getDoctrine()->getManager('company_group');
  6420.                 $post_data $request->request;
  6421.                 $TransID Accounts::CreateNewTransaction(
  6422.                     $voucherId,
  6423.                     $this->getDoctrine()->getManager(),
  6424.                     $request->request->get('date'),
  6425.                     array_sum($request->request->get('drAmount')),
  6426.                     AccountsConstant::VOUCHER_JOURNAL,
  6427.                     $request->request->get('description'),
  6428.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  6429.                     $request->request->get('type_hash'),
  6430.                     $request->request->get('prefix_hash'),
  6431.                     $request->request->get('assoc_hash'),
  6432.                     $request->request->get('number_hash'),
  6433.                     $check_allowed,
  6434.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6435.                     $this->getLoggedUserCompanyId($request)
  6436.                 );
  6437.                 $file_path_list = [];
  6438.                 if ($TransID != 0)
  6439.                     if (!empty($request->files)) {
  6440.                         MiscActions::RemoveFilesForEntityDoc($em_goc'AccTransactions'$TransID);
  6441.                         $storePath 'uploads/Voucher/';
  6442.                         $path "";
  6443.                         $file_path "";
  6444.                         $session $request->getSession();
  6445.                         MiscActions::RemoveExpiredFiles($em_goc);
  6446.                         foreach ($request->files as $uploadedFileGG) {
  6447.                             //            if($uploadedFile->getImage())
  6448.                             //                var_dump($uploadedFile->getFile());
  6449.                             //                var_dump($uploadedFile);
  6450.                             $tempD $uploadedFileGG;
  6451.                             if (!is_array($uploadedFileGG)) {
  6452.                                 $uploadedFileGG = array();
  6453.                                 $uploadedFileGG[] = $tempD;
  6454.                             }
  6455.                             foreach ($uploadedFileGG as $uploadedFile) {
  6456.                                 if ($uploadedFile != null) {
  6457.                                     $extension $uploadedFile->guessExtension();
  6458.                                     $size $uploadedFile->getSize();
  6459.                                     $fileName 'TRANS_' $TransID '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  6460.                                     $path $fileName;
  6461.                                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  6462.                                     if (!file_exists($upl_dir)) {
  6463.                                         mkdir($upl_dir0777true);
  6464.                                     }
  6465.                                     if (file_exists($upl_dir '' $path)) {
  6466.                                         chmod($upl_dir '' $path0755);
  6467.                                         unlink($upl_dir '' $path);
  6468.                                     }
  6469.                                     $file $uploadedFile->move($upl_dir$path);
  6470.                                     $expireNever 1;
  6471.                                     $expireTs 0;
  6472.                                     $EntityFile = new EntityFile();
  6473.                                     $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  6474.                                     $EntityFile->setName($path);
  6475.                                     $EntityFile->setMarker('_GEN_');
  6476.                                     $EntityFile->setExtension($extension);
  6477.                                     $EntityFile->setExpireTs($expireTs);
  6478.                                     $EntityFile->setSize($size);
  6479.                                     $EntityFile->setRelativePath($storePath $path);
  6480.                                     $EntityFile->setEntityName('AccTransactions');
  6481.                                     $EntityFile->setEntityBundle('ApplicationBundle');
  6482.                                     $EntityFile->setEntityId($TransID);
  6483.                                     $EntityFile->setEntityIdField('transactionId');
  6484.                                     $EntityFile->setModifyFieldSetter('setFiles');
  6485.                                     $EntityFile->setDocIdForApplicant(0);
  6486.                                     $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  6487.                                     $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  6488.                                     $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  6489.                                     $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  6490.                                     $em_goc->persist($EntityFile);
  6491.                                     $em_goc->flush();
  6492.                                     $EntityFileId $EntityFile->getId();
  6493.                                 }
  6494.                                 if ($path != "")
  6495.                                     $file_path_list[] = ($storePath $path);
  6496.                             }
  6497.                         }
  6498.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  6499.                         $v $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  6500.                             'transactionId' => $TransID,
  6501.                         ));
  6502.                         if ($v) {
  6503.                             $v->setFiles(implode(','$file_path_list));
  6504.                             $em->flush();
  6505.                         } else {
  6506.                         }
  6507.                     }
  6508.                 for ($i 0$i count($ledgerHeads); $i++) {
  6509.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  6510.                         Accounts::CreateNewTransactionDetails(
  6511.                             $this->getDoctrine()->getManager(),
  6512.                             $request->request->get('date'),
  6513.                             $TransID,
  6514.                             Generic::CurrToInt($drAmount[$i]),
  6515.                             $ledgerHeads[$i],
  6516.                             $notes[$i],
  6517.                             AccountsConstant::DEBIT,
  6518.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6519.                             [],
  6520.                             [],
  6521.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6522.                         );
  6523.                     }
  6524.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  6525.                         Accounts::CreateNewTransactionDetails(
  6526.                             $this->getDoctrine()->getManager(),
  6527.                             $request->request->get('date'),
  6528.                             $TransID,
  6529.                             Generic::CurrToInt($crAmount[$i]),
  6530.                             $ledgerHeads[$i],
  6531.                             $notes[$i],
  6532.                             AccountsConstant::CREDIT,
  6533.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6534.                             [],
  6535.                             [],
  6536.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6537.                         );
  6538.                     }
  6539.                 }
  6540.                 //now add Approval info
  6541.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6542.                 $approveRole $request->request->get('approvalRole');
  6543.                 $options = array(
  6544.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6545.                     'notification_server' => $this->container->getParameter('notification_server'),
  6546.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6547.                     'url' => $this->generateUrl(
  6548.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  6549.                     )
  6550.                 );
  6551.                 System::setApprovalInfo(
  6552.                     $this->getDoctrine()->getManager(),
  6553.                     $options,
  6554.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  6555.                     $TransID,
  6556.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6557.                     3    //journal voucher
  6558.                 );
  6559.                 System::createEditSignatureHash(
  6560.                     $this->getDoctrine()->getManager(),
  6561.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  6562.                     $TransID,
  6563.                     $loginId,
  6564.                     $approveRole,
  6565.                     $request->request->get('approvalHash')
  6566.                 );
  6567.                 $trans_here $this->getDoctrine()
  6568.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  6569.                     ->findOneBy(
  6570.                         array(
  6571.                             'transactionId' => $TransID
  6572.                         )
  6573.                     );
  6574.                 //notify
  6575.                 $this->addFlash(
  6576.                     'success',
  6577.                     'New Transaction Added.'
  6578.                 );
  6579.                 $url $this->generateUrl(
  6580.                     'view_voucher'
  6581.                 );
  6582.                 System::AddNewNotification(
  6583.                     $this->container->getParameter('notification_enabled'),
  6584.                     $this->container->getParameter('notification_server'),
  6585.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  6586.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  6587.                     "Journal Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  6588.                     'pos',
  6589.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  6590.                     'success',
  6591.                     //                    $url . "/" . $TransID,
  6592.                     $url "/" $TransID,
  6593.                     "Journal"
  6594.                 );
  6595.                 return new JsonResponse(
  6596.                     array(
  6597.                         'success' => true,
  6598.                     )
  6599.                 );
  6600.             }
  6601.         }
  6602.         //for edits
  6603.         $extVoucherData = [];
  6604.         $extVoucherDetailsData = [];
  6605.         if ($voucherId == 0) {
  6606.         } else {
  6607.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  6608.                 array(
  6609.                     'transactionId' => $voucherId///material
  6610.                 )
  6611.             );
  6612.             //now if its not editable, redirect to view
  6613.             if ($extTrans) {
  6614.                 if ($extTrans->getEditFlag() != 1) {
  6615.                     $url $this->generateUrl(
  6616.                         'view_voucher'
  6617.                     );
  6618.                     return $this->redirect($url "/" $voucherId);
  6619.                 } else {
  6620.                     $extVoucherData $extTrans;
  6621.                     $extVoucherDetailsData Accounts::GetVoucherDataForEdit($em$voucherId);
  6622.                 }
  6623.             } else {
  6624.             }
  6625.         }
  6626.         return $this->render(
  6627.             '@Accounts/pages/input_forms/journal_voucher.html.twig',
  6628.             array(
  6629.                 'page_title' => 'Create Journal Voucher',
  6630.                 'transaction' => [],
  6631.                 'extVoucherData' => $extVoucherData,
  6632.                 'extVoucherDetailsData' => $extVoucherDetailsData
  6633.             )
  6634.         );
  6635.     }
  6636.     public function CreateFinancialBudget(Request $request$id 0)
  6637.     {
  6638.         $em $this->getDoctrine()->getManager();
  6639.         if ($request->isMethod('POST')) {
  6640.             //            Generic::debugMessage($_POST);
  6641.             $em $this->getDoctrine()->getManager();
  6642.             $entity_id array_flip(GeneralConstant::$Entity_list)['FinancialBudget']; //change
  6643.             $dochash $request->request->get('voucherNumber'); //change
  6644.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6645.             $approveRole $request->request->get('approvalRole');
  6646.             $approveHash $request->request->get('approvalHash');
  6647.             if (!DocValidation::isInsertable(
  6648.                 $em,
  6649.                 $entity_id,
  6650.                 $dochash,
  6651.                 $loginId,
  6652.                 $approveRole,
  6653.                 $approveHash,
  6654.                 $id
  6655.             )) {
  6656.                 $this->addFlash(
  6657.                     'error',
  6658.                     'Sorry Couldnot insert Data.'
  6659.                 );
  6660.             } else {
  6661.                 $funcname 'FinancialBudget';
  6662.                 $doc_id $id;
  6663.                 DeleteDocument::$funcname($em$doc_id0);
  6664.                 $ledgerHeads $request->request->get('ledgerHeads');
  6665.                 $notes = [];
  6666.                 $costCenters $request->request->get('costCenters');
  6667.                 $drAmount $request->request->get('drAmount');
  6668.                 $crAmount $request->request->get('crAmount');
  6669.                 $check_allowed 0;
  6670.                 $BudgetId Accounts::CreateNewBudget(
  6671.                     $id,
  6672.                     $this->getDoctrine()->getManager(),
  6673.                     $request->request->get('start_date'),
  6674.                     $request->request->get('end_date'),
  6675.                     array_sum($request->request->get('drAmount')),
  6676.                     $request->request->get('description'),
  6677.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  6678.                     $request->request->get('type_hash'),
  6679.                     $request->request->get('prefix_hash'),
  6680.                     $request->request->get('assoc_hash'),
  6681.                     $request->request->get('number_hash'),
  6682.                     $check_allowed,
  6683.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6684.                     $this->getLoggedUserCompanyId($request)
  6685.                 );
  6686.                 for ($i 0$i count($ledgerHeads); $i++) {
  6687.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  6688.                         Accounts::CreateNewBudgetDetails(
  6689.                             $this->getDoctrine()->getManager(),
  6690.                             $request->request->get('start_date'),
  6691.                             $request->request->get('end_date'),
  6692.                             $BudgetId,
  6693.                             Generic::CurrToInt($drAmount[$i]),
  6694.                             $ledgerHeads[$i],
  6695.                             //                            $notes[$i],
  6696.                             AccountsConstant::DEBIT,
  6697.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6698.                             [],
  6699.                             [],
  6700.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6701.                         );
  6702.                     }
  6703.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  6704.                         Accounts::CreateNewBudgetDetails(
  6705.                             $this->getDoctrine()->getManager(),
  6706.                             $request->request->get('start_date'),
  6707.                             $request->request->get('end_date'),
  6708.                             $BudgetId,
  6709.                             Generic::CurrToInt($crAmount[$i]),
  6710.                             $ledgerHeads[$i],
  6711.                             //                            $notes[$i],
  6712.                             AccountsConstant::CREDIT,
  6713.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6714.                             [],
  6715.                             [],
  6716.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6717.                         );
  6718.                     }
  6719.                 }
  6720.                 //now add Approval info
  6721.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6722.                 $approveRole $request->request->get('approvalRole');
  6723.                 $options = array(
  6724.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6725.                     'notification_server' => $this->container->getParameter('notification_server'),
  6726.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6727.                     'url' => $this->generateUrl(
  6728.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['FinancialBudget']]['entity_view_route_path_name']
  6729.                     )
  6730.                 );
  6731.                 System::setApprovalInfo(
  6732.                     $this->getDoctrine()->getManager(),
  6733.                     $options,
  6734.                     array_flip(GeneralConstant::$Entity_list)['FinancialBudget'],
  6735.                     $BudgetId,
  6736.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)   //journal voucher
  6737.                 );
  6738.                 System::createEditSignatureHash(
  6739.                     $this->getDoctrine()->getManager(),
  6740.                     array_flip(GeneralConstant::$Entity_list)['FinancialBudget'],
  6741.                     $BudgetId,
  6742.                     $loginId,
  6743.                     $approveRole,
  6744.                     $request->request->get('approvalHash')
  6745.                 );
  6746.                 $trans_here $this->getDoctrine()
  6747.                     ->getRepository('ApplicationBundle\\Entity\\FinancialBudget')
  6748.                     ->findOneBy(
  6749.                         array(
  6750.                             'budgetId' => $BudgetId
  6751.                         )
  6752.                     );
  6753.                 //notify
  6754.                 $this->addFlash(
  6755.                     'success',
  6756.                     'New Budget Added.'
  6757.                 );
  6758.                 $url $this->generateUrl(
  6759.                     'view_financial_budget'
  6760.                 );
  6761.                 System::AddNewNotification(
  6762.                     $this->container->getParameter('notification_enabled'),
  6763.                     $this->container->getParameter('notification_server'),
  6764.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  6765.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  6766.                     "Financial Budget : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  6767.                     'pos',
  6768.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  6769.                     'success',
  6770.                     $url "/" $BudgetId,
  6771.                     "Journal"
  6772.                 );
  6773.                 // return $this->redirect($url."/".$BudgetId);
  6774.             }
  6775.         }
  6776.         //for edits
  6777.         $extBudgetData = [];
  6778.         $extBudgetDetailsData = [];
  6779.         if ($id == 0) {
  6780.         } else {
  6781.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findOneBy(
  6782.                 array(
  6783.                     'budgetId' => $id///material
  6784.                 )
  6785.             );
  6786.             //now if its not editable, redirect to view
  6787.             if ($extTrans) {
  6788.                 if ($extTrans->getEditFlag() != 1) {
  6789.                     $url $this->generateUrl(
  6790.                         'view_financial_budget'
  6791.                     );
  6792.                     return $this->redirect($url "/" $id);
  6793.                 } else {
  6794.                     $extBudgetData $extTrans;
  6795.                     $extBudgetDetailsData Accounts::GetBudgetDataForEdit($em$id);
  6796.                 }
  6797.             } else {
  6798.             }
  6799.         }
  6800.         return $this->render(
  6801.             '@Accounts/pages/input_forms/financial_budget.html.twig',
  6802.             array(
  6803.                 'page_title' => 'Create Financial Budget',
  6804.                 'transaction' => [],
  6805.                 'currBudgetList' => $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findBy(
  6806.                     array(
  6807.                         //                        'budgetId'=>$id, ///material
  6808.                         'CompanyId' => $this->getLoggedUserCompanyId($request), ///material
  6809.                     )
  6810.                 ),
  6811.                 'headListForBudget' => Accounts::HeadListFullPathExtended($em'>'$this->getLoggedUserCompanyId($request)),
  6812.                 'extBudgetData' => $extBudgetData,
  6813.                 'extBudgetDetailsData' => $extBudgetDetailsData
  6814.             )
  6815.         );
  6816.     }
  6817.     public function CreateJournalVoucher(Request $request$id 0)
  6818.     {
  6819.         $em $this->getDoctrine()->getManager();
  6820.         $voucherId $id;
  6821.         if ($request->isMethod('POST')) {
  6822.             //            Generic::debugMessage($_POST);
  6823.             $em $this->getDoctrine()->getManager();
  6824.             MiscActions::RemoveExpiredDocs($em);
  6825.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  6826.             $dochash $request->request->get('voucherNumber'); //change
  6827.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6828.             $approveRole $request->request->get('approvalRole');
  6829.             $approveHash $request->request->get('approvalHash');
  6830.             if (!DocValidation::isInsertable(
  6831.                 $em,
  6832.                 $entity_id,
  6833.                 $dochash,
  6834.                 $loginId,
  6835.                 $approveRole,
  6836.                 $approveHash,
  6837.                 $id
  6838.             )) {
  6839.                 $this->addFlash(
  6840.                     'error',
  6841.                     'Sorry Could not insert Data.'
  6842.                 );
  6843.             } else {
  6844.                 $funcname 'AccTransactions';
  6845.                 $doc_id $voucherId;
  6846.                 DeleteDocument::$funcname($em$doc_id0);
  6847.                 $ledgerHeads $request->request->get('ledgerHeads');
  6848.                 $notes $request->request->get('trNote');
  6849.                 $costCenters $request->request->get('costCenters');
  6850.                 $drAmount $request->request->get('drAmount');
  6851.                 $crAmount $request->request->get('crAmount');
  6852.                 $check_allowed 0;
  6853.                 if ($request->request->has('check_allowed'))
  6854.                     $check_allowed 1;
  6855.                 $em_goc $this->getDoctrine()->getManager('company_group');
  6856.                 $post_data $request->request;
  6857.                 $TransID Accounts::CreateNewTransaction(
  6858.                     $voucherId,
  6859.                     $this->getDoctrine()->getManager(),
  6860.                     $request->request->get('date'),
  6861.                     array_sum($request->request->get('drAmount')),
  6862.                     AccountsConstant::VOUCHER_JOURNAL,
  6863.                     $request->request->get('description'),
  6864.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  6865.                     $request->request->get('type_hash'),
  6866.                     $request->request->get('prefix_hash'),
  6867.                     $request->request->get('assoc_hash'),
  6868.                     $request->request->get('number_hash'),
  6869.                     $check_allowed,
  6870.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6871.                     $this->getLoggedUserCompanyId($request)
  6872.                 );
  6873.                 $file_path_list = [];
  6874.                 if ($TransID != 0)
  6875.                     if (!empty($request->files)) {
  6876.                         MiscActions::RemoveFilesForEntityDoc($em_goc'AccTransactions'$TransID);
  6877.                         $storePath 'uploads/Voucher/';
  6878.                         $path "";
  6879.                         $file_path "";
  6880.                         $session $request->getSession();
  6881.                         MiscActions::RemoveExpiredFiles($em_goc);
  6882.                         foreach ($request->files as $uploadedFileGG) {
  6883.                             //            if($uploadedFile->getImage())
  6884.                             //                var_dump($uploadedFile->getFile());
  6885.                             //                var_dump($uploadedFile);
  6886.                             $tempD $uploadedFileGG;
  6887.                             if (!is_array($uploadedFileGG)) {
  6888.                                 $uploadedFileGG = array();
  6889.                                 $uploadedFileGG[] = $tempD;
  6890.                             }
  6891.                             foreach ($uploadedFileGG as $uploadedFile) {
  6892.                                 if ($uploadedFile != null) {
  6893.                                     $extension $uploadedFile->guessExtension();
  6894.                                     $size $uploadedFile->getSize();
  6895.                                     $fileName 'TRANS_' $TransID '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  6896.                                     $path $fileName;
  6897.                                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  6898.                                     if (!file_exists($upl_dir)) {
  6899.                                         mkdir($upl_dir0777true);
  6900.                                     }
  6901.                                     if (file_exists($upl_dir '' $path)) {
  6902.                                         chmod($upl_dir '' $path0755);
  6903.                                         unlink($upl_dir '' $path);
  6904.                                     }
  6905.                                     $file $uploadedFile->move($upl_dir$path);
  6906.                                     $expireNever 1;
  6907.                                     $expireTs 0;
  6908.                                     $EntityFile = new EntityFile();
  6909.                                     $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  6910.                                     $EntityFile->setName($path);
  6911.                                     $EntityFile->setMarker('_GEN_');
  6912.                                     $EntityFile->setExtension($extension);
  6913.                                     $EntityFile->setExpireTs($expireTs);
  6914.                                     $EntityFile->setSize($size);
  6915.                                     $EntityFile->setRelativePath($storePath $path);
  6916.                                     $EntityFile->setEntityName('AccTransactions');
  6917.                                     $EntityFile->setEntityBundle('ApplicationBundle');
  6918.                                     $EntityFile->setEntityId($TransID);
  6919.                                     $EntityFile->setEntityIdField('transactionId');
  6920.                                     $EntityFile->setModifyFieldSetter('setFiles');
  6921.                                     $EntityFile->setDocIdForApplicant(0);
  6922.                                     $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  6923.                                     $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  6924.                                     $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  6925.                                     $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  6926.                                     $em_goc->persist($EntityFile);
  6927.                                     $em_goc->flush();
  6928.                                     $EntityFileId $EntityFile->getId();
  6929.                                 }
  6930.                                 if ($path != "")
  6931.                                     $file_path_list[] = ($storePath $path);
  6932.                             }
  6933.                         }
  6934.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  6935.                         $v $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  6936.                             'transactionId' => $TransID,
  6937.                         ));
  6938.                         if ($v) {
  6939.                             $v->setFiles(implode(','$file_path_list));
  6940.                             $em->flush();
  6941.                         } else {
  6942.                         }
  6943.                     }
  6944.                 for ($i 0$i count($ledgerHeads); $i++) {
  6945.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  6946.                         Accounts::CreateNewTransactionDetails(
  6947.                             $this->getDoctrine()->getManager(),
  6948.                             $request->request->get('date'),
  6949.                             $TransID,
  6950.                             Generic::CurrToInt($drAmount[$i]),
  6951.                             $ledgerHeads[$i],
  6952.                             $notes[$i],
  6953.                             AccountsConstant::DEBIT,
  6954.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6955.                             [],
  6956.                             [],
  6957.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6958.                             0,
  6959.                             0,
  6960.                             '_UNSET_',
  6961.                             $request->request->get('currency')[$i],
  6962.                             1,
  6963.                             $request->request->get('currencyMultiplyRate')[$i]
  6964.                         );
  6965.                     }
  6966.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  6967.                         Accounts::CreateNewTransactionDetails(
  6968.                             $this->getDoctrine()->getManager(),
  6969.                             $request->request->get('date'),
  6970.                             $TransID,
  6971.                             Generic::CurrToInt($crAmount[$i]),
  6972.                             $ledgerHeads[$i],
  6973.                             $notes[$i],
  6974.                             AccountsConstant::CREDIT,
  6975.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6976.                             [],
  6977.                             [],
  6978.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6979.                             0,
  6980.                             0,
  6981.                             '_UNSET_',
  6982.                             $request->request->get('currency')[$i],
  6983.                             1,
  6984.                             $request->request->get('currencyMultiplyRate')[$i]
  6985.                         );
  6986.                     }
  6987.                 }
  6988.                 //now add Approval info
  6989.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6990.                 $approveRole $request->request->get('approvalRole');
  6991.                 $options = array(
  6992.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6993.                     'notification_server' => $this->container->getParameter('notification_server'),
  6994.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6995.                     'url' => $this->generateUrl(
  6996.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  6997.                     )
  6998.                 );
  6999.                 System::setApprovalInfo(
  7000.                     $this->getDoctrine()->getManager(),
  7001.                     $options,
  7002.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  7003.                     $TransID,
  7004.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7005.                     3    //journal voucher
  7006.                 );
  7007.                 System::createEditSignatureHash(
  7008.                     $this->getDoctrine()->getManager(),
  7009.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  7010.                     $TransID,
  7011.                     $loginId,
  7012.                     $approveRole,
  7013.                     $request->request->get('approvalHash')
  7014.                 );
  7015.                 $trans_here $this->getDoctrine()
  7016.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  7017.                     ->findOneBy(
  7018.                         array(
  7019.                             'transactionId' => $TransID
  7020.                         )
  7021.                     );
  7022.                 //notify
  7023.                 $url $this->generateUrl(
  7024.                     'view_voucher'
  7025.                 );
  7026.                 System::AddNewNotification(
  7027.                     $this->container->getParameter('notification_enabled'),
  7028.                     $this->container->getParameter('notification_server'),
  7029.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  7030.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  7031.                     "Journal Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  7032.                     'pos',
  7033.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  7034.                     'success',
  7035.                     //                    $url . "/" . $TransID,
  7036.                     $url "/" $TransID,
  7037.                     "Journal"
  7038.                 );
  7039.                 if ($request->request->has('returnJson')) {
  7040.                     $doc $trans_here;
  7041.                     return new JsonResponse(array(
  7042.                         'success' => true,
  7043.                         'documentHash' => $trans_here->getDocumentHash(),
  7044.                         'documentId' => $TransID,
  7045.                         'documentIdPadded' => str_pad($TransID8'0'STR_PAD_LEFT),
  7046.                         'documentDate' => $trans_here->getTransactionDate()->format('Y-m-d'),
  7047.                         'documentAmount' => $trans_here->getTransactionAmount(),
  7048.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  7049.                         'viewUrl' => $url "/" $TransID,
  7050.                         'docPrintMainUrl' => $this->generateUrl('print_voucher'),
  7051.                     ));
  7052.                 } else {
  7053.                     $this->addFlash(
  7054.                         'success',
  7055.                         'New Document Created'
  7056.                     );
  7057.                     return $this->redirect($url "/" $TransID);
  7058.                 }
  7059.             }
  7060.         }
  7061.         //for edits
  7062.         $extVoucherData = [];
  7063.         $extVoucherDetailsData = [];
  7064.         if ($voucherId == 0) {
  7065.         } else {
  7066.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  7067.                 array(
  7068.                     'transactionId' => $voucherId///material
  7069.                 )
  7070.             );
  7071.             //now if its not editable, redirect to view
  7072.             if ($extTrans) {
  7073.                 if ($extTrans->getEditFlag() != 1) {
  7074.                     $url $this->generateUrl(
  7075.                         'view_voucher'
  7076.                     );
  7077.                     return $this->redirect($url "/" $voucherId);
  7078.                 } else {
  7079.                     $extVoucherData $extTrans;
  7080.                     $extVoucherDetailsData Accounts::GetVoucherDataForEdit($em$voucherId);
  7081.                 }
  7082.             } else {
  7083.             }
  7084.         }
  7085.         return $this->render(
  7086.             '@Accounts/pages/input_forms/journal_voucher.html.twig',
  7087.             array(
  7088.                 'page_title' => 'Create Journal Voucher',
  7089.                 'transaction' => [],
  7090.                 'extVoucherData' => $extVoucherData,
  7091.                 'extVoucherDetailsData' => $extVoucherDetailsData
  7092.             )
  7093.         );
  7094.     }
  7095.     public function CreateContraVoucher(Request $request$id 0)
  7096.     {
  7097.         $em $this->getDoctrine()->getManager();
  7098.         $voucherId $id;
  7099.         $details_ids = [];
  7100.         if ($request->isMethod('POST')) {
  7101.             //            Generic::debugMessage($_POST);
  7102.             $em $this->getDoctrine()->getManager();
  7103.             MiscActions::RemoveExpiredDocs($em);
  7104.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  7105.             $dochash $request->request->get('voucherNumber'); //change
  7106.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7107.             $approveRole $request->request->get('approvalRole');
  7108.             $approveHash $request->request->get('approvalHash');
  7109.             if (!DocValidation::isInsertable(
  7110.                 $em,
  7111.                 $entity_id,
  7112.                 $dochash,
  7113.                 $loginId,
  7114.                 $approveRole,
  7115.                 $approveHash,
  7116.                 $id
  7117.             )) {
  7118.                 $this->addFlash(
  7119.                     'error',
  7120.                     'Sorry Could not insert Data.'
  7121.                 );
  7122.             } else {
  7123.                 $funcname 'AccTransactions';
  7124.                 $doc_id $voucherId;
  7125.                 DeleteDocument::$funcname($em$doc_id0);
  7126.                 $ledgerHeads $request->request->get('ledgerHeads');
  7127.                 $notes $request->request->get('trNote');
  7128.                 $costCenters $request->request->get('costCenters');
  7129.                 $drAmount $request->request->get('drAmount');
  7130.                 $crAmount $request->request->get('crAmount');
  7131.                 $currencies $request->request->get('currency', []);
  7132.                 $currencyMultiplyRates $request->request->get('currencyMultiplyRate', []);
  7133.                 $em $this->getDoctrine()->getManager();
  7134.                 $check_allowed 0;
  7135.                 $provisional 0;
  7136.                 if ($request->request->has('check_allowed'))
  7137.                     $check_allowed 1;
  7138.                 if ($request->request->has('provisional'))
  7139.                     $provisional 1;
  7140.                 $em_goc $this->getDoctrine()->getManager('company_group');
  7141.                 $post_data $request->request;
  7142.                 $TransID Accounts::CreateNewTransaction(
  7143.                     $voucherId,
  7144.                     $this->getDoctrine()->getManager(),
  7145.                     $request->request->get('date'),
  7146.                     array_sum($request->request->get('drAmount')),
  7147.                     AccountsConstant::VOUCHER_CONTRA,
  7148.                     $request->request->get('description'),
  7149.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  7150.                     $request->request->get('type_hash'),
  7151.                     $request->request->get('prefix_hash'),
  7152.                     $request->request->get('assoc_hash'),
  7153.                     $request->request->get('number_hash'),
  7154.                     $check_allowed,
  7155.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7156.                     $this->getLoggedUserCompanyId($request),
  7157.                     '',
  7158.                     $provisional,
  7159.                     0,
  7160.                     $request->request->has('checkAssignType') ? $request->request->get('checkAssignType') : 1,
  7161.                     $request->request->has('prReference') ? $request->request->get('prReference') : '',
  7162.                     0,
  7163.                     '_UNSET_',
  7164.                     '_UNSET_',
  7165.                     0,
  7166.                     '',
  7167.                     '',
  7168.                     isset($currencies[0]) ? $currencies[0] : 0,
  7169.                     1,
  7170.                     isset($currencyMultiplyRates[0]) ? $currencyMultiplyRates[0] : 1
  7171.                 );
  7172.                 $file_path_list = [];
  7173.                 if ($TransID != 0)
  7174.                     if (!empty($request->files)) {
  7175.                         MiscActions::RemoveFilesForEntityDoc($em_goc'AccTransactions'$TransID);
  7176.                         $storePath 'uploads/Voucher/';
  7177.                         $path "";
  7178.                         $file_path "";
  7179.                         $session $request->getSession();
  7180.                         MiscActions::RemoveExpiredFiles($em_goc);
  7181.                         foreach ($request->files as $uploadedFileGG) {
  7182.                             //            if($uploadedFile->getImage())
  7183.                             //                var_dump($uploadedFile->getFile());
  7184.                             //                var_dump($uploadedFile);
  7185.                             $tempD $uploadedFileGG;
  7186.                             if (!is_array($uploadedFileGG)) {
  7187.                                 $uploadedFileGG = array();
  7188.                                 $uploadedFileGG[] = $tempD;
  7189.                             }
  7190.                             foreach ($uploadedFileGG as $uploadedFile) {
  7191.                                 if ($uploadedFile != null) {
  7192.                                     $extension $uploadedFile->guessExtension();
  7193.                                     $size $uploadedFile->getSize();
  7194.                                     $fileName 'TRANS_' $TransID '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  7195.                                     $path $fileName;
  7196.                                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  7197.                                     if (!file_exists($upl_dir)) {
  7198.                                         mkdir($upl_dir0777true);
  7199.                                     }
  7200.                                     if (file_exists($upl_dir '' $path)) {
  7201.                                         chmod($upl_dir '' $path0755);
  7202.                                         unlink($upl_dir '' $path);
  7203.                                     }
  7204.                                     $file $uploadedFile->move($upl_dir$path);
  7205.                                     $expireNever 1;
  7206.                                     $expireTs 0;
  7207.                                     $EntityFile = new EntityFile();
  7208.                                     $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  7209.                                     $EntityFile->setName($path);
  7210.                                     $EntityFile->setMarker('_GEN_');
  7211.                                     $EntityFile->setExtension($extension);
  7212.                                     $EntityFile->setExpireTs($expireTs);
  7213.                                     $EntityFile->setSize($size);
  7214.                                     $EntityFile->setRelativePath($storePath $path);
  7215.                                     $EntityFile->setEntityName('AccTransactions');
  7216.                                     $EntityFile->setEntityBundle('ApplicationBundle');
  7217.                                     $EntityFile->setEntityId($TransID);
  7218.                                     $EntityFile->setEntityIdField('transactionId');
  7219.                                     $EntityFile->setModifyFieldSetter('setFiles');
  7220.                                     $EntityFile->setDocIdForApplicant(0);
  7221.                                     $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  7222.                                     $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  7223.                                     $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  7224.                                     $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  7225.                                     $em_goc->persist($EntityFile);
  7226.                                     $em_goc->flush();
  7227.                                     $EntityFileId $EntityFile->getId();
  7228.                                 }
  7229.                                 if ($path != "")
  7230.                                     $file_path_list[] = ($storePath $path);
  7231.                             }
  7232.                         }
  7233.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  7234.                         $v $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  7235.                             'transactionId' => $TransID,
  7236.                         ));
  7237.                         if ($v) {
  7238.                             $v->setFiles(implode(','$file_path_list));
  7239.                             $em->flush();
  7240.                         } else {
  7241.                         }
  7242.                     }
  7243.                 $check_here = [];
  7244.                 $id_list_for_check = [];
  7245.                 $details_ids = [];
  7246.                 for ($i 0$i count($ledgerHeads); $i++) {
  7247.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  7248.                         $id_list_for_check[$ledgerHeads[$i]] = $ledgerHeads[$i];
  7249.                         Accounts::CreateNewTransactionDetails(
  7250.                             $this->getDoctrine()->getManager(),
  7251.                             $request->request->get('date'),
  7252.                             $TransID,
  7253.                             Generic::CurrToInt($drAmount[$i]),
  7254.                             $ledgerHeads[$i],
  7255.                             $notes[$i],
  7256.                             AccountsConstant::DEBIT,
  7257.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7258.                             [],
  7259.                             [],
  7260.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7261.                             0,
  7262.                             0,
  7263.                             '_UNSET_',
  7264.                             isset($currencies[$i]) ? $currencies[$i] : 0,
  7265.                             1,
  7266.                             isset($currencyMultiplyRates[$i]) ? $currencyMultiplyRates[$i] : 1
  7267.                         );
  7268.                     }
  7269.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  7270.                         Accounts::CreateNewTransactionDetails(
  7271.                             $this->getDoctrine()->getManager(),
  7272.                             $request->request->get('date'),
  7273.                             $TransID,
  7274.                             Generic::CurrToInt($crAmount[$i]),
  7275.                             $ledgerHeads[$i],
  7276.                             $notes[$i],
  7277.                             AccountsConstant::CREDIT,
  7278.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7279.                             [],
  7280.                             [],
  7281.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7282.                             0,
  7283.                             0,
  7284.                             '_UNSET_',
  7285.                             isset($currencies[$i]) ? $currencies[$i] : 0,
  7286.                             1,
  7287.                             isset($currencyMultiplyRates[$i]) ? $currencyMultiplyRates[$i] : 1
  7288.                         );
  7289.                     }
  7290.                 }
  7291.                 if ($request->request->has('check_id')) {
  7292.                     $check_assign_type $request->request->get('checkAssignType');
  7293.                     foreach ($request->request->get('check_id') as $k => $value) {
  7294.                         $check_here $this->getDoctrine()
  7295.                             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  7296.                             ->findOneBy(
  7297.                                 array(
  7298.                                     'CheckId' => $value
  7299.                                 )
  7300.                             );
  7301.                         if ($check_assign_type == 1) {
  7302.                             $ind_head_id json_decode($request->request->get('check_received_id')[$k], true)[0];
  7303.                             $check_here->setRecAccountsHeadId($id_list_for_check[$ind_head_id]);
  7304.                             $check_here->setRecAccountsHeadIdList(json_encode([$id_list_for_check[$ind_head_id]]));
  7305.                         }
  7306.                         if ($check_assign_type == 2) {
  7307.                             $ind_head_id_list json_decode($request->request->get('check_received_id')[$k], true);
  7308.                             $new_id_list = [];
  7309.                             foreach ($ind_head_id_list as $ind_head_id) {
  7310.                                 $new_id_list[] = $id_list_for_check[$ind_head_id];
  7311.                             }
  7312.                             $check_here->setRecAccountsHeadId(null);
  7313.                             $check_here->setRecAccountsHeadIdList(json_encode($new_id_list));
  7314.                         }
  7315.                         $check_here->setCheckNarration($request->request->get('check_narration')[$k]);
  7316.                         $check_here->setCheckAmount($request->request->get('check_assigned_amount')[$k]);
  7317.                         $check_here->setCheckDate(new \DateTime($request->request->get('checkDate')[$k]));
  7318.                         $check_here->setTransactionDate(new \DateTime($request->request->get('date')));
  7319.                         //                        $check_here->setCheckDate(new \DateTime($request->request->get('date')));
  7320.                         $check_here->setAssigned(1);
  7321.                         $check_here->setVoucherId($TransID);
  7322.                     }
  7323.                 }
  7324.                 //approval system
  7325.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7326.                 $approveRole $request->request->get('approvalRole');
  7327.                 //            Accounts::UpdatePurchasePayments($em,$pi_list,$po_list,$details_ids, $request->request->get('date'));
  7328.                 $options = array(
  7329.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  7330.                     'notification_server' => $this->container->getParameter('notification_server'),
  7331.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  7332.                     'url' => $this->generateUrl(
  7333.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  7334.                     )
  7335.                 );
  7336.                 System::setApprovalInfo(
  7337.                     $this->getDoctrine()->getManager(),
  7338.                     $options,
  7339.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  7340.                     $TransID,
  7341.                     $loginId,
  7342.                     4    //contra voucher
  7343.                 );
  7344.                 System::createEditSignatureHash(
  7345.                     $em,
  7346.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  7347.                     $TransID,
  7348.                     $loginId,
  7349.                     $approveRole,
  7350.                     $request->request->get('approvalHash')
  7351.                 );
  7352.                 $url $this->generateUrl(
  7353.                     'view_voucher'
  7354.                 );
  7355.                 $trans_here $this->getDoctrine()
  7356.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  7357.                     ->findOneBy(
  7358.                         array(
  7359.                             'transactionId' => $TransID
  7360.                         )
  7361.                     );
  7362.                 System::AddNewNotification(
  7363.                     $this->container->getParameter('notification_enabled'),
  7364.                     $this->container->getParameter('notification_server'),
  7365.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  7366.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  7367.                     "Contra Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  7368.                     'pos',
  7369.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  7370.                     'success',
  7371.                     $url "/" $TransID,
  7372.                     "Contra Voucher"
  7373.                 );
  7374.                 if ($request->request->has('returnJson')) {
  7375.                     $doc $trans_here;
  7376.                     return new JsonResponse(array(
  7377.                         'success' => true,
  7378.                         'documentHash' => $trans_here->getDocumentHash(),
  7379.                         'documentId' => $TransID,
  7380.                         'documentIdPadded' => str_pad($TransID8'0'STR_PAD_LEFT),
  7381.                         'documentDate' => $trans_here->getTransactionDate()->format('Y-m-d'),
  7382.                         'documentAmount' => $trans_here->getTransactionAmount(),
  7383.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  7384.                         'viewUrl' => $url "/" $TransID,
  7385.                         'docPrintMainUrl' => $this->generateUrl('print_voucher'),
  7386.                     ));
  7387.                 } else {
  7388.                     $this->addFlash(
  7389.                         'success',
  7390.                         'New Document Created'
  7391.                     );
  7392.                     return $this->redirect($url "/" $TransID);
  7393.                 }
  7394.             }
  7395.         }
  7396.         $extVoucherData = [];
  7397.         $extVoucherDetailsData = [];
  7398.         if ($voucherId == 0) {
  7399.         } else {
  7400.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  7401.                 array(
  7402.                     'transactionId' => $voucherId///material
  7403.                 )
  7404.             );
  7405.             //now if its not editable, redirect to view
  7406.             if ($extTrans) {
  7407.                 if ($extTrans->getEditFlag() != 1) {
  7408.                     $url $this->generateUrl(
  7409.                         'view_voucher'
  7410.                     );
  7411.                     return $this->redirect($url "/" $voucherId);
  7412.                 } else {
  7413.                     $extVoucherData $extTrans;
  7414.                     $extVoucherDetailsData Accounts::GetVoucherDataForEdit($em$voucherId);
  7415.                 }
  7416.             } else {
  7417.             }
  7418.         }
  7419.         return $this->render(
  7420.             '@Accounts/pages/input_forms/contra_voucher.html.twig',
  7421.             array(
  7422.                 'page_title' => 'Create Contra Voucher',
  7423.                 'test' => $details_ids,
  7424.                 'extVoucherData' => $extVoucherData,
  7425.                 'extVoucherDetailsData' => $extVoucherDetailsData,
  7426.                 'supplier_list' => Accounts::SupplierListForPv($this->getDoctrine()->getManager()),
  7427.                 'supplier_list_by_ac_head' => Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
  7428.                 'supplier_list_by_advance_head' => Accounts::SupplierListByAdvanceHead($this->getDoctrine()->getManager())
  7429.             )
  7430.         );
  7431.     }
  7432.     public function CreatePaymentVoucher(Request $request$id 0)
  7433.     {
  7434.         $details_ids = [];
  7435.         $voucherId $id;
  7436.         $em $this->getDoctrine()->getManager();
  7437.         $FundRequisitionDetails $em->getRepository(FundRequisition::class)->findAll();
  7438.         $prePopulateData = [];
  7439.         $skipInvoiceBalancing $request->get('skipInvoiceBalancing'0);
  7440.         if ($request->request->get('payslip_ids''') != '') {
  7441.             $payslip_ids_array explode(','$request->request->get('payslip_ids'''));
  7442.             $payslips $em->getRepository('ApplicationBundle\\Entity\\Payslip')->findBy(
  7443.                 array(
  7444.                     'payslipId' => $payslip_ids_array///material
  7445.                 )
  7446.             );
  7447.             foreach ($payslips as $payslip) {
  7448.                 $employee $em->getRepository('ApplicationBundle\\Entity\\Employee')->findOneBy(array(
  7449.                         'employeeId' => $payslip->getSysId())
  7450.                 );
  7451.                 $dtHead 0;
  7452.                 if ($employee)
  7453.                     $dtHead $employee->getAccountsHeadId();
  7454.                 if ($dtHead != '' && $dtHead != && $dtHead != null)
  7455.                     $prePopulateData[] = array(
  7456.                         'accountsHeadId' => $dtHead,
  7457.                         'position' => 'dr',
  7458.                         'payslipId' => $payslip->getPayslipId(),
  7459.                         'payslipPaymentType' => $request->request->get('disburse_type''bank'),
  7460.                         'amount' => $request->request->get('disburse_type''bank') == 'bank' $payslip->getBankTransfer() : $payslip->getHandCash(),
  7461.                         'note' => $employee->getName(),
  7462.                     );
  7463.             }
  7464.         } else if ($request->isMethod('POST')) {
  7465.             //            Generic::debugMessage($_POST);
  7466.             $em $this->getDoctrine()->getManager();
  7467.             MiscActions::RemoveExpiredDocs($em);
  7468.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  7469.             $dochash $request->request->get('voucherNumber'); //change
  7470.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7471.             $approveRole $request->request->get('approvalRole');
  7472.             $approveHash $request->request->get('approvalHash');
  7473.             if (!DocValidation::isInsertable(
  7474.                 $em,
  7475.                 $entity_id,
  7476.                 $dochash,
  7477.                 $loginId,
  7478.                 $approveRole,
  7479.                 $approveHash,
  7480.                 $id
  7481.             )) {
  7482.                 if ($request->request->has('returnJson')) {
  7483.                     return new JsonResponse(array(
  7484.                         'success' => false,
  7485.                         'documentHash' => 0,
  7486.                         'documentId' => 0,
  7487.                     ));
  7488.                 } else
  7489.                     $this->addFlash(
  7490.                         'error',
  7491.                         'Sorry Could not insert Data.'
  7492.                     );
  7493.             } else {
  7494.                 $funcname 'AccTransactions';
  7495.                 $doc_id $voucherId;
  7496.                 DeleteDocument::$funcname($em$doc_id0);
  7497.                 $ledgerHeads $request->request->get('ledgerHeads');
  7498.                 $notes $request->request->get('trNote');
  7499.                 $costCenters $request->request->get('costCenters');
  7500.                 $drAmount $request->request->get('drAmount');
  7501.                 $crAmount $request->request->get('crAmount');
  7502.                 $em $this->getDoctrine()->getManager();
  7503.                 $pi_list = [];
  7504.                 $po_list = [];
  7505.                 $ei_list = [];
  7506.                 //1stly lets set the invoices po etc before we save the transaction normally
  7507.                 if ($request->request->has('ei_id'))
  7508.                     $ei_list = array(
  7509.                         'id' => $request->request->get('ei_id'),
  7510.                         'aa' => $request->request->get('ei_aa'),
  7511.                         'ei_head_id' => $request->request->get('ei_head_id')
  7512.                     );
  7513.                 if ($request->request->has('pi_id'))
  7514.                     $pi_list = array(
  7515.                         'id' => $request->request->get('pi_id'),
  7516.                         'aa' => $request->request->get('pi_aa')
  7517.                     );
  7518.                 if ($request->request->has('po_id'))
  7519.                     $po_list = array(
  7520.                         'id' => $request->request->get('po_id'),
  7521.                         'aa' => $request->request->get('po_aa')
  7522.                     );
  7523.                 $check_allowed 0;
  7524.                 $provisional 0;
  7525.                 if ($request->request->has('check_allowed'))
  7526.                     $check_allowed 1;
  7527.                 if ($request->request->has('provisional'))
  7528.                     $provisional 1;
  7529.                 $em_goc $this->getDoctrine()->getManager('company_group');
  7530.                 $post_data $request->request;
  7531.                 $TransID Accounts::CreateNewTransaction(
  7532.                     $voucherId,
  7533.                     $this->getDoctrine()->getManager(),
  7534.                     $request->request->get('date'),
  7535.                     array_sum($request->request->get('drAmount')),
  7536.                     AccountsConstant::VOUCHER_PAYMENT,
  7537.                     $request->request->get('description'),
  7538.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  7539.                     $request->request->get('type_hash'),
  7540.                     $request->request->get('prefix_hash'),
  7541.                     $request->request->get('assoc_hash'),
  7542.                     $request->request->get('number_hash'),
  7543.                     $check_allowed,
  7544.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7545.                     $this->getLoggedUserCompanyId($request),
  7546.                     '',
  7547.                     $provisional,
  7548.                     0,
  7549.                     $request->request->has('checkAssignType') ? $request->request->get('checkAssignType') : 1,
  7550.                     $request->request->has('prReference') ? $request->request->get('prReference') : '',
  7551.                     0,
  7552.                     '_UNSET_',
  7553.                     '_UNSET_',
  7554.                     0,
  7555.                     '',
  7556.                     '',
  7557.                     $request->request->get('currency', [''])[0]
  7558.                 );
  7559.                 $check_here = [];
  7560.                 $id_list_for_check = [];
  7561.                 $file_path_list = [];
  7562.                 if ($TransID != 0)
  7563.                     if (!empty($request->files)) {
  7564.                         MiscActions::RemoveFilesForEntityDoc($em_goc'AccTransactions'$TransID);
  7565.                         $storePath 'uploads/Voucher/';
  7566.                         $path "";
  7567.                         $file_path "";
  7568.                         $session $request->getSession();
  7569.                         MiscActions::RemoveExpiredFiles($em_goc);
  7570.                         foreach ($request->files as $uploadedFileGG) {
  7571.                             //            if($uploadedFile->getImage())
  7572.                             //                var_dump($uploadedFile->getFile());
  7573.                             //                var_dump($uploadedFile);
  7574.                             $tempD $uploadedFileGG;
  7575.                             if (!is_array($uploadedFileGG)) {
  7576.                                 $uploadedFileGG = array();
  7577.                                 $uploadedFileGG[] = $tempD;
  7578.                             }
  7579.                             foreach ($uploadedFileGG as $uploadedFile) {
  7580.                                 if ($uploadedFile != null) {
  7581.                                     $extension $uploadedFile->guessExtension();
  7582.                                     $size $uploadedFile->getSize();
  7583.                                     $fileName 'TRANS_' $TransID '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  7584.                                     $path $fileName;
  7585.                                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  7586.                                     if (!file_exists($upl_dir)) {
  7587.                                         mkdir($upl_dir0777true);
  7588.                                     }
  7589.                                     if (file_exists($upl_dir '' $path)) {
  7590.                                         chmod($upl_dir '' $path0755);
  7591.                                         unlink($upl_dir '' $path);
  7592.                                     }
  7593.                                     $file $uploadedFile->move($upl_dir$path);
  7594.                                     $expireNever 1;
  7595.                                     $expireTs 0;
  7596.                                     $EntityFile = new EntityFile();
  7597.                                     $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  7598.                                     $EntityFile->setMarker('_GEN_');
  7599.                                     $EntityFile->setName($path);
  7600.                                     $EntityFile->setExtension($extension);
  7601.                                     $EntityFile->setExpireTs($expireTs);
  7602.                                     $EntityFile->setSize($size);
  7603.                                     $EntityFile->setRelativePath($storePath $path);
  7604.                                     $EntityFile->setEntityName(GeneralConstant::$Entity_list[$entity_id]);
  7605.                                     $EntityFile->setEntityBundle('ApplicationBundle');
  7606.                                     $EntityFile->setEntityId($TransID);
  7607.                                     $EntityFile->setEntityIdField(GeneralConstant::$Entity_id_field_list[$entity_id]);
  7608.                                     $EntityFile->setModifyFieldSetter('setFiles');
  7609.                                     $EntityFile->setDocIdForApplicant(0);
  7610.                                     $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  7611.                                     $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  7612.                                     $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  7613.                                     $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  7614.                                     $em_goc->persist($EntityFile);
  7615.                                     $em_goc->flush();
  7616.                                     $EntityFileId $EntityFile->getId();
  7617.                                 }
  7618.                                 if ($path != "")
  7619.                                     $file_path_list[] = ($storePath $path);
  7620.                             }
  7621.                         }
  7622.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  7623.                         $v $em->getRepository(isset(GeneralConstant::$Entity_fqcn_by_id[$entity_id])?GeneralConstant::$Entity_fqcn_by_id[$entity_id] :('ApplicationBundle\\Entity\\'.GeneralConstant::$Entity_list[$entity_id]))->findOneBy(array(
  7624.                             GeneralConstant::$Entity_id_field_list[$entity_id] => $TransID,
  7625.                         ));
  7626.                         if ($v) {
  7627.                             $v->setFiles(implode(','$file_path_list));
  7628.                             $em->flush();
  7629.                         } else {
  7630.                         }
  7631.                     }
  7632.                 $details_ids = [];
  7633.                 for ($i 0$i count($ledgerHeads); $i++) {
  7634.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  7635.                         $id_list_for_check[$ledgerHeads[$i]] = $ledgerHeads[$i]; //initially same all
  7636.                         //now lets see if any supplier exists and if yes , sprlit the value in advance and normal
  7637.                         $supplier_list Accounts::SupplierListThreeTypes($this->getDoctrine()->getManager());
  7638.                         $supplier_head_id_list = [];
  7639.                         $s_b_ac_h $supplier_list[1];
  7640.                         $s_b_advance_h $supplier_list[2];
  7641.                         //        $s_list=self::SupplierListForPv();
  7642.                         $head_index_calibrate = [];
  7643.                         $supplier_by_id '';
  7644.                         if (array_key_exists($ledgerHeads[$i], $s_b_ac_h)) {
  7645.                             $supplier_by_id $s_b_ac_h[$ledgerHeads[$i]];
  7646.                         }
  7647.                         if (array_key_exists($ledgerHeads[$i], $s_b_advance_h)) {
  7648.                             $supplier_by_id $s_b_advance_h[$ledgerHeads[$i]];
  7649.                         }
  7650.                         if ($supplier_by_id != '') {
  7651.                             $gt 0;
  7652.                             //use normal transaction
  7653.                             $tot 0;
  7654.                             if ($request->request->has('pi_id') || $request->request->has('ei_id')) {
  7655.                                 if ($request->request->has('pi_id'))
  7656.                                     foreach ($request->request->get('pi_id') as $k => $v) {
  7657.                                         if ($request->request->get('pi_head_id')[$k] == $ledgerHeads[$i])
  7658.                                             $tot += $request->request->get('pi_aa')[$k];
  7659.                                     }
  7660.                                 if ($request->request->has('ei_id'))
  7661.                                     foreach ($request->request->get('ei_id') as $k => $v) {
  7662.                                         if ($request->request->get('ei_head_id')[$k] == $ledgerHeads[$i])
  7663.                                             $tot += $request->request->get('ei_aa')[$k];
  7664.                                     }
  7665.                                 if ($tot 0) {
  7666.                                     $id_list_for_check[$ledgerHeads[$i]] = $supplier_by_id['supplier_head_id'];
  7667.                                     $details_ids[$supplier_by_id['supplier_head_id']] = Accounts::CreateNewTransactionDetails(
  7668.                                         $this->getDoctrine()->getManager(),
  7669.                                         $request->request->get('date'),
  7670.                                         $TransID,
  7671.                                         Generic::CurrToInt($tot),
  7672.                                         $supplier_by_id['supplier_head_id'],
  7673.                                         $notes[$i],
  7674.                                         AccountsConstant::DEBIT,
  7675.                                         isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7676.                                         array($pi_list$po_list$ei_list),
  7677.                                         [],
  7678.                                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7679.                                         $provisional,
  7680.                                         0,
  7681.                                         '_UNSET_',
  7682.                                         $request->request->get('currency')[$i],
  7683.                                         1,
  7684.                                         $request->request->get('currencyMultiplyRate')[$i],
  7685.                                         isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
  7686.                                         isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
  7687.                                     );
  7688.                                 }
  7689.                             }
  7690.                             $gt $gt $tot;
  7691.                             //now advance transaction
  7692.                             $tot 0;
  7693.                             if ($request->request->has('po_id')) {
  7694.                                 foreach ($request->request->get('po_id') as $k => $v) {
  7695.                                     if ($request->request->get('po_head_id')[$k] == $ledgerHeads[$i])
  7696.                                         $tot += $request->request->get('po_aa')[$k];
  7697.                                 }
  7698.                                 if ($tot 0) {
  7699.                                     $id_list_for_check[$ledgerHeads[$i]] = $supplier_by_id['supplier_advance_head_id'];
  7700.                                     $details_ids[$supplier_by_id['supplier_advance_head_id']] = Accounts::CreateNewTransactionDetails(
  7701.                                         $this->getDoctrine()->getManager(),
  7702.                                         $request->request->get('date'),
  7703.                                         $TransID,
  7704.                                         Generic::CurrToInt($tot),
  7705.                                         $supplier_by_id['supplier_advance_head_id'],
  7706.                                         $notes[$i],
  7707.                                         AccountsConstant::DEBIT,
  7708.                                         isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7709.                                         array($pi_list$po_list$ei_list),
  7710.                                         [],
  7711.                                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7712.                                         $provisional,
  7713.                                         0,
  7714.                                         '_UNSET_',
  7715.                                         $request->request->get('currency')[$i],
  7716.                                         1,
  7717.                                         $request->request->get('currencyMultiplyRate')[$i],
  7718.                                         isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
  7719.                                         isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
  7720.                                     );
  7721.                                 }
  7722.                             }
  7723.                             $gt $gt $tot;
  7724.                             //now assigning rest as normal trans
  7725.                             Accounts::CreateNewTransactionDetails(
  7726.                                 $this->getDoctrine()->getManager(),
  7727.                                 $request->request->get('date'),
  7728.                                 $TransID,
  7729.                                 Generic::CurrToInt($drAmount[$i] - $gt),
  7730.                                 $ledgerHeads[$i],
  7731.                                 $notes[$i],
  7732.                                 AccountsConstant::DEBIT,
  7733.                                 isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7734.                                 array($pi_list$po_list$ei_list),
  7735.                                 [],
  7736.                                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7737.                                 $provisional,
  7738.                                 0,
  7739.                                 '_UNSET_',
  7740.                                 $request->request->get('currency')[$i],
  7741.                                 1,
  7742.                                 $request->request->get('currencyMultiplyRate')[$i],
  7743.                                 isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
  7744.                                 isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
  7745.                             );
  7746.                         } else
  7747.                             $details_ids[$ledgerHeads[$i]] = Accounts::CreateNewTransactionDetails(
  7748.                                 $this->getDoctrine()->getManager(),
  7749.                                 $request->request->get('date'),
  7750.                                 $TransID,
  7751.                                 Generic::CurrToInt($drAmount[$i]),
  7752.                                 $ledgerHeads[$i],
  7753.                                 $notes[$i],
  7754.                                 AccountsConstant::DEBIT,
  7755.                                 isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7756.                                 array($pi_list$po_list$ei_list),
  7757.                                 [],
  7758.                                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7759.                                 $provisional,
  7760.                                 0,
  7761.                                 '_UNSET_',
  7762.                                 $request->request->get('currency')[$i],
  7763.                                 1,
  7764.                                 $request->request->get('currencyMultiplyRate')[$i],
  7765.                                 isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
  7766.                                 isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
  7767.                             );
  7768.                     }
  7769.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  7770.                         $details_ids[$ledgerHeads[$i]] = Accounts::CreateNewTransactionDetails(
  7771.                             $this->getDoctrine()->getManager(),
  7772.                             $request->request->get('date'),
  7773.                             $TransID,
  7774.                             Generic::CurrToInt($crAmount[$i]),
  7775.                             $ledgerHeads[$i],
  7776.                             $notes[$i],
  7777.                             AccountsConstant::CREDIT,
  7778.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7779.                             array($pi_list$po_list$ei_list),
  7780.                             [],
  7781.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7782.                             $provisional,
  7783.                             0,
  7784.                             '_UNSET_',
  7785.                             $request->request->get('currency')[$i],
  7786.                             1,
  7787.                             $request->request->get('currencyMultiplyRate')[$i],
  7788.                             isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
  7789.                             isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
  7790.                         );
  7791.                     }
  7792.                 }
  7793.                 if ($request->request->has('check_id')) {
  7794.                     $check_assign_type $request->request->has('checkAssignType') ? $request->request->get('checkAssignType') : 1;
  7795.                     foreach ($request->request->get('check_id') as $k => $value) {
  7796.                         $check_here $this->getDoctrine()
  7797.                             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  7798.                             ->findOneBy(
  7799.                                 array(
  7800.                                     'CheckId' => $value
  7801.                                 )
  7802.                             );
  7803.                         if ($check_assign_type == 1) {
  7804.                             $ind_head_id json_decode($request->request->get('check_received_id')[$k], true)[0];
  7805.                             $check_here->setRecAccountsHeadId($id_list_for_check[$ind_head_id]);
  7806.                             $check_here->setRecAccountsHeadIdList(json_encode([$id_list_for_check[$ind_head_id]]));
  7807.                         }
  7808.                         if ($check_assign_type == 2) {
  7809.                             $ind_head_id_list json_decode($request->request->get('check_received_id')[$k], true);
  7810.                             $new_id_list = [];
  7811.                             foreach ($ind_head_id_list as $ind_head_id) {
  7812.                                 $new_id_list[] = $id_list_for_check[$ind_head_id];
  7813.                             }
  7814.                             $check_here->setRecAccountsHeadId(null);
  7815.                             $check_here->setRecAccountsHeadIdList(json_encode($new_id_list));
  7816.                         }
  7817.                         $check_here->setCheckNarration($request->request->get('check_narration')[$k]);
  7818.                         $check_here->setCheckAmount($request->request->get('check_assigned_amount')[$k]);
  7819.                         $check_here->setCheckDate(new \DateTime($request->request->get('checkDate')[$k]));
  7820.                         $check_here->setTransactionDate(new \DateTime($request->request->get('date')));
  7821.                         //                        $check_here->setCheckDate(new \DateTime($request->request->get('date')));
  7822.                         $check_here->setAssigned(1);
  7823.                         $check_here->setVoucherId($TransID);
  7824.                     }
  7825.                 }
  7826.                 //approval system
  7827.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7828.                 $approveRole $request->request->get('approvalRole');
  7829.                 Accounts::UpdatePurchasePayments($em$pi_list$po_list$details_ids$request->request->get('date'));
  7830.                 Accounts::UpdateExpensePayments($em$ei_list$details_ids$request->request->get('date'));
  7831.                 $options = array(
  7832.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  7833.                     'notification_server' => $this->container->getParameter('notification_server'),
  7834.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  7835.                     'url' => $this->generateUrl(
  7836.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  7837.                     )
  7838.                 );
  7839.                 System::setApprovalInfo(
  7840.                     $this->getDoctrine()->getManager(),
  7841.                     $options,
  7842.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  7843.                     $TransID,
  7844.                     $loginId,
  7845.                     5    //payment voucher
  7846.                 );
  7847.                 System::createEditSignatureHash(
  7848.                     $em,
  7849.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  7850.                     $TransID,
  7851.                     $loginId,
  7852.                     $approveRole,
  7853.                     $request->request->get('approvalHash')
  7854.                 );
  7855.                 $url $this->generateUrl(
  7856.                     'view_voucher'
  7857.                 );
  7858.                 $trans_here $this->getDoctrine()
  7859.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  7860.                     ->findOneBy(
  7861.                         array(
  7862.                             'transactionId' => $TransID
  7863.                         )
  7864.                     );
  7865.                 System::AddNewNotification(
  7866.                     $this->container->getParameter('notification_enabled'),
  7867.                     $this->container->getParameter('notification_server'),
  7868.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  7869.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  7870.                     "Debit Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  7871.                     'pos',
  7872.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  7873.                     'success',
  7874.                     $url "/" $TransID,
  7875.                     "Debit Voucher"
  7876.                 );
  7877.                 if ($request->request->has('returnJson')) {
  7878.                     $doc $trans_here;
  7879.                     return new JsonResponse(array(
  7880.                         'success' => true,
  7881.                         'documentHash' => $trans_here->getDocumentHash(),
  7882.                         'documentId' => $TransID,
  7883.                         'documentIdPadded' => str_pad($TransID8'0'STR_PAD_LEFT),
  7884.                         'documentDate' => $trans_here->getTransactionDate()->format('Y-m-d'),
  7885.                         'documentAmount' => $trans_here->getTransactionAmount(),
  7886.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  7887.                         'viewUrl' => $url "/" $TransID,
  7888.                         'docPrintMainUrl' => $this->generateUrl('print_voucher'),
  7889.                     ));
  7890.                 } else {
  7891.                     $this->addFlash(
  7892.                         'success',
  7893.                         'New Document Created'
  7894.                     );
  7895.                     return $this->redirect($url "/" $TransID);
  7896.                 }
  7897.             }
  7898.         }
  7899.         //for edits
  7900.         $extVoucherData = [];
  7901.         $extVoucherDetailsData = [];
  7902.         if ($voucherId == 0) {
  7903.         } else {
  7904.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  7905.                 array(
  7906.                     'transactionId' => $voucherId///material
  7907.                 )
  7908.             );
  7909.             //now if its not editable, redirect to view
  7910.             if ($extTrans) {
  7911.                 if ($extTrans->getEditFlag() != 1) {
  7912.                     $url $this->generateUrl(
  7913.                         'view_voucher'
  7914.                     );
  7915.                     return $this->redirect($url "/" $voucherId);
  7916.                 } else {
  7917.                     $extVoucherData $extTrans;
  7918.                     $extVoucherDetailsData Accounts::GetVoucherDataForEdit($em$voucherId);
  7919.                 }
  7920.             } else {
  7921.             }
  7922.         }
  7923.         return $this->render(
  7924.             '@Accounts/pages/input_forms/payment_voucher.html.twig',
  7925.             array(
  7926.                 'page_title' => 'Create Payment Voucher',
  7927.                 'test' => $details_ids,
  7928.                 'prePopulateData' => $prePopulateData,
  7929.                 'skipInvoiceBalancing' => $skipInvoiceBalancing,
  7930.                 'extVoucherData' => $extVoucherData,
  7931.                 'extVoucherDetailsData' => $extVoucherDetailsData,
  7932.                 'supplier_list' => Accounts::SupplierListForPv($this->getDoctrine()->getManager()),
  7933.                 'supplier_list_by_ac_head' => Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
  7934.                 'supplier_list_by_advance_head' => Accounts::SupplierListByAdvanceHead($this->getDoctrine()->getManager()),
  7935.                 'fundRequisitionDetails' => $FundRequisitionDetails
  7936.             )
  7937.         );
  7938.     }
  7939.     public function CreateReceiptVoucher(Request $request$id 0)
  7940.     {
  7941.         $details_ids = [];
  7942.         $voucherId $id;
  7943.         $em $this->getDoctrine()->getManager();
  7944.         if ($request->isMethod('POST')) {
  7945.             //            Generic::debugMessage($_POST);
  7946.             $em $this->getDoctrine()->getManager();
  7947.             MiscActions::RemoveExpiredDocs($em);
  7948.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  7949.             $dochash $request->request->get('voucherNumber'); //change
  7950.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7951.             $approveRole $request->request->get('approvalRole');
  7952.             $approveHash $request->request->get('approvalHash');
  7953.             if (!DocValidation::isInsertable(
  7954.                 $em,
  7955.                 $entity_id,
  7956.                 $dochash,
  7957.                 $loginId,
  7958.                 $approveRole,
  7959.                 $approveHash,
  7960.                 $id
  7961.             )) {
  7962.                 if ($request->request->has('returnJson')) {
  7963.                     return new JsonResponse(array(
  7964.                         'success' => false,
  7965.                         'documentHash' => 0,
  7966.                         'documentId' => 0,
  7967.                     ));
  7968.                 } else
  7969.                     $this->addFlash(
  7970.                         'error',
  7971.                         'Sorry Could not insert Data.'
  7972.                     );
  7973.             } else {
  7974.                 $funcname 'AccTransactions';
  7975.                 $doc_id $voucherId;
  7976.                 DeleteDocument::$funcname($em$doc_id0);
  7977.                 $ledgerHeads $request->request->get('ledgerHeads');
  7978.                 $notes $request->request->get('trNote');
  7979.                 $costCenters $request->request->get('costCenters');
  7980.                 $drAmount $request->request->get('drAmount');
  7981.                 $crAmount $request->request->get('crAmount');
  7982.                 $em $this->getDoctrine()->getManager();
  7983.                 $pi_list = [];
  7984.                 $po_list = [];
  7985.                 $ei_list = [];
  7986.                 //1stly lets set the invoices po etc before we save the transaction normally
  7987.                 if ($request->request->has('ei_id'))
  7988.                     $ei_list = array(
  7989.                         'id' => $request->request->get('ei_id'),
  7990.                         'aa' => $request->request->get('ei_aa'),
  7991.                         'ei_head_id' => $request->request->get('ei_head_id')
  7992.                     );
  7993.                 if ($request->request->has('pi_id'))
  7994.                     $pi_list = array(
  7995.                         'id' => $request->request->get('pi_id'),
  7996.                         'aa' => $request->request->get('pi_aa')
  7997.                     );
  7998.                 if ($request->request->has('po_id'))
  7999.                     $po_list = array(
  8000.                         'id' => $request->request->get('po_id'),
  8001.                         'aa' => $request->request->get('po_aa')
  8002.                     );
  8003.                 $check_allowed 0;
  8004.                 $provisional 0;
  8005.                 $pr_method 0;
  8006.                 $check_number '';
  8007.                 if ($request->request->has('check_allowed'))
  8008.                     $check_allowed 1;
  8009.                 if ($request->request->has('provisional'))
  8010.                     $provisional 1;
  8011.                 //            if($request->request->has('provisional'))
  8012.                 $pr_method $request->request->get('receipt_method');
  8013.                 //            $check_number=$request->request->get('receipt_method');
  8014.                 $em_goc $this->getDoctrine()->getManager('company_group');
  8015.                 $post_data $request->request;
  8016.                 $TransID Accounts::CreateNewTransaction(
  8017.                     $voucherId,
  8018.                     $this->getDoctrine()->getManager(),
  8019.                     $request->request->get('date'),
  8020.                     array_sum($request->request->get('drAmount')),
  8021.                     AccountsConstant::VOUCHER_RECEIPT,
  8022.                     $request->request->get('description'),
  8023.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  8024.                     $request->request->get('type_hash'),
  8025.                     $request->request->get('prefix_hash'),
  8026.                     $request->request->get('assoc_hash'),
  8027.                     $request->request->get('number_hash'),
  8028.                     $check_allowed,
  8029.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8030.                     $this->getLoggedUserCompanyId($request),
  8031.                     '',
  8032.                     $provisional,
  8033.                     0,
  8034.                     $pr_method
  8035.                 );
  8036.                 $file_path_list = [];
  8037.                 if ($TransID != 0)
  8038.                     if (!empty($request->files)) {
  8039.                         MiscActions::RemoveFilesForEntityDoc($em_goc'AccTransactions'$TransID);
  8040.                         $storePath 'uploads/Voucher/';
  8041.                         $path "";
  8042.                         $file_path "";
  8043.                         $session $request->getSession();
  8044.                         MiscActions::RemoveExpiredFiles($em_goc);
  8045.                         foreach ($request->files as $uploadedFileGG) {
  8046.                             //            if($uploadedFile->getImage())
  8047.                             //                var_dump($uploadedFile->getFile());
  8048.                             //                var_dump($uploadedFile);
  8049.                             $tempD $uploadedFileGG;
  8050.                             if (!is_array($uploadedFileGG)) {
  8051.                                 $uploadedFileGG = array();
  8052.                                 $uploadedFileGG[] = $tempD;
  8053.                             }
  8054.                             foreach ($uploadedFileGG as $uploadedFile) {
  8055.                                 if ($uploadedFile != null) {
  8056.                                     $extension $uploadedFile->guessExtension();
  8057.                                     $size $uploadedFile->getSize();
  8058.                                     $fileName 'TRANS_' $TransID '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  8059.                                     $path $fileName;
  8060.                                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  8061.                                     if (!file_exists($upl_dir)) {
  8062.                                         mkdir($upl_dir0777true);
  8063.                                     }
  8064.                                     if (file_exists($upl_dir '' $path)) {
  8065.                                         chmod($upl_dir '' $path0755);
  8066.                                         unlink($upl_dir '' $path);
  8067.                                     }
  8068.                                     $file $uploadedFile->move($upl_dir$path);
  8069.                                     $expireNever 1;
  8070.                                     $expireTs 0;
  8071.                                     $EntityFile = new EntityFile();
  8072.                                     $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  8073.                                     $EntityFile->setMarker('_GEN_');
  8074.                                     $EntityFile->setName($path);
  8075.                                     $EntityFile->setExtension($extension);
  8076.                                     $EntityFile->setExpireTs($expireTs);
  8077.                                     $EntityFile->setSize($size);
  8078.                                     $EntityFile->setRelativePath($storePath $path);
  8079.                                     $EntityFile->setEntityName('AccTransactions');
  8080.                                     $EntityFile->setEntityBundle('ApplicationBundle');
  8081.                                     $EntityFile->setEntityId($TransID);
  8082.                                     $EntityFile->setEntityIdField('transactionId');
  8083.                                     $EntityFile->setModifyFieldSetter('setFiles');
  8084.                                     $EntityFile->setDocIdForApplicant(0);
  8085.                                     $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  8086.                                     $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  8087.                                     $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  8088.                                     $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  8089.                                     $em_goc->persist($EntityFile);
  8090.                                     $em_goc->flush();
  8091.                                     $EntityFileId $EntityFile->getId();
  8092.                                 }
  8093.                                 if ($path != "")
  8094.                                     $file_path_list[] = ($storePath $path);
  8095.                             }
  8096.                         }
  8097.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  8098.                         $v $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  8099.                             'transactionId' => $TransID,
  8100.                         ));
  8101.                         if ($v) {
  8102.                             $v->setFiles(implode(','$file_path_list));
  8103.                             $em->flush();
  8104.                         } else {
  8105.                         }
  8106.                     }
  8107.                 $check_here = [];
  8108.                 $id_list_for_check = [];
  8109.                 $debit_head '';
  8110.                 $credit_head '';
  8111.                 $debit_amount '';
  8112.                 $details_ids = [];
  8113.                 for ($i 0$i count($ledgerHeads); $i++) {
  8114.                     //                if(!empty($drAmount[$i]) && $drAmount[$i]!=0){
  8115.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  8116.                         $id_list_for_check[$ledgerHeads[$i]] = $ledgerHeads[$i]; //initially same all
  8117.                         //now lets see if any supplier exists and if yes , sprlit the value in advance and normal
  8118.                         $supplier_list Accounts::ClientListThreeTypes($this->getDoctrine()->getManager());
  8119.                         $supplier_head_id_list = [];
  8120.                         $s_b_ac_h $supplier_list[1];
  8121.                         $s_b_advance_h $supplier_list[2];
  8122.                         //        $s_list=self::SupplierListForPv();
  8123.                         $head_index_calibrate = [];
  8124.                         $supplier_by_id '';
  8125.                         if (array_key_exists($ledgerHeads[$i], $s_b_ac_h)) {
  8126.                             $supplier_by_id $s_b_ac_h[$ledgerHeads[$i]];
  8127.                         }
  8128.                         if (array_key_exists($ledgerHeads[$i], $s_b_advance_h)) {
  8129.                             $supplier_by_id $s_b_advance_h[$ledgerHeads[$i]];
  8130.                         }
  8131.                         if ($supplier_by_id != '') {
  8132.                             $credit_head $supplier_by_id['client_head_id'];
  8133.                             $gt 0;
  8134.                             //use normal transaction
  8135.                             $tot 0;
  8136.                             if ($request->request->has('pi_id')) {
  8137.                                 foreach ($request->request->get('pi_id') as $k => $v) {
  8138.                                     if ($request->request->get('pi_head_id')[$k] == $ledgerHeads[$i])
  8139.                                         $tot += $request->request->get('pi_aa')[$k];
  8140.                                 }
  8141.                                 if ($tot 0) {
  8142.                                     $id_list_for_check[$ledgerHeads[$i]] = $supplier_by_id['client_head_id'];
  8143.                                     $details_ids[$supplier_by_id['client_head_id']] = Accounts::CreateNewTransactionDetails(
  8144.                                         $this->getDoctrine()->getManager(),
  8145.                                         $request->request->get('date'),
  8146.                                         $TransID,
  8147.                                         Generic::CurrToInt($tot),
  8148.                                         $supplier_by_id['client_head_id'],
  8149.                                         $notes[$i],
  8150.                                         AccountsConstant::CREDIT,
  8151.                                         isset($costCenters[$i]) ? $costCenters[$i] : 0,
  8152.                                         array($pi_list$po_list$ei_list),
  8153.                                         [],
  8154.                                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8155.                                         $provisional
  8156.                                     );
  8157.                                 }
  8158.                             }
  8159.                             $gt $gt $tot;
  8160.                             //now advance transaction
  8161.                             $tot 0;
  8162.                             if ($request->request->has('po_id')) {
  8163.                                 foreach ($request->request->get('po_id') as $k => $v) {
  8164.                                     if ($request->request->get('po_head_id')[$k] == $ledgerHeads[$i])
  8165.                                         $tot += $request->request->get('po_aa')[$k];
  8166.                                 }
  8167.                                 if ($tot 0) {
  8168.                                     $id_list_for_check[$ledgerHeads[$i]] = $supplier_by_id['client_advance_head_id'];
  8169.                                     $details_ids[$supplier_by_id['client_advance_head_id']] = Accounts::CreateNewTransactionDetails(
  8170.                                         $this->getDoctrine()->getManager(),
  8171.                                         $request->request->get('date'),
  8172.                                         $TransID,
  8173.                                         Generic::CurrToInt($tot),
  8174.                                         $supplier_by_id['client_advance_head_id'],
  8175.                                         $notes[$i],
  8176.                                         AccountsConstant::CREDIT,
  8177.                                         isset($costCenters[$i]) ? $costCenters[$i] : 0,
  8178.                                         array($pi_list$po_list$ei_list),
  8179.                                         [],
  8180.                                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8181.                                         $provisional
  8182.                                     );
  8183.                                 }
  8184.                             }
  8185.                             $gt $gt $tot;
  8186.                             Accounts::CreateNewTransactionDetails(
  8187.                                 $this->getDoctrine()->getManager(),
  8188.                                 $request->request->get('date'),
  8189.                                 $TransID,
  8190.                                 Generic::CurrToInt($crAmount[$i] - $gt),
  8191.                                 $ledgerHeads[$i],
  8192.                                 $notes[$i],
  8193.                                 AccountsConstant::CREDIT,
  8194.                                 isset($costCenters[$i]) ? $costCenters[$i] : 0,
  8195.                                 array($pi_list$po_list$ei_list),
  8196.                                 [],
  8197.                                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8198.                                 $provisional,
  8199.                                 0,
  8200.                                 '_UNSET_',
  8201.                                 $request->request->get('currency')[$i],
  8202.                                 1,
  8203.                                 $request->request->get('currencyMultiplyRate')[$i]
  8204.                             );
  8205.                         } else {
  8206.                             $credit_head $ledgerHeads[$i];
  8207.                             $details_ids[$ledgerHeads[$i]] = Accounts::CreateNewTransactionDetails(
  8208.                                 $this->getDoctrine()->getManager(),
  8209.                                 $request->request->get('date'),
  8210.                                 $TransID,
  8211.                                 Generic::CurrToInt($crAmount[$i]),
  8212.                                 $ledgerHeads[$i],
  8213.                                 $notes[$i],
  8214.                                 AccountsConstant::CREDIT,
  8215.                                 isset($costCenters[$i]) ? $costCenters[$i] : 0,
  8216.                                 array($pi_list$po_list$ei_list),
  8217.                                 [],
  8218.                                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8219.                                 $provisional,
  8220.                                 0,
  8221.                                 '_UNSET_',
  8222.                                 $request->request->get('currency')[$i],
  8223.                                 1,
  8224.                                 $request->request->get('currencyMultiplyRate')[$i]
  8225.                             );
  8226.                         }
  8227.                     }
  8228.                     //                if(!empty($crAmount[$i]) && $crAmount[$i]!=0){
  8229.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  8230.                         $debit_head $ledgerHeads[$i];
  8231.                         $debit_amount Generic::CurrToInt($drAmount[$i]);
  8232.                         $details_ids[$ledgerHeads[$i]] = Accounts::CreateNewTransactionDetails(
  8233.                             $this->getDoctrine()->getManager(),
  8234.                             $request->request->get('date'),
  8235.                             $TransID,
  8236.                             Generic::CurrToInt($drAmount[$i]),
  8237.                             $ledgerHeads[$i],
  8238.                             $notes[$i],
  8239.                             AccountsConstant::DEBIT,
  8240.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  8241.                             array($pi_list$po_list$ei_list),
  8242.                             [],
  8243.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8244.                             $provisional,
  8245.                             0,
  8246.                             '_UNSET_',
  8247.                             $request->request->get('currency')[$i],
  8248.                             1,
  8249.                             $request->request->get('currencyMultiplyRate')[$i]
  8250.                         );
  8251.                     }
  8252.                 }
  8253.                 if ($pr_method == 2) {
  8254.                     //                foreach($request->request->get('check_id') as $k=>$value)
  8255.                     //                {
  8256.                     $check_here = new AccCheck();
  8257.                     $check_here->setRecAccountsHeadId($debit_head);
  8258.                     $check_here->setRecAccountsHeadIdList(json_encode([$debit_head]));
  8259.                     $check_here->setAccountsHeadId($credit_head);
  8260.                     //                    $check_here->setCheckNarration($request->request->get('check_narration')[$k]);
  8261.                     $check_here->setCheckAmount($debit_amount);
  8262.                     $check_here->setCheckDate(new \DateTime($request->request->get('receiptCheckDate')));
  8263.                     $check_here->setTransactionDate(new \DateTime($request->request->get('date')));
  8264.                     //                    $check_here->setCheckDate(new \DateTime($request->request->get('date')));
  8265.                     $check_here->setAssigned(1);
  8266.                     $check_here->setActive(1);
  8267.                     $check_here->setDetails('');
  8268.                     $check_here->setCheckNumber($request->request->get('receiptCheckNo'));
  8269.                     $check_here->setStatus(3);
  8270.                     $check_here->setType(2); //receipt check
  8271.                     $check_here->setVoucherId($TransID);
  8272.                     //                }
  8273.                     $em->persist($check_here);
  8274.                     $em->flush();
  8275.                 }
  8276.                 //approval system
  8277.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8278.                 $approveRole $request->request->get('approvalRole');
  8279.                 Accounts::UpdateSalesPayments($em$pi_list$po_list$details_ids$request->request->get('date'));
  8280.                 //            Accounts::UpdateExpensePayments($em,$ei_list,$details_ids, $request->request->get('date'));
  8281.                 $options = array(
  8282.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8283.                     'notification_server' => $this->container->getParameter('notification_server'),
  8284.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8285.                     'url' => $this->generateUrl(
  8286.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  8287.                     )
  8288.                 );
  8289.                 System::setApprovalInfo(
  8290.                     $this->getDoctrine()->getManager(),
  8291.                     $options,
  8292.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  8293.                     $TransID,
  8294.                     $loginId,
  8295.                     AccountsConstant::VOUCHER_RECEIPT    //Receipt voucher
  8296.                 );
  8297.                 System::createEditSignatureHash(
  8298.                     $em,
  8299.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  8300.                     $TransID,
  8301.                     $loginId,
  8302.                     $approveRole,
  8303.                     $request->request->get('approvalHash')
  8304.                 );
  8305.                 $url $this->generateUrl(
  8306.                     'view_voucher'
  8307.                 );
  8308.                 $trans_here $this->getDoctrine()
  8309.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  8310.                     ->findOneBy(
  8311.                         array(
  8312.                             'transactionId' => $TransID
  8313.                         )
  8314.                     );
  8315.                 System::AddNewNotification(
  8316.                     $this->container->getParameter('notification_enabled'),
  8317.                     $this->container->getParameter('notification_server'),
  8318.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  8319.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8320.                     "Receipt Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  8321.                     'pos',
  8322.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  8323.                     'success',
  8324.                     $url "/" $TransID,
  8325.                     "Receipt Voucher"
  8326.                 );
  8327.                 if ($request->request->has('returnJson')) {
  8328.                     $doc $trans_here;
  8329.                     return new JsonResponse(array(
  8330.                         'success' => true,
  8331.                         'documentHash' => $trans_here->getDocumentHash(),
  8332.                         'documentId' => $TransID,
  8333.                         'documentIdPadded' => str_pad($TransID8'0'STR_PAD_LEFT),
  8334.                         'documentDate' => $trans_here->getTransactionDate()->format('Y-m-d'),
  8335.                         'documentAmount' => $trans_here->getTransactionAmount(),
  8336.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  8337.                         'viewUrl' => $url "/" $TransID,
  8338.                         'docPrintMainUrl' => $this->generateUrl('print_voucher'),
  8339.                     ));
  8340.                 } else {
  8341.                     $this->addFlash(
  8342.                         'success',
  8343.                         'New Document Created'
  8344.                     );
  8345.                     return $this->redirect($url "/" $TransID);
  8346.                 }
  8347.             }
  8348.         }
  8349.         $extVoucherData = [];
  8350.         $extVoucherDetailsData = [];
  8351.         if ($voucherId == 0) {
  8352.         } else {
  8353.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  8354.                 array(
  8355.                     'transactionId' => $voucherId///material
  8356.                 )
  8357.             );
  8358.             //now if its not editable, redirect to view
  8359.             if ($extTrans) {
  8360.                 if ($extTrans->getEditFlag() != 1) {
  8361.                     $url $this->generateUrl(
  8362.                         'view_voucher'
  8363.                     );
  8364.                     return $this->redirect($url "/" $voucherId);
  8365.                 } else {
  8366.                     $extVoucherData $extTrans;
  8367.                     $extVoucherDetailsData Accounts::GetVoucherDataForEdit($em$voucherId);
  8368.                 }
  8369.             } else {
  8370.             }
  8371.         }
  8372.         return $this->render(
  8373.             '@Accounts/pages/input_forms/receipt_voucher.html.twig',
  8374.             array(
  8375.                 'page_title' => 'Create Receipt Voucher',
  8376.                 'test' => $details_ids,
  8377.                 'extVoucherData' => $extVoucherData,
  8378.                 'extVoucherDetailsData' => $extVoucherDetailsData,
  8379.                 'client_list' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  8380.                 'client_list_by_ac_head' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  8381.                 'client_list_by_advance_head' => SalesOrderM::GetClientListByAdvanceHead($this->getDoctrine()->getManager())
  8382.             )
  8383.         );
  8384.     }
  8385.     public function CheckFormat(Request $request$id 0)
  8386.     {
  8387.         $data = array(
  8388.             'formatId' => '',
  8389.             'name' => '',
  8390.             'width' => 6,
  8391.             'height' => 2,
  8392.             'checkPayToLeft' => '130px',
  8393.             'checkPayToTop' => '58px',
  8394.             'checkAmountLeft' => '451px',
  8395.             'checkAmountTop' => '88px',
  8396.             'checkAiWLeft' => '131px',
  8397.             'checkAiWTop' => '82px',
  8398.             'checkDateLeft' => '487px',
  8399.             'checkDatePartLeft' => '459px',
  8400.             'checkDateD1Left' => '-49px',
  8401.             'checkDateD2Left' => '-28px',
  8402.             'checkDateM1Left' => '-10px',
  8403.             'checkDateM2Left' => '10px',
  8404.             'checkDateY1Left' => '27px',
  8405.             'checkDateY2Left' => '47px',
  8406.             'checkDateY3Left' => '64px',
  8407.             'checkDateY4Left' => '85px',
  8408.             'checkDateTop' => '34px',
  8409.             'checkDatePartTop' => '31px',
  8410.             'checkImage' => '',
  8411.             'dateDividerDisabled' => 1,
  8412.         );
  8413.         if ($request->isMethod('POST')) {
  8414.             $post $request->request;
  8415.             if ($request->request->get('formatId') != '') {
  8416.                 $query_here $this->getDoctrine()
  8417.                     ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  8418.                     ->findOneBy(
  8419.                         array(
  8420.                             'formatId' => $request->request->get('formatId')
  8421.                         )
  8422.                     );
  8423.                 if (!empty($query_here))
  8424.                     $new $query_here;
  8425.             } else
  8426.                 $new = new CheckFormat();
  8427.             $new->setName($request->request->get('name'));
  8428.             $new->setWidth($request->request->get('width'));
  8429.             $new->setHeight($request->request->get('height'));
  8430.             $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
  8431.             $new->setCheckPayToTop($request->request->get('checkPayToTop'));
  8432.             $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
  8433.             $new->setCheckAmountTop($request->request->get('checkAmountTop'));
  8434.             $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
  8435.             $new->setCheckAiWTop($request->request->get('checkAiWTop'));
  8436.             $new->setCheckDateLeft($request->request->get('checkDateLeft'));
  8437.             $new->setCheckDateTop($request->request->get('checkDateTop'));
  8438.             $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
  8439.             $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
  8440.             $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
  8441.             $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
  8442.             $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
  8443.             $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
  8444.             $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
  8445.             $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
  8446.             $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
  8447.             $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
  8448.             $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 0);
  8449.             $new->setCheckImage($request->request->get('checkImage'));
  8450.             $em $this->getDoctrine()->getManager();
  8451.             $em->persist($new);
  8452.             $em->flush();
  8453.         }
  8454.         if ($id != 0) {
  8455.             $query_here $this->getDoctrine()
  8456.                 ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  8457.                 ->findOneBy(
  8458.                     array(
  8459.                         'formatId' => $id
  8460.                     )
  8461.                 );
  8462.             if ($query_here)
  8463.                 $data $query_here;
  8464.         } else if ($request->query->has('formatId')) {
  8465.             $query_here $this->getDoctrine()
  8466.                 ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  8467.                 ->findOneBy(
  8468.                     array(
  8469.                         'formatId' => $request->query->get('formatId')
  8470.                     )
  8471.                 );
  8472.             if ($query_here)
  8473.                 $data $query_here;
  8474.         }
  8475.         return $this->render(
  8476.             '@Application/pages/accounts/settings/check_format.html.twig',
  8477.             array(
  8478.                 'page_title' => 'Cheque Format',
  8479.                 'data' => $data,
  8480.                 'formatList' => $this->getDoctrine()
  8481.                     ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  8482.                     ->findBy(
  8483.                         array( //                            'formatId' => $request->query->get('formatId')
  8484.                         )
  8485.                     )
  8486.                 //                'incomeLedgerHeads'=>Accounts::getChildLedgerHeads($this->getDoctrine()->getManager(),AccountsConstant::INCOME)
  8487.             )
  8488.         );
  8489.     }
  8490.     public function PrintCheck(Request $request$id)
  8491.     {
  8492.         $data = array(
  8493.             'formatId' => '',
  8494.             'name' => '',
  8495.             'width' => 6,
  8496.             'height' => 2,
  8497.             'checkPayToLeft' => '130px',
  8498.             'checkPayToTop' => '58px',
  8499.             'checkAmountLeft' => '451px',
  8500.             'checkAmountTop' => '88px',
  8501.             'checkAiWLeft' => '131px',
  8502.             'checkAiWTop' => '82px',
  8503.             'checkDateLeft' => '487px',
  8504.             'checkDatePartLeft' => '459px',
  8505.             'checkDateD1Left' => '-49px',
  8506.             'checkDateD2Left' => '-28px',
  8507.             'checkDateM1Left' => '-10px',
  8508.             'checkDateM2Left' => '10px',
  8509.             'checkDateY1Left' => '27px',
  8510.             'checkDateY2Left' => '47px',
  8511.             'checkDateY3Left' => '64px',
  8512.             'checkDateY4Left' => '85px',
  8513.             'checkDateTop' => '34px',
  8514.             'checkDatePartTop' => '31px',
  8515.             'checkImage' => '',
  8516.             'marginTopAdd' => '0',
  8517.             'dateDividerDisabled' => 1
  8518.         );
  8519.         $print_ac_payee_tag 0;
  8520.         if ($request->query->has('print_ac_payee_tag'))
  8521.             if ($request->query->get('print_ac_payee_tag') == 1)
  8522.                 $print_ac_payee_tag $request->query->get('print_ac_payee_tag');
  8523.         //first get check data
  8524.         $check_query $this->getDoctrine()
  8525.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  8526.             ->findOneBy(
  8527.                 array(
  8528.                     'CheckId' => $id
  8529.                 )
  8530.             );
  8531.         //now get the format data
  8532.         if (!empty($check_query))
  8533.             $query_here $this->getDoctrine()
  8534.                 ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  8535.                 ->findOneBy(
  8536.                     array(
  8537.                         'formatId' => $check_query->getFormatId()
  8538.                     )
  8539.                 );
  8540.         if (!empty($query_here))
  8541.             $data $query_here;
  8542.         $inv_parts explode('.'number_format($check_query->getCheckAmount(), 2'.'''));
  8543.         return $this->render(
  8544.             '@Accounts/pages/print/print_check.html.twig',
  8545.             array(
  8546.                 'page_title' => 'Print Check',
  8547.                 'red' => 0,
  8548.                 'data' => $data,
  8549.                 'print_ac_payee_tag' => $print_ac_payee_tag,
  8550.                 'check_data' => $check_query,
  8551.                 'amount_in_word_integer' => Accounts::ConvertNumberToWords($inv_parts[0]),
  8552.                 'amount_in_word_dec' => Accounts::ConvertNumberToWords((isset($inv_parts[1])) ? $inv_parts[1] * 0),
  8553.             )
  8554.         );
  8555.     }
  8556.     public function MarkCheckPrinted(Request $request$id)
  8557.     {
  8558.         //first get check data
  8559.         $check_query $this->getDoctrine()
  8560.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  8561.             ->findOneBy(
  8562.                 array(
  8563.                     'CheckId' => $id
  8564.                 )
  8565.             );
  8566.         $check_query->setPrinted(1);
  8567.         $em $this->getDoctrine()->getManager();
  8568.         $em->flush();
  8569.         return 1;
  8570.     }
  8571.     public function RemoveFile(Request $request)
  8572.     {
  8573.         $em_goc $this->getDoctrine()->getManager('company_group');
  8574.         $EntityFileId 0;
  8575.         $relId 0;
  8576.         MiscActions::RemoveExpiredFiles($em_goc);
  8577.         if ($request->isMethod('POST')) {
  8578.             $post $request->request;
  8579.             $relId $post->get('relId');
  8580.             $afterRemoveConfig $post->get('afterRemoveConfig', []);
  8581.             if ($post->get('path''') != '') {
  8582.                 MiscActions::RemoveFileByPath($em_goc$post->get('path'''), $afterRemoveConfig);
  8583.                 return new JsonResponse(array(
  8584.                     "success" => true,
  8585.                     "relId" => $relId,
  8586.                 ));
  8587.             } else if ($post->get('conditionOptions', []) != []) {
  8588.                 MiscActions::RemoveFileByCondition($em_goc$post->get('conditionOptions', []));
  8589.                 return new JsonResponse(array(
  8590.                     "success" => true,
  8591.                     "relId" => $relId,
  8592.                 ));
  8593.             } else if ($post->get('fileId'0) != 0) {
  8594.                 MiscActions::RemoveFileById($em_goc$post->get('fileId'0), $afterRemoveConfig);
  8595.                 return new JsonResponse(array(
  8596.                     "success" => true,
  8597.                     "relId" => $relId,
  8598.                 ));
  8599.             }
  8600.         }
  8601.         return new JsonResponse(array(
  8602.             "success" => false,
  8603.             "relId" => $relId,
  8604.         ));
  8605.     }
  8606.     public function FileUpload(Request $request)
  8607.     {
  8608.         $em_goc $this->getDoctrine()->getManager('company_group');
  8609.         $EntityFileId 0;
  8610.         $file_path_list = [];
  8611.         if ($request->isMethod('POST')) {
  8612.             $post_data $request->request;
  8613.             if ($request->request->get('clearExistingFilesForThisDoc'0) == 1) {
  8614.                 MiscActions::RemoveFilesForEntityDoc($em_goc$request->request->get('entityName'''), $request->request->get('entityId'0));
  8615.             }
  8616.             if ($post_data->has('isBase64') || $post_data->has('imageBase64')) {
  8617.                 $imageBase64 $post_data->get('imageBase64');
  8618.                 $data base64_decode(preg_replace('#^data:image/\w+;base64,#i'''$imageBase64));
  8619.                 $fileName md5(uniqid()) . '.png';
  8620.                 if ($request->request->has('buddybee_profile_image_flag'))
  8621.                     $storePath 'uploads/applicants/';
  8622.                 if ($request->request->has('central_profile_image_flag'))
  8623.                     $storePath 'uploads/UserImage/';
  8624.                 if ($request->request->has('expense_invoice_attachment'))
  8625.                     $storePath 'uploads/ExpenseInvoice/';
  8626.                 if ($request->request->has('voucher_attachment'))
  8627.                     $storePath 'uploads/Voucher/';
  8628.                 if ($request->request->has('leave_attachment'))
  8629.                     $storePath 'uploads/LeaveDoc/';
  8630.                 if ($request->request->has('sales_invoice_attachment'))
  8631.                     $storePath 'uploads/SalesInvoice/';
  8632.                 if ($request->request->has('purchase_invoice_attachment'))
  8633.                     $storePath 'uploads/PurchaseInvoice/';
  8634.                 if ($request->request->has('po_attachment'))
  8635.                     $storePath 'uploads/PurchaseOrder/';
  8636.                 if ($request->request->has('so_attachment'))
  8637.                     $storePath 'uploads/SalesOrder/';
  8638.                 if ($request->request->has('product_mrp_attachment'))
  8639.                     $storePath 'uploads/PriceDoc/';
  8640.                 if ($request->request->has('pr_attachment'))
  8641.                     $storePath 'uploads/PurchaseRequisition/';
  8642.                 if ($request->request->has('so_amendment_attachment'))
  8643.                     $storePath 'uploads/SoAmendment/';
  8644.                 if ($request->request->has('fund_requisition_attachment'))
  8645.                     $storePath 'uploads/FundRequisition/';
  8646.                 if ($request->request->has('delivery_order_attachment'))
  8647.                     $storePath 'uploads/DeliveryOrder/';
  8648.                 if ($request->request->has('proforma_invoice_attachment'))
  8649.                     $storePath 'uploads/ProformaInvoice/';
  8650.                 if ($request->request->has('insurance_pay_request_attachment'))
  8651.                     $storePath 'uploads/InsurancePayRequest/';
  8652.                 if ($request->request->has('grn_attachment'))
  8653.                     $storePath 'uploads/Grn/';
  8654.                 if ($request->request->has('service_challan_attachment'))
  8655.                     $storePath 'uploads/ServiceChallan/';
  8656.                 if ($request->request->has('stock_requisition_attachment'))
  8657.                     $storePath 'uploads/StockRequisition/';
  8658.                 if ($request->request->has('store_requisition_attachment'))
  8659.                     $storePath 'uploads/StoreRequisition/';
  8660.                 if ($request->request->has('stock_transfer_attachment'))
  8661.                     $storePath 'uploads/StockTransfer/';
  8662.                 if ($request->request->has('stock_received_note_attachment'))
  8663.                     $storePath 'uploads/StockReceivedNote/';
  8664.                 if ($request->request->has('delivery_receipt_attachment'))
  8665.                     $storePath 'uploads/DeliveryReceipt/';
  8666.                 if ($request->request->has('item_received_and_replacement_attachment'))
  8667.                     $storePath 'uploads/ItemReceivedAndReplacement/';
  8668.                 if ($request->request->has('stock_consumption_note_attachment'))
  8669.                     $storePath 'uploads/StockConsumptionNote/';
  8670.                 if ($request->request->has('general_attachment'))
  8671.                     $storePath 'uploads/General/';
  8672.                 if ($request->request->has('product_datasheets_attachment'))
  8673.                     $storePath 'uploads/Product/Datasheets/';
  8674.                 if ($request->request->has('sales_proposal_cover_attachment'))
  8675.                     $storePath 'uploads/SalesProposal/';
  8676.                 $path "";
  8677.                 $file_path "";
  8678.                 $session $request->getSession();
  8679.                 MiscActions::RemoveExpiredFiles($em_goc);
  8680.                 $path $fileName;
  8681.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  8682.                 if (!file_exists($upl_dir)) {
  8683.                     mkdir($upl_dir0777true);
  8684.                 }
  8685.                 if (file_exists($upl_dir '' $path)) {
  8686.                     chmod($upl_dir '' $path0755);
  8687.                     unlink($upl_dir '' $path);
  8688.                 }
  8689.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/' $path;
  8690.                 file_put_contents($upl_dir$data);
  8691.                 if ($path != "")
  8692.                     $file_path_list[] = ($storePath $path);
  8693.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  8694.             } else {
  8695.                 $storePath $request->request->get('storePath''uploads/FileUploads/');
  8696.                 if ($request->request->has('buddybee_profile_image_flag'))
  8697.                     $storePath 'uploads/applicants/';
  8698.                 if ($request->request->has('central_profile_image_flag'))
  8699.                     $storePath 'uploads/UserImage/';
  8700.                 if ($request->request->has('expense_invoice_attachment'))
  8701.                     $storePath 'uploads/ExpenseInvoice/';
  8702.                 if ($request->request->has('voucher_attachment'))
  8703.                     $storePath 'uploads/Voucher/';
  8704.                 if ($request->request->has('leave_attachment'))
  8705.                     $storePath 'uploads/LeaveDoc/';
  8706.                 if ($request->request->has('sales_invoice_attachment'))
  8707.                     $storePath 'uploads/SalesInvoice/';
  8708.                 if ($request->request->has('po_attachment'))
  8709.                     $storePath 'uploads/PurchaseOrder/';
  8710.                 if ($request->request->has('so_attachment'))
  8711.                     $storePath 'uploads/SalesOrder/';
  8712.                 if ($request->request->has('product_mrp_attachment'))
  8713.                     $storePath 'uploads/PriceDoc/';
  8714.                 if ($request->request->has('pr_attachment'))
  8715.                     $storePath 'uploads/PurchaseRequisition/';
  8716.                 if ($request->request->has('purchase_invoice_attachment'))
  8717.                     $storePath 'uploads/PurchaseInvoice/';
  8718.                 if ($request->request->has('so_amendment_attachment'))
  8719.                     $storePath 'uploads/SoAmendment/';
  8720.                 if ($request->request->has('fund_requisition_attachment'))
  8721.                     $storePath 'uploads/FundRequisition/';
  8722.                 if ($request->request->has('delivery_order_attachment'))
  8723.                     $storePath 'uploads/DeliveryOrder/';
  8724.                 if ($request->request->has('proforma_invoice_attachment'))
  8725.                     $storePath 'uploads/ProformaInvoice/';
  8726.                 if ($request->request->has('insurance_pay_request_attachment'))
  8727.                     $storePath 'uploads/InsurancePayRequest/';
  8728.                 if ($request->request->has('grn_attachment'))
  8729.                     $storePath 'uploads/Grn/';
  8730.                 if ($request->request->has('service_challan_attachment'))
  8731.                     $storePath 'uploads/ServiceChallan/';
  8732.                 if ($request->request->has('stock_requisition_attachment'))
  8733.                     $storePath 'uploads/StockRequisition/';
  8734.                 if ($request->request->has('store_requisition_attachment'))
  8735.                     $storePath 'uploads/StoreRequisition/';
  8736.                 if ($request->request->has('stock_transfer_attachment'))
  8737.                     $storePath 'uploads/StockTransfer/';
  8738.                 if ($request->request->has('stock_received_note_attachment'))
  8739.                     $storePath 'uploads/StockReceivedNote/';
  8740.                 if ($request->request->has('delivery_receipt_attachment'))
  8741.                     $storePath 'uploads/DeliveryReceipt/';
  8742.                 if ($request->request->has('item_received_and_replacement_attachment'))
  8743.                     $storePath 'uploads/ItemReceivedAndReplacement/';
  8744.                 if ($request->request->has('stock_consumption_note_attachment'))
  8745.                     $storePath 'uploads/StockConsumptionNote/';
  8746.                 if ($request->request->has('general_attachment'))
  8747.                     $storePath 'uploads/General/';
  8748.                 if ($request->request->has('product_datasheets_attachment'))
  8749.                     $storePath 'uploads/Product/Datasheets/';
  8750.                 if ($request->request->has('sales_proposal_cover_attachment'))
  8751.                     $storePath 'uploads/SalesProposal/';
  8752.                 $path "";
  8753.                 $file_path "";
  8754.                 $session $request->getSession();
  8755.                 MiscActions::RemoveExpiredFiles($em_goc);
  8756.                 foreach ($request->files as $uploadedFileGG) {
  8757.                     //            if($uploadedFile->getImage())
  8758.                     //                var_dump($uploadedFile->getFile());
  8759.                     //                var_dump($uploadedFile);
  8760.                     $tempD $uploadedFileGG;
  8761.                     if (!is_array($uploadedFileGG)) {
  8762.                         $uploadedFileGG = array();
  8763.                         $uploadedFileGG[] = $tempD;
  8764.                     }
  8765.                     foreach ($uploadedFileGG as $uploadedFile) {
  8766.                         if ($uploadedFile != null) {
  8767.                             $extension $uploadedFile->guessExtension();
  8768.                             $size $uploadedFile->getSize();
  8769.                             $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  8770.                             $path $fileName;
  8771.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  8772.                             if (!file_exists($upl_dir)) {
  8773.                                 mkdir($upl_dir0777true);
  8774.                             }
  8775.                             if (file_exists($upl_dir '' $path)) {
  8776.                                 chmod($upl_dir '' $path0755);
  8777.                                 unlink($upl_dir '' $path);
  8778.                             }
  8779.                             $file $uploadedFile->move($upl_dir$path);
  8780.                             $expireTs $request->request->get('expireTs'0);
  8781.                             $expireNever $request->request->get('expireNever'0);
  8782.                             if ($expireNever == 1) {
  8783.                                 $expireTs 0;
  8784.                             } else {
  8785.                                 if ($expireTs == 0) {
  8786.                                     if ($request->request->get('expiryDays'0) != 0) {
  8787.                                         $currDate = new \DateTime();
  8788.                                         $currDate->modify('+' $request->request->get('expiryDays'0) . ' day');
  8789.                                         $expireTs $currDate->format('U');
  8790.                                     } else if ($request->request->get('expiryDate''') != '') {
  8791.                                         $currDate = new \DateTime($request->request->get('expiryDate'''));
  8792.                                         $currDate->modify('+14 day');
  8793.                                         $expireTs $currDate->format('U');
  8794.                                     } else {
  8795.                                         $currDate = new \DateTime();
  8796.                                         $currDate->modify('+720 day');
  8797.                                         $expireTs $currDate->format('U');
  8798.                                     }
  8799.                                 }
  8800.                             }
  8801.                             $EntityFile = new EntityFile();
  8802.                             $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  8803.                             $EntityFile->setMarker($request->request->get('markerHash''_GEN_'));
  8804.                             $EntityFile->setName($path);
  8805.                             $EntityFile->setExtension($extension);
  8806.                             $EntityFile->setExpireTs($expireTs);
  8807.                             $EntityFile->setSize($size);
  8808.                             $EntityFile->setRelativePath($storePath $path);
  8809.                             $EntityFile->setEntityName($request->request->get('entityName'''));
  8810.                             $EntityFile->setEntityBundle($request->request->get('entityBundle''CompanyGroupBundle'));
  8811.                             $EntityFile->setEntityId($request->request->get('entityId'0));
  8812.                             $EntityFile->setEntityIdField($request->request->get('entityIdField'''));
  8813.                             $EntityFile->setModifyFieldSetter($request->request->get('modifyFieldSetter'''));
  8814.                             $EntityFile->setDocIdForApplicant($request->request->get('docId'0));
  8815.                             $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  8816.                             $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  8817.                             $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  8818.                             $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  8819.                             $em_goc->persist($EntityFile);
  8820.                             $em_goc->flush();
  8821.                             $EntityFileId $EntityFile->getId();
  8822.                         }
  8823.                         if ($path != "")
  8824.                             $file_path_list[] = ($storePath $path);
  8825.                     }
  8826.                 }
  8827.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  8828.             }
  8829.             $baseUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  8830.             //            $img_file = file_get_contents($g_path);
  8831.             //            $r = base64_encode($img_file);
  8832.             //            $url = url('dashboard');
  8833.             return new JsonResponse(array(
  8834.                 "success" => true,
  8835.                 "file_path" => implode(','$file_path_list),
  8836.                 "file_url" => $baseUrl implode(',' $baseUrl$file_path_list),
  8837.                 "fileId" => $EntityFileId,
  8838.                 "refId" => $request->request->get('refId'0),
  8839.                 "rowId" => $request->request->get('rowId'0),
  8840.                 //                "r"=>$r,
  8841.                 //                "debug_data"=>System::encryptSignature($r)
  8842.             ));
  8843.         }
  8844.         return new JsonResponse(array(
  8845.             "success" => false,
  8846.             "file_path" => '',
  8847.             "refId" => $request->request->get('refId'0),
  8848.             "rowId" => $request->request->get('rowId'0),
  8849.         ));
  8850.     }
  8851.     public function BankReconExcelUpload(Request $request)
  8852.     {
  8853.         if ($request->isMethod('POST')) {
  8854.             $post $request->request;
  8855.             $path "";
  8856.             $file_path "";
  8857.             //            var_dump($request->files);
  8858.             //        var_dump($request->getFile());
  8859.             foreach ($request->files as $uploadedFile) {
  8860.                 //            if($uploadedFile->getImage())
  8861.                 //                var_dump($uploadedFile->getFile());
  8862.                 //                var_dump($uploadedFile);
  8863.                 if ($uploadedFile != null) {
  8864.                     $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  8865.                     $path $fileName;
  8866.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  8867.                     if (!file_exists($upl_dir)) {
  8868.                         mkdir($upl_dir0777true);
  8869.                     }
  8870.                     $file $uploadedFile->move($upl_dir$path);
  8871.                 }
  8872.             }
  8873.             //        print_r($file);
  8874.             if ($path != "")
  8875.                 $file_path 'uploads/FileUploads/' $path;
  8876.             $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  8877.             //
  8878.             //            $img_file = file_get_contents($g_path);
  8879.             //            $r=base64_encode($img_file);
  8880.             $row 1;
  8881.             $csv_data = [];
  8882.             if (($handle fopen($g_path"r")) !== FALSE) {
  8883.                 while (($data fgetcsv($handle1000",")) !== FALSE) {
  8884.                     $num count($data);
  8885.                     $csv_data[$row] = $data;
  8886.                     //                    echo "<p> $num fields in line $row: <br /></p>\n";
  8887.                     $row++;
  8888.                     //                    for ($c=0; $c < $num; $c++) {
  8889.                     //                        echo $data[$c] . "<br />\n";
  8890.                     //                    }
  8891.                 }
  8892.                 fclose($handle);
  8893.             }
  8894.             //now getting the relevant checks
  8895.             $check_list = [];
  8896.             foreach ($csv_data as $data_row) {
  8897.                 $get_kids_sql "SELECT acc_check.*,
  8898.                   DATE_FORMAT(acc_transactions.transaction_date, '%b %d,%Y') trans_date,
  8899.                   DATE_FORMAT(acc_check.check_date, '%b %d,%Y') chk_date,
  8900.                   acc_transactions.document_hash FROM acc_check
  8901.                                 JOIN acc_transactions on acc_check.voucher_id= acc_transactions.transaction_id
  8902.                                 WHERE acc_check.check_number like '$data_row[0]' LIMIT 1";
  8903.                 //                $get_kids_sql .=' ORDER BY name ASC';
  8904.                 $stmt $this->getDoctrine()->getConnection()->fetchAllAssociative($get_kids_sql);
  8905.                 
  8906.                 $check_here $stmt;
  8907.                 if ($check_here) {
  8908.                     //                    $transdate = strtotime( $check_here['transaction_date'] );
  8909.                     //                    $checkdate = strtotime( $check_here['check_date'] );
  8910.                     $recondate strtotime($data_row[1]);
  8911.                     $recondatestr date('F d,Y'$recondate);
  8912.                     $new_check_data = array(
  8913.                         'checkId' => $check_here[0]['check_id'],
  8914.                         'checkNumber' => $check_here[0]['check_number'],
  8915.                         'voucherId' => $check_here[0]['voucher_id'],
  8916.                         'voucherNumber' => $check_here[0]['document_hash'],
  8917.                         'checkDate' => $check_here[0]['chk_date'],
  8918.                         'transactionDate' => $check_here[0]['trans_date'],
  8919.                         'reconDate' => $recondatestr,
  8920.                     );
  8921.                     $check_list[] = $new_check_data;
  8922.                 }
  8923.             }
  8924.             return new JsonResponse(array(
  8925.                 "success" => true,
  8926.                 "file_path" => $file_path,
  8927.                 "csv_data" => $csv_data,
  8928.                 "check_data" => $check_list,
  8929.                 //                "debug_data"=>System::encryptSignature($r)
  8930.             ));
  8931.         }
  8932.         return new JsonResponse(array(
  8933.             "success" => false,
  8934.             "file_path" => '',
  8935.         ));
  8936.     }
  8937.     public function AddExpense(Request $request)
  8938.     {
  8939.         $details_ids = [];
  8940.         $em $this->getDoctrine()->getManager();
  8941.         $em_goc $this->getDoctrine()->getManager('company_group');
  8942.         $expenseSubTypes GeneralConstant::$expenseSubTypes;
  8943.         if ($request->isMethod('POST')) {
  8944.             $em $this->getDoctrine()->getManager();
  8945.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  8946.             $dochash $request->request->get('voucherNumber'); //change
  8947.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8948.             $approveRole $request->request->get('approvalRole');
  8949.             $approveHash $request->request->get('approvalHash');
  8950.             if (!DocValidation::isSignatureOk($em$loginId$approveHash)) {
  8951.                 //                $this->addFlash(
  8952.                 //                    'error',
  8953.                 //                    'Sorry Could Not insert Data.'
  8954.                 //                );
  8955.                 return new JsonResponse(array(
  8956.                     "success" => false,
  8957.                     'errorText' => 'Approval Hash Mismatch',
  8958.                     'errorStr' => 'Approval Hash Mismatch'
  8959.                 ));
  8960.             } else {
  8961.                 $new_ei = [];
  8962.                 $expenseDataList = array();
  8963.                 $primaryInvoiceId 0;
  8964.                 $hasChildInvoice 0;
  8965.                 $primaryInvoiceData = [];
  8966.                 $expense_data $request->request->get('expenseData', []);
  8967.                 $exp_distribution_poitemId $request->request->get('exp_distribution_poitemId', []);
  8968.                 $exp_distribution_amount $request->request->get('exp_distribution_amount', []);
  8969.                 $costDistributionData = [];
  8970.                 foreach ($exp_distribution_poitemId as $key => $value) {
  8971.                     $costDistributionData[$value] = array(
  8972.                         'poItemId' => $value,
  8973.                         'amount' => $exp_distribution_amount[$key],
  8974.                     );
  8975.                 }
  8976.                 $expense_type $request->request->get('expense_type'0);
  8977.                 if (is_string($expense_data)) $expense_data json_decode($expense_datatrue);
  8978.                 if (!empty($expense_data)) {
  8979.                     //multiple invoices so add childs and parent
  8980.                     if (count($expense_data) > 1$hasChildInvoice 1;
  8981.                     if ($hasChildInvoice == 1)
  8982.                         $expenseDataList[] = array(
  8983.                             "expenseType" => 4//primary
  8984.                             "expenseSubType" => 0,
  8985.                             "expenseId" => 0,
  8986.                             "ccId" => 0,
  8987.                             "currencyId" => 0,
  8988.                             "currencyMultiply" => 1,
  8989.                             "currencyMultiplyRate" => 1,
  8990.                             "docId" => 0,
  8991.                             "expenseToBePaidTo" => 0,
  8992.                             "expenseFrom" => 0,
  8993.                             "expenseFromNote" => '',
  8994.                             "expenseTo" => 0,
  8995.                             "expenseToNote" => 0,
  8996.                             "expenseAmount" => 0,
  8997.                             "previousAdvanceAmount" => 0,
  8998.                             "checkDate" => '',
  8999.                             "checkNumber" => '',
  9000.                             "checkNarration" => '',
  9001.                             "checkId" => 0,
  9002.                             "description" => '',
  9003.                             "expenseMarkerHash" => '',
  9004.                             "expenseDate" => $expense_data[0]['expenseDate'],
  9005.                             "invoiceBalancing" => 0,
  9006.                             "attachedFile" => [],
  9007.                             "uploadedFile" => '',
  9008.                             'expenseInvocationStrategyOnGrn' => null,
  9009.                             'expenseInvocationTypeOnItems' => null,
  9010.                             "isChildInvoice" => 0,
  9011.                             "costDistributionData" => $costDistributionData,
  9012.                         );
  9013.                     $currTime = new \DateTime();
  9014.                     $currTs $currTime->format('U');
  9015.                     foreach ($expense_data as $key => $expData) {
  9016.                         if (isset($expData['imageBase64'])) {
  9017.                             $imageBase64 $expData['imageBase64'];
  9018.                             $data base64_decode(preg_replace('#^data:image/\w+;base64,#i'''$imageBase64));
  9019.                             $fileName $currTs . (md5(uniqid())) . '.png';
  9020.                             $storePath 'uploads/ExpenseInvoice/';
  9021.                             $path "";
  9022.                             $file_path "";
  9023.                             $session $request->getSession();
  9024.                             MiscActions::RemoveExpiredFiles($em_goc);
  9025.                             $path $fileName;
  9026.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  9027.                             if (!file_exists($upl_dir)) {
  9028.                                 mkdir($upl_dir0777true);
  9029.                             }
  9030.                             if (file_exists($upl_dir '' $path)) {
  9031.                                 chmod($upl_dir '' $path0755);
  9032.                                 unlink($upl_dir '' $path);
  9033.                             }
  9034.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/' $path;
  9035.                             file_put_contents($upl_dir$data);
  9036.                             if ($path != "")
  9037.                                 $file_path $storePath $path;
  9038.                             $expense_data[$key]['uploadedFile'] = $file_path;
  9039.                         }
  9040.                         if (!isset($expData['attachedFile'])) {
  9041.                             $expense_data[$key]['attachedFile'] = [];
  9042.                         }
  9043.                         $expense_data[$key]['isChildInvoice'] = $hasChildInvoice == 0;
  9044.                         $expenseDataList[] = $expense_data[$key];
  9045.                     }
  9046.                 } else {
  9047.                     $expense_type $request->request->get('expense_type'0);
  9048.                     $expenseDataList[] = array(
  9049.                         "expenseType" => $expense_type,
  9050.                         "currencyId" => $request->request->get('expense_currency_id'0),
  9051.                         "currencyMultiply" => $request->request->get('expense_currency_multiply'1),
  9052.                         "currencyMultiplyRate" => $request->request->get('expense_currency_multiply_rate'1),
  9053.                         "expenseSubType" => $request->request->get('expense_sub_type'0),
  9054.                         "expenseId" => $request->request->get('expense_id'0),
  9055.                         "ccId" => $request->request->get('ccId'0),
  9056.                         "docId" => $expense_type == $request->request->get('poId')
  9057.                             : ($expense_type == $request->request->get('soId')
  9058.                                 : ($expense_type == $request->request->get('opportunityId'$request->request->get('leadId'))
  9059.                                     : ($expense_type == $request->request->get('tour_id') : 0))),
  9060.                         "directProjectId" => $request->request->get('directProjectId'0),
  9061.                         "expenseToBePaidTo" => $request->request->get('expense_to_be_paid_to'0),
  9062.                         "expenseFrom" => $request->request->get('expense_from'0),
  9063.                         "checkDate" => $request->request->get('check_date'''),
  9064.                         "checkNumber" => $request->request->get('check_number'''),
  9065.                         "checkNarration" => $request->request->get('check_narration'''),
  9066.                         "checkId" => $request->request->get('check_id'0),
  9067.                         "expenseFromNote" => $request->request->get('expense_from_note'''),
  9068.                         "expenseTo" => $request->request->get('expense_to_' $expense_type0),
  9069.                         "expenseToNote" => $request->request->get('expense_to_note_' $expense_type''),
  9070.                         "expenseAmount" => $request->request->get('expense_amount'''),
  9071.                         "previousAdvanceAmount" => $request->request->get('prev_advance_amount'0),
  9072.                         "description" => $request->request->get('description'''),
  9073.                         "expenseMarkerHash" => $request->request->get('markerHash'''),
  9074.                         "expenseDate" => $request->request->get('expense_date'),
  9075.                         'expenseInvocationStrategyOnGrn' => $request->request->get('expenseInvocationStrategyOnGrn'null),
  9076.                         'expenseInvocationTypeOnItems' => $request->request->get('expenseInvocationTypeOnItems'null),
  9077.                         "invoiceBalancing" => $request->request->has('auto_balance' $expense_type) ? $request->request->get('auto_balance' $expense_type) : 0,
  9078.                         "attachedFile" => $request->files->get('file', []),
  9079.                         "expenseSubCategory" => $request->request->get('expense_sub_category'0),
  9080.                         "expenseSubCategoryOption" => $request->request->get('expense_sub_category_option'0),
  9081.                         "uploadedFile" => $request->request->get('uploadedFile'''),
  9082.                         "expenseDistributionOnProduct" => $request->request->get('exp_check_expense_distribution_on_product'0),
  9083.                         "isChildInvoice" => 0,
  9084.                         "costDistributionData" => $costDistributionData,
  9085.                     );
  9086.                 }
  9087.                 ///SIngle one
  9088.                 ///
  9089.                 //                 System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expenseDataList),'test_mult_exp');
  9090.                 foreach ($expenseDataList as $expData) {
  9091.                     //            Generic::debugMessage($_POST);
  9092.                     $new_ei = [];
  9093.                     $em $this->getDoctrine()->getManager();
  9094.                     //            $to_assign=0;
  9095.                     if ($expData['expenseType'] == 4) {   ////// primary Invoice
  9096.                         $expBillType 4;
  9097.                         $data = array(
  9098.                             'doc_id' => $expData['docId'],
  9099.                             'expense_id' => $expData['expenseId'],
  9100.                             'party_id' => '',
  9101.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9102.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  9103.                             'invoice_amount' => $expData['expenseAmount'],
  9104.                             'description' => $expData['description'],
  9105.                             'expense_to_note' => $expData['expenseToNote'],
  9106.                             'expense_from_note' => $expData['expenseFromNote'],
  9107.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  9108.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  9109.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  9110.                             'date' => $expData['expenseDate'],
  9111.                             'file' => $expData['attachedFile'],
  9112.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9113.                             'expense_from' => $expData['expenseFrom'],
  9114.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9115.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9116.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9117.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9118.                         );
  9119.                         if ($request->request->has('latitude')) {
  9120.                             $data['latitude'] = $request->request->get('latitude');
  9121.                             $data['longitude'] = $request->request->get('longitude');
  9122.                         }
  9123.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  9124.                             $this->getDoctrine()->getManager(),
  9125.                             $data,
  9126.                             '',
  9127.                             $expBillType,
  9128.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9129.                             0,
  9130.                             0,
  9131.                             0,
  9132.                             $expData['ccId'],
  9133.                             $expData['isChildInvoice'],
  9134.                             $primaryInvoiceId,
  9135.                             1
  9136.                         );
  9137.                         //now add Approval info
  9138.                     }
  9139.                     if ($expData['expenseType'] == 0) {
  9140.                         $expBillType 0;
  9141.                         $data = array(
  9142.                             'doc_id' => $expData['docId'],
  9143.                             'expense_id' => $expData['expenseId'],
  9144.                             'party_id' => '',
  9145.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9146.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  9147.                             'invoice_amount' => $expData['expenseAmount'],
  9148.                             'description' => $expData['description'],
  9149.                             'expense_to_note' => $expData['expenseToNote'],
  9150.                             'expense_from_note' => $expData['expenseFromNote'],
  9151.                             'date' => $expData['expenseDate'],
  9152.                             'file' => $expData['attachedFile'],
  9153.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  9154.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  9155.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  9156.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9157.                             'expense_from' => $expData['expenseFrom'],
  9158.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9159.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9160.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9161.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9162.                             'expenseMarkerHash' => isset($expData['markerHash']) ? $expData['markerHash'] : '',
  9163.                             'expenseSubCategory' => isset($expData['expense_sub_category']) ? $expData['expense_sub_category'] : 0,
  9164.                             'expenseSubCategoryOption' => isset($expData['expense_sub_category_option']) ? $expData['expense_sub_category_option'] : 0,
  9165.                         );
  9166.                         if ($request->request->has('latitude')) {
  9167.                             $data['latitude'] = $request->request->get('latitude');
  9168.                             $data['longitude'] = $request->request->get('longitude');
  9169.                         }
  9170.                         if ($expData['expenseMarkerHash'] != '') {
  9171.                             $get_kids_sql "SELECT accounts_head_id FROM acc_accounts_head where marker_hash like '%" $expData['expenseMarkerHash'] . "%'  limit 1";
  9172.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9173.                             
  9174.                             $query_output $stmt;
  9175.                             if (empty($query_output))
  9176.                                 return new JsonResponse(array("success" => false'errorText' => 'Could not find relevant Expense Head'));
  9177.                             else
  9178.                                 $data['expense_id'] = $query_output[0]['accounts_head_id'];
  9179.                         }
  9180.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  9181.                         {
  9182.                             $get_kids_sql "SELECT accounts_head_id, advance_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9183.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9184.                             
  9185.                             $query_output $stmt;
  9186.                             if (empty($query_output)) {
  9187.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9188.                                 return new JsonResponse(array(
  9189.                                     "success" => false,
  9190.                                     'errorText' => 'You are not listed as Employee',
  9191.                                     'errorStr' => 'You are not listed as Employee',
  9192.                                 ));
  9193.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  9194.                                 return new JsonResponse(array(
  9195.                                     "success" => false,
  9196.                                     'errorText' => 'Could not Find Employee Head',
  9197.                                     'errorStr' => 'Could not Find Employee Head',
  9198.                                 ));
  9199.                             else {
  9200.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  9201.                                 $data['description'] = $expData['expenseToNote'];
  9202.                                 $data['personal_expense_flag'] = 1;
  9203.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9204.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9205.                             }
  9206.                         }
  9207.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  9208.                         {
  9209.                             $get_kids_sql "SELECT accounts_head_id,advance_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9210.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9211.                             
  9212.                             $query_output $stmt;
  9213.                             if (empty($query_output)) {
  9214.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9215.                                 return new JsonResponse(array(
  9216.                                     "success" => false,
  9217.                                     'errorText' => 'You are not listed as Employee',
  9218.                                     'errorStr' => 'You are not listed as Employee',
  9219.                                 ));
  9220.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  9221.                                 return new JsonResponse(array(
  9222.                                     "success" => false,
  9223.                                     'errorText' => 'Could not Find Employee Advance Head',
  9224.                                     'errorStr' => 'Could not Find Employee Advance Head',
  9225.                                 ));
  9226.                             else {
  9227.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  9228.                                 $data['description'] = $expData['expenseToNote'];
  9229.                                 $data['personal_expense_flag'] = 1;
  9230.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9231.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9232.                             }
  9233.                         }
  9234.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  9235.                             $this->getDoctrine()->getManager(),
  9236.                             $data,
  9237.                             '',
  9238.                             $expBillType,
  9239.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9240.                             0,
  9241.                             0,
  9242.                             0,
  9243.                             $expData['ccId'],
  9244.                             $expData['isChildInvoice'],
  9245.                             $primaryInvoiceId
  9246.                         );
  9247.                         //now add Approval info
  9248.                     }
  9249.                     //for purchase
  9250.                     if ($expData['expenseType'] == 1) {
  9251.                         $expBillType 1;
  9252.                         $po_data $this->getDoctrine()
  9253.                             ->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')
  9254.                             ->findOneBy(
  9255.                                 array(
  9256.                                     'purchaseOrderId' => $expData['docId']
  9257.                                 )
  9258.                             );
  9259.                         //                $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
  9260.                         $data = array(
  9261.                             'doc_id' => $expData['docId'],
  9262.                             'expense_id' => $expData['expenseId'],
  9263.                             'party_id' => '',
  9264.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9265.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  9266.                             'invoice_amount' => $expData['expenseAmount'],
  9267.                             'description' => $expData['description'],
  9268.                             'expense_to_note' => $expData['expenseToNote'],
  9269.                             'expense_from_note' => $expData['expenseFromNote'],
  9270.                             'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
  9271.                             'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
  9272.                             'date' => $expData['expenseDate'],
  9273.                             'file' => $expData['attachedFile'],
  9274.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  9275.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  9276.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  9277.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9278.                             'expense_from' => $expData['expenseFrom'],
  9279.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9280.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9281.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9282.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9283.                             'costDistributionData' => isset($expData['costDistributionData']) ? $expData['costDistributionData'] : 0,
  9284.                             'expenseDistributionOnProduct' => isset($expData['expenseDistributionOnProduct']) ? $expData['expenseDistributionOnProduct'] : 0,
  9285.                         );
  9286.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  9287.                         {
  9288.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9289.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9290.                             
  9291.                             $query_output $stmt;
  9292.                             if (empty($query_output)) {
  9293.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9294.                                 return new JsonResponse(array(
  9295.                                     "success" => false,
  9296.                                     'errorText' => 'You are not listed as Employee',
  9297.                                     'errorStr' => 'You are not listed as Employee',
  9298.                                 ));
  9299.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  9300.                                 return new JsonResponse(array(
  9301.                                     "success" => false,
  9302.                                     'errorText' => 'Could not Find Employee Head',
  9303.                                     'errorStr' => 'Could not Find Employee Head',
  9304.                                 ));
  9305.                             else {
  9306.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  9307.                                 $data['description'] = $expData['expenseToNote'];
  9308.                                 $data['personal_expense_flag'] = 1;
  9309.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9310.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9311.                             }
  9312.                         }
  9313.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  9314.                         {
  9315.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9316.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9317.                             
  9318.                             $query_output $stmt;
  9319.                             if (empty($query_output)) {
  9320.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9321.                                 return new JsonResponse(array(
  9322.                                     "success" => false,
  9323.                                     'errorText' => 'You are not listed as Employee',
  9324.                                     'errorStr' => 'You are not listed as Employee',
  9325.                                 ));
  9326.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  9327.                                 return new JsonResponse(array(
  9328.                                     "success" => false,
  9329.                                     'errorText' => 'Could not Find Employee Advance Head',
  9330.                                     'errorStr' => 'Could not Find Employee Advance Head',
  9331.                                 ));
  9332.                             else {
  9333.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  9334.                                 $data['description'] = $expData['expenseToNote'];
  9335.                                 $data['personal_expense_flag'] = 1;
  9336.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9337.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9338.                             }
  9339.                         }
  9340.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  9341.                             $this->getDoctrine()->getManager(),
  9342.                             $data,
  9343.                             '',
  9344.                             $expBillType,
  9345.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9346.                             0,
  9347.                             $po_data->getProjectId(),
  9348.                             0,
  9349.                             $expData['ccId'],
  9350.                             $expData['isChildInvoice'],
  9351.                             $primaryInvoiceId
  9352.                         );
  9353.                         //now add Approval info
  9354.                     }
  9355.                     if ($expData['expenseType'] == 2) {
  9356.                         $data $request->request;
  9357.                         //                <option value="1">Against Purchase</option>
  9358.                         //                                                    <option value="2">Against Sales</option>
  9359.                         //                                                    <option value="3">Against Maintenance</option>
  9360.                         $expBillType 2;
  9361.                         $so_data $this->getDoctrine()
  9362.                             ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  9363.                             ->findOneBy(
  9364.                                 array(
  9365.                                     'salesOrderId' => $expData['docId']
  9366.                                 )
  9367.                             );
  9368.                         $supplier_data $this->getDoctrine()
  9369.                             ->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
  9370.                             ->findOneBy(
  9371.                                 array(
  9372.                                     'accountsHeadId' => $expData['expenseToBePaidTo']
  9373.                                 )
  9374.                             );
  9375.                         //                $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
  9376.                         $data = array(
  9377.                             'doc_id' => $expData['docId'],
  9378.                             'expense_id' => $expData['expenseId'],
  9379.                             'party_id' => $supplier_data $supplier_data->getSupplierId() : 0,
  9380.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9381.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  9382.                             'invoice_amount' => $expData['expenseAmount'],
  9383.                             'description' => $expData['description'],
  9384.                             'expense_to_note' => $expData['expenseToNote'],
  9385.                             'expense_from_note' => $expData['expenseFromNote'],
  9386.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  9387.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  9388.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  9389.                             'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
  9390.                             'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
  9391.                             'date' => $expData['expenseDate'],
  9392.                             'file' => $expData['attachedFile'],
  9393.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9394.                             'expense_from' => $expData['expenseFrom'],
  9395.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9396.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9397.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9398.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9399.                         );
  9400.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  9401.                         {
  9402.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9403.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9404.                             
  9405.                             $query_output $stmt;
  9406.                             if (empty($query_output)) {
  9407.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9408.                                 return new JsonResponse(array(
  9409.                                     "success" => false,
  9410.                                     'errorText' => 'You are not listed as Employee',
  9411.                                     'errorStr' => 'You are not listed as Employee',
  9412.                                 ));
  9413.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  9414.                                 return new JsonResponse(array(
  9415.                                     "success" => false,
  9416.                                     'errorText' => 'Could not Find Employee Head',
  9417.                                     'errorStr' => 'Could not Find Employee Head',
  9418.                                 ));
  9419.                             else {
  9420.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  9421.                                 $data['description'] = $expData['expenseToNote'];
  9422.                                 $data['personal_expense_flag'] = 1;
  9423.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9424.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9425.                             }
  9426.                         }
  9427.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  9428.                         {
  9429.                             $get_kids_sql "SELECT advance_head_id, accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9430.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9431.                             
  9432.                             $query_output $stmt;
  9433.                             if (empty($query_output)) {
  9434.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9435.                                 return new JsonResponse(array(
  9436.                                     "success" => false,
  9437.                                     'errorText' => 'You are not listed as Employee',
  9438.                                     'errorStr' => 'You are not listed as Employee',
  9439.                                 ));
  9440.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  9441.                                 return new JsonResponse(array(
  9442.                                     "success" => false,
  9443.                                     'errorText' => 'Could not Find Employee Advance Head',
  9444.                                     'errorStr' => 'Could not Find Employee Advance Head',
  9445.                                 ));
  9446.                             else {
  9447.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  9448.                                 $data['description'] = $expData['expenseToNote'];
  9449.                                 $data['personal_expense_flag'] = 1;
  9450.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9451.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9452.                             }
  9453.                         }
  9454.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  9455.                             $this->getDoctrine()->getManager(),
  9456.                             $data,
  9457.                             '',
  9458.                             $expBillType,
  9459.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9460.                             0,
  9461.                             ((int) ($expData['directProjectId'] ?? 0) > ? (int) $expData['directProjectId'] : ($so_data $so_data->getProjectId() : 0)),
  9462.                             0,
  9463.                             $expData['ccId'],
  9464.                             $expData['isChildInvoice'],
  9465.                             $primaryInvoiceId
  9466.                         );
  9467.                     }
  9468.                     if ($expData['expenseType'] == 3) {
  9469.                         $data $request->request;
  9470.                         $expBillType 3;
  9471.                         $so_data $this->getDoctrine()
  9472.                             ->getRepository('ApplicationBundle\\Entity\\Opportunity')
  9473.                             ->findOneBy(
  9474.                                 array(
  9475.                                     'opportunityId' => $expData['docId']
  9476.                                 )
  9477.                             );
  9478.                         $supplier_data $this->getDoctrine()
  9479.                             ->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
  9480.                             ->findOneBy(
  9481.                                 array(
  9482.                                     'accountsHeadId' => $expData['expenseToBePaidTo']
  9483.                                 )
  9484.                             );
  9485.                         //                $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
  9486.                         $data = array(
  9487.                             'doc_id' => $expData['docId'],
  9488.                             'expense_id' => $expData['expenseId'],
  9489.                             'party_id' => $supplier_data $supplier_data->getSupplierId() : 0,
  9490.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9491.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  9492.                             'invoice_amount' => $expData['expenseAmount'],
  9493.                             'description' => $expData['description'],
  9494.                             'expense_to_note' => $expData['expenseToNote'],
  9495.                             'expense_from_note' => $expData['expenseFromNote'],
  9496.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  9497.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  9498.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  9499.                             'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
  9500.                             'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
  9501.                             'date' => $expData['expenseDate'],
  9502.                             'file' => $expData['attachedFile'],
  9503.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9504.                             'expense_from' => $expData['expenseFrom'],
  9505.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9506.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9507.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9508.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9509.                         );
  9510.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  9511.                         {
  9512.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9513.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9514.                             
  9515.                             $query_output $stmt;
  9516.                             if (empty($query_output)) {
  9517.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9518.                                 return new JsonResponse(array(
  9519.                                     "success" => false,
  9520.                                     'errorText' => 'You are not listed as Employee',
  9521.                                     'errorStr' => 'You are not listed as Employee',
  9522.                                 ));
  9523.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  9524.                                 return new JsonResponse(array(
  9525.                                     "success" => false,
  9526.                                     'errorText' => 'Could not Find Employee Head',
  9527.                                     'errorStr' => 'Could not Find Employee Head',
  9528.                                 ));
  9529.                             else {
  9530.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  9531.                                 $data['description'] = $expData['expenseToNote'];
  9532.                                 $data['personal_expense_flag'] = 1;
  9533.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9534.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9535.                             }
  9536.                         }
  9537.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  9538.                         {
  9539.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9540.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9541.                             
  9542.                             $query_output $stmt;
  9543.                             if (empty($query_output)) {
  9544.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9545.                                 return new JsonResponse(array(
  9546.                                     "success" => false,
  9547.                                     'errorText' => 'You are not listed as Employee',
  9548.                                     'errorStr' => 'You are not listed as Employee',
  9549.                                 ));
  9550.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  9551.                                 return new JsonResponse(array(
  9552.                                     "success" => false,
  9553.                                     'errorText' => 'Could not Find Employee Advance Head',
  9554.                                     'errorStr' => 'Could not Find Employee Advance Head',
  9555.                                 ));
  9556.                             else {
  9557.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  9558.                                 $data['description'] = $expData['expenseToNote'];
  9559.                                 $data['personal_expense_flag'] = 1;
  9560.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9561.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9562.                             }
  9563.                         }
  9564.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  9565.                             $this->getDoctrine()->getManager(),
  9566.                             $data,
  9567.                             '',
  9568.                             $expBillType,
  9569.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9570.                             0,
  9571.                             ((int) ($expData['directProjectId'] ?? 0) > ? (int) $expData['directProjectId'] : ($so_data $so_data->getProjectId() : 0)),
  9572.                             0,
  9573.                             $expData['ccId'],
  9574.                             $expData['isChildInvoice'],
  9575.                             $primaryInvoiceId
  9576.                         );
  9577.                     }
  9578.                     if ($expData['expenseType'] == 5) {
  9579.                         $expBillType 0;
  9580.                         // Fetch the Tour data
  9581.                         $tour_data $this->getDoctrine()
  9582.                             ->getRepository('ApplicationBundle\\Entity\\PlanVisit')
  9583.                             ->findOneBy([
  9584.                                 'id' => $expData['docId']
  9585.                             ]);
  9586.                         $supplier_data $this->getDoctrine()
  9587.                             ->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
  9588.                             ->findOneBy([
  9589.                                 'accountsHeadId' => $expData['expenseToBePaidTo']
  9590.                             ]);
  9591.                         $data = [
  9592.                             'doc_id' => $expData['docId'],
  9593.                             'expense_id' => $expData['expenseId'],
  9594.                             'party_id' => $supplier_data $supplier_data->getSupplierId() : '',
  9595.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9596.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  9597.                             'invoice_amount' => $expData['expenseAmount'],
  9598.                             'description' => $expData['description'],
  9599.                             'expense_to_note' => $expData['expenseToNote'],
  9600.                             'expense_from_note' => $expData['expenseFromNote'],
  9601.                             'date' => $expData['expenseDate'],
  9602.                             'file' => $expData['attachedFile'],
  9603.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9604.                             'expense_from' => $expData['expenseFrom'],
  9605.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9606.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9607.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9608.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9609.                             'expenseMarkerHash' => isset($expData['markerHash']) ? $expData['markerHash'] : '',
  9610.                             'expenseSubCategory' => isset($expData['expense_sub_category']) ? $expData['expense_sub_category'] : 0,
  9611.                             'expenseSubCategoryOption' => isset($expData['expense_sub_category_option']) ? $expData['expense_sub_category_option'] : 0,
  9612.                             'tour_title' => $tour_data $tour_data->getTitle() : '',
  9613.                             'tour_document_hash' => $tour_data $tour_data->getDocumentHash() : '',
  9614.                             'tour_id' => $tour_data $tour_data->getId() : ''
  9615.                         ];
  9616.                         if ($request->request->has('latitude')) {
  9617.                             $data['latitude'] = $request->request->get('latitude');
  9618.                             $data['longitude'] = $request->request->get('longitude');
  9619.                         }
  9620.                         // Handle personal expense if own head
  9621.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1) {
  9622.                             $get_kids_sql "SELECT accounts_head_id, advance_head_id, employee_id, user_id 
  9623.                          FROM employee 
  9624.                          WHERE user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  
  9625.                          LIMIT 1";
  9626.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9627.                             
  9628.                             $query_output $stmt;
  9629.                             if (empty($query_output)) {
  9630.                                 return new JsonResponse([
  9631.                                     "success" => false,
  9632.                                     'errorText' => 'You are not listed as Employee',
  9633.                                     'errorStr' => 'You are not listed as Employee',
  9634.                                 ]);
  9635.                             }
  9636.                             $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  9637.                             $data['description'] = $expData['expenseToNote'];
  9638.                             $data['personal_expense_flag'] = 1;
  9639.                             $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9640.                             $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9641.                         }
  9642.                         // Handle own advance
  9643.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2) {
  9644.                             $get_kids_sql "SELECT accounts_head_id, advance_head_id, employee_id, user_id 
  9645.                          FROM employee 
  9646.                          WHERE user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  
  9647.                          LIMIT 1";
  9648.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9649.                             
  9650.                             $query_output $stmt;
  9651.                             if (empty($query_output)) {
  9652.                                 return new JsonResponse([
  9653.                                     "success" => false,
  9654.                                     'errorText' => 'You are not listed as Employee',
  9655.                                     'errorStr' => 'You are not listed as Employee',
  9656.                                 ]);
  9657.                             }
  9658.                             $data['party_head_id'] = $query_output[0]['advance_head_id'];
  9659.                             $data['description'] = $expData['expenseToNote'];
  9660.                             $data['personal_expense_flag'] = 1;
  9661.                             $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9662.                             $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9663.                         }
  9664.                         // Create Expense Invoice
  9665.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  9666.                             $this->getDoctrine()->getManager(),
  9667.                             $data,
  9668.                             '',
  9669.                             $expBillType,
  9670.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9671.                             0,
  9672.                             0,
  9673.                             0,
  9674.                             $expData['ccId'],
  9675.                             $expData['isChildInvoice'],
  9676.                             $primaryInvoiceId
  9677.                         );
  9678.                     }
  9679.                     if ($expData['isChildInvoice'] != && isset($new_ei['ei_id'])) {
  9680.                         $primaryInvoiceId $new_ei['ei_id'];
  9681.                     }
  9682.                 }
  9683.                 //single end
  9684.                 if ($primaryInvoiceId != 0) {
  9685.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  9686.                     $approveRole $request->request->get('approvalRole');
  9687.                     $options = array(
  9688.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  9689.                         'notification_server' => $this->container->getParameter('notification_server'),
  9690.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  9691.                         'url' => $this->generateUrl(
  9692.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice']]['entity_view_route_path_name']
  9693.                         )
  9694.                     );
  9695.                     System::setApprovalInfo(
  9696.                         $this->getDoctrine()->getManager(),
  9697.                         $options,
  9698.                         array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  9699.                         $primaryInvoiceId,
  9700.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  9701.                     );
  9702.                     System::createEditSignatureHash(
  9703.                         $this->getDoctrine()->getManager(),
  9704.                         array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  9705.                         $primaryInvoiceId,
  9706.                         $loginId,
  9707.                         $approveRole,
  9708.                         $request->request->get('approvalHash')
  9709.                     );
  9710.                 }
  9711.                 return new JsonResponse(array(
  9712.                     "success" => true,
  9713.                     'docId' => isset($new_ei['ei_id']) ? $new_ei['ei_id'] : '',
  9714.                     'docHash' => isset($new_ei['ei_doc_hash']) ? $new_ei['ei_doc_hash'] : '',
  9715.                 ));
  9716.             }
  9717.         }
  9718.         return new JsonResponse(array(
  9719.             "success" => true,
  9720.             'docId' => isset($new_ei['ei_id']) ? $new_ei['ei_id'] : '',
  9721.             'docHash' => isset($new_ei['ei_doc_hash']) ? $new_ei['ei_doc_hash'] : '',
  9722.             'expenseSubTypes' => $expenseSubTypes
  9723.         ));
  9724.         //
  9725.         //        return $this->render('@Accounts/pages/input_forms/payment_voucher.html.twig',
  9726.         //            array(
  9727.         //                'page_title'=>'Create Payment Voucher',
  9728.         //                'test'=>$details_ids,
  9729.         //                'supplier_list'=>Accounts::SupplierListForPv($this->getDoctrine()->getManager()),
  9730.         //                'supplier_list_by_ac_head'=>Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
  9731.         //                'supplier_list_by_advance_head'=>Accounts::SupplierListByAdvanceHead($this->getDoctrine()->getManager())
  9732.         //            )
  9733.         //        );
  9734.     }
  9735.     public function AddExpenseForApp(Request $request)
  9736.     {
  9737.         $details_ids = [];
  9738.         $em $this->getDoctrine()->getManager();
  9739.         $em_goc $this->getDoctrine()->getManager('company_group');
  9740.         $expenseSubTypes GeneralConstant::$expenseSubTypes;
  9741.         if ($request->isMethod('POST')) {
  9742.             $em $this->getDoctrine()->getManager();
  9743.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  9744.             $dochash $request->request->get('voucherNumber'); //change
  9745.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  9746.             $approveRole $request->request->get('approvalRole'1);
  9747.             $approveHash $request->request->get('approvalHash');
  9748.             if (!DocValidation::isSignatureOk($em$loginId$approveHash)) {
  9749.                 //                $this->addFlash(
  9750.                 //                    'error',
  9751.                 //                    'Sorry Could Not insert Data.'
  9752.                 //                );
  9753.                 return new JsonResponse(array(
  9754.                     "success" => false,
  9755.                     'errorText' => 'Approval Hash Mismatch',
  9756.                     'errorStr' => 'Approval Hash Mismatch'
  9757.                 ));
  9758.             } else {
  9759.                 $new_ei = [];
  9760.                 $expenseDataList = array();
  9761.                 $primaryInvoiceId 0;
  9762.                 $hasChildInvoice 0;
  9763.                 $primaryInvoiceData = [];
  9764.                 $expense_data $request->request->get('expenseData', []);
  9765.                 if (is_string($expense_data)) $expense_data json_decode($expense_datatrue);
  9766.                 if (!empty($expense_data)) {
  9767.                     //multiple invoices so add childs and parent
  9768.                     if (count($expense_data) > 1$hasChildInvoice 1;
  9769.                     if ($hasChildInvoice == 1)
  9770.                         $expenseDataList[] = array(
  9771.                             "expenseType" => 4//primary
  9772.                             "expenseSubType" => 0,
  9773.                             "expenseId" => 0,
  9774.                             "ccId" => 0,
  9775.                             "currencyId" => 0,
  9776.                             "currencyMultiply" => 1,
  9777.                             "currencyMultiplyRate" => 1,
  9778.                             "docId" => 0,
  9779.                             "expenseToBePaidTo" => 0,
  9780.                             "expenseFrom" => 0,
  9781.                             "expenseFromNote" => '',
  9782.                             "expenseTo" => 0,
  9783.                             "expenseToNote" => 0,
  9784.                             "expenseAmount" => 0,
  9785.                             "previousAdvanceAmount" => 0,
  9786.                             "checkDate" => '',
  9787.                             "checkNumber" => '',
  9788.                             "checkNarration" => '',
  9789.                             "checkId" => 0,
  9790.                             "description" => '',
  9791.                             "expenseMarkerHash" => '',
  9792.                             "expenseDate" => $expense_data[0]['expenseDate'],
  9793.                             "invoiceBalancing" => 0,
  9794.                             "attachedFile" => [],
  9795.                             "uploadedFile" => '',
  9796.                             'expenseInvocationStrategyOnGrn' => null,
  9797.                             'expenseInvocationTypeOnItems' => null,
  9798.                             "isChildInvoice" => 0,
  9799.                         );
  9800.                     $currTime = new \DateTime();
  9801.                     $currTs $currTime->format('U');
  9802.                     foreach ($expense_data as $key => $expData) {
  9803.                         if (isset($expData['imageBase64'])) {
  9804.                             $imageBase64 $expData['imageBase64'];
  9805.                             $data base64_decode(preg_replace('#^data:image/\w+;base64,#i'''$imageBase64));
  9806.                             $fileName $currTs . (md5(uniqid())) . '.png';
  9807.                             $storePath 'uploads/ExpenseInvoice/';
  9808.                             $path "";
  9809.                             $file_path "";
  9810.                             $session $request->getSession();
  9811.                             MiscActions::RemoveExpiredFiles($em_goc);
  9812.                             $path $fileName;
  9813.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  9814.                             if (!file_exists($upl_dir)) {
  9815.                                 mkdir($upl_dir0777true);
  9816.                             }
  9817.                             if (file_exists($upl_dir '' $path)) {
  9818.                                 chmod($upl_dir '' $path0755);
  9819.                                 unlink($upl_dir '' $path);
  9820.                             }
  9821.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/' $path;
  9822.                             file_put_contents($upl_dir$data);
  9823.                             if ($path != "")
  9824.                                 $file_path $storePath $path;
  9825.                             $expense_data[$key]['uploadedFile'] = $file_path;
  9826.                         }
  9827.                         if (!isset($expData['attachedFile'])) {
  9828.                             $expense_data[$key]['attachedFile'] = [];
  9829.                         }
  9830.                         $expense_data[$key]['isChildInvoice'] = $hasChildInvoice == 0;
  9831.                         $expenseDataList[] = $expense_data[$key];
  9832.                     }
  9833.                 } else {
  9834.                     $expense_type $request->request->get('expense_type'0);
  9835.                     $expenseDataList[] = array(
  9836.                         "expenseType" => $expense_type,
  9837.                         "currencyId" => $request->request->get('expense_currency_id'0),
  9838.                         "currencyMultiply" => $request->request->get('expense_currency_multiply'1),
  9839.                         "currencyMultiplyRate" => $request->request->get('expense_currency_multiply_rate'1),
  9840.                         "expenseSubType" => $request->request->get('expense_sub_type'0),
  9841.                         "expenseId" => $request->request->get('expense_id'0),
  9842.                         "ccId" => $request->request->get('ccId'0),
  9843.                         "docId" => $expense_type == $request->request->get('poId') : ($expense_type == $request->request->get('soId') : 0),
  9844.                         "expenseToBePaidTo" => $request->request->get('expense_to_be_paid_to'0),
  9845.                         "expenseFrom" => $request->request->get('expense_from'0),
  9846.                         "checkDate" => $request->request->get('check_date'''),
  9847.                         "checkNumber" => $request->request->get('check_number'''),
  9848.                         "checkNarration" => $request->request->get('check_narration'''),
  9849.                         "checkId" => $request->request->get('check_id'0),
  9850.                         "expenseFromNote" => $request->request->get('expense_from_note'''),
  9851.                         "expenseTo" => $request->request->get('expense_to_' $expense_type0),
  9852.                         "expenseToNote" => $request->request->get('expense_to_note_' $expense_type''),
  9853.                         "expenseAmount" => $request->request->get('expense_amount'''),
  9854.                         "previousAdvanceAmount" => $request->request->get('prev_advance_amount'0),
  9855.                         "description" => $request->request->get('description'''),
  9856.                         "expenseMarkerHash" => $request->request->get('markerHash'''),
  9857.                         "expenseDate" => $request->request->get('expense_date'),
  9858.                         'expenseInvocationStrategyOnGrn' => $request->request->get('expenseInvocationStrategyOnGrn'null),
  9859.                         'expenseInvocationTypeOnItems' => $request->request->get('expenseInvocationTypeOnItems'null),
  9860.                         "invoiceBalancing" => $request->request->has('auto_balance' $expense_type) ? $request->request->get('auto_balance' $expense_type) : 0,
  9861.                         "attachedFile" => $request->files->get('file', []),
  9862.                         "uploadedFile" => $request->request->get('uploadedFile'''),
  9863.                         "expenseSubCategory" => $request->request->get('expense_sub_category'0),
  9864.                         "expenseSubCategoryOption" => $request->request->get('expense_sub_category_option'0),
  9865.                         "isChildInvoice" => 0,
  9866.                     );
  9867.                 }
  9868.                 ///SIngle one
  9869.                 ///
  9870.                 //                 System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expenseDataList),'test_mult_exp');
  9871.                 foreach ($expenseDataList as $expData) {
  9872.                     //            Generic::debugMessage($_POST);
  9873.                     $new_ei = [];
  9874.                     $em $this->getDoctrine()->getManager();
  9875.                     //            $to_assign=0;
  9876.                     if ($expData['expenseType'] == 4) {   ////// primary Invoice
  9877.                         $expBillType 4;
  9878.                         $data = array(
  9879.                             'doc_id' => $expData['docId'],
  9880.                             'expense_id' => $expData['expenseId'],
  9881.                             'party_id' => '',
  9882.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9883.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  9884.                             'invoice_amount' => $expData['expenseAmount'],
  9885.                             'description' => $expData['description'],
  9886.                             'expense_to_note' => $expData['expenseToNote'],
  9887.                             'expense_from_note' => $expData['expenseFromNote'],
  9888.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  9889.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  9890.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  9891.                             'date' => $expData['expenseDate'],
  9892.                             'file' => $expData['attachedFile'],
  9893.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9894.                             'expense_from' => $expData['expenseFrom'],
  9895.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9896.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9897.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9898.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9899.                         );
  9900.                         if ($request->request->has('latitude')) {
  9901.                             $data['latitude'] = $request->request->get('latitude');
  9902.                             $data['longitude'] = $request->request->get('longitude');
  9903.                         }
  9904.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  9905.                             $this->getDoctrine()->getManager(),
  9906.                             $data,
  9907.                             '',
  9908.                             $expBillType,
  9909.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9910.                             0,
  9911.                             0,
  9912.                             0,
  9913.                             $expData['ccId'],
  9914.                             $expData['isChildInvoice'],
  9915.                             $primaryInvoiceId,
  9916.                             1
  9917.                         );
  9918.                         //now add Approval info
  9919.                     }
  9920.                     if ($expData['expenseType'] == 0) {
  9921.                         $expBillType 0;
  9922.                         $data = array(
  9923.                             'doc_id' => $expData['docId'],
  9924.                             'expense_id' => $expData['expenseId'],
  9925.                             'party_id' => '',
  9926.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9927.                             'advance_amount_to_assign' => isset($expData['previousAdvanceAmount']) ? $expData['previousAdvanceAmount'] : '',
  9928.                             'invoice_amount' => $expData['expenseAmount'],
  9929.                             'description' => $expData['description'],
  9930.                             'expense_to_note' => isset($expData['expenseToNote']) ? $expData['expenseToNote'] : '',
  9931.                             'expense_from_note' => isset($expData['expenseFromNote']) ? $expData['expenseFromNote'] : '',
  9932.                             'date' => $expData['expenseDate'],
  9933.                             'file' => $expData['attachedFile'],
  9934.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  9935.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  9936.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  9937.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9938.                             'expense_from' => isset($expData['expenseFrom']) ? $expData['expenseFrom'] : '',
  9939.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9940.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9941.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9942.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9943.                             'markerHash' => isset($expData['expenseMarkerHash']) ? $expData['expenseMarkerHash'] : 0,
  9944.                             'expenseSubCategory' => isset($expData['expenseSubCategory']) ? $expData['expenseSubCategory'] : 0,
  9945.                             'expenseSubCategoryOption' => isset($expData['expenseSubCategoryOption']) ? $expData['expenseSubCategoryOption'] : 0,
  9946.                         );
  9947.                         if ($request->request->has('latitude')) {
  9948.                             $data['latitude'] = $request->request->get('latitude');
  9949.                             $data['longitude'] = $request->request->get('longitude');
  9950.                         }
  9951.                         if ($expData['expenseMarkerHash'] != '') {
  9952.                             $get_kids_sql "SELECT accounts_head_id FROM acc_accounts_head where marker_hash like '%" $expData['expenseMarkerHash'] . "%'  limit 1";
  9953.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9954.                             
  9955.                             $query_output $stmt;
  9956.                             if (empty($query_output))
  9957.                                 return new JsonResponse(array("success" => false'errorText' => 'Could not find relevant Expense Head'));
  9958.                             else
  9959.                                 $data['expense_id'] = $query_output[0]['accounts_head_id'];
  9960.                         }
  9961.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  9962.                         {
  9963.                             $get_kids_sql "SELECT accounts_head_id, advance_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9964.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9965.                             
  9966.                             $query_output $stmt;
  9967.                             if (empty($query_output)) {
  9968.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9969.                                 return new JsonResponse(array(
  9970.                                     "success" => false,
  9971.                                     'errorText' => 'You are not listed as Employee',
  9972.                                     'errorStr' => 'You are not listed as Employee',
  9973.                                 ));
  9974.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  9975.                                 return new JsonResponse(array(
  9976.                                     "success" => false,
  9977.                                     'errorText' => 'Could not Find Employee Head',
  9978.                                     'errorStr' => 'Could not Find Employee Head',
  9979.                                 ));
  9980.                             else {
  9981.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  9982.                                 //                                $data['description'] = $expData['expenseToNote'];
  9983.                                 $data['description'] = $expData['description'];
  9984.                                 $data['personal_expense_flag'] = 1;
  9985.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9986.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9987.                             }
  9988.                         }
  9989.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  9990.                         {
  9991.                             $get_kids_sql "SELECT accounts_head_id,advance_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9992.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9993.                             
  9994.                             $query_output $stmt;
  9995.                             if (empty($query_output)) {
  9996.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9997.                                 return new JsonResponse(array(
  9998.                                     "success" => false,
  9999.                                     'errorText' => 'You are not listed as Employee',
  10000.                                     'errorStr' => 'You are not listed as Employee',
  10001.                                 ));
  10002.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  10003.                                 return new JsonResponse(array(
  10004.                                     "success" => false,
  10005.                                     'errorText' => 'Could not Find Employee Advance Head',
  10006.                                     'errorStr' => 'Could not Find Employee Advance Head',
  10007.                                 ));
  10008.                             else {
  10009.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  10010.                                 $data['description'] = $expData['expenseToNote'];
  10011.                                 $data['personal_expense_flag'] = 1;
  10012.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  10013.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  10014.                             }
  10015.                         }
  10016.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  10017.                             $this->getDoctrine()->getManager(),
  10018.                             $data,
  10019.                             '',
  10020.                             $expBillType,
  10021.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10022.                             0,
  10023.                             0,
  10024.                             0,
  10025.                             $expData['ccId'],
  10026.                             $expData['isChildInvoice'],
  10027.                             $primaryInvoiceId
  10028.                         );
  10029.                         //now add Approval info
  10030.                     }
  10031.                     //for purchase
  10032.                     if ($expData['expenseType'] == 1) {
  10033.                         $expBillType 1;
  10034.                         $po_data $this->getDoctrine()
  10035.                             ->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')
  10036.                             ->findOneBy(
  10037.                                 array(
  10038.                                     'purchaseOrderId' => $expData['docId']
  10039.                                 )
  10040.                             );
  10041.                         //                $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
  10042.                         $data = array(
  10043.                             'doc_id' => $expData['docId'],
  10044.                             'expense_id' => $expData['expenseId'],
  10045.                             'party_id' => '',
  10046.                             'party_head_id' => $expData['expenseToBePaidTo'],
  10047.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  10048.                             'invoice_amount' => $expData['expenseAmount'],
  10049.                             'description' => $expData['description'],
  10050.                             'expense_to_note' => $expData['expenseToNote'],
  10051.                             'expense_from_note' => $expData['expenseFromNote'],
  10052.                             'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
  10053.                             'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
  10054.                             'date' => $expData['expenseDate'],
  10055.                             'file' => $expData['attachedFile'],
  10056.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  10057.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  10058.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  10059.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  10060.                             'expense_from' => $expData['expenseFrom'],
  10061.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  10062.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  10063.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  10064.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  10065.                         );
  10066.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  10067.                         {
  10068.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  10069.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  10070.                             
  10071.                             $query_output $stmt;
  10072.                             if (empty($query_output)) {
  10073.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  10074.                                 return new JsonResponse(array(
  10075.                                     "success" => false,
  10076.                                     'errorText' => 'You are not listed as Employee',
  10077.                                     'errorStr' => 'You are not listed as Employee',
  10078.                                 ));
  10079.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  10080.                                 return new JsonResponse(array(
  10081.                                     "success" => false,
  10082.                                     'errorText' => 'Could not Find Employee Head',
  10083.                                     'errorStr' => 'Could not Find Employee Head',
  10084.                                 ));
  10085.                             else {
  10086.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  10087.                                 $data['description'] = $expData['expenseToNote'];
  10088.                                 $data['personal_expense_flag'] = 1;
  10089.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  10090.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  10091.                             }
  10092.                         }
  10093.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  10094.                         {
  10095.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  10096.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  10097.                             
  10098.                             $query_output $stmt;
  10099.                             if (empty($query_output)) {
  10100.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  10101.                                 return new JsonResponse(array(
  10102.                                     "success" => false,
  10103.                                     'errorText' => 'You are not listed as Employee',
  10104.                                     'errorStr' => 'You are not listed as Employee',
  10105.                                 ));
  10106.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  10107.                                 return new JsonResponse(array(
  10108.                                     "success" => false,
  10109.                                     'errorText' => 'Could not Find Employee Advance Head',
  10110.                                     'errorStr' => 'Could not Find Employee Advance Head',
  10111.                                 ));
  10112.                             else {
  10113.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  10114.                                 $data['description'] = $expData['expenseToNote'];
  10115.                                 $data['personal_expense_flag'] = 1;
  10116.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  10117.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  10118.                             }
  10119.                         }
  10120.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  10121.                             $this->getDoctrine()->getManager(),
  10122.                             $data,
  10123.                             '',
  10124.                             $expBillType,
  10125.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10126.                             0,
  10127.                             $po_data->getProjectId(),
  10128.                             0,
  10129.                             $expData['ccId'],
  10130.                             $expData['isChildInvoice'],
  10131.                             $primaryInvoiceId
  10132.                         );
  10133.                         //now add Approval info
  10134.                     }
  10135.                     if ($expData['expenseType'] == 2) {
  10136.                         $data $request->request;
  10137.                         //                <option value="1">Against Purchase</option>
  10138.                         //                                                    <option value="2">Against Sales</option>
  10139.                         //                                                    <option value="3">Against Maintenance</option>
  10140.                         $expBillType 2;
  10141.                         $so_data $this->getDoctrine()
  10142.                             ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  10143.                             ->findOneBy(
  10144.                                 array(
  10145.                                     'salesOrderId' => $expData['docId']
  10146.                                 )
  10147.                             );
  10148.                         $supplier_data $this->getDoctrine()
  10149.                             ->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
  10150.                             ->findOneBy(
  10151.                                 array(
  10152.                                     'accountsHeadId' => $expData['expenseToBePaidTo']
  10153.                                 )
  10154.                             );
  10155.                         //                $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
  10156.                         $data = array(
  10157.                             'doc_id' => $expData['docId'],
  10158.                             'expense_id' => $expData['expenseId'],
  10159.                             'party_id' => $supplier_data $supplier_data->getSupplierId() : 0,
  10160.                             'party_head_id' => $expData['expenseToBePaidTo'],
  10161.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  10162.                             'invoice_amount' => $expData['expenseAmount'],
  10163.                             'description' => $expData['description'],
  10164.                             'expense_to_note' => $expData['expenseToNote'],
  10165.                             'expense_from_note' => $expData['expenseFromNote'],
  10166.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  10167.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  10168.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  10169.                             'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
  10170.                             'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
  10171.                             'date' => $expData['expenseDate'],
  10172.                             'file' => $expData['attachedFile'],
  10173.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  10174.                             'expense_from' => $expData['expenseFrom'],
  10175.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  10176.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  10177.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  10178.                             'markerHash' => isset($expData['expenseMarkerHash']) ? $expData['expenseMarkerHash'] : 0,
  10179.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  10180.                         );
  10181.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  10182.                         {
  10183.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  10184.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  10185.                             
  10186.                             $query_output $stmt;
  10187.                             if (empty($query_output)) {
  10188.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  10189.                                 return new JsonResponse(array(
  10190.                                     "success" => false,
  10191.                                     'errorText' => 'You are not listed as Employee',
  10192.                                     'errorStr' => 'You are not listed as Employee',
  10193.                                 ));
  10194.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  10195.                                 return new JsonResponse(array(
  10196.                                     "success" => false,
  10197.                                     'errorText' => 'Could not Find Employee Head',
  10198.                                     'errorStr' => 'Could not Find Employee Head',
  10199.                                 ));
  10200.                             else {
  10201.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  10202.                                 $data['description'] = $expData['expenseToNote'];
  10203.                                 $data['personal_expense_flag'] = 1;
  10204.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  10205.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  10206.                             }
  10207.                         }
  10208.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  10209.                         {
  10210.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  10211.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  10212.                             
  10213.                             $query_output $stmt;
  10214.                             if (empty($query_output)) {
  10215.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  10216.                                 return new JsonResponse(array(
  10217.                                     "success" => false,
  10218.                                     'errorText' => 'You are not listed as Employee',
  10219.                                     'errorStr' => 'You are not listed as Employee',
  10220.                                 ));
  10221.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  10222.                                 return new JsonResponse(array(
  10223.                                     "success" => false,
  10224.                                     'errorText' => 'Could not Find Employee Advance Head',
  10225.                                     'errorStr' => 'Could not Find Employee Advance Head',
  10226.                                 ));
  10227.                             else {
  10228.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  10229.                                 $data['description'] = $expData['expenseToNote'];
  10230.                                 $data['personal_expense_flag'] = 1;
  10231.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  10232.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  10233.                             }
  10234.                         }
  10235.                         if ($expData['expenseMarkerHash'] != '') {
  10236.                             $get_kids_sql "SELECT accounts_head_id FROM acc_accounts_head where marker_hash like '%" $expData['expenseMarkerHash'] . "%'  limit 1";
  10237.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  10238.                             
  10239.                             $query_output $stmt;
  10240.                             if (empty($query_output))
  10241.                                 return new JsonResponse(array("success" => false'errorText' => 'Could not find relevant Expense Head'));
  10242.                             else
  10243.                                 $data['expense_id'] = $query_output[0]['accounts_head_id'];
  10244.                         }
  10245.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  10246.                             $this->getDoctrine()->getManager(),
  10247.                             $data,
  10248.                             '',
  10249.                             $expBillType,
  10250.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10251.                             0,
  10252.                             ((int) ($expData['directProjectId'] ?? 0) > ? (int) $expData['directProjectId'] : ($so_data $so_data->getProjectId() : 0)),
  10253.                             0,
  10254.                             $expData['ccId'],
  10255.                             $expData['isChildInvoice'],
  10256.                             $primaryInvoiceId
  10257.                         );
  10258.                     }
  10259.                     if ($expData['isChildInvoice'] != && isset($new_ei['ei_id'])) {
  10260.                         $primaryInvoiceId $new_ei['ei_id'];
  10261.                     }
  10262.                 }
  10263.                 //single end
  10264.                 if ($primaryInvoiceId != 0) {
  10265.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10266.                     $approveRole $request->request->get('approvalRole');
  10267.                     $options = array(
  10268.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  10269.                         'notification_server' => $this->container->getParameter('notification_server'),
  10270.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  10271.                         'url' => $this->generateUrl(
  10272.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice']]['entity_view_route_path_name']
  10273.                         )
  10274.                     );
  10275.                     System::setApprovalInfo(
  10276.                         $this->getDoctrine()->getManager(),
  10277.                         $options,
  10278.                         array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  10279.                         $primaryInvoiceId,
  10280.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  10281.                     );
  10282.                     System::createEditSignatureHash(
  10283.                         $this->getDoctrine()->getManager(),
  10284.                         array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  10285.                         $primaryInvoiceId,
  10286.                         $loginId,
  10287.                         $request->request->get('approvalRole'1),
  10288.                         $request->request->get('approvalHash')
  10289.                     );
  10290.                 }
  10291.                 return new JsonResponse(array(
  10292.                     "success" => true,
  10293.                     'docId' => isset($new_ei['ei_id']) ? $new_ei['ei_id'] : '',
  10294.                     'docHash' => isset($new_ei['ei_doc_hash']) ? $new_ei['ei_doc_hash'] : '',
  10295.                 ));
  10296.             }
  10297.         }
  10298.         return new JsonResponse(array(
  10299.             "success" => true,
  10300.             'docId' => isset($new_ei['ei_id']) ? $new_ei['ei_id'] : '',
  10301.             'docHash' => isset($new_ei['ei_doc_hash']) ? $new_ei['ei_doc_hash'] : '',
  10302.             'expenseSubTypes' => $expenseSubTypes
  10303.         ));
  10304.         //
  10305.         //        return $this->render('@Accounts/pages/input_forms/payment_voucher.html.twig',
  10306.         //            array(
  10307.         //                'page_title'=>'Create Payment Voucher',
  10308.         //                'test'=>$details_ids,
  10309.         //                'supplier_list'=>Accounts::SupplierListForPv($this->getDoctrine()->getManager()),
  10310.         //                'supplier_list_by_ac_head'=>Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
  10311.         //                'supplier_list_by_advance_head'=>Accounts::SupplierListByAdvanceHead($this->getDoctrine()->getManager())
  10312.         //            )
  10313.         //        );
  10314.     }
  10315.     public function GetSalesOrderDocument()
  10316.     {
  10317.         $em $this->getDoctrine()->getManager();
  10318.         $qb $em->createQueryBuilder();
  10319.         $qb->select('s.salesOrderId''s.documentHash''c.clientName')
  10320.             ->from('ApplicationBundle:SalesOrder''s')
  10321.             ->leftJoin('ApplicationBundle:AccClients''c''WITH''s.clientId = c.clientId')
  10322.             ->orderBy('s.salesOrderId''DESC');
  10323.         $results $qb->getQuery()->getArrayResult();
  10324.         return new JsonResponse([
  10325.             'success' => true,
  10326.             'data' => $results
  10327.         ]);
  10328.     }
  10329.     public function GetCostCenter()
  10330.     {
  10331.         $em $this->getDoctrine()->getManager();
  10332.         $qb $em->createQueryBuilder();
  10333.         $qb->select('c.costCentreId''c.name')
  10334.             ->from('ApplicationBundle:AccCostCentre''c');
  10335.         $results $qb->getQuery()->getArrayResult();
  10336.         return new JsonResponse([
  10337.             'success' => true,
  10338.             'data' => $results
  10339.         ]);
  10340.     }
  10341.     public function GetExpenseType()
  10342.     {
  10343.         $em $this->getDoctrine()->getManager();
  10344.         // Fetch Sales Orders
  10345.         $qb $em->createQueryBuilder();
  10346.         $qb->select(
  10347.             's.salesOrderId',
  10348.             's.documentHash',
  10349.             'c.clientName',
  10350.             'p.projectId',
  10351.             'p.projectName'
  10352.         )
  10353.             ->from('ApplicationBundle:SalesOrder''s')
  10354.             ->leftJoin('ApplicationBundle:AccClients''c''WITH''s.clientId = c.clientId')
  10355.             ->leftJoin('ApplicationBundle:Project''p''WITH''s.projectId = p.projectId')
  10356.             ->orderBy('s.salesOrderId''DESC');
  10357.         $salesOrders $qb->getQuery()->getArrayResult();
  10358.         // Fetch Cost Centres
  10359.         $qb2 $em->createQueryBuilder();
  10360.         $qb2->select('c.costCentreId''c.name')
  10361.             ->from('ApplicationBundle:AccCostCentre''c');
  10362.         $costCentres $qb2->getQuery()->getArrayResult();
  10363.         // Build Expense Types
  10364.         $types = [];
  10365.         foreach (GeneralConstant::$expenseType as $id => $name) {
  10366.             $types[] = [
  10367.                 'id' => $id,
  10368.                 'name' => $name,
  10369.                 'salesOrders' => $id === $salesOrders : [],
  10370.                 'costCentres' => $id === $costCentres : []
  10371.             ];
  10372.         }
  10373.         return new JsonResponse($types);
  10374.     }
  10375.     public function AddPayment(Request $request)
  10376.     {
  10377.         $details_ids = [];
  10378.         $em $this->getDoctrine()->getManager();
  10379.         if ($request->isMethod('POST')) {
  10380.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10381.             $approveRole $request->request->get('approvalRole');
  10382.             $approveHash $request->request->get('approvalHash');
  10383.             if (!DocValidation::isSignatureOk($em$loginId$approveHash)) {
  10384.                 //                $this->addFlash(
  10385.                 //                    'error',
  10386.                 //                    'Sorry Could Not insert Data.'
  10387.                 //                );
  10388.                 return new JsonResponse(array(
  10389.                     "success" => false,
  10390.                     'errorText' => 'Approval Hash Mismatch',
  10391.                     'errorStr' => 'Approval Hash Mismatch'
  10392.                 ));
  10393.             } else {
  10394.                 //            Generic::debugMessage($_POST);
  10395.                 $payment_type $request->request->get('payment_type'); //1=supp, 2=employee 3=ac head
  10396.                 $payment_sub_type $request->request->get('payment_sub_type'); //1=gen, 2=adv 3=loan
  10397.                 $payment_to $request->request->get('payment_to_' $payment_type);
  10398.                 $payment_to_note $request->request->get('payment_to_note_' $payment_type);
  10399.                 $payment_from $request->request->get('payment_from');
  10400.                 $payment_from_note $request->request->get('payment_from_note');
  10401.                 $description $request->request->get('description');
  10402.                 $payment_amount $request->request->get('payment_amount');
  10403.                 $invoice_balancing $request->request->has('auto_balance' $payment_type) ? $request->request->get('auto_balance' $payment_type) : 0;
  10404.                 $em $this->getDoctrine()->getManager();
  10405.                 $pi_list = [];
  10406.                 $po_list = [];
  10407.                 $ei_list = [];
  10408.                 $assignable $payment_amount;
  10409.                 $general_amount 0;
  10410.                 $advance_amount 0;
  10411.                 $TransID 0;
  10412.                 $check_here = [];
  10413.                 $id_list_for_check = [];
  10414.                 $id_for_check '';
  10415.                 $details_ids = [];
  10416.                 $head_list Accounts::HeadList($em);
  10417.                 $balancing_data = [];
  10418.                 $purchase_invoices = [];
  10419.                 //            $to_assign=0;
  10420.                 //for supplier
  10421.                 if ($payment_type == 1) {
  10422.                     //                    $supplier_list = Accounts::SupplierListForPv($em);
  10423.                     $supp $em->getRepository('ApplicationBundle\\Entity\\AccSuppliers')->findOneBy(array(
  10424.                         'supplierId' => $payment_to,
  10425.                         'status' => GeneralConstant::ACTIVE
  10426.                     ));
  10427.                     $supplier_list = [];
  10428.                     $pa = array();
  10429.                     $pa['id'] = $supp->getSupplierId();
  10430.                     $pa['name'] = $supp->getSupplierName();
  10431.                     $pa['supplierShortCode'] = $supp->getSupplierShortCode();
  10432.                     $pa['supplier_head_id'] = $supp->getAccountsHeadId();
  10433.                     $pa['supplier_advance_head_id'] = $supp->getAdvanceHeadId();
  10434.                     $supplier_list[$supp->getSupplierId()] = $pa;
  10435.                     //                    $supplier_list = Accounts::SupplierListByAcHead($em, [$payment_to]);
  10436.                     $balancing_data Accounts::GetPurchaseInvoiceBalancingData($em, [], [$supplier_list[$payment_to]['supplier_head_id']]);
  10437.                     $id_for_check $supplier_list[$payment_to]['supplier_head_id'];
  10438.                     $purchase_invoices $balancing_data['purchase_invoices'];
  10439.                     if (!empty($purchase_invoices))
  10440.                         foreach ($purchase_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10441.                             $pi_list['id'][] = $entry['purchase_invoice_id'];
  10442.                             $pi_list['aa'][] = $assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10443.                             $general_amount += ($assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10444.                             $assignable $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable 0);
  10445.                         }
  10446.                     $expense_invoices $balancing_data['expense_invoices'];
  10447.                     if (!empty($expense_invoices))
  10448.                         foreach ($expense_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10449.                             $ei_list['id'][] = $entry['expense_invoice_id'];
  10450.                             $ei_list['ei_head_id'][] = $supplier_list[$payment_to]['supplier_head_id'];
  10451.                             $ei_list['aa'][] = $assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10452.                             $general_amount += ($assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10453.                             $assignable $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable 0);
  10454.                         }
  10455.                     $purchase_orders $balancing_data['purchase_orders'];
  10456.                     if (!empty($purchase_orders))
  10457.                         foreach ($purchase_orders[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10458.                             $po_list['id'][] = $entry['purchase_order_id'];
  10459.                             $po_list['aa'][] = $assignable $entry['po_amount'] ? $entry['po_amount'] : $assignable;
  10460.                             $advance_amount += ($assignable $entry['po_amount'] ? $entry['po_amount'] : $assignable);
  10461.                             $assignable $entry['po_amount'] ? ($assignable -= $entry['po_amount']) : ($assignable 0);
  10462.                         }
  10463.                     $ledgerHeads = [$supplier_list[$payment_to]['supplier_head_id'], $payment_to];
  10464.                     $notes = [$payment_from_note$payment_to_note];
  10465.                     $costCenters = [];
  10466.                     $drAmount $payment_amount;
  10467.                     $crAmount $payment_amount;
  10468.                     $notes $request->request->get('trNote');
  10469.                     $check_allowed 0;
  10470.                     //                $provisional=0;
  10471.                     if ($request->request->get('check_id') != '')
  10472.                         $check_allowed 1;
  10473.                     //                if($request->request->has('provisional'))
  10474.                     $provisional 1;
  10475.                     $TransID Accounts::CreateNewTransaction(
  10476.                         0,
  10477.                         $this->getDoctrine()->getManager(),
  10478.                         $request->request->get('payment_date'),
  10479.                         $payment_amount,
  10480.                         AccountsConstant::VOUCHER_PAYMENT,
  10481.                         $description,
  10482.                         'DV/GN/1/' Accounts::GetVNoHash($em'dv''gn'1),
  10483.                         'DV',
  10484.                         'GN',
  10485.                         1,
  10486.                         Accounts::GetVNoHash($em'dv''gn'1),
  10487.                         $check_allowed,
  10488.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10489.                         $this->getLoggedUserCompanyId($request),
  10490.                         '',
  10491.                         $provisional
  10492.                     );
  10493.                     $check_here = [];
  10494.                     //                $id_list_for_check=[];
  10495.                     //                $id_list_for_check[$supplier_list[$payment_to]['supplier_head_id']]=$supplier_list[$payment_to]['supplier_head_id'];
  10496.                     if ($general_amount 0) {
  10497.                         $details_ids[$supplier_list[$payment_to]['supplier_head_id']] = Accounts::CreateNewTransactionDetails(
  10498.                             $this->getDoctrine()->getManager(),
  10499.                             $request->request->get('payment_date'),
  10500.                             $TransID,
  10501.                             Generic::CurrToInt($general_amount),
  10502.                             $supplier_list[$payment_to]['supplier_head_id'],
  10503.                             $payment_to_note,
  10504.                             AccountsConstant::DEBIT,
  10505.                             0,
  10506.                             array($pi_list$po_list$ei_list),
  10507.                             [],
  10508.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10509.                             $provisional
  10510.                         );
  10511.                     }
  10512.                     if ($advance_amount 0) {
  10513.                         //                    $id_list_for_check[$supplier_list[$payment_to]['supplier_advance_head_id']]=$supplier_list[$payment_to]['supplier_head_id'];
  10514.                         $details_ids[$supplier_list[$payment_to]['supplier_advance_head_id']] = Accounts::CreateNewTransactionDetails(
  10515.                             $this->getDoctrine()->getManager(),
  10516.                             $request->request->get('payment_date'),
  10517.                             $TransID,
  10518.                             Generic::CurrToInt($advance_amount),
  10519.                             $supplier_list[$payment_to]['supplier_advance_head_id'],
  10520.                             $payment_to_note ' As Advance',
  10521.                             AccountsConstant::DEBIT,
  10522.                             0,
  10523.                             array($pi_list$po_list$ei_list),
  10524.                             [],
  10525.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10526.                             $provisional
  10527.                         );
  10528.                     }
  10529.                     $details_ids[$payment_from] = Accounts::CreateNewTransactionDetails(
  10530.                         $this->getDoctrine()->getManager(),
  10531.                         $request->request->get('payment_date'),
  10532.                         $TransID,
  10533.                         Generic::CurrToInt($payment_amount),
  10534.                         $payment_from,
  10535.                         $payment_from_note,
  10536.                         AccountsConstant::CREDIT,
  10537.                         0,
  10538.                         array($pi_list$po_list$ei_list),
  10539.                         [],
  10540.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10541.                         $provisional
  10542.                     );
  10543.                 }
  10544.                 if ($payment_type == 2) {
  10545.                     $id_for_check $payment_to;
  10546.                     //                    if(isset($supplier_list[$payment_to])) {
  10547.                     //                        $balancing_data = Accounts::GetPurchaseInvoiceBalancingData($em, [], [$supplier_list[$payment_to]['supplier_head_id']]);
  10548.                     //                        $id_for_check = $supplier_list[$payment_to]['supplier_head_id'];
  10549.                     //                        $purchase_invoices = $balancing_data['purchase_invoices'];
  10550.                     //
  10551.                     //                        if (!empty($purchase_invoices))
  10552.                     //                            foreach ($purchase_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10553.                     //                                $pi_list['id'][] = $entry['purchase_invoice_id'];
  10554.                     //                                $pi_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10555.                     //                                $general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10556.                     //                                $assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
  10557.                     //                            }
  10558.                     //                        $expense_invoices = $balancing_data['expense_invoices'];
  10559.                     //                        if (!empty($expense_invoices))
  10560.                     //                            foreach ($expense_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10561.                     //                                $ei_list['id'][] = $entry['expense_invoice_id'];
  10562.                     //                                $ei_list['ei_head_id'][] = $supplier_list[$payment_to]['supplier_head_id'];
  10563.                     //                                $ei_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10564.                     //                                $general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10565.                     //                                $assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
  10566.                     //                            }
  10567.                     //                        $purchase_orders = $balancing_data['purchase_orders'];
  10568.                     //                        if (!empty($purchase_orders))
  10569.                     //                            foreach ($purchase_orders[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10570.                     //                                $po_list['id'][] = $entry['purchase_order_id'];
  10571.                     //                                $po_list['aa'][] = $assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable;
  10572.                     //                                $advance_amount += ($assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable);
  10573.                     //                                $assignable > $entry['po_amount'] ? ($assignable -= $entry['po_amount']) : ($assignable = 0);
  10574.                     //                            }
  10575.                     //                    }
  10576.                     $check_allowed 0;
  10577.                     //                $provisional=0;
  10578.                     if ($request->request->get('check_id') != '')
  10579.                         $check_allowed 1;
  10580.                     //                if($request->request->has('provisional'))
  10581.                     $provisional 1;
  10582.                     $TransID Accounts::CreateNewTransaction(
  10583.                         0,
  10584.                         $this->getDoctrine()->getManager(),
  10585.                         $request->request->get('payment_date'),
  10586.                         $payment_amount,
  10587.                         AccountsConstant::VOUCHER_PAYMENT,
  10588.                         $description,
  10589.                         'DV/GN/1/' Accounts::GetVNoHash($em'dv''gn'1),
  10590.                         'DV',
  10591.                         'GN',
  10592.                         1,
  10593.                         Accounts::GetVNoHash($em'dv''gn'1),
  10594.                         $check_allowed,
  10595.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10596.                         $this->getLoggedUserCompanyId($request),
  10597.                         '',
  10598.                         $provisional
  10599.                     );
  10600.                     $check_here = [];
  10601.                     //                $id_list_for_check=[];
  10602.                     //                $id_list_for_check[$supplier_list[$payment_to]['supplier_head_id']]=$supplier_list[$payment_to]['supplier_head_id'];
  10603.                     $details_ids[$payment_to] = Accounts::CreateNewTransactionDetails(
  10604.                         $this->getDoctrine()->getManager(),
  10605.                         $request->request->get('payment_date'),
  10606.                         $TransID,
  10607.                         Generic::CurrToInt($payment_amount),
  10608.                         $payment_to,
  10609.                         $payment_to_note,
  10610.                         AccountsConstant::DEBIT,
  10611.                         0,
  10612.                         array($pi_list$po_list$ei_list),
  10613.                         [],
  10614.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10615.                         $provisional
  10616.                     );
  10617.                     $details_ids[$payment_from] = Accounts::CreateNewTransactionDetails(
  10618.                         $this->getDoctrine()->getManager(),
  10619.                         $request->request->get('payment_date'),
  10620.                         $TransID,
  10621.                         Generic::CurrToInt($payment_amount),
  10622.                         $payment_from,
  10623.                         $payment_from_note,
  10624.                         AccountsConstant::CREDIT,
  10625.                         0,
  10626.                         array($pi_list$po_list$ei_list),
  10627.                         [],
  10628.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10629.                         $provisional
  10630.                     );
  10631.                 }
  10632.                 if ($payment_type == 3) {
  10633.                     $id_for_check $payment_to;
  10634.                     $supplier_list Accounts::SupplierListForPv($em);
  10635.                     //                    if(isset($supplier_list[$payment_to])) {
  10636.                     //                        $balancing_data = Accounts::GetPurchaseInvoiceBalancingData($em, [], [$supplier_list[$payment_to]['supplier_head_id']]);
  10637.                     //                        $id_for_check = $supplier_list[$payment_to]['supplier_head_id'];
  10638.                     //                        $purchase_invoices = $balancing_data['purchase_invoices'];
  10639.                     //
  10640.                     //                        if (!empty($purchase_invoices))
  10641.                     //                            foreach ($purchase_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10642.                     //                                $pi_list['id'][] = $entry['purchase_invoice_id'];
  10643.                     //                                $pi_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10644.                     //                                $general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10645.                     //                                $assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
  10646.                     //                            }
  10647.                     //                        $expense_invoices = $balancing_data['expense_invoices'];
  10648.                     //                        if (!empty($expense_invoices))
  10649.                     //                            foreach ($expense_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10650.                     //                                $ei_list['id'][] = $entry['expense_invoice_id'];
  10651.                     //                                $ei_list['ei_head_id'][] = $supplier_list[$payment_to]['supplier_head_id'];
  10652.                     //                                $ei_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10653.                     //                                $general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10654.                     //                                $assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
  10655.                     //                            }
  10656.                     //                        $purchase_orders = $balancing_data['purchase_orders'];
  10657.                     //                        if (!empty($purchase_orders))
  10658.                     //                            foreach ($purchase_orders[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10659.                     //                                $po_list['id'][] = $entry['purchase_order_id'];
  10660.                     //                                $po_list['aa'][] = $assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable;
  10661.                     //                                $advance_amount += ($assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable);
  10662.                     //                                $assignable > $entry['po_amount'] ? ($assignable -= $entry['po_amount']) : ($assignable = 0);
  10663.                     //                            }
  10664.                     //                    }
  10665.                     $check_allowed 0;
  10666.                     //                $provisional=0;
  10667.                     if ($request->request->get('check_id') != '')
  10668.                         $check_allowed 1;
  10669.                     //                if($request->request->has('provisional'))
  10670.                     $provisional 1;
  10671.                     $TransID Accounts::CreateNewTransaction(
  10672.                         0,
  10673.                         $this->getDoctrine()->getManager(),
  10674.                         $request->request->get('payment_date'),
  10675.                         $payment_amount,
  10676.                         AccountsConstant::VOUCHER_PAYMENT,
  10677.                         $description,
  10678.                         'DV/GN/1/' Accounts::GetVNoHash($em'dv''gn'1),
  10679.                         'DV',
  10680.                         'GN',
  10681.                         1,
  10682.                         Accounts::GetVNoHash($em'dv''gn'1),
  10683.                         $check_allowed,
  10684.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10685.                         $this->getLoggedUserCompanyId($request),
  10686.                         '',
  10687.                         $provisional
  10688.                     );
  10689.                     $check_here = [];
  10690.                     //                $id_list_for_check=[];
  10691.                     //                $id_list_for_check[$supplier_list[$payment_to]['supplier_head_id']]=$supplier_list[$payment_to]['supplier_head_id'];
  10692.                     $details_ids[$payment_to] = Accounts::CreateNewTransactionDetails(
  10693.                         $this->getDoctrine()->getManager(),
  10694.                         $request->request->get('payment_date'),
  10695.                         $TransID,
  10696.                         Generic::CurrToInt($payment_amount),
  10697.                         $payment_to,
  10698.                         $payment_to_note,
  10699.                         AccountsConstant::DEBIT,
  10700.                         0,
  10701.                         array($pi_list$po_list$ei_list),
  10702.                         [],
  10703.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10704.                         $provisional
  10705.                     );
  10706.                     $details_ids[$payment_from] = Accounts::CreateNewTransactionDetails(
  10707.                         $this->getDoctrine()->getManager(),
  10708.                         $request->request->get('payment_date'),
  10709.                         $TransID,
  10710.                         Generic::CurrToInt($payment_amount),
  10711.                         $payment_from,
  10712.                         $payment_from_note,
  10713.                         AccountsConstant::CREDIT,
  10714.                         0,
  10715.                         array($pi_list$po_list$ei_list),
  10716.                         [],
  10717.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10718.                         $provisional
  10719.                     );
  10720.                 }
  10721.                 if ($request->request->has('check_id')) {
  10722.                     $check_here $this->getDoctrine()
  10723.                         ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  10724.                         ->findOneBy(
  10725.                             array(
  10726.                                 'CheckId' => $request->request->get('check_id')
  10727.                             )
  10728.                         );
  10729.                     if ($check_here) {
  10730.                         $check_here->setRecAccountsHeadId($id_for_check);
  10731.                         $check_here->setRecAccountsHeadIdList(json_encode([$id_for_check]));
  10732.                         $check_here->setCheckNarration(empty($request->request->get('check_narration')) ? $head_list[$id_for_check]['name'] : $request->request->get('check_narration'));
  10733.                         $check_here->setCheckAmount($payment_amount);
  10734.                         $check_here->setCheckDate(new \DateTime($request->request->get('check_date')));
  10735.                         $check_here->setAssigned(1);
  10736.                         $check_here->setVoucherId($TransID);
  10737.                     }
  10738.                 }
  10739.                 //approval system
  10740.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10741.                 $approveRole $request->request->get('approvalRole');
  10742.                 Accounts::UpdatePurchasePayments($em$pi_list$po_list$details_ids$request->request->get('payment_date'), $payment_to);
  10743.                 Accounts::UpdateExpensePayments($em$ei_list$details_ids$request->request->get('payment_date'));
  10744.                 System::setApprovalInfo(
  10745.                     $this->getDoctrine()->getManager(),
  10746.                     [],
  10747.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  10748.                     $TransID,
  10749.                     $loginId,
  10750.                     5    //payment voucher
  10751.                 );
  10752.                 System::createEditSignatureHash(
  10753.                     $em,
  10754.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  10755.                     $TransID,
  10756.                     $loginId,
  10757.                     $approveRole,
  10758.                     $request->request->get('approvalHash')
  10759.                 );
  10760.                 //                $this->addFlash(
  10761.                 //                    'success',
  10762.                 //                    'New Transaction Added.'
  10763.                 //                );
  10764.                 $url $this->generateUrl(
  10765.                     'view_voucher'
  10766.                 );
  10767.                 $trans_here $this->getDoctrine()
  10768.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  10769.                     ->findOneBy(
  10770.                         array(
  10771.                             'transactionId' => $TransID
  10772.                         )
  10773.                     );
  10774.                 System::AddNewNotification(
  10775.                     $this->container->getParameter('notification_enabled'),
  10776.                     $this->container->getParameter('notification_server'),
  10777.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  10778.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  10779.                     "Debit Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  10780.                     'pos',
  10781.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  10782.                     'success',
  10783.                     $url "/" $TransID,
  10784.                     "Debit Voucher"
  10785.                 );
  10786.                 return new JsonResponse(array(
  10787.                     "success" => true,
  10788.                     'docId' => $TransID,
  10789.                     'docHash' => $trans_here->getDocumentHash(),
  10790.                 ));
  10791.             }
  10792.         }
  10793.         return new JsonResponse(array("success" => true));
  10794.     }
  10795.     public function AddReceipt(Request $request)
  10796.     {
  10797.         $details_ids = [];
  10798.         $em $this->getDoctrine()->getManager();
  10799.         $docId 0;
  10800.         $docHash 0;
  10801.         $companyId $this->getLoggedUserCompanyId($request);
  10802.         if ($request->isMethod('POST')) {
  10803.             $balancing_data = [];
  10804.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10805.             $approveRole $request->request->get('approvalRole');
  10806.             $approveHash $request->request->get('approvalHash');
  10807.             if (!DocValidation::isSignatureOk($em$loginId$approveHash)) {
  10808.                 //                $this->addFlash(
  10809.                 //                    'error',
  10810.                 //                    'Sorry Could Not insert Data.'
  10811.                 //                );
  10812.                 return new JsonResponse(array(
  10813.                     "success" => false,
  10814.                     'errorText' => 'Approval Hash Mismatch',
  10815.                     'errorStr' => 'Approval Hash Mismatch'
  10816.                 ));
  10817.             } else {
  10818.                 //            Generic::debugMessage($_POST);
  10819.                 //                $em->getRepository('ApplicationBundle\\Entity\\AccService')->findAll();
  10820.                 $receipt_type $request->request->get('receipt_type'); //1=client, 2=employee 3=ac head
  10821.                 $receipt_sub_type $request->request->get('receipt_sub_type'); //1=gen, 2=adv 3=loan
  10822.                 $receipt_from $request->request->get('receipt_from_' $receipt_type);
  10823.                 $receipt_from_note $request->request->get('receipt_from_note_' $receipt_type);
  10824.                 $receipt_to $request->request->get('receipt_to');
  10825.                 $receipt_to_note $request->request->get('receipt_to_note');
  10826.                 $description $request->request->get('description');
  10827.                 $receipt_amount $request->request->get('receipt_amount');
  10828.                 $receipt_charge_amount = ($request->request->get('receipt_charge_amount'));
  10829.                 $receipt_charge_head $request->request->get('receipt_charge_head');
  10830.                 $receipt_charge_note $request->request->get('receipt_charge_note');
  10831.                 $receipt_deposit_amount = ($request->request->get('receipt_deposit_amount'));
  10832.                 //                $em->getRepository('ApplicationBundle\\Entity\\AccService')->findAll();
  10833.                 //                $receipt_deposit_head = $request->request->get('receipt_deposit_head');
  10834.                 if ($receipt_charge_amount && $receipt_charge_head == '')
  10835.                     return new JsonResponse(array("success" => false));
  10836.                 if ($receipt_charge_amount $receipt_deposit_amount != $receipt_amount)
  10837.                     return new JsonResponse(array("success" => false));
  10838.                 $invoice_balancing $request->request->has('auto_balance' $receipt_type) ? $request->request->get('auto_balance' $receipt_type) : 0;
  10839.                 $em $this->getDoctrine()->getManager();
  10840.                 $si_list = [];
  10841.                 $so_list = [];
  10842.                 $ei_list = [];
  10843.                 $assignable $receipt_amount;
  10844.                 $general_amount 0;
  10845.                 $advance_amount 0;
  10846.                 $TransID 0;
  10847.                 $check_here = [];
  10848.                 $id_list_for_check = [];
  10849.                 $id_for_check '';
  10850.                 $details_ids = [];
  10851.                 $head_list Accounts::HeadList($em);
  10852.                 $client_list Client::GetExistingClientList($em$companyId);
  10853.                 //                $clnt = $client_list[$receipt_from];
  10854.                 //            $to_assign=0;
  10855.                 //for client
  10856.                 if ($receipt_type == 1) {
  10857.                     $clnt $client_list[$receipt_from];
  10858.                     //now check if special case like came form SO
  10859.                     $balancing_data Accounts::GetSalesInvoiceBalancingData(
  10860.                         $em,
  10861.                         [],
  10862.                         [$client_list[$receipt_from]['accHeadId']],
  10863.                         $request->request->get('AddReceiptModalSpecialType'),
  10864.                         [$request->request->get('AddReceiptModalSpecialTypeSoDocId')],
  10865.                         [$request->request->get('AddReceiptModalSpecialTypeSiDocId')]
  10866.                     );
  10867.                     $id_for_check $client_list[$receipt_from]['accHeadId'];
  10868.                     $sales_invoices $balancing_data['sales_invoices'];
  10869.                     if (!empty($sales_invoices))
  10870.                         foreach ($sales_invoices[$client_list[$receipt_from]['accHeadId']] as $entry) {
  10871.                             $si_list['id'][] = $entry['sales_invoice_id'];
  10872.                             $si_list['aa'][] = $assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10873.                             $general_amount += ($assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10874.                             $assignable $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable 0);
  10875.                         }
  10876.                     $expense_invoices $balancing_data['expense_invoices'];
  10877.                     if (!empty($expense_invoices))
  10878.                         foreach ($expense_invoices[$client_list[$receipt_from]['accHeadId']] as $entry) {
  10879.                             $ei_list['id'][] = $entry['expense_invoice_id'];
  10880.                             $ei_list['ei_head_id'][] = $client_list[$receipt_from]['accHeadId'];
  10881.                             $ei_list['aa'][] = $assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10882.                             $general_amount += ($assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10883.                             $assignable $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable 0);
  10884.                         }
  10885.                     $sales_orders $balancing_data['sales_orders'];
  10886.                     if (!empty($sales_orders))
  10887.                         foreach ($sales_orders[$client_list[$receipt_from]['accHeadId']] as $entry) {
  10888.                             $so_list['id'][] = $entry['sales_order_id'];
  10889.                             $so_list['aa'][] = $assignable $entry['so_amount'] ? $entry['so_amount'] : $assignable;
  10890.                             $advance_amount += ($assignable $entry['so_amount'] ? $entry['so_amount'] : $assignable);
  10891.                             $assignable $entry['so_amount'] ? ($assignable -= $entry['so_amount']) : ($assignable 0);
  10892.                         }
  10893.                     $ledgerHeads = [$client_list[$receipt_from]['accHeadId'], $receipt_from];
  10894.                     $notes = [$receipt_to_note$receipt_from_note];
  10895.                     $costCenters = [];
  10896.                     $drAmount $receipt_amount;
  10897.                     $crAmount $receipt_amount;
  10898.                     $notes $request->request->get('trNote');
  10899.                     $check_allowed 0;
  10900.                     //                $provisional=0;
  10901.                     if ($request->request->get('check_id') != '')
  10902.                         $check_allowed 1;
  10903.                     //                if($request->request->has('provisional'))
  10904.                     $provisional 1;
  10905.                     $TransID Accounts::CreateNewTransaction(
  10906.                         0,
  10907.                         $this->getDoctrine()->getManager(),
  10908.                         $request->request->get('receipt_date'),
  10909.                         $receipt_amount,
  10910.                         AccountsConstant::VOUCHER_RECEIPT,
  10911.                         $description,
  10912.                         'CV/GN/1/' Accounts::GetVNoHash($em'CV''GN'1),
  10913.                         'CV',
  10914.                         'GN',
  10915.                         1,
  10916.                         Accounts::GetVNoHash($em'CV''GN'1),
  10917.                         $check_allowed,
  10918.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10919.                         $this->getLoggedUserCompanyId($request),
  10920.                         '',
  10921.                         $provisional,
  10922.                         0,
  10923.                         0,
  10924.                         '',
  10925.                         $request->request->get('branchId'0),
  10926.                         '_UNSET_',
  10927.                         '_UNSET_',
  10928.                         0,
  10929.                         '',
  10930.                         $request->request->get('uploaded_image_path''')
  10931.                     );
  10932.                     $check_here = [];
  10933.                     //                $id_list_for_check=[];
  10934.                     //                $id_list_for_check[$client_list[$receipt_from]['supplier_head_id']]=$client_list[$receipt_from]['supplier_head_id'];
  10935.                     if ($general_amount 0) {
  10936.                         $details_ids[$client_list[$receipt_from]['accHeadId']] = Accounts::CreateNewTransactionDetails(
  10937.                             $this->getDoctrine()->getManager(),
  10938.                             $request->request->get('receipt_date'),
  10939.                             $TransID,
  10940.                             Generic::CurrToInt($general_amount),
  10941.                             $client_list[$receipt_from]['accHeadId'],
  10942.                             $receipt_from_note,
  10943.                             AccountsConstant::CREDIT,
  10944.                             0,
  10945.                             array($si_list$so_list$ei_list),
  10946.                             [],
  10947.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10948.                             $provisional
  10949.                         );
  10950.                     }
  10951.                     if ($advance_amount 0) {
  10952.                         //                    $id_list_for_check[$client_list[$receipt_from]['supplier_advance_head_id']]=$client_list[$receipt_from]['supplier_head_id'];
  10953.                         $details_ids[$client_list[$receipt_from]['advanceHeadId']] = Accounts::CreateNewTransactionDetails(
  10954.                             $this->getDoctrine()->getManager(),
  10955.                             $request->request->get('receipt_date'),
  10956.                             $TransID,
  10957.                             Generic::CurrToInt($advance_amount),
  10958.                             $client_list[$receipt_from]['advanceHeadId'],
  10959.                             $receipt_from_note ' As Advance',
  10960.                             AccountsConstant::CREDIT,
  10961.                             0,
  10962.                             array($si_list$so_list$ei_list),
  10963.                             [],
  10964.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10965.                             $provisional
  10966.                         );
  10967.                     }
  10968.                     $details_ids[$receipt_to] = Accounts::CreateNewTransactionDetails(
  10969.                         $this->getDoctrine()->getManager(),
  10970.                         $request->request->get('receipt_date'),
  10971.                         $TransID,
  10972.                         Generic::CurrToInt($receipt_deposit_amount),
  10973.                         $receipt_to,
  10974.                         $receipt_to_note,
  10975.                         AccountsConstant::DEBIT,
  10976.                         0,
  10977.                         array($si_list$so_list$ei_list),
  10978.                         [],
  10979.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10980.                         $provisional
  10981.                     );
  10982.                     if ($receipt_charge_amount != 0) {
  10983.                         $details_ids[$receipt_to] = Accounts::CreateNewTransactionDetails(
  10984.                             $this->getDoctrine()->getManager(),
  10985.                             $request->request->get('receipt_date'),
  10986.                             $TransID,
  10987.                             Generic::CurrToInt($receipt_charge_amount),
  10988.                             $receipt_charge_head,
  10989.                             $receipt_charge_note,
  10990.                             AccountsConstant::DEBIT,
  10991.                             0,
  10992.                             array($si_list$so_list$ei_list),
  10993.                             [],
  10994.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10995.                             $provisional
  10996.                         );
  10997.                     }
  10998.                 }
  10999.                 //now check if the head is bank head if so add a check entry
  11000.                 $bank_settings $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  11001.                     'name' => 'bank_parents'
  11002.                 ));
  11003.                 $under_bank 0;
  11004.                 $bank_id_list = [];
  11005.                 if ($bank_settings)
  11006.                     $bank_id_list json_decode($bank_settings->getData());
  11007.                 $the_head $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array('accountsHeadId' => $receipt_to));
  11008.                 if ($the_head) {
  11009.                     $path_tree_list explode('/'$the_head->getPathTree());
  11010.                     foreach ($path_tree_list as $pt) {
  11011.                         if (in_array($pt$bank_id_list)) {
  11012.                             $under_bank 1;
  11013.                         }
  11014.                     }
  11015.                 }
  11016.                 if ($under_bank == 1) {
  11017.                     //                foreach($request->request->get('check_id') as $k=>$value)
  11018.                     //                {
  11019.                     $check_here = new AccCheck();
  11020.                     $check_here->setRecAccountsHeadId($receipt_to);
  11021.                     $check_here->setRecAccountsHeadIdList(json_encode([$receipt_to]));
  11022.                     $check_here->setAccountsHeadId($client_list[$receipt_from]['accHeadId']);
  11023.                     //                    $check_here->setCheckNarration($request->request->get('check_narration')[$k]);
  11024.                     $check_here->setCheckAmount($receipt_amount);
  11025.                     $check_here->setCheckDate(new \DateTime($request->request->get('receipt_date')));
  11026.                     $check_here->setTransactionDate(new \DateTime($request->request->get('receipt_date')));
  11027.                     //                    $check_here->setCheckDate(new \DateTime($request->request->get('date')));
  11028.                     $check_here->setAssigned(1);
  11029.                     $check_here->setActive(1);
  11030.                     $check_here->setDetails('');
  11031.                     $check_here->setCheckNumber($request->request->get('receipt_check_number'));
  11032.                     $check_here->setStatus(3);
  11033.                     $check_here->setType(2); //receipt check
  11034.                     $check_here->setVoucherId($TransID);
  11035.                     //                }
  11036.                     $em->persist($check_here);
  11037.                     $em->flush();
  11038.                 }
  11039.                 //approval system
  11040.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  11041.                 $approveRole $request->request->get('approvalRole');
  11042.                 Accounts::UpdateSalesPayments($em$si_list$so_list$details_ids$request->request->get('receipt_date'), $receipt_from);
  11043.                 //            Accounts::UpdateExpenseReceipts($em,$ei_list,$details_ids,  $request->request->get('receipt_date'));
  11044.                 System::setApprovalInfo(
  11045.                     $this->getDoctrine()->getManager(),
  11046.                     [],
  11047.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  11048.                     $TransID,
  11049.                     $loginId,
  11050.                     6    //receipt voucher
  11051.                 );
  11052.                 System::createEditSignatureHash(
  11053.                     $em,
  11054.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  11055.                     $TransID,
  11056.                     $loginId,
  11057.                     $approveRole,
  11058.                     $request->request->get('approvalHash')
  11059.                 );
  11060.                 //                $this->addFlash(
  11061.                 //                    'success',
  11062.                 //                    'New Transaction Added.'
  11063.                 //                );
  11064.                 $url $this->generateUrl(
  11065.                     'view_voucher'
  11066.                 );
  11067.                 $trans_here $this->getDoctrine()
  11068.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  11069.                     ->findOneBy(
  11070.                         array(
  11071.                             'transactionId' => $TransID
  11072.                         )
  11073.                     );
  11074.                 System::AddNewNotification(
  11075.                     $this->container->getParameter('notification_enabled'),
  11076.                     $this->container->getParameter('notification_server'),
  11077.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  11078.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  11079.                     "Debit Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  11080.                     'pos',
  11081.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  11082.                     'success',
  11083.                     $url "/" $TransID,
  11084.                     "Debit Voucher"
  11085.                 );
  11086.                 return new JsonResponse(array(
  11087.                     'success' => true,
  11088.                     'transactionId' => $TransID,
  11089.                     'docId' => $TransID,
  11090.                     'docHash' => $trans_here->getDocumentHash(),
  11091.                     'balancing_data' => $balancing_data,
  11092.                     'clnt' => $clnt,
  11093.                     'general_amount' => $general_amount,
  11094.                     'advance_amount' => $advance_amount,
  11095.                     'assignable' => $assignable,
  11096.                 ));
  11097.             }
  11098.         }
  11099.         return new JsonResponse(array(
  11100.             'success' => false,
  11101.             'transactionId' => 0,
  11102.             'balancing_data' => [],
  11103.             'clnt' => 0,
  11104.             'general_amount' => 0,
  11105.             'advance_amount' => 0,
  11106.             'assignable' => 0,
  11107.         ));
  11108.     }
  11109.     public function GetChildHeadsByMarkerHash(Request $request$queryStr '')
  11110.     {
  11111.         $em $this->getDoctrine()->getManager();
  11112.         $dataList = [];
  11113.         $data_by_id = [];
  11114.         $lastChildrenOnly $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0;
  11115.         $renderTextFormat $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '';
  11116.         $valueField $request->request->has('valueField') ? $request->request->get('valueField') : 'accounts_head_id';
  11117.         $textField $request->request->has('textField') ? $request->request->get('textField') : 'name';
  11118.         $parentOnly $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0;
  11119.         $queryText $request->request->get('query''_EMPTY_');
  11120.         $itemLimit $request->request->get('itemLimit'25);
  11121.         $offset $request->request->get('offset'0);
  11122.         $isMultiple $request->request->get('isMultiple'0);
  11123.         $selectorId $request->request->get('selectorId''');
  11124.         $dataId $request->request->get('dataId''');
  11125.         $joinTableData $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [];
  11126.         if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  11127.         $setValueArray = [];
  11128.         $setValue 0;
  11129.         $selectedId 0;
  11130.         $selectAll 0;
  11131.         $table 'acc_accounts_head';
  11132.         if (!(strpos($queryText'#setValue:') === false)) {
  11133.             $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryText));
  11134.             foreach ($setValueArrayBeforeFilter as $svf) {
  11135.                 if ($svf == '_ALL_') {
  11136.                     $selectAll 1;
  11137.                     $setValueArray = [];
  11138.                     continue;
  11139.                 }
  11140.                 if (is_numeric($svf)) {
  11141.                     $setValueArray[] = ($svf 1);
  11142.                     $setValue $svf 1;
  11143.                 }
  11144.             }
  11145.             $queryText '_EMPTY_';
  11146.             $marker_hash_list = ['_ALL_'];
  11147.         } else
  11148.             $marker_hash_list explode(','$request->request->get('marker_hash'''));
  11149.         if (!empty($marker_hash_list)) {
  11150.             $markerHashLikeStr '';
  11151.             $first_item 1;
  11152.             $skipMarkerHash 0;
  11153.             foreach ($marker_hash_list as $marker_hash) {
  11154.                 if ($first_item == 0$markerHashLikeStr .= " or ";
  11155.                 if ($marker_hash == '_ALL_') {
  11156.                     $skipMarkerHash 1;
  11157.                     continue;
  11158.                 } else
  11159.                     $markerHashLikeStr .= "acc_accounts_head.marker_hash like '%$marker_hash%' ";
  11160.                 $first_item 0;
  11161.             }
  11162.             $markerHashQuery "SELECT  acc_accounts_head.accounts_head_id, acc_accounts_head.marker_hash, acc_accounts_head_0.name  parent_table_name  FROM acc_accounts_head 
  11163. cross join acc_accounts_head acc_accounts_head_0 on    `acc_accounts_head_0`.`accounts_head_id` = `acc_accounts_head`.`parent_id`
  11164. ";
  11165.             if ($skipMarkerHash == 1) {
  11166.                 $markerHashQuery "SELECT  acc_accounts_head.* , acc_accounts_head_0.name  parent_table_name FROM acc_accounts_head 
  11167. cross join acc_accounts_head acc_accounts_head_0 on    `acc_accounts_head_0`.`accounts_head_id` = `acc_accounts_head`.`parent_id` 
  11168.     
  11169.     ";
  11170.                 if ($lastChildrenOnly == 1) {
  11171.                     $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id not in (select distinct parent_id from acc_accounts_head) ";
  11172.                 } else if ($parentOnly == 1) {
  11173.                     $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id  in (select distinct parent_id from acc_accounts_head) ";
  11174.                 } else
  11175.                     $markerHashQuery .= "WHERE  1=1 ";
  11176.                 //                $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id not in (select distinct parent_id from acc_accounts_head) ";
  11177.                 if ($queryText != '_EMPTY_') {
  11178.                     $markerHashQuery .= " AND (";
  11179.                     if (is_numeric($queryText)) {
  11180.                         $markerHashQuery .= (" acc_accounts_head.accounts_head_id = " $queryText " ");
  11181.                     } else {
  11182.                         $queryTextArray explode(','$queryText);
  11183.                         $addOn '';
  11184.                         foreach ($queryTextArray as $dd) {
  11185.                             $markerHashQuery .= ($addOn " acc_accounts_head.name like '%" $dd "%' ");
  11186.                             $addOn ' or ';
  11187.                         }
  11188.                     }
  11189.                     $markerHashQuery .= " ) ";
  11190.                 }
  11191.                 if (!empty($setValueArray) || $selectAll == 1) {
  11192.                     if (!empty($setValueArray)) {
  11193.                         if ($markerHashQuery != '')
  11194.                             $markerHashQuery .= " and ";
  11195.                         $markerHashQuery .= " acc_accounts_head.accounts_head_id in (" implode(','$setValueArray) . ") ";
  11196.                     }
  11197.                 }
  11198.                 if ($itemLimit != '_ALL_')
  11199.                     $markerHashQuery .= "  limit $offset$itemLimit ";
  11200.                 else
  11201.                     $markerHashQuery .= "  limit $offset, 18446744073709551615 ";
  11202.                 $markerHashQuery .= " ;";
  11203.                 $stmt $em->getConnection()->fetchAllAssociative($markerHashQuery);
  11204.                 
  11205.                 $markerHashQueryResults $stmt;
  11206.                 foreach ($markerHashQueryResults as $markerHashQueryResult) {
  11207.                     $markerHashQueryResult['value'] = $markerHashQueryResult['accounts_head_id'];
  11208.                     $markerHashQueryResult['text'] = $markerHashQueryResult['name'];
  11209.                     $markerHashQueryResult['id_value'] = '# ' $markerHashQueryResult['accounts_head_id'] . ' ' $markerHashQueryResult['name'];
  11210.                     $renderedText $renderTextFormat;
  11211.                     $compare_array = [];
  11212.                     if ($renderTextFormat != '') {
  11213.                         $renderedText $renderTextFormat;
  11214.                         $compare_arrayFull = [];
  11215.                         $compare_array = [];
  11216.                         $toBeReplacedData = array( //                        'curr'=>'tobereplaced'
  11217.                         );
  11218.                         preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  11219.                         if (isset($compare_arrayFull[0]))
  11220.                             $compare_array $compare_arrayFull[0];
  11221.                         //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  11222.                         foreach ($compare_array as $cmpdt) {
  11223.                             $tbr str_replace("__"""$cmpdt);
  11224.                             if ($tbr != '') {
  11225.                                 if (isset($markerHashQueryResult[$tbr])) {
  11226.                                     if ($markerHashQueryResult[$tbr] == null)
  11227.                                         $renderedText str_replace($cmpdt''$renderedText);
  11228.                                     else
  11229.                                         $renderedText str_replace($cmpdt$markerHashQueryResult[$tbr], $renderedText);
  11230.                                 } else {
  11231.                                     $renderedText str_replace($cmpdt''$renderedText);
  11232.                                 }
  11233.                             }
  11234.                         }
  11235.                     }
  11236.                     $markerHashQueryResult['rendered_text'] = $renderedText;
  11237.                     $markerHashQueryResult['text'] = ($textField != '' $markerHashQueryResult[$textField] : '');
  11238.                     $dataList[] = $markerHashQueryResult;
  11239.                     if ($valueField != '') {
  11240.                         $data_by_id[$markerHashQueryResult[$valueField]] = $markerHashQueryResult;
  11241.                         $selectedId $markerHashQueryResult[$valueField];
  11242.                     }
  11243.                 }
  11244.             } else {
  11245.                 $markerHashQuery .= "WHERE ( $markerHashLikeStr );";
  11246.                 $stmt $em->getConnection()->fetchAllAssociative($markerHashQuery);
  11247.                 
  11248.                 $markerHashQueryResults $stmt;
  11249.                 $hids = [];
  11250.                 foreach ($markerHashQueryResults as $h) {
  11251.                     $hids[] = $h['accounts_head_id'];
  11252.                 }
  11253.                 $markerHashLikeStr '';
  11254.                 if (!empty($hids))
  11255.                     $markerHashLikeStr 'accounts_head_id in (' implode(','$hids) . ') ';
  11256.                 foreach ($markerHashQueryResults as $h) {
  11257.                     $markerHashLikeStr .= "OR path_tree LIKE '%/" $h['accounts_head_id'] . "/%'  ";
  11258.                 }
  11259.                 if ($markerHashLikeStr != '') {
  11260.                     $markerHashQuery "SELECT  acc_accounts_head.* FROM acc_accounts_head ";
  11261.                     //                    $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id not in (select distinct parent_id from acc_accounts_head) and ( $markerHashLikeStr )";
  11262.                     if ($lastChildrenOnly == 1) {
  11263.                         $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id not in (select distinct parent_id from acc_accounts_head) and ( $markerHashLikeStr )";
  11264.                     } else if ($parentOnly == 1) {
  11265.                         $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id  in (select distinct parent_id from acc_accounts_head) and ( $markerHashLikeStr )";
  11266.                     } else
  11267.                         $markerHashQuery .= "WHERE  ( $markerHashLikeStr )";
  11268.                     if ($queryText != '_EMPTY_') {
  11269.                         $markerHashQuery .= " AND (";
  11270.                         if (is_numeric($queryText)) {
  11271.                             $markerHashQuery .= (" acc_accounts_head.accounts_head_id = " $queryText " ");
  11272.                         } else {
  11273.                             $queryTextArray explode(','$queryText);
  11274.                             $addOn '';
  11275.                             foreach ($queryTextArray as $dd) {
  11276.                                 $markerHashQuery .= ($addOn " acc_accounts_head.name like '%" $dd "%' ");
  11277.                                 $addOn ' or ';
  11278.                             }
  11279.                         }
  11280.                         $markerHashQuery .= " ) ";
  11281.                     }
  11282.                     if ($itemLimit != '_ALL_')
  11283.                         $markerHashQuery .= "  limit $offset$itemLimit ";
  11284.                     else
  11285.                         $markerHashQuery .= "  limit $offset, 18446744073709551615 ";
  11286.                     $markerHashQuery .= " ;";
  11287.                     $stmt $em->getConnection()->fetchAllAssociative($markerHashQuery);
  11288.                     
  11289.                     $markerHashQueryResults $stmt;
  11290.                     foreach ($markerHashQueryResults as $markerHashQueryResult) {
  11291.                         $markerHashQueryResult['value'] = $markerHashQueryResult['accounts_head_id'];
  11292.                         $markerHashQueryResult['text'] = $markerHashQueryResult['name'];
  11293.                         $markerHashQueryResult['id_value'] = '# ' $markerHashQueryResult['accounts_head_id'] . ' ' $markerHashQueryResult['name'];
  11294.                         $renderedText $renderTextFormat;
  11295.                         $compare_array = [];
  11296.                         if ($renderTextFormat != '') {
  11297.                             $renderedText $renderTextFormat;
  11298.                             $compare_arrayFull = [];
  11299.                             $compare_array = [];
  11300.                             $toBeReplacedData = array( //                        'curr'=>'tobereplaced'
  11301.                             );
  11302.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  11303.                             if (isset($compare_arrayFull[0]))
  11304.                                 $compare_array $compare_arrayFull[0];
  11305.                             //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  11306.                             foreach ($compare_array as $cmpdt) {
  11307.                                 $tbr str_replace("__"""$cmpdt);
  11308.                                 if ($tbr != '') {
  11309.                                     if (isset($markerHashQueryResult[$tbr])) {
  11310.                                         if ($markerHashQueryResult[$tbr] == null)
  11311.                                             $renderedText str_replace($cmpdt''$renderedText);
  11312.                                         else
  11313.                                             $renderedText str_replace($cmpdt$markerHashQueryResult[$tbr], $renderedText);
  11314.                                     } else {
  11315.                                         $renderedText str_replace($cmpdt''$renderedText);
  11316.                                     }
  11317.                                 }
  11318.                             }
  11319.                         }
  11320.                         $markerHashQueryResult['rendered_text'] = $renderedText;
  11321.                         $markerHashQueryResult['text'] = ($textField != '' $markerHashQueryResult[$textField] : '');
  11322.                         $dataList[] = $markerHashQueryResult;
  11323.                         if ($valueField != '') {
  11324.                             $data_by_id[$markerHashQueryResult[$valueField]] = $markerHashQueryResult;
  11325.                             $selectedId $markerHashQueryResult[$valueField];
  11326.                         }
  11327.                     }
  11328.                 }
  11329.             }
  11330.         }
  11331.         return new JsonResponse(array(
  11332.             'success' => empty($dataList) ? false true,
  11333.             'tableName' => $table,
  11334.             'setValue' => $setValue,
  11335.             'currentTs' => (new \Datetime())->format('U'),
  11336.             'dataList' => $dataList,
  11337.             'data' => $dataList,
  11338.             'dataById' => $data_by_id,
  11339.             'isMultiple' => $isMultiple,
  11340.             'selectorId' => $selectorId,
  11341.             'setValueArray' => $setValueArray,
  11342.             'queryStr' => $queryStr,
  11343.             //                    'andStr' => $andString,
  11344.             //                    'andOrStr' => $andOrString,
  11345.             'selectedId' => $selectedId,
  11346.             'dataId' => $dataId,
  11347.         ));
  11348.     }
  11349.     public function CreatePaymentRequisitionVoucher(Request $request)
  11350.     {
  11351.         $em $this->getDoctrine()->getManager();
  11352.         $new_cc $this->getDoctrine()
  11353.             ->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
  11354.             ->findBy(
  11355.                 array(
  11356.                     'approved' => 1,
  11357.                     'voucherIds' => null
  11358.                 )
  11359.             );
  11360.         foreach ($new_cc as $d) {
  11361.             ApprovalFunction::SalesInvoice($em$d->getSalesInvoiceId());
  11362.         }
  11363.         return $this->render(
  11364.             '@Accounts/pages/input_forms/payment_requisition.html.twig',
  11365.             array(
  11366.                 'page_title' => 'Create Contra Voucher'
  11367.             )
  11368.         );
  11369.     }
  11370.     public function ViewBalanceSheet(Request $request)
  11371.     {
  11372.         $em $this->getDoctrine()->getManager();
  11373.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  11374.         $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : "";
  11375.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : "";
  11376.         //        $end_date="";
  11377.         $em $this->getDoctrine()->getManager();
  11378.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  11379.         $bs_details Accounts::GetBsDetails($em$start_date$end_date);
  11380.         $grouped_heads Accounts::GroupedHeads($em);
  11381.         //        if($mis_start_date!=''&&$mis_start_date!=0)
  11382.         //            $start_date=$mis_start_date;
  11383.         //        if($mis_end_date!=''&&$mis_start_date!=0)
  11384.         //            $end_date=$mis_end_date;
  11385.         return $this->render(
  11386.             '@Accounts/pages/views/balance_sheet.html.twig',
  11387.             array(
  11388.                 'page_title' => 'Balance Sheet',
  11389.                 'company_name' => $company_data->getName(),
  11390.                 'company_data' => $company_data,
  11391.                 'details' => $bs_details
  11392.             )
  11393.         );
  11394.     }
  11395.     public function FiscalClosing(Request $request)
  11396.     {
  11397.         $em $this->getDoctrine()->getManager();
  11398.         if ($request->isMethod('POST')) {
  11399.             //now lets create new fiscal closing
  11400.             //            Accounts::FiscalClosing($em,$request->request->get('start_date'),$request->request->get('end_date'));
  11401.             $new = new FiscalClosing();
  11402.             $new->setClosingStartDate(new \DateTime($request->request->get('start_date')));
  11403.             $new->setClosingEndDate(new \DateTime($request->request->get('end_date')));
  11404.             $new->setClosingData(json_encode(array(
  11405.                 'heads' => $request->request->get('head_id'),
  11406.                 'balance' => $request->request->get('head_balance'),
  11407.                 'recon_balance' => $request->request->get('head_recon_balance')
  11408.             )));
  11409.             $new->setCompanyId($this->getLoggedUserCompanyId($request));
  11410.             $new->setLedgerHit(0);
  11411.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  11412.             $em->persist($new);
  11413.             $em->flush();
  11414.             Accounts::DoFiscalClosing($em$new->getClosingId());
  11415.             //            $new_cc = $this->getDoctrine()
  11416.             //                ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  11417.             //                ->findOneBy(
  11418.             //                    array(
  11419.             //                        'name' => 'accounting_year_start',
  11420.             //                    )
  11421.             //                );
  11422.             //            $new_cc->setData($request->request->get('end_date'));
  11423.             //            $em->flush();
  11424.         }
  11425.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  11426.         $new_cc $this->getDoctrine()
  11427.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  11428.             ->findOneBy(
  11429.                 array(
  11430.                     'name' => 'accounting_year_start',
  11431.                     //                    'CompanyId'=>$this->getLoggedUserCompanyId($request)
  11432.                 )
  11433.             );
  11434.         $today = new \DateTime();
  11435.         $start_date $new_cc $new_cc->getData() : "";
  11436.         //        $start_date=($request->query->has('start_date'))?$request->query->get('start_date'):"";
  11437.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : $today->format('F d, Y');
  11438.         //        $end_date="";
  11439.         $em $this->getDoctrine()->getManager();
  11440.         $url $this->generateUrl('view_ledger_head', array(), true);
  11441.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  11442.         $details Accounts::GetFiscalClosing($em1$start_date$end_date$url);
  11443.         $grouped_heads Accounts::GroupedHeads($em);
  11444.         //        if($mis_start_date!=''&&$mis_start_date!=0)
  11445.         //            $start_date=$mis_start_date;
  11446.         //        if($mis_end_date!=''&&$mis_start_date!=0)
  11447.         //            $end_date=$mis_end_date;
  11448.         return $this->render(
  11449.             '@Application/pages/accounts/settings/fiscal_closing.html.twig',
  11450.             array(
  11451.                 'page_title' => 'Fiscal Closing',
  11452.                 'company_name' => $company_data->getName(),
  11453.                 'company_data' => $company_data,
  11454.                 'start_date' => $start_date,
  11455.                 'end_date' => $end_date,
  11456.                 'details' => $details
  11457.             )
  11458.         );
  11459.     }
  11460.     public function ViewTrialBalance(Request $request)
  11461.     {
  11462.         $em $this->getDoctrine()->getManager();
  11463.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  11464.         $new_cc $this->getDoctrine()
  11465.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  11466.             ->findOneBy(
  11467.                 array(
  11468.                     'name' => 'accounting_year_start',
  11469.                 )
  11470.             );
  11471. //        $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc ? $new_cc->getData() : "");
  11472.         $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : "";
  11473.         $skip_parent_head = ($request->query->has('skip_parent_head')) ? $request->query->get('skip_parent_head') : 0;
  11474.         $cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
  11475.         $expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 1;
  11476.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('Y-m-d');
  11477.         $em $this->getDoctrine()->getManager();
  11478.         $url $this->generateUrl('view_ledger_head', array(), true);
  11479.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  11480.         $bs_details = [];
  11481.         $get_kids_sql "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
  11482.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  11483.         
  11484.         $query_output $stmt;
  11485.         $max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
  11486.         $budgetVarianceSettings = [];
  11487.         $budgetEnabled 0;
  11488.         $budgetEnabled 0;
  11489.         $budgetVarianceSettings = [];
  11490.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  11491.         $allocationFilters $allocationSupportData['allocation_filters'];
  11492.         if ($request->query->has('budget_variance_enabled')) {
  11493.             $budgetVarianceSettings['enabled'] = $request->query->get('budget_variance_enabled');
  11494.             $budgetEnabled $request->query->get('budget_variance_enabled');
  11495.             $budgetVarianceSettings['scale'] = ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 1;
  11496.             $budgetVarianceSettings['budgetId'] = ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 1;
  11497.         }
  11498.         $tb_details Accounts::GetTrialBalance($em$cur_level$start_date$end_date$url, [], $expand_level'view'$skip_parent_head$budgetVarianceSettings$request->get('forceShowTrans'0), $allocationFilters);
  11499.         //        $grouped_heads=Accounts::GroupedHeads($em);
  11500.         //        if($mis_start_date!=''&&$mis_start_date!=0)
  11501.         //            $start_date=$mis_start_date;
  11502.         //        if($mis_end_date!=''&&$mis_start_date!=0)
  11503.         //            $end_date=$mis_end_date
  11504.         return $this->render(
  11505.             '@Accounts/pages/views/trial_balance.html.twig',
  11506.             array(
  11507.                 'page_title' => 'Trial Balance',
  11508.                 'company_name' => $company_data->getName(),
  11509.                 'company_data' => $company_data,
  11510.                 'details' => $bs_details,
  11511.                 'tb_details' => $tb_details,
  11512.                 'skip_parent_head' => $skip_parent_head,
  11513.                 'start_date' => $start_date,
  11514.                 'end_date' => $end_date,
  11515.                 'max_level' => $max_level,
  11516.                 'budget_variance_enabled' => $budgetEnabled,
  11517.                 'currBudgetList' => $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findBy(
  11518.                     array(
  11519.                         //                        'budgetId'=>$id, ///material
  11520.                         'CompanyId' => $this->getLoggedUserCompanyId($request), ///material
  11521.                     )
  11522.                 ),
  11523.                 'scale_variance' => ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 0,
  11524.                 'budgetId' => ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 0,
  11525.                 'expand_level' => $expand_level,
  11526.                 'cur_level' => $cur_level,
  11527.                 'allocation_filters' => $allocationFilters,
  11528.                 'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  11529.                 'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  11530.                 'project_list' => $allocationSupportData['project_list'],
  11531.                 'branch_list' => $allocationSupportData['branch_list'],
  11532.                 'cost_centers' => $allocationSupportData['cost_centers'],
  11533.                 //                'end_date'=>new \DateTime(),
  11534.             )
  11535.         );
  11536.     }
  11537.     public function ViewTrialBalanceForApp(Request $request)
  11538.     {
  11539.         $em $this->getDoctrine()->getManager();
  11540.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  11541.         $new_cc $this->getDoctrine()
  11542.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  11543.             ->findOneBy(
  11544.                 array(
  11545.                     'name' => 'accounting_year_start',
  11546.                 )
  11547.             );
  11548. //        $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc ? $new_cc->getData() : "");
  11549.         $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : "";
  11550.         $skip_parent_head = ($request->query->has('skip_parent_head')) ? $request->query->get('skip_parent_head') : 0;
  11551.         $cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
  11552.         $expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 1;
  11553.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('Y-m-d');
  11554.         $em $this->getDoctrine()->getManager();
  11555.         $url $this->generateUrl('view_ledger_head', array(), true);
  11556.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  11557.         $bs_details = [];
  11558.         $get_kids_sql "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
  11559.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  11560.         
  11561.         $query_output $stmt;
  11562.         $max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
  11563.         $budgetVarianceSettings = [];
  11564.         $budgetEnabled 0;
  11565.         $budgetEnabled 0;
  11566.         $budgetVarianceSettings = [];
  11567.         if ($request->query->has('budget_variance_enabled')) {
  11568.             $budgetVarianceSettings['enabled'] = $request->query->get('budget_variance_enabled');
  11569.             $budgetEnabled $request->query->get('budget_variance_enabled');
  11570.             $budgetVarianceSettings['scale'] = ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 1;
  11571.             $budgetVarianceSettings['budgetId'] = ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 1;
  11572.         }
  11573.         $tb_details Accounts::GetTrialBalance($em$cur_level$start_date$end_date$url, [], $expand_level'view'$skip_parent_head$budgetVarianceSettings);
  11574.         //        $grouped_heads=Accounts::GroupedHeads($em);
  11575.         //        if($mis_start_date!=''&&$mis_start_date!=0)
  11576.         //            $start_date=$mis_start_date;
  11577.         //        if($mis_end_date!=''&&$mis_start_date!=0)
  11578.         //            $end_date=$mis_end_date
  11579.         $heads_0 = isset($tb_details['heads'][0]) ? $tb_details['heads'][0] : [];
  11580.         $calculated_values = [];
  11581.         foreach ($heads_0 as $item) {
  11582.             $name $item['name'] ?? 'Unknown';
  11583.             $head_balance $item['head_data']['head_balance'] ?? 0;
  11584.             $head_debit $item['head_data']['head_debit'] ?? 0;
  11585.             $head_credit $item['head_data']['head_credit'] ?? 0;
  11586.             $value abs($head_debit $head_credit);
  11587.             $calculated_values[] = [
  11588.                 'tag' => $name,
  11589.                 'debit_credit' => round($value2),
  11590.                 'budget_variance' => 0
  11591.             ];
  11592.         }
  11593.         return new JsonResponse([
  11594.             'page_title' => 'Trial Balance',
  11595.             'calculated_values' => $calculated_values
  11596.         ]);
  11597.     }
  11598.     public function ViewFinancialReport(Request $request)
  11599.     {
  11600.         $em $this->getDoctrine()->getManager();
  11601.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  11602.         $new_cc $this->getDoctrine()
  11603.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  11604.             ->findOneBy(
  11605.                 array(
  11606.                     'name' => 'accounting_year_start',
  11607.                 )
  11608.             );
  11609.         $start_date $new_cc $new_cc->getData() : "";
  11610.         $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc $new_cc->getData() : "");
  11611.         $cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
  11612.         $expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 3;
  11613.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('F d, Y');
  11614.         $em $this->getDoctrine()->getManager();
  11615.         $url $this->generateUrl('view_ledger_head', array(), true);
  11616.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  11617.         $bs_details = [];
  11618.         $get_kids_sql "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
  11619.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  11620.         
  11621.         $query_output $stmt;
  11622.         $max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
  11623.         //*************Data generation start here
  11624.         $report_cats = [1234];
  11625.         $periodic 0;
  11626.         $last_entries_count 1;
  11627. //        if ($request->query->has('print_all')) {
  11628. //            if ($request->query->get('print_all') == 1)
  11629. //                $report_cats = [1, 2, 3, 4];
  11630. //        } else {
  11631. //            if ($request->query->has('statement'))
  11632. //                $report_cats = $request->query->get('statement');
  11633. //        }
  11634.         if ($request->query->has('periodic'))
  11635.             if ($request->query->get('periodic') == 1)
  11636.                 $periodic 1;
  11637.         if ($request->query->has('last_entries'))
  11638.             $last_entries_count $request->query->get('last_entries');
  11639.         //lets get prev fiscal closing data
  11640.         $new_cc_list $this->getDoctrine()
  11641.             ->getRepository('ApplicationBundle\\Entity\\FiscalClosing')
  11642.             ->findBy(
  11643.                 array(),
  11644.                 array(
  11645.                     'closingId' => 'DESC'
  11646.                 ),
  11647.                 $last_entries_count
  11648.             );
  11649.         $prev_data_list = array();
  11650.         $prev_data_amounts = array();
  11651.         $prev_data_amounts_for_is = array();
  11652.         $prev_data_amounts_for_cf = array();
  11653.         if (!empty($new_cc_list)) {
  11654.             $prev_data = array();
  11655.             foreach ($new_cc_list as $new_cc) {
  11656.                 $prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
  11657.                 $prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
  11658.                 $prev_data['closing_data'] = array();
  11659.                 $last_f_c_data json_decode($new_cc->getClosingData(), true);
  11660.                 //                foreach ($last_f_c_data['heads'] as $key => $entry) {
  11661.                 //                    $add_data = array(
  11662.                 //                        'head_id' => $entry,
  11663.                 //                        'balance' => $last_f_c_data['balance'][$key],
  11664.                 //                        'recon_balance' => $last_f_c_data['recon_balance'][$key]
  11665.                 //                    );
  11666.                 //                    $prev_data['closing_data'][$entry] = $add_data;
  11667.                 //                    $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
  11668.                 //                }
  11669.                 foreach ($last_f_c_data as $key => $entry) {
  11670.                     $add_data = array(
  11671.                         'head_id' => $key,
  11672.                         'balance' => $entry,
  11673.                         'recon_balance' => $entry
  11674.                     );
  11675.                     $prev_data['closing_data'][$key] = $add_data;
  11676.                     $prev_data_amounts[$key][] = $entry;
  11677.                 }
  11678.                 $prev_data_list[] = $prev_data;
  11679.             }
  11680.         }
  11681.         if (!empty($new_cc_list)) {
  11682.             $prev_data = array();
  11683.             foreach ($new_cc_list as $new_cc) {
  11684.                 $prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
  11685.                 $prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
  11686.                 $prev_data['closing_data'] = array();
  11687.                 $last_f_c_data json_decode($new_cc->getBeforeClosingData(), true);
  11688.                 if ($last_f_c_data == null$last_f_c_data = [];
  11689.                 //                foreach ($last_f_c_data['heads'] as $key => $entry) {
  11690.                 //                    $add_data = array(
  11691.                 //                        'head_id' => $entry,
  11692.                 //                        'balance' => $last_f_c_data['balance'][$key],
  11693.                 //                        'recon_balance' => $last_f_c_data['recon_balance'][$key]
  11694.                 //                    );
  11695.                 //                    $prev_data['closing_data'][$entry] = $add_data;
  11696.                 //                    $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
  11697.                 //                }
  11698.                 foreach ($last_f_c_data as $key => $entry) {
  11699.                     $add_data = array(
  11700.                         'head_id' => $key,
  11701.                         'balance' => $entry,
  11702.                         'recon_balance' => $entry
  11703.                     );
  11704.                     $prev_data['closing_data'][$key] = $add_data;
  11705.                     $prev_data_amounts_for_is[$key][] = $entry;
  11706.                 }
  11707.                 //                $prev_data_list[]=$prev_data;
  11708.             }
  11709.         }
  11710.         $balance_sheet_data = [];
  11711.         $is_data = [];
  11712.         $cf_data = [];
  11713.         $oe_data = [];
  11714.         $wacc_data = [];
  11715.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  11716.         $allocationFilters $allocationSupportData['allocation_filters'];
  11717.         //now get balance sheet if needed
  11718.         if (in_array(1$report_cats)) {
  11719.             $balance_sheet_data Accounts::GetBalanceSheet($em$cur_level$start_date$end_date$url, [], $expand_level'view'$periodic$prev_data_amounts$allocationFilters);
  11720.         }
  11721.         $CurrentRoute $request->attributes->get('_route');
  11722.         if ($CurrentRoute == 'app_get_financial_report') {
  11723.             if (in_array(1$report_cats)) {
  11724.                 $balance_sheet_data Accounts::GetBalanceSheetForApp($em$cur_level$start_date$end_date$url, [], $expand_level'view'$periodic$prev_data_amounts$allocationFilters);
  11725.             }
  11726.             return new JsonResponse([
  11727.                 'success' => true,
  11728.                 'message' => "Financial Report data fetch",
  11729.                 'data' => $balance_sheet_data
  11730.             ]);
  11731.         }
  11732.         //now the income statement
  11733. //        if (in_array(2, $report_cats)) {
  11734. //            $is_data = Accounts::GetIncomeStatement($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'print', $periodic, $prev_data_amounts_for_is);
  11735. //        }
  11736.         if (in_array(2$report_cats)) {
  11737.             $markerHashes array_column(AccountsConstant::$incomeConfigData'markerHash');
  11738.             $is_data Accounts::GetBalanceOnDateByMarkerHash($em$end_date, [], [AccountsConstant::OPERATING_REVENUE_PARENTAccountsConstant::COGS_PARENTAccountsConstant::NONOPERATING_REVENUE_PARENTAccountsConstant::ADMIN_EXPENSE_PARENTAccountsConstant::SELLING_EXPENSE_PARENTAccountsConstant::MARKETING_EXPENSE_PARENTAccountsConstant::ADVERTISEMENT_EXPENSE_PARENTAccountsConstant::FINANCIAL_EXPENSE_PARENTAccountsConstant::TAX_EXPENSE_PARENTAccountsConstant::OCI_RECLASSIFIABLE_PARENTAccountsConstant::OCI_NONRECLASSIFIABLE_PARENT], 1, [], $allocationFilters);
  11739.             $is_data['tree'] = "";
  11740.             $incomeConfigData AccountsConstant::$incomeConfigData;
  11741.             $currBal 0;
  11742.             $currBalByClosingDate = array();
  11743.             $totalBalByClosingDate = array();
  11744.             $totalBal 0;
  11745. //            dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
  11746.             foreach ($is_data['fiscal_years'] as $fiscal_year) {
  11747.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  11748.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  11749.             }
  11750.             foreach ($incomeConfigData as $config) {
  11751.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  11752.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  11753.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  11754.                     $row .= "<td ></td>";
  11755.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  11756.                         $row .= "<td style='text-align: right' ></td>";
  11757.                     }
  11758.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  11759.                     //                    $row.="<td >pika$currBal</td>";
  11760.                     if ($currBal >= 0)
  11761.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  11762.                     else
  11763.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  11764.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  11765.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  11766.                         if ($currValByFiscalYear >= 0)
  11767.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  11768.                         else
  11769.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  11770.                     }
  11771.                 } else {
  11772.                     $currVal 0;
  11773.                     $currentMarkerData null;
  11774.                     if (isset($is_data[$config['markerHash']])) {
  11775.                         $currentMarkerData $is_data[$config['markerHash']];
  11776.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  11777.                     }
  11778.                     if ($currVal >= 0)
  11779.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  11780.                     else
  11781.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  11782.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  11783.                         if ($currentMarkerData) {
  11784.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  11785.                             if ($currVal >= 0)
  11786.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  11787.                             else
  11788.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  11789.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  11790.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  11791.                         } else {
  11792.                             $row .= "<td style='text-align: right' ></td>";
  11793.                         }
  11794.                     }
  11795.                     $totalBal += $currVal;
  11796.                     $currBal += $currVal;
  11797.                 }
  11798.                 $row .= "</tr>";
  11799.                 if (isset($config['resetCurrentBal'])) {
  11800.                     if ($config['resetCurrentBal'] == true)
  11801.                         $currBal 0;
  11802.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  11803.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  11804.                     }
  11805.                 }
  11806.                 $is_data['tree'] .= $row;
  11807.                 $is_data['grandTotal'] = $totalBal;
  11808.                 $is_data['grandTotal'] = $totalBal;
  11809.                 $is_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  11810.             }
  11811.             //For Profit loss
  11812.             $finalProfit $currBal;
  11813.             $oe_data['_IS_PROFIT_'] = [
  11814.                 'transDr' => 0,
  11815.                 'transCr' => $finalProfit,
  11816.                 'dataByFiscalClosing' => []
  11817.             ];
  11818.         }
  11819.         if ($CurrentRoute == 'app_get_financial_report_by_marker_hash') {
  11820.             $markerHashes array_column(AccountsConstant::$incomeConfigData'markerHash');
  11821.             $is_data Accounts::GetBalanceOnDateByMarkerHash($em$end_date, [], [
  11822.                 AccountsConstant::OPERATING_REVENUE_PARENT,
  11823.                 AccountsConstant::COGS_PARENT,
  11824.                 AccountsConstant::NONOPERATING_REVENUE_PARENT,
  11825.                 AccountsConstant::ADMIN_EXPENSE_PARENT,
  11826.                 AccountsConstant::SELLING_EXPENSE_PARENT,
  11827.                 AccountsConstant::MARKETING_EXPENSE_PARENT,
  11828.                 AccountsConstant::ADVERTISEMENT_EXPENSE_PARENT,
  11829.                 AccountsConstant::FINANCIAL_EXPENSE_PARENT,
  11830.                 AccountsConstant::TAX_EXPENSE_PARENT,
  11831.                 AccountsConstant::OCI_RECLASSIFIABLE_PARENT,
  11832.                 AccountsConstant::OCI_NONRECLASSIFIABLE_PARENT
  11833.             ], 1);
  11834.             $incomeConfigData AccountsConstant::$incomeConfigData;
  11835.             $currBal 0;
  11836.             $currBalByClosingDate = [];
  11837.             $totalBalByClosingDate = [];
  11838.             $totalBal 0;
  11839.             foreach ($is_data['fiscal_years'] as $fiscal_year) {
  11840.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  11841.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  11842.             }
  11843.             $treeArray = [];
  11844.             foreach ($incomeConfigData as $config) {
  11845.                 $node = [
  11846.                     'title' => $config['title'],
  11847.                     'bold' => $config['bold'],
  11848.                     'paddingMultiplier' => $config['paddingMultiplier'],
  11849.                     'currentValue' => null,
  11850.                     'yearlyValues' => [],
  11851.                 ];
  11852.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  11853.                     $node['currentValue'] = null;
  11854.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  11855.                         $node['yearlyValues'][$fiscal_year['closing_end_date']] = null;
  11856.                     }
  11857.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  11858.                     $node['currentValue'] = $currBal;
  11859.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  11860.                         $node['yearlyValues'][$fiscal_year['closing_end_date']] = $currBalByClosingDate[$fiscal_year['closing_end_date']];
  11861.                     }
  11862.                 } else {
  11863.                     $currVal 0;
  11864.                     $currentMarkerData null;
  11865.                     if (isset($is_data[$config['markerHash']])) {
  11866.                         $currentMarkerData $is_data[$config['markerHash']];
  11867.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  11868.                     }
  11869.                     $node['currentValue'] = $currVal;
  11870.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  11871.                         if ($currentMarkerData) {
  11872.                             $fiscalDate $fiscal_year['closing_end_date'];
  11873.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscalDate]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscalDate]['transDr'];
  11874.                             $node['yearlyValues'][$fiscalDate] = $currFiscalTransVal;
  11875.                             $currBalByClosingDate[$fiscalDate] += $currFiscalTransVal;
  11876.                             $totalBalByClosingDate[$fiscalDate] += $currFiscalTransVal;
  11877.                         } else {
  11878.                             $node['yearlyValues'][$fiscal_year['closing_end_date']] = null;
  11879.                         }
  11880.                     }
  11881.                     $totalBal += $currVal;
  11882.                     $currBal += $currVal;
  11883.                 }
  11884.                 if (isset($config['resetCurrentBal']) && $config['resetCurrentBal'] === true) {
  11885.                     $currBal 0;
  11886.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  11887.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  11888.                     }
  11889.                 }
  11890.                 $treeArray[] = $node;
  11891.             }
  11892.             // Helper function to build nested tree by paddingMultiplier
  11893.             function buildNestedTree(array $flatList)
  11894.             {
  11895.                 $stack = [];
  11896.                 $tree = [];
  11897.                 foreach ($flatList as &$node) {
  11898.                     unset($node['children']); // clear any existing children
  11899.                     // Pop stack while top has equal or greater paddingMultiplier
  11900.                     while (!empty($stack) && end($stack)['paddingMultiplier'] >= $node['paddingMultiplier']) {
  11901.                         array_pop($stack);
  11902.                     }
  11903.                     if (empty($stack)) {
  11904.                         // Root node
  11905.                         $tree[] = &$node;
  11906.                     } else {
  11907.                         // Add as child to last node in stack
  11908.                         $parent = &$stack[count($stack) - 1];
  11909.                         if (!isset($parent['children'])) {
  11910.                             $parent['children'] = [];
  11911.                         }
  11912.                         $parent['children'][] = &$node;
  11913.                     }
  11914.                     $stack[] = &$node;
  11915.                 }
  11916.                 return $tree;
  11917.             }
  11918.             $nestedTree buildNestedTree($treeArray);
  11919.             $response = [
  11920.                 'tree' => $nestedTree,
  11921.                 'grandTotal' => $totalBal,
  11922.                 'grandTotalByClosingDate' => $totalBalByClosingDate,
  11923.                 'fiscalYears' => $is_data['fiscal_years'],
  11924.             ];
  11925.             $finalProfit $currBal;
  11926.             $oe_data['_IS_PROFIT_'] = [
  11927.                 'transDr' => 0,
  11928.                 'transCr' => $finalProfit,
  11929.                 'dataByFiscalClosing' => []
  11930.             ];
  11931.             return new JsonResponse($response);
  11932.         }
  11933.         //now get cash flow
  11934.         if (in_array(3$report_cats)) {
  11935.             $markerHashes array_column(AccountsConstant::$cashFlowConfigData'markerHash');
  11936.             $cf_data Accounts::GetBalanceOnDateByMarkerHash($em$end_date, [], [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENTAccountsConstant::CUSTOMER_RECEIVABLE_PARENTAccountsConstant::SUPPLIER_PAYABLE_PARENTAccountsConstant::OPERATING_EXPENSE_PARENTAccountsConstant::GENERAL_EMPLOYEE_PARENTAccountsConstant::INTEREST_RECEIVABLE_PARENTAccountsConstant::FINANCIAL_EXPENSE_PARENTAccountsConstant::TAX_EXPENSE_PARENTAccountsConstant::FIXED_ASSET_PARENTAccountsConstant::ASSET_SALE_PARENTAccountsConstant::INVESTMENT_PARENTAccountsConstant::NONOPERATING_REVENUE_PARENTAccountsConstant::LOAN_RECEIVED_PARENTAccountsConstant::LOAN_REPAYMENT_PARENTAccountsConstant::DIVIDEND_PAYMENT_PARENT], 1, [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT], $allocationFilters);
  11937.             $openingData Accounts::GetBalanceOnDateByMarkerHash(
  11938.                 $em,
  11939.                 $start_date,
  11940.                 [],
  11941.                 [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],
  11942.                 1,
  11943.                 [],
  11944.                 $allocationFilters
  11945.             );
  11946.             $closingData Accounts::GetBalanceOnDateByMarkerHash(
  11947.                 $em,
  11948.                 $end_date,
  11949.                 [],
  11950.                 [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],
  11951.                 1,
  11952.                 [],
  11953.                 $allocationFilters
  11954.             );
  11955.             $openingCashBalance = isset($openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT])
  11956.                 ? $openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transCr'] - $openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transDr']
  11957.                 : 0;
  11958.             $closingCashBalance = isset($closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT])
  11959.                 ? $closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transCr'] - $closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transDr']
  11960.                 : 0;
  11961.             $cf_data['_CASH_OPENING_'] = [
  11962.                 'transDr' => 0,
  11963.                 'transCr' => $openingCashBalance,
  11964.                 'dataByFiscalClosing' => []
  11965.             ];
  11966.             $cf_data['_CASH_CLOSING_'] = [
  11967.                 'transDr' => 0,
  11968.                 'transCr' => $closingCashBalance,
  11969.                 'dataByFiscalClosing' => []
  11970.             ];
  11971.             $cf_data['tree'] = "";
  11972.             $cashFlowConfigData AccountsConstant::$cashFlowConfigData;
  11973.             $currBal 0;
  11974.             $currBalByClosingDate = array();
  11975.             $totalBalByClosingDate = array();
  11976.             $totalBal 0;
  11977. //            dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
  11978.             foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  11979.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  11980.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  11981.             }
  11982.             foreach ($cashFlowConfigData as $config) {
  11983.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  11984.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  11985.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  11986.                     $row .= "<td ></td>";
  11987.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  11988.                         $row .= "<td style='text-align: right' ></td>";
  11989.                     }
  11990.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  11991.                     //                    $row.="<td >pika$currBal</td>";
  11992.                     if ($currBal >= 0)
  11993.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  11994.                     else
  11995.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  11996.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  11997.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  11998.                         if ($currValByFiscalYear >= 0)
  11999.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  12000.                         else
  12001.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  12002.                     }
  12003.                 } else {
  12004.                     $currVal 0;
  12005.                     $currentMarkerData null;
  12006.                     if (isset($cf_data[$config['markerHash']])) {
  12007.                         $currentMarkerData $cf_data[$config['markerHash']];
  12008.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  12009.                     }
  12010.                     if ($currVal >= 0)
  12011.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  12012.                     else
  12013.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  12014.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12015.                         if ($currentMarkerData) {
  12016.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  12017.                             if ($currVal >= 0)
  12018.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  12019.                             else
  12020.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  12021.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12022.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12023.                         } else {
  12024.                             $row .= "<td style='text-align: right' ></td>";
  12025.                         }
  12026.                     }
  12027.                     $totalBal += $currVal;
  12028.                     $currBal += $currVal;
  12029.                 }
  12030.                 $row .= "</tr>";
  12031.                 if (isset($config['resetCurrentBal'])) {
  12032.                     if ($config['resetCurrentBal'] == true)
  12033.                         $currBal 0;
  12034.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12035.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12036.                     }
  12037.                 }
  12038.                 $cf_data['tree'] .= $row;
  12039.                 $cf_data['grandTotal'] = $totalBal;
  12040.                 $cf_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  12041.             }
  12042.         }
  12043.         if (in_array(4$report_cats)) {
  12044.             $markerHashes array_column(AccountsConstant::$changesInEquityConfigData'markerHash');
  12045.             $oe_data Accounts::GetBalanceOnDateByMarkerHash($em$end_date, [], [AccountsConstant::SHARE_CAPITAL_PARENTAccountsConstant::RETAINED_EARNING_PARENTAccountsConstant::REVALUATION_SURPLUS_PARENTAccountsConstant::DIVIDEND_PAYMENT_PARENTAccountsConstant::OCI_RECLASSIFIABLE_PARENTAccountsConstant::OCI_NONRECLASSIFIABLE_PARENT], 1, [], $allocationFilters);
  12046.             if (isset($is_data['grandTotal'])) {
  12047.                 $finalProfit $is_data['grandTotal'];
  12048.             } else {
  12049.                 $finalProfit 0;
  12050.             }
  12051.             $oe_data['_IS_PROFIT_'] = [
  12052.                 'transDr' => 0,
  12053.                 'transCr' => $finalProfit,
  12054.                 'dataByFiscalClosing' => []
  12055.             ];
  12056.             $oe_data['tree'] = "";
  12057.             $changesInEquityConfigData AccountsConstant::$changesInEquityConfigData;
  12058.             $currBal 0;
  12059.             $currBalByClosingDate = array();
  12060.             $totalBalByClosingDate = array();
  12061.             $totalBal 0;
  12062. //            dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
  12063.             foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12064.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12065.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12066.             }
  12067.             foreach ($changesInEquityConfigData as $config) {
  12068.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  12069.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  12070.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  12071.                     $row .= "<td ></td>";
  12072.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12073.                         $row .= "<td style='text-align: right' ></td>";
  12074.                     }
  12075.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  12076.                     //                    $row.="<td >pika$currBal</td>";
  12077.                     if ($currBal >= 0)
  12078.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  12079.                     else
  12080.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  12081.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12082.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  12083.                         if ($currValByFiscalYear >= 0)
  12084.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  12085.                         else
  12086.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  12087.                     }
  12088.                 } else {
  12089.                     $currVal 0;
  12090.                     $currentMarkerData null;
  12091.                     if (isset($oe_data[$config['markerHash']])) {
  12092.                         $currentMarkerData $oe_data[$config['markerHash']];
  12093.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  12094.                     }
  12095.                     if ($currVal >= 0)
  12096.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  12097.                     else
  12098.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  12099.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12100.                         if ($currentMarkerData) {
  12101.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  12102.                             if ($currVal >= 0)
  12103.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  12104.                             else
  12105.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  12106.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12107.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12108.                         } else {
  12109.                             $row .= "<td style='text-align: right' ></td>";
  12110.                         }
  12111.                     }
  12112.                     $totalBal += $currVal;
  12113.                     $currBal += $currVal;
  12114.                 }
  12115.                 $row .= "</tr>";
  12116.                 if (isset($config['resetCurrentBal'])) {
  12117.                     if ($config['resetCurrentBal'] == true)
  12118.                         $currBal 0;
  12119.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12120.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12121.                     }
  12122.                 }
  12123.                 $oe_data['tree'] .= $row;
  12124.                 $oe_data['grandTotal'] = $totalBal;
  12125.                 $oe_data['grandTotal'] = $totalBal;
  12126.                 $oe_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  12127.             }
  12128.         }
  12129.         if (in_array(5$report_cats)) {
  12130.             $wacc_data Accounts::GetWaccStatement($em$cur_level$start_date$end_date$url$periodic$prev_data_amounts_for_cf$expand_level);
  12131.         }
  12132.         //now get prev balance totals
  12133.         //*******Data generation Ends here
  12134.         $provisional_option 1//include
  12135.         if ($request->query->has('provisional')) {
  12136.             $provisional_option $request->query->get('provisional'); //include
  12137.         }
  12138.         // now lets get its tree for the description
  12139.         //        $id_list_for_ledger=[];
  12140.         //        if($request->query->has('id_list') )
  12141.         //            $id_list_for_ledger=explode(',',$request->query->get('id_list'));
  12142.         //        if($id=0&&empty($id_list))
  12143.         //            $id_list_for_ledger=[0];
  12144.         //        $ledger_det=[];
  12145.         //        $head_name_list=[];
  12146.         //        foreach($id_list_for_ledger as $ind_head_id) {
  12147.         //            $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
  12148.         //            $ledger_det[$ind_head_id]=$ledger_data;
  12149.         //            $head_name_list[]=$ledger_data['basic_data']['name'];
  12150.         //        }
  12151.         //        $grouped_heads=Accounts::GroupedHeads($em);
  12152.         //        $grouped_heads=Accounts::GroupedHeads($em);
  12153.         //        if($mis_start_date!=''&&$mis_start_date!=0)
  12154.         //            $start_date=$mis_start_date;
  12155.         //        if($mis_end_date!=''&&$mis_start_date!=0)
  12156.         //            $end_date=$mis_end_date;
  12157. //        return new JsonResponse($oe_data);
  12158. //        dump(AccountsConstant::SHARE_CAPITAL_PARENT);
  12159.         return $this->render(
  12160.             '@Accounts/pages/report/view_financial_report.html.twig',
  12161.             array(
  12162.                 'page_title' => 'Financial Statement',
  12163.                 'company_name' => $company_data->getName(),
  12164.                 'company_data' => $company_data,
  12165.                 //                'details'=>$bs_details,
  12166.                 'bs_details' => $balance_sheet_data,
  12167.                 'is_details' => $is_data,
  12168.                 'cf_details' => $cf_data,
  12169.                 'oe_details' => $oe_data,
  12170.                 'prev_data_list' => $prev_data_list,
  12171.                 'report_cats' => $report_cats,
  12172.                 'start_date' => $start_date,
  12173.                 'end_date' => $end_date,
  12174.                 'max_level' => $max_level,
  12175.                 'expand_level' => $expand_level,
  12176.                 'cur_level' => $cur_level,
  12177.                 //                'ledger_data'=>$ledger_det,
  12178.                 'page_header' => 'Ledger',
  12179.                 'document_type' => 'Financial Statement',
  12180.                 'page_header_sub' => 'Add',
  12181.                 'head_list' => Accounts::HeadList($em),
  12182.                 'provisional' => $provisional_option,
  12183.                 //                'type_list'=>$type_list,
  12184.                 //            'child_list'=>$child_list,
  12185.                 //                'trans_data_by_closing'=>$trans_data_by_closing,
  12186.                 'item_data' => [],
  12187.                 'received' => 2,
  12188.                 'return' => 1,
  12189.                 'total_w_vat' => 1,
  12190.                 'total_vat' => 1,
  12191.                 'total_wo_vat' => 1,
  12192.                 'invoice_id' => 'abcd1234',
  12193.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12194.                 'created_by' => 'created by',
  12195.                 'created_at' => '',
  12196.                 'red' => 0,
  12197.                 'company_address' => $company_data->getAddress(),
  12198.                 'company_image' => $company_data->getImage(),
  12199.                 'allocation_filters' => $allocationFilters,
  12200.                 'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  12201.                 'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  12202.                 'project_list' => $allocationSupportData['project_list'],
  12203.                 'branch_list' => $allocationSupportData['branch_list'],
  12204.                 'cost_centers' => $allocationSupportData['cost_centers'],
  12205.                 //                'p'=>$p
  12206.             )
  12207.         );
  12208. //        return $this->render(
  12209. //            '@Accounts/pages/report/view_financial_report.html.twig',
  12210. //            array(
  12211. //                'page_title' => 'Financial Statements',
  12212. //                'company_name' => $company_data->getName(),
  12213. //                'company_data' => $company_data,
  12214. //                'details' => $bs_details,
  12215. //                'tb_details' => $tb_details,
  12216. //                'start_date' => $start_date,
  12217. //
  12218. //                'end_date' => $end_date,
  12219. //                'print_all' => $print_all,
  12220. //                'max_level' => $max_level,
  12221. //                'expand_level' => $expand_level,
  12222. //                'cur_level' => $cur_level,
  12223. //
  12224. //                //                'end_date'=>new \DateTime(),
  12225. //            )
  12226. //        );
  12227.     }
  12228.     public function TestController(Request $request)
  12229.     {
  12230.         $em $this->getDoctrine()->getManager();
  12231.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  12232.         $new_cc $this->getDoctrine()
  12233.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  12234.             ->findOneBy(
  12235.                 array(
  12236.                     'name' => 'accounting_year_start',
  12237.                 )
  12238.             );
  12239.         $start_date $new_cc $new_cc->getData() : "";
  12240.         $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc $new_cc->getData() : "");
  12241.         $cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
  12242.         $expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 3;
  12243.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('Y-m-d');
  12244.         $em $this->getDoctrine()->getManager();
  12245.         $url $this->generateUrl('view_ledger_head', array(), true);
  12246.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  12247.         $bs_details = [];
  12248.         $get_kids_sql "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
  12249.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12250.         
  12251.         $query_output $stmt;
  12252.         $max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
  12253.         $report_cats = [1234];
  12254.         $periodic 0;
  12255.         $last_entries_count 1;
  12256.         if ($request->query->has('print_all')) {
  12257.             if ($request->query->get('print_all') == 1)
  12258.                 $report_cats = [1234];
  12259.         } else {
  12260.             if ($request->query->has('statement'))
  12261.                 $report_cats $request->query->get('statement');
  12262.         }
  12263.         if ($request->query->has('periodic'))
  12264.             if ($request->query->get('periodic') == 1)
  12265.                 $periodic 1;
  12266.         if ($request->query->has('last_entries'))
  12267.             $last_entries_count $request->query->get('last_entries');
  12268.         //lets get prev fiscal closing data
  12269.         $new_cc_list $this->getDoctrine()
  12270.             ->getRepository('ApplicationBundle\\Entity\\FiscalClosing')
  12271.             ->findBy(
  12272.                 array(),
  12273.                 array(
  12274.                     'closingId' => 'DESC'
  12275.                 ),
  12276.                 $last_entries_count
  12277.             );
  12278.         $prev_data_list = array();
  12279.         $prev_data_amounts = array();
  12280.         $prev_data_amounts_for_is = array();
  12281.         $prev_data_amounts_for_cf = array();
  12282.         if (!empty($new_cc_list)) {
  12283.             $prev_data = array();
  12284.             foreach ($new_cc_list as $new_cc) {
  12285.                 $prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
  12286.                 $prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
  12287.                 $prev_data['closing_data'] = array();
  12288.                 $last_f_c_data json_decode($new_cc->getClosingData(), true);
  12289.                 //                foreach ($last_f_c_data['heads'] as $key => $entry) {
  12290.                 //                    $add_data = array(
  12291.                 //                        'head_id' => $entry,
  12292.                 //                        'balance' => $last_f_c_data['balance'][$key],
  12293.                 //                        'recon_balance' => $last_f_c_data['recon_balance'][$key]
  12294.                 //                    );
  12295.                 //                    $prev_data['closing_data'][$entry] = $add_data;
  12296.                 //                    $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
  12297.                 //                }
  12298.                 foreach ($last_f_c_data as $key => $entry) {
  12299.                     $add_data = array(
  12300.                         'head_id' => $key,
  12301.                         'balance' => $entry,
  12302.                         'recon_balance' => $entry
  12303.                     );
  12304.                     $prev_data['closing_data'][$key] = $add_data;
  12305.                     $prev_data_amounts[$key][] = $entry;
  12306.                 }
  12307.                 $prev_data_list[] = $prev_data;
  12308.             }
  12309.         }
  12310.         if (!empty($new_cc_list)) {
  12311.             $prev_data = array();
  12312.             foreach ($new_cc_list as $new_cc) {
  12313.                 $prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
  12314.                 $prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
  12315.                 $prev_data['closing_data'] = array();
  12316.                 $last_f_c_data json_decode($new_cc->getBeforeClosingData(), true);
  12317.                 if ($last_f_c_data == null$last_f_c_data = [];
  12318.                 //                foreach ($last_f_c_data['heads'] as $key => $entry) {
  12319.                 //                    $add_data = array(
  12320.                 //                        'head_id' => $entry,
  12321.                 //                        'balance' => $last_f_c_data['balance'][$key],
  12322.                 //                        'recon_balance' => $last_f_c_data['recon_balance'][$key]
  12323.                 //                    );
  12324.                 //                    $prev_data['closing_data'][$entry] = $add_data;
  12325.                 //                    $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
  12326.                 //                }
  12327.                 foreach ($last_f_c_data as $key => $entry) {
  12328.                     $add_data = array(
  12329.                         'head_id' => $key,
  12330.                         'balance' => $entry,
  12331.                         'recon_balance' => $entry
  12332.                     );
  12333.                     $prev_data['closing_data'][$key] = $add_data;
  12334.                     $prev_data_amounts_for_is[$key][] = $entry;
  12335.                 }
  12336.                 //                $prev_data_list[]=$prev_data;
  12337.             }
  12338.         }
  12339.         $balance_sheet_data = [];
  12340.         $is_data = [];
  12341.         $cf_data = [];
  12342.         $oe_data = [];
  12343.         $wacc_data = [];
  12344.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  12345.         $allocationFilters $allocationSupportData['allocation_filters'];
  12346.         //now get balance sheet if needed
  12347.         if (in_array(1$report_cats)) {
  12348.             $balance_sheet_data Accounts::GetBalanceSheet($em$cur_level$start_date$end_date$url, [], $expand_level'print'$periodic$prev_data_amounts$allocationFilters);
  12349.         }
  12350.         //now the income statement
  12351.         if (in_array(2$report_cats)) {
  12352.             $is_data Accounts::GetIncomeStatement($em$cur_level$start_date$end_date$url, [], $expand_level'print'$periodic$prev_data_amounts_for_is);
  12353.         }
  12354.         //now get cash flow
  12355.         if (in_array(3$report_cats)) {
  12356.             $cf_data Accounts::GetBalanceOnDateByMarkerHash($em$end_date, [], [], 1, [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENTAccountsConstant::SALES_REVENUE_PARENT], $allocationFilters);
  12357.             $cf_data['tree'] = "";
  12358.             $cashFlowConfigData AccountsConstant::$cashFlowConfigData;
  12359.             return new JsonResponse($cashFlowConfigData);
  12360.             $currBal 0;
  12361.             $currBalByClosingDate = array();
  12362.             $totalBalByClosingDate = array();
  12363.             $totalBal 0;
  12364.             foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12365.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12366.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12367.             }
  12368.             foreach ($cashFlowConfigData as $config) {
  12369.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  12370.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  12371.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  12372.                     $row .= "<td ></td>";
  12373.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12374.                         $row .= "<td style='text-align: right' ></td>";
  12375.                     }
  12376.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  12377.                     //                    $row.="<td >pika$currBal</td>";
  12378.                     if ($currBal >= 0)
  12379.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  12380.                     else
  12381.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  12382.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12383.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  12384.                         if ($currValByFiscalYear >= 0)
  12385.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  12386.                         else
  12387.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  12388.                     }
  12389.                 } else {
  12390.                     $currVal 0;
  12391.                     $currentMarkerData null;
  12392.                     if (isset($cf_data[$config['markerHash']])) {
  12393.                         $currentMarkerData $cf_data[$config['markerHash']];
  12394.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  12395.                     }
  12396.                     if ($currVal >= 0)
  12397.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  12398.                     else
  12399.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  12400.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12401.                         if ($currentMarkerData) {
  12402.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  12403.                             if ($currVal >= 0)
  12404.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  12405.                             else
  12406.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  12407.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12408.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12409.                         } else {
  12410.                             $row .= "<td style='text-align: right' ></td>";
  12411.                         }
  12412.                     }
  12413.                     $totalBal += $currVal;
  12414.                     $currBal += $currVal;
  12415.                 }
  12416.                 $row .= "</tr>";
  12417.                 if (isset($config['resetCurrentBal'])) {
  12418.                     if ($config['resetCurrentBal'] == true)
  12419.                         $currBal 0;
  12420.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12421.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12422.                     }
  12423.                 }
  12424.                 $cf_data['tree'] .= $row;
  12425.                 $cf_data['grandTotal'] = $totalBal;
  12426.                 $cf_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  12427.             }
  12428.         }
  12429.         if (in_array(4$report_cats)) {
  12430.             $oe_data Accounts::GetCashFlowStatement($em$cur_level$start_date$end_date$url$periodic$prev_data_amounts_for_cf$expand_level$allocationFilters);
  12431.         }
  12432.         if (in_array(5$report_cats)) {
  12433.             $wacc_data Accounts::GetWaccStatement($em$cur_level$start_date$end_date$url$periodic$prev_data_amounts_for_cf$expand_level);
  12434.         }
  12435.     }
  12436.     public function PrintFinancialReport(Request $request)
  12437.     {
  12438.         $em $this->getDoctrine()->getManager();
  12439.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  12440.         $new_cc $this->getDoctrine()
  12441.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  12442.             ->findOneBy(
  12443.                 array(
  12444.                     'name' => 'accounting_year_start',
  12445.                 )
  12446.             );
  12447.         $start_date $new_cc $new_cc->getData() : "";
  12448.         $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc $new_cc->getData() : "");
  12449.         $cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
  12450.         $expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 3;
  12451.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('Y-m-d');
  12452.         $em $this->getDoctrine()->getManager();
  12453.         $url $this->generateUrl('view_ledger_head', array(), true);
  12454.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  12455.         $allocationFilters $allocationSupportData['allocation_filters'];
  12456.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  12457.         $bs_details = [];
  12458.         $get_kids_sql "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
  12459.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12460.         
  12461.         $query_output $stmt;
  12462.         $max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
  12463.         //*************Data generation start here
  12464.         $report_cats = [1234];
  12465.         $periodic 0;
  12466.         $last_entries_count 1;
  12467.         if ($request->query->has('print_all')) {
  12468.             if ($request->query->get('print_all') == 1)
  12469.                 $report_cats = [1234];
  12470.         } else {
  12471.             if ($request->query->has('statement'))
  12472.                 $report_cats $request->query->get('statement');
  12473.         }
  12474.         if ($request->query->has('periodic'))
  12475.             if ($request->query->get('periodic') == 1)
  12476.                 $periodic 1;
  12477.         if ($request->query->has('last_entries'))
  12478.             $last_entries_count $request->query->get('last_entries');
  12479.         //lets get prev fiscal closing data
  12480.         $new_cc_list $this->getDoctrine()
  12481.             ->getRepository('ApplicationBundle\\Entity\\FiscalClosing')
  12482.             ->findBy(
  12483.                 array(),
  12484.                 array(
  12485.                     'closingId' => 'DESC'
  12486.                 ),
  12487.                 $last_entries_count
  12488.             );
  12489.         $prev_data_list = array();
  12490.         $prev_data_amounts = array();
  12491.         $prev_data_amounts_for_is = array();
  12492.         $prev_data_amounts_for_cf = array();
  12493.         if (!empty($new_cc_list)) {
  12494.             $prev_data = array();
  12495.             foreach ($new_cc_list as $new_cc) {
  12496.                 $prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
  12497.                 $prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
  12498.                 $prev_data['closing_data'] = array();
  12499.                 $last_f_c_data json_decode($new_cc->getClosingData(), true);
  12500.                 //                foreach ($last_f_c_data['heads'] as $key => $entry) {
  12501.                 //                    $add_data = array(
  12502.                 //                        'head_id' => $entry,
  12503.                 //                        'balance' => $last_f_c_data['balance'][$key],
  12504.                 //                        'recon_balance' => $last_f_c_data['recon_balance'][$key]
  12505.                 //                    );
  12506.                 //                    $prev_data['closing_data'][$entry] = $add_data;
  12507.                 //                    $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
  12508.                 //                }
  12509.                 foreach ($last_f_c_data as $key => $entry) {
  12510.                     $add_data = array(
  12511.                         'head_id' => $key,
  12512.                         'balance' => $entry,
  12513.                         'recon_balance' => $entry
  12514.                     );
  12515.                     $prev_data['closing_data'][$key] = $add_data;
  12516.                     $prev_data_amounts[$key][] = $entry;
  12517.                 }
  12518.                 $prev_data_list[] = $prev_data;
  12519.             }
  12520.         }
  12521.         if (!empty($new_cc_list)) {
  12522.             $prev_data = array();
  12523.             foreach ($new_cc_list as $new_cc) {
  12524.                 $prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
  12525.                 $prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
  12526.                 $prev_data['closing_data'] = array();
  12527.                 $last_f_c_data json_decode($new_cc->getBeforeClosingData(), true);
  12528.                 if ($last_f_c_data == null$last_f_c_data = [];
  12529.                 //                foreach ($last_f_c_data['heads'] as $key => $entry) {
  12530.                 //                    $add_data = array(
  12531.                 //                        'head_id' => $entry,
  12532.                 //                        'balance' => $last_f_c_data['balance'][$key],
  12533.                 //                        'recon_balance' => $last_f_c_data['recon_balance'][$key]
  12534.                 //                    );
  12535.                 //                    $prev_data['closing_data'][$entry] = $add_data;
  12536.                 //                    $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
  12537.                 //                }
  12538.                 foreach ($last_f_c_data as $key => $entry) {
  12539.                     $add_data = array(
  12540.                         'head_id' => $key,
  12541.                         'balance' => $entry,
  12542.                         'recon_balance' => $entry
  12543.                     );
  12544.                     $prev_data['closing_data'][$key] = $add_data;
  12545.                     $prev_data_amounts_for_is[$key][] = $entry;
  12546.                 }
  12547.                 //                $prev_data_list[]=$prev_data;
  12548.             }
  12549.         }
  12550.         $balance_sheet_data = [];
  12551.         $is_data = [];
  12552.         $cf_data = [];
  12553.         $oe_data = [];
  12554.         $wacc_data = [];
  12555.         //now get balance sheet if needed
  12556.         if (in_array(1$report_cats)) {
  12557.             $balance_sheet_data Accounts::GetBalanceSheet($em$cur_level$start_date$end_date$url, [], $expand_level'print'$periodic$prev_data_amounts$allocationFilters);
  12558.         }
  12559.         //now the income statement
  12560. //        if (in_array(2, $report_cats)) {
  12561. //            $is_data = Accounts::GetIncomeStatement($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'print', $periodic, $prev_data_amounts_for_is);
  12562. //        }
  12563.         if (in_array(2$report_cats)) {
  12564.             $markerHashes array_column(AccountsConstant::$incomeConfigData'markerHash');
  12565.             $is_data Accounts::GetBalanceOnDateByMarkerHash($em$end_date, [], [AccountsConstant::OPERATING_REVENUE_PARENTAccountsConstant::COGS_PARENTAccountsConstant::NONOPERATING_REVENUE_PARENTAccountsConstant::ADMIN_EXPENSE_PARENTAccountsConstant::SELLING_EXPENSE_PARENTAccountsConstant::MARKETING_EXPENSE_PARENTAccountsConstant::ADVERTISEMENT_EXPENSE_PARENTAccountsConstant::FINANCIAL_EXPENSE_PARENTAccountsConstant::TAX_EXPENSE_PARENTAccountsConstant::OCI_RECLASSIFIABLE_PARENTAccountsConstant::OCI_NONRECLASSIFIABLE_PARENT], 1, [], $allocationFilters);
  12566.             $is_data['tree'] = "";
  12567.             $incomeConfigData AccountsConstant::$incomeConfigData;
  12568.             $currBal 0;
  12569.             $currBalByClosingDate = array();
  12570.             $totalBalByClosingDate = array();
  12571.             $totalBal 0;
  12572. //            dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
  12573.             foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12574.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12575.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12576.             }
  12577.             foreach ($incomeConfigData as $config) {
  12578.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  12579.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  12580.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  12581.                     $row .= "<td ></td>";
  12582.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12583.                         $row .= "<td style='text-align: right' ></td>";
  12584.                     }
  12585.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  12586.                     //                    $row.="<td >pika$currBal</td>";
  12587.                     if ($currBal >= 0)
  12588.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  12589.                     else
  12590.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  12591.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12592.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  12593.                         if ($currValByFiscalYear >= 0)
  12594.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  12595.                         else
  12596.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  12597.                     }
  12598.                 } else {
  12599.                     $currVal 0;
  12600.                     $currentMarkerData null;
  12601.                     if (isset($is_data[$config['markerHash']])) {
  12602.                         $currentMarkerData $is_data[$config['markerHash']];
  12603.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  12604.                     }
  12605.                     if ($currVal >= 0)
  12606.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  12607.                     else
  12608.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  12609.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12610.                         if ($currentMarkerData) {
  12611.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  12612.                             if ($currVal >= 0)
  12613.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  12614.                             else
  12615.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  12616.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12617.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12618.                         } else {
  12619.                             $row .= "<td style='text-align: right' ></td>";
  12620.                         }
  12621.                     }
  12622.                     $totalBal += $currVal;
  12623.                     $currBal += $currVal;
  12624.                 }
  12625.                 $row .= "</tr>";
  12626.                 if (isset($config['resetCurrentBal'])) {
  12627.                     if ($config['resetCurrentBal'] == true)
  12628.                         $currBal 0;
  12629.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12630.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12631.                     }
  12632.                 }
  12633.                 $is_data['tree'] .= $row;
  12634.                 $is_data['grandTotal'] = $totalBal;
  12635.                 $is_data['grandTotal'] = $totalBal;
  12636.                 $is_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  12637.             }
  12638.             //For Profit loss
  12639.             $finalProfit $currBal;
  12640.             $oe_data['_IS_PROFIT_'] = [
  12641.                 'transDr' => 0,
  12642.                 'transCr' => $finalProfit,
  12643.                 'dataByFiscalClosing' => []
  12644.             ];
  12645.         }
  12646.         //now get cash flow
  12647.         if (in_array(3$report_cats)) {
  12648.             $markerHashes array_column(AccountsConstant::$cashFlowConfigData'markerHash');
  12649.             $cf_data Accounts::GetBalanceOnDateByMarkerHash($em$end_date, [], [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENTAccountsConstant::CUSTOMER_RECEIVABLE_PARENTAccountsConstant::SUPPLIER_PAYABLE_PARENTAccountsConstant::OPERATING_EXPENSE_PARENTAccountsConstant::GENERAL_EMPLOYEE_PARENTAccountsConstant::INTEREST_RECEIVABLE_PARENTAccountsConstant::FINANCIAL_EXPENSE_PARENTAccountsConstant::TAX_EXPENSE_PARENTAccountsConstant::FIXED_ASSET_PARENTAccountsConstant::ASSET_SALE_PARENTAccountsConstant::INVESTMENT_PARENTAccountsConstant::NONOPERATING_REVENUE_PARENTAccountsConstant::LOAN_RECEIVED_PARENTAccountsConstant::LOAN_REPAYMENT_PARENTAccountsConstant::DIVIDEND_PAYMENT_PARENT], 1, [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT], $allocationFilters);
  12650.             $openingData Accounts::GetBalanceOnDateByMarkerHash(
  12651.                 $em,
  12652.                 $start_date,
  12653.                 [],
  12654.                 [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],
  12655.                 1,
  12656.                 [],
  12657.                 $allocationFilters
  12658.             );
  12659.             $closingData Accounts::GetBalanceOnDateByMarkerHash(
  12660.                 $em,
  12661.                 $end_date,
  12662.                 [],
  12663.                 [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],
  12664.                 1,
  12665.                 [],
  12666.                 $allocationFilters
  12667.             );
  12668.             $openingCashBalance = isset($openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT])
  12669.                 ? $openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transCr'] - $openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transDr']
  12670.                 : 0;
  12671.             $closingCashBalance = isset($closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT])
  12672.                 ? $closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transCr'] - $closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transDr']
  12673.                 : 0;
  12674.             $cf_data['_CASH_OPENING_'] = [
  12675.                 'transDr' => 0,
  12676.                 'transCr' => $openingCashBalance,
  12677.                 'dataByFiscalClosing' => []
  12678.             ];
  12679.             $cf_data['_CASH_CLOSING_'] = [
  12680.                 'transDr' => 0,
  12681.                 'transCr' => $closingCashBalance,
  12682.                 'dataByFiscalClosing' => []
  12683.             ];
  12684.             $cf_data['tree'] = "";
  12685.             $cashFlowConfigData AccountsConstant::$cashFlowConfigData;
  12686.             $currBal 0;
  12687.             $currBalByClosingDate = array();
  12688.             $totalBalByClosingDate = array();
  12689.             $totalBal 0;
  12690. //            dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
  12691.             foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12692.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12693.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12694.             }
  12695.             foreach ($cashFlowConfigData as $config) {
  12696.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  12697.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  12698.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  12699.                     $row .= "<td ></td>";
  12700.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12701.                         $row .= "<td style='text-align: right' ></td>";
  12702.                     }
  12703.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  12704.                     //                    $row.="<td >pika$currBal</td>";
  12705.                     if ($currBal >= 0)
  12706.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  12707.                     else
  12708.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  12709.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12710.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  12711.                         if ($currValByFiscalYear >= 0)
  12712.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  12713.                         else
  12714.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  12715.                     }
  12716.                 } else {
  12717.                     $currVal 0;
  12718.                     $currentMarkerData null;
  12719.                     if (isset($cf_data[$config['markerHash']])) {
  12720.                         $currentMarkerData $cf_data[$config['markerHash']];
  12721.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  12722.                     }
  12723.                     if ($currVal >= 0)
  12724.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  12725.                     else
  12726.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  12727.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12728.                         if ($currentMarkerData) {
  12729.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  12730.                             if ($currVal >= 0)
  12731.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  12732.                             else
  12733.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  12734.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12735.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12736.                         } else {
  12737.                             $row .= "<td style='text-align: right' ></td>";
  12738.                         }
  12739.                     }
  12740.                     $totalBal += $currVal;
  12741.                     $currBal += $currVal;
  12742.                 }
  12743.                 $row .= "</tr>";
  12744.                 if (isset($config['resetCurrentBal'])) {
  12745.                     if ($config['resetCurrentBal'] == true)
  12746.                         $currBal 0;
  12747.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12748.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12749.                     }
  12750.                 }
  12751.                 $cf_data['tree'] .= $row;
  12752.                 $cf_data['grandTotal'] = $totalBal;
  12753.                 $cf_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  12754.             }
  12755.         }
  12756.         if (in_array(4$report_cats)) {
  12757.             $markerHashes array_column(AccountsConstant::$changesInEquityConfigData'markerHash');
  12758.             $oe_data Accounts::GetBalanceOnDateByMarkerHash($em$end_date, [], [AccountsConstant::SHARE_CAPITAL_PARENTAccountsConstant::RETAINED_EARNING_PARENTAccountsConstant::REVALUATION_SURPLUS_PARENTAccountsConstant::DIVIDEND_PAYMENT_PARENTAccountsConstant::OCI_RECLASSIFIABLE_PARENTAccountsConstant::OCI_NONRECLASSIFIABLE_PARENT], 1, [], $allocationFilters);
  12759.             if (isset($is_data['grandTotal'])) {
  12760.                 $finalProfit $is_data['grandTotal'];
  12761.             } else {
  12762.                 $finalProfit 0;
  12763.             }
  12764.             $oe_data['_IS_PROFIT_'] = [
  12765.                 'transDr' => 0,
  12766.                 'transCr' => $finalProfit,
  12767.                 'dataByFiscalClosing' => []
  12768.             ];
  12769.             $oe_data['tree'] = "";
  12770.             $changesInEquityConfigData AccountsConstant::$changesInEquityConfigData;
  12771.             $currBal 0;
  12772.             $currBalByClosingDate = array();
  12773.             $totalBalByClosingDate = array();
  12774.             $totalBal 0;
  12775. //            dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
  12776.             foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12777.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12778.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12779.             }
  12780.             foreach ($changesInEquityConfigData as $config) {
  12781.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  12782.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  12783.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  12784.                     $row .= "<td ></td>";
  12785.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12786.                         $row .= "<td style='text-align: right' ></td>";
  12787.                     }
  12788.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  12789.                     //                    $row.="<td >pika$currBal</td>";
  12790.                     if ($currBal >= 0)
  12791.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  12792.                     else
  12793.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  12794.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12795.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  12796.                         if ($currValByFiscalYear >= 0)
  12797.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  12798.                         else
  12799.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  12800.                     }
  12801.                 } else {
  12802.                     $currVal 0;
  12803.                     $currentMarkerData null;
  12804.                     if (isset($oe_data[$config['markerHash']])) {
  12805.                         $currentMarkerData $oe_data[$config['markerHash']];
  12806.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  12807.                     }
  12808.                     if ($currVal >= 0)
  12809.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  12810.                     else
  12811.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  12812.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12813.                         if ($currentMarkerData) {
  12814.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  12815.                             if ($currVal >= 0)
  12816.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  12817.                             else
  12818.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  12819.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12820.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12821.                         } else {
  12822.                             $row .= "<td style='text-align: right' ></td>";
  12823.                         }
  12824.                     }
  12825.                     $totalBal += $currVal;
  12826.                     $currBal += $currVal;
  12827.                 }
  12828.                 $row .= "</tr>";
  12829.                 if (isset($config['resetCurrentBal'])) {
  12830.                     if ($config['resetCurrentBal'] == true)
  12831.                         $currBal 0;
  12832.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12833.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12834.                     }
  12835.                 }
  12836.                 $oe_data['tree'] .= $row;
  12837.                 $oe_data['grandTotal'] = $totalBal;
  12838.                 $oe_data['grandTotal'] = $totalBal;
  12839.                 $oe_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  12840.             }
  12841.         }
  12842.         if (in_array(5$report_cats)) {
  12843.             $wacc_data Accounts::GetWaccStatement($em$cur_level$start_date$end_date$url$periodic$prev_data_amounts_for_cf$expand_level);
  12844.         }
  12845.         //now get prev balance totals
  12846.         //*******Data generation Ends here
  12847.         $provisional_option 1//include
  12848.         if ($request->query->has('provisional')) {
  12849.             $provisional_option $request->query->get('provisional'); //include
  12850.         }
  12851.         // now lets get its tree for the description
  12852.         //        $id_list_for_ledger=[];
  12853.         //        if($request->query->has('id_list') )
  12854.         //            $id_list_for_ledger=explode(',',$request->query->get('id_list'));
  12855.         //        if($id=0&&empty($id_list))
  12856.         //            $id_list_for_ledger=[0];
  12857.         //        $ledger_det=[];
  12858.         //        $head_name_list=[];
  12859.         //        foreach($id_list_for_ledger as $ind_head_id) {
  12860.         //            $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
  12861.         //            $ledger_det[$ind_head_id]=$ledger_data;
  12862.         //            $head_name_list[]=$ledger_data['basic_data']['name'];
  12863.         //        }
  12864.         //        $grouped_heads=Accounts::GroupedHeads($em);
  12865.         $document_mark = array(
  12866.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12867.             'copy' => ''
  12868.         );
  12869.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12870.             $html $this->renderView(
  12871.                 '@Accounts/pages/print/print_financial_report.html.twig',
  12872.                 array(
  12873.                     'pdf' => true,
  12874.                     'page_title' => 'Financial Statement',
  12875.                     'company_name' => $company_data->getName(),
  12876.                     'company_data' => $company_data,
  12877.                     //                'details'=>$bs_details,
  12878.                     'bs_details' => $balance_sheet_data,
  12879.                     'is_details' => $is_data,
  12880.                     'cf_details' => $cf_data,
  12881.                     'oe_details' => $oe_data,
  12882.                     'wacc_details' => $wacc_data,
  12883.                     'prev_data_list' => $prev_data_list,
  12884.                     'report_cats' => $report_cats,
  12885.                     'start_date' => $start_date,
  12886.                     'end_date' => $end_date,
  12887.                     'max_level' => $max_level,
  12888.                     'expand_level' => $expand_level,
  12889.                     'cur_level' => $cur_level,
  12890.                     //                'ledger_data'=>$ledger_det,
  12891.                     'page_header' => 'Ledger',
  12892.                     'document_type' => 'Financial Statement',
  12893.                     'document_mark_image' => $document_mark['original'],
  12894.                     'page_header_sub' => 'Add',
  12895.                     'head_list' => Accounts::HeadList($em),
  12896.                     'provisional' => $provisional_option,
  12897.                     //                'type_list'=>$type_list,
  12898.                     //            'child_list'=>$child_list,
  12899.                     //                'trans_data_by_closing'=>$trans_data_by_closing,
  12900.                     'item_data' => [],
  12901.                     'received' => 2,
  12902.                     'return' => 1,
  12903.                     'total_w_vat' => 1,
  12904.                     'total_vat' => 1,
  12905.                     'total_wo_vat' => 1,
  12906.                     'invoice_id' => 'abcd1234',
  12907.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12908.                     'created_by' => 'created by',
  12909.                     'created_at' => '',
  12910.                     'red' => 0,
  12911.                     'company_address' => $company_data->getAddress(),
  12912.                     'company_image' => $company_data->getImage(),
  12913.                     'allocation_filters' => $allocationFilters,
  12914.                     'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  12915.                     'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  12916.                     'project_list' => $allocationSupportData['project_list'],
  12917.                     'branch_list' => $allocationSupportData['branch_list'],
  12918.                     'cost_centers' => $allocationSupportData['cost_centers'],
  12919.                 )
  12920.             );
  12921.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12922.                 //                'orientation' => 'landscape',
  12923.                 //                'enable-javascript' => false,
  12924.                 //                'javascript-delay' => 1000,
  12925.                 'no-stop-slow-scripts' => true,
  12926.                 'no-background' => false,
  12927.                 'lowquality' => false,
  12928.                 'encoding' => 'utf-8',
  12929.                 //            'images' => true,
  12930.                 //            'cookie' => array(),
  12931.                 'dpi' => 300,
  12932.                 'image-dpi' => 300,
  12933.                 //                'enable-external-links' => true,
  12934.                 //                'enable-internal-links' => true
  12935.             ));
  12936.             return new Response(
  12937.                 $pdf_response,
  12938.                 200,
  12939.                 array(
  12940.                     'Content-Type' => 'application/pdf',
  12941.                     'Content-Disposition' => 'attachment; filename="Financial_Report.pdf"'
  12942.                 )
  12943.             );
  12944.         }
  12945.         return $this->render(
  12946.             '@Accounts/pages/print/print_financial_report.html.twig',
  12947.             array(
  12948.                 'export' => 'all',
  12949.                 'page_title' => 'Financial Statement',
  12950.                 'company_name' => $company_data->getName(),
  12951.                 'company_data' => $company_data,
  12952.                 //                'details'=>$bs_details,
  12953.                 'bs_details' => $balance_sheet_data,
  12954.                 'is_details' => $is_data,
  12955.                 'cf_details' => $cf_data,
  12956.                 'oe_details' => $oe_data,
  12957.                 'prev_data_list' => $prev_data_list,
  12958.                 'report_cats' => $report_cats,
  12959.                 'start_date' => $start_date,
  12960.                 'end_date' => $end_date,
  12961.                 'max_level' => $max_level,
  12962.                 'expand_level' => $expand_level,
  12963.                 'cur_level' => $cur_level,
  12964.                 //                'ledger_data'=>$ledger_det,
  12965.                 'page_header' => 'Ledger',
  12966.                 'document_type' => 'Financial Statement',
  12967.                 'document_mark_image' => $document_mark['original'],
  12968.                 'page_header_sub' => 'Add',
  12969.                 'head_list' => Accounts::HeadList($em),
  12970.                 'provisional' => $provisional_option,
  12971.                 //                'type_list'=>$type_list,
  12972.                 //            'child_list'=>$child_list,
  12973.                 //                'trans_data_by_closing'=>$trans_data_by_closing,
  12974.                 'item_data' => [],
  12975.                 'received' => 2,
  12976.                 'return' => 1,
  12977.                 'total_w_vat' => 1,
  12978.                 'total_vat' => 1,
  12979.                 'total_wo_vat' => 1,
  12980.                 'invoice_id' => 'abcd1234',
  12981.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12982.                 'created_by' => 'created by',
  12983.                 'created_at' => '',
  12984.                 'red' => 0,
  12985.                 'company_address' => $company_data->getAddress(),
  12986.                 'company_image' => $company_data->getImage(),
  12987.                 'allocation_filters' => $allocationFilters,
  12988.                 'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  12989.                 'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  12990.                 'project_list' => $allocationSupportData['project_list'],
  12991.                 'branch_list' => $allocationSupportData['branch_list'],
  12992.                 'cost_centers' => $allocationSupportData['cost_centers'],
  12993.                 //                'p'=>$p
  12994.             )
  12995.         );
  12996.     }
  12997.     public function PrintTrialBalance(Request $request)
  12998.     {
  12999.         $em $this->getDoctrine()->getManager();
  13000.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  13001.         $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : "";
  13002.         $skip_parent_head = ($request->query->has('skip_parent_head')) ? $request->query->get('skip_parent_head') : 0;
  13003.         $cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
  13004.         $expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 1;
  13005.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('Y-m-d');
  13006.         $em $this->getDoctrine()->getManager();
  13007.         $url $this->generateUrl('view_ledger_head', array(), true);
  13008.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  13009.         $bs_details = [];
  13010.         $get_kids_sql "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
  13011.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  13012.         
  13013.         $query_output $stmt;
  13014.         $max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
  13015.         $budgetEnabled 0;
  13016.         $budgetVarianceSettings = [];
  13017.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  13018.         $allocationFilters $allocationSupportData['allocation_filters'];
  13019.         if ($request->query->has('budget_variance_enabled')) {
  13020.             $budgetVarianceSettings['enabled'] = $request->query->get('budget_variance_enabled');
  13021.             $budgetEnabled $request->query->get('budget_variance_enabled');
  13022.             $budgetVarianceSettings['scale'] = ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 1;
  13023.             $budgetVarianceSettings['budgetId'] = ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 1;
  13024.         }
  13025.         $tb_details Accounts::GetTrialBalance($em$cur_level$start_date$end_date$url, [], $expand_level'print'$skip_parent_head$budgetVarianceSettings0$allocationFilters);
  13026.         //        $tb_details=Accounts::GetTrialBalance($em,$cur_level,$start_date, $end_date,$url,[],$expand_level,'print',$skip_parent_head);
  13027.         //        $grouped_heads=Accounts::GroupedHeads($em);
  13028.         //        if($mis_start_date!=''&&$mis_start_date!=0)
  13029.         //            $start_date=$mis_start_date;
  13030.         //        if($mis_end_date!=''&&$mis_start_date!=0)
  13031.         //            $end_date=$mis_end_date;
  13032.         $provisional_option 1//include
  13033.         if ($request->query->has('provisional')) {
  13034.             $provisional_option $request->query->get('provisional'); //include
  13035.         }
  13036.         // now lets get its tree for the description
  13037.         //        $id_list_for_ledger=[];
  13038.         //        if($request->query->has('id_list') )
  13039.         //            $id_list_for_ledger=explode(',',$request->query->get('id_list'));
  13040.         //        if($id=0&&empty($id_list))
  13041.         //            $id_list_for_ledger=[0];
  13042.         //        $ledger_det=[];
  13043.         //        $head_name_list=[];
  13044.         //        foreach($id_list_for_ledger as $ind_head_id) {
  13045.         //            $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
  13046.         //            $ledger_det[$ind_head_id]=$ledger_data;
  13047.         //            $head_name_list[]=$ledger_data['basic_data']['name'];
  13048.         //        }
  13049.         //        $grouped_heads=Accounts::GroupedHeads($em);
  13050.         $document_mark = array(
  13051.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13052.             'copy' => ''
  13053.         );
  13054.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13055.             $html $this->renderView(
  13056.                 '@Accounts/pages/print/trial_balance_print.html.twig',
  13057.                 array(
  13058.                     //                    'pdf'=>true,
  13059.                     'page_title' => 'Trial Balance',
  13060.                     'company_name' => $company_data->getName(),
  13061.                     'company_data' => $company_data,
  13062.                     //                'details'=>$bs_details,
  13063.                     'tb_details' => $tb_details,
  13064.                     'start_date' => $start_date,
  13065.                     'end_date' => $end_date,
  13066.                     'max_level' => $max_level,
  13067.                     'expand_level' => $expand_level,
  13068.                     'cur_level' => $cur_level,
  13069.                     //                'ledger_data'=>$ledger_det,
  13070.                     'page_header' => 'Ledger',
  13071.                     'document_type' => 'Trial Balance',
  13072.                     'document_mark_image' => $document_mark['original'],
  13073.                     'page_header_sub' => 'Add',
  13074.                     'budget_variance_enabled' => $budgetEnabled,
  13075.                     'currBudgetList' => $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findBy(
  13076.                         array(
  13077.                             //                        'budgetId'=>$id, ///material
  13078.                             'CompanyId' => $this->getLoggedUserCompanyId($request), ///material
  13079.                         )
  13080.                     ),
  13081.                     'scale_variance' => ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 0,
  13082.                     'budgetId' => ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 0,
  13083.                     'head_list' => Accounts::HeadList($em),
  13084.                     'provisional' => $provisional_option,
  13085.                     //                'type_list'=>$type_list,
  13086.                     //            'child_list'=>$child_list,
  13087.                     //                'trans_data_by_closing'=>$trans_data_by_closing,
  13088.                     'item_data' => [],
  13089.                     'received' => 2,
  13090.                     'return' => 1,
  13091.                     'total_w_vat' => 1,
  13092.                     'total_vat' => 1,
  13093.                     'total_wo_vat' => 1,
  13094.                     'invoice_id' => 'abcd1234',
  13095.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13096.                     'created_by' => 'created by',
  13097.                     'created_at' => '',
  13098.                     'red' => 0,
  13099.                     'company_address' => $company_data->getAddress(),
  13100.                     'company_image' => $company_data->getImage(),
  13101.                     'allocation_filters' => $allocationFilters,
  13102.                     'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  13103.                     'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  13104.                     'project_list' => $allocationSupportData['project_list'],
  13105.                     'branch_list' => $allocationSupportData['branch_list'],
  13106.                     'cost_centers' => $allocationSupportData['cost_centers'],
  13107.                 )
  13108.             );
  13109.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13110.                 //                'orientation' => 'landscape',
  13111.                 //                'enable-javascript' => false,
  13112.                 //                'javascript-delay' => 1000,
  13113.                 'no-stop-slow-scripts' => true,
  13114.                 'no-background' => false,
  13115.                 'lowquality' => false,
  13116.                 'encoding' => 'utf-8',
  13117.                 //            'images' => true,
  13118.                 //            'cookie' => array(),
  13119.                 'dpi' => 300,
  13120.                 'image-dpi' => 300,
  13121.                 //                'enable-external-links' => true,
  13122.                 //                'enable-internal-links' => true
  13123.             ));
  13124.             return new Response(
  13125.                 $pdf_response,
  13126.                 200,
  13127.                 array(
  13128.                     'Content-Type' => 'application/pdf',
  13129.                     'Content-Disposition' => 'attachment; filename="Trial Balance.pdf"'
  13130.                 )
  13131.             );
  13132.         }
  13133.         return $this->render(
  13134.             '@Accounts/pages/print/trial_balance_print.html.twig',
  13135.             array(
  13136.                 'page_title' => 'Trial Balance',
  13137.                 'export' => 'all',
  13138.                 'company_name' => $company_data->getName(),
  13139.                 'company_data' => $company_data,
  13140.                 //                'details'=>$bs_details,
  13141.                 'tb_details' => $tb_details,
  13142.                 'start_date' => $start_date,
  13143.                 'end_date' => $end_date,
  13144.                 'max_level' => $max_level,
  13145.                 'expand_level' => $expand_level,
  13146.                 'cur_level' => $cur_level,
  13147.                 //                'ledger_data'=>$ledger_det,
  13148.                 'page_header' => 'Ledger',
  13149.                 'document_type' => 'Trial Balance',
  13150.                 'document_mark_image' => $document_mark['original'],
  13151.                 'page_header_sub' => 'Add',
  13152.                 'budget_variance_enabled' => $budgetEnabled,
  13153.                 'currBudgetList' => $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findBy(
  13154.                     array(
  13155.                         //                        'budgetId'=>$id, ///material
  13156.                         'CompanyId' => $this->getLoggedUserCompanyId($request), ///material
  13157.                     )
  13158.                 ),
  13159.                 'scale_variance' => ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 0,
  13160.                 'budgetId' => ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 0,
  13161.                 'head_list' => Accounts::HeadList($em),
  13162.                 'provisional' => $provisional_option,
  13163.                 //                'type_list'=>$type_list,
  13164.                 //            'child_list'=>$child_list,
  13165.                 //                'trans_data_by_closing'=>$trans_data_by_closing,
  13166.                 'item_data' => [],
  13167.                 'received' => 2,
  13168.                 'return' => 1,
  13169.                 'total_w_vat' => 1,
  13170.                 'total_vat' => 1,
  13171.                 'total_wo_vat' => 1,
  13172.                 'invoice_id' => 'abcd1234',
  13173.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13174.                 'created_by' => 'created by',
  13175.                 'created_at' => '',
  13176.                 'red' => 0,
  13177.                 'company_address' => $company_data->getAddress(),
  13178.                 'company_image' => $company_data->getImage(),
  13179.                 //                'p'=>$p
  13180.             )
  13181.         );
  13182.     }
  13183.     public function testSnappy(Request $request)
  13184.     {
  13185.         $em $this->getDoctrine()->getManager();
  13186.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  13187.         $document_mark = array(
  13188.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13189.             'copy' => ''
  13190.         );
  13191.         $html $this->renderView(
  13192.             '@Accounts/pages/print/test.html.twig',
  13193.             array(
  13194.                 //                    'pdf'=>true,
  13195.                 'page_title' => 'Trial Balance',
  13196.                 'company_name' => $company_data->getName(),
  13197.                 'company_data' => $company_data,
  13198.                 //                'details'=>$bs_details,
  13199.                 //                'ledger_data'=>$ledger_det,
  13200.                 'page_header' => 'Ledger',
  13201.                 'document_type' => 'Trial Balance',
  13202.                 'document_mark_image' => $document_mark['original'],
  13203.                 'page_header_sub' => 'Add',
  13204.                 'company_address' => $company_data->getAddress(),
  13205.                 'company_image' => $company_data->getImage(),
  13206.                 'allocation_filters' => $allocationFilters,
  13207.                 'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  13208.                 'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  13209.                 'project_list' => $allocationSupportData['project_list'],
  13210.                 'branch_list' => $allocationSupportData['branch_list'],
  13211.                 'cost_centers' => $allocationSupportData['cost_centers'],
  13212.             )
  13213.         );
  13214.         $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13215.             //                'orientation' => 'landscape',
  13216.             //                'enable-javascript' => false,
  13217.             //                'javascript-delay' => 1000,
  13218.             //                'no-stop-slow-scripts' => true,
  13219.             'no-background' => false,
  13220.             //                'lowquality' => false,
  13221.             'encoding' => 'utf-8',
  13222.             //            'images' => true,
  13223.             //            'cookie' => array(),
  13224.             'dpi' => 300,
  13225.             'image-dpi' => 300,
  13226.             //                'enable-external-links' => true,
  13227.             //                'enable-internal-links' => true
  13228.         ));
  13229.         return new Response(
  13230.             $pdf_response,
  13231.             200,
  13232.             array(
  13233.                 'Content-Type' => 'application/pdf',
  13234.                 'Content-Disposition' => 'attachment; filename="TestSnappy.pdf"'
  13235.             )
  13236.         );
  13237.     }
  13238.     public function CreateLedgerHead(Request $request)
  13239.     {
  13240.         $companyId $this->getLoggedUserCompanyId($request);
  13241.         if ($request->isMethod('POST')) {
  13242.             $em $this->getDoctrine()->getManager();
  13243.             $devAdmin $request->getSession()->get('devAdminMode'0) == 1;
  13244.             //first lets assume replication is not selected so lets get the parent and check if any head has this parents id as replication id
  13245.             $head_id Accounts::CreateNewHead(
  13246.                 $em,
  13247.                 GeneralConstant::OPENING_YEAR,
  13248.                 $request->request->get('parent_id'),
  13249.                 $request->request->get('name'),
  13250.                 $request->request->get('code'),
  13251.                 $request->request->get('opening_balance'),
  13252.                 $request->request->get('cc_enabled'),
  13253.                 $request->request->get('head_nature'),
  13254.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13255.                 $request->request->get('replication_head_id'),
  13256.                 $request->request->has('checkAdvanceParent') ? 0,
  13257.                 "",
  13258.                 "",
  13259.                 $companyId,
  13260.                 $request->request->has('markerHash') ? $request->request->get('markerHash') : null,
  13261.                 $request->request->has('costCentreTypes') ? $request->request->get('costCentreTypes') : '',
  13262.                 $request->request->has('narrationOnCheck') ? $request->request->get('narrationOnCheck') : '',
  13263.                 $devAdmin && $request->request->has('flag_is_system')       ? (bool)$request->request->get('flag_is_system')       : false,
  13264.                 $devAdmin && $request->request->has('flag_is_editable')     ? (bool)$request->request->get('flag_is_editable')     : true,
  13265.                 $devAdmin && $request->request->has('flag_is_deletable')    ? (bool)$request->request->get('flag_is_deletable')    : true,
  13266.                 $devAdmin && $request->request->has('flag_is_child_allowed') ? (bool)$request->request->get('flag_is_child_allowed') : true
  13267.             ); //blahere
  13268.             // Optional: attach DATEV mapping if provided during creation
  13269.             if ($head_id && $request->request->has('datev_code') && $request->request->get('datev_code') != '') {
  13270.                 $newHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  13271.                     ->findOneBy(['accountsHeadId' => $head_id]);
  13272.                 if ($newHead) {
  13273.                     AccountHeadExternalMappingService::setDatevMapping(
  13274.                         $em,
  13275.                         $newHead,
  13276.                         $companyId,
  13277.                         $request->request->get('datev_code'),
  13278.                         $request->request->has('datev_name') ? $request->request->get('datev_name') : null
  13279.                     );
  13280.                 }
  13281.             }
  13282.             if ($request->request->get('replication_head_id') == '') {
  13283.                 $replicate_data_qry $this->getDoctrine()
  13284.                     ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  13285.                     ->findBy(
  13286.                         array(
  13287.                             'replicationHeadId' => $request->request->get('parent_id'),
  13288.                             'replicate' => 1
  13289.                         )
  13290.                     );
  13291.                 //now create replicated heads for all of these
  13292.                 $p 0;
  13293.                 foreach ($replicate_data_qry as $entry) {
  13294.                     $p++;
  13295.                     $replicated_id Accounts::CreateNewHead(
  13296.                         $em,
  13297.                         GeneralConstant::OPENING_YEAR,
  13298.                         $entry->getAccountsHeadId(),
  13299.                         $request->request->get('name'),
  13300.                         $request->request->get('code') . $p,
  13301.                         $request->request->get('opening_balance'),
  13302.                         $request->request->get('cc_enabled'),
  13303.                         "",
  13304.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13305.                         $head_id,
  13306.                         $entry->getAdvanceOf() == $request->request->get('parent_id') ? 0
  13307.                     );
  13308.                 }
  13309.             } else {
  13310.                 //                //creating the re
  13311.                 //                $head_id=Accounts::CreateNewHead(
  13312.                 //                    $em,
  13313.                 //                    GeneralConstant::OPENING_YEAR,
  13314.                 //                    $request->request->get('parent_id'),
  13315.                 //                    $request->request->get('name'),
  13316.                 //                    $request->request->get('code'),
  13317.                 //                    $request->request->get('opening_balance'),
  13318.                 //                    $request->request->get('cc_enabled'),
  13319.                 //                    $request->request->get('head_nature'),
  13320.                 //                    $request->getSession()->get(UserConstants::USER_LOGIN_ID,
  13321.                 //                        $request->request->get('replication_head_id'),
  13322.                 //                        $request->request->has('checkAdvanceParent')?1:0
  13323.                 //                    )
  13324.                 //                );
  13325.             }
  13326.             //            $url = $this->generateUrl(
  13327.             //                'edit_ledger_head'
  13328.             //            );
  13329.             //
  13330.             //            return $this->redirect($url . "/" . $head_id);
  13331.         }
  13332.         return $this->render(
  13333.             '@Accounts/pages/input_forms/add_ledger_heads.html.twig',
  13334.             array(
  13335.                 'page_title' => 'Create Ledger Head',
  13336.                 'headMarkers' => AccountsConstant::$HEAD_MARKER_ARRAY,
  13337.                 'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
  13338.             )
  13339.         );
  13340.     }
  13341.     public function CreateLedgerHeadForApp(Request $request)
  13342.     {
  13343.         $companyId $this->getLoggedUserCompanyId($request);
  13344.         if ($request->isMethod('POST')) {
  13345.             $em $this->getDoctrine()->getManager();
  13346.             //first lets assume replication is not selected so lets get the parent and check if any head has this parents id as replication id
  13347.             $head_id Accounts::CreateNewHead(
  13348.                 $em,
  13349.                 GeneralConstant::OPENING_YEAR,
  13350.                 $request->request->get('parent_id'),
  13351.                 $request->request->get('name'),
  13352.                 $request->request->get('code'),
  13353.                 $request->request->get('opening_balance'),
  13354.                 $request->request->get('cc_enabled'),
  13355.                 $request->request->get('head_nature'),
  13356.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13357.                 $request->request->get('replication_head_id'),
  13358.                 $request->request->has('checkAdvanceParent') ? 0,
  13359.                 "",
  13360.                 "",
  13361.                 $companyId,
  13362.                 $request->request->has('markerHash') ? $request->request->get('markerHash') : null,
  13363.                 $request->request->has('costCentreTypes') ? $request->request->get('costCentreTypes') : '',
  13364.                 $request->request->has('narrationOnCheck') ? $request->request->get('narrationOnCheck') : ''
  13365.             ); //blahere
  13366.             if ($request->request->get('replication_head_id') == '') {
  13367.                 $replicate_data_qry $this->getDoctrine()
  13368.                     ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  13369.                     ->findBy(
  13370.                         array(
  13371.                             'replicationHeadId' => $request->request->get('parent_id'),
  13372.                             'replicate' => 1
  13373.                         )
  13374.                     );
  13375.                 //now create replicated heads for all of these
  13376.                 $p 0;
  13377.                 foreach ($replicate_data_qry as $entry) {
  13378.                     $p++;
  13379.                     $replicated_id Accounts::CreateNewHead(
  13380.                         $em,
  13381.                         GeneralConstant::OPENING_YEAR,
  13382.                         $entry->getAccountsHeadId(),
  13383.                         $request->request->get('name'),
  13384.                         $request->request->get('code') . $p,
  13385.                         $request->request->get('opening_balance'),
  13386.                         $request->request->get('cc_enabled'),
  13387.                         "",
  13388.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13389.                         $head_id,
  13390.                         $entry->getAdvanceOf() == $request->request->get('parent_id') ? 0
  13391.                     );
  13392.                 }
  13393.             } else {
  13394.                 //                //creating the re
  13395.                 //                $head_id=Accounts::CreateNewHead(
  13396.                 //                    $em,
  13397.                 //                    GeneralConstant::OPENING_YEAR,
  13398.                 //                    $request->request->get('parent_id'),
  13399.                 //                    $request->request->get('name'),
  13400.                 //                    $request->request->get('code'),
  13401.                 //                    $request->request->get('opening_balance'),
  13402.                 //                    $request->request->get('cc_enabled'),
  13403.                 //                    $request->request->get('head_nature'),
  13404.                 //                    $request->getSession()->get(UserConstants::USER_LOGIN_ID,
  13405.                 //                        $request->request->get('replication_head_id'),
  13406.                 //                        $request->request->has('checkAdvanceParent')?1:0
  13407.                 //                    )
  13408.                 //                );
  13409.             }
  13410.             //            $url = $this->generateUrl(
  13411.             //                'edit_ledger_head'
  13412.             //            );
  13413.             //
  13414.             //            return $this->redirect($url . "/" . $head_id);
  13415.         }
  13416.         return new JsonResponse([
  13417.             'success' => 'true',
  13418.         ]);
  13419. //        return $this->render(
  13420. //            '@Accounts/pages/input_forms/add_ledger_heads.html.twig',
  13421. //            array(
  13422. //                'page_title' => 'Create Ledger Head',
  13423. //                'headMarkers' => AccountsConstant::$HEAD_MARKER_ARRAY,
  13424. //                'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
  13425. //            )
  13426. //        );
  13427.     }
  13428.     public function ChartOfAccounts(Request $request)
  13429.     {
  13430.         $em $this->getDoctrine()->getManager();
  13431.         $session $request->getSession();
  13432.         //        if($request->isMethod('POST')) {
  13433.         //
  13434.         //
  13435.         //
  13436.         //            //first lets assume replication is not selected so lets get the parent and check if any head has this parents id as replication id
  13437.         //
  13438.         //            $head_id=Accounts::CreateNewHead(
  13439.         //                $em,
  13440.         //                GeneralConstant::OPENING_YEAR,
  13441.         //                $request->request->get('parent_id'),
  13442.         //                $request->request->get('name'),
  13443.         //                $request->request->get('code'),
  13444.         //                $request->request->get('opening_balance'),
  13445.         //                $request->request->get('cc_enabled'),
  13446.         //                $request->request->get('head_nature'),
  13447.         //                $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13448.         //                $request->request->get('replication_head_id'),
  13449.         //                $request->request->has('checkAdvanceParent')?1:0
  13450.         //
  13451.         //            ); //blahere
  13452.         //            if($request->request->get('replication_head_id')=='')
  13453.         //            {
  13454.         //                $replicate_data_qry= $this->getDoctrine()
  13455.         //                    ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  13456.         //                    ->findBy(
  13457.         //                        array(
  13458.         //                            'replicationHeadId' =>  $request->request->get('parent_id'),
  13459.         //                            'replicate'=>1
  13460.         //                        )
  13461.         //                    );
  13462.         //
  13463.         //                //now create replicated heads for all of these
  13464.         //                $p=0;
  13465.         //                foreach($replicate_data_qry as $entry)
  13466.         //                {
  13467.         //                    $p++;
  13468.         //
  13469.         //                    $replicated_id=Accounts::CreateNewHead(
  13470.         //                        $em,
  13471.         //                        GeneralConstant::OPENING_YEAR,
  13472.         //                        $entry->getAccountsHeadId(),
  13473.         //                        $request->request->get('name'),
  13474.         //                        $request->request->get('code').$p,
  13475.         //                        $request->request->get('opening_balance'),
  13476.         //                        $request->request->get('cc_enabled'),
  13477.         //                        "",
  13478.         //                        $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13479.         //                        $head_id,
  13480.         //                        $entry->getAdvanceOf()==$request->request->get('parent_id')?1:0
  13481.         //
  13482.         //                    );
  13483.         //
  13484.         //                }
  13485.         //
  13486.         //            }
  13487.         //            else
  13488.         //            {
  13489.         ////                //creating the re
  13490.         ////                $head_id=Accounts::CreateNewHead(
  13491.         ////                    $em,
  13492.         ////                    GeneralConstant::OPENING_YEAR,
  13493.         ////                    $request->request->get('parent_id'),
  13494.         ////                    $request->request->get('name'),
  13495.         ////                    $request->request->get('code'),
  13496.         ////                    $request->request->get('opening_balance'),
  13497.         ////                    $request->request->get('cc_enabled'),
  13498.         ////                    $request->request->get('head_nature'),
  13499.         ////                    $request->getSession()->get(UserConstants::USER_LOGIN_ID,
  13500.         ////                        $request->request->get('replication_head_id'),
  13501.         ////                        $request->request->has('checkAdvanceParent')?1:0
  13502.         ////                    )
  13503.         ////                );
  13504.         //            }
  13505.         ////            $url = $this->generateUrl(
  13506.         ////                'edit_ledger_head'
  13507.         ////            );
  13508.         ////
  13509.         ////            return $this->redirect($url . "/" . $head_id);
  13510.         //
  13511.         //        }
  13512.         return $this->render(
  13513.             '@Accounts/pages/report/chart_of_accounts.html.twig',
  13514.             array(
  13515.                 'page_title' => 'Chart of Accounts',
  13516.                 //                'debug_data'=>  Company::getMonthlyDataForDashboard($em, $session->get(UserConstants::USER_COMPANY_ID, 1))
  13517.             )
  13518.         );
  13519.     }
  13520.     public function EditLedgerHead(Request $request$id)
  13521.     {
  13522.         $headExists 1;
  13523.         if ($request->isMethod('POST')) {
  13524.             $em $this->getDoctrine()->getManager();
  13525.             $head_data_qry $this->getDoctrine()
  13526.                 ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  13527.                 ->findOneBy(
  13528.                     array(
  13529.                         'accountsHeadId' => $id,
  13530.                         //                        'lockFlag'=>[0,null]
  13531.                     )
  13532.                 );
  13533.             $headExists 1;
  13534.             if ($request->request->has('transferTransactionsFlag')) {
  13535.                 $query "update acc_transaction_details set accounts_head_id =" $request->request->get('transferTransactionTo') . " where accounts_head_id =" $id ";";
  13536.                 //transfer any payment checks
  13537.                 $query .= "update acc_check set accounts_head_id =" $request->request->get('transferTransactionTo') . " where accounts_head_id =" $id ";";
  13538.                 $query .= "update acc_check set rec_accounts_head_id =" $request->request->get('transferTransactionTo') . " where rec_accounts_head_id =" $id ";";
  13539.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  13540.                 
  13541.                 //now transfer any received checks
  13542.                 $query "SELECT *  from  acc_check where rec_accounts_head_id_list like '%\"" $id "\"%'  ;";
  13543.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  13544.                 
  13545.                 $results $stmt;
  13546.                 foreach ($results as $result) {
  13547.                     $query 'update acc_check set rec_accounts_head_id_list=\''
  13548.                         str_replace("\"" $id "\"""\"" $request->request->get('transferTransactionTo') . "\""$result['rec_accounts_head_id_list']) . '\' '
  13549.                         'where check_id=' $result['check_id'];
  13550.                     $stmt $em->getConnection()->fetchAllAssociative($query);
  13551.                     
  13552.                 }
  13553.                 $this->addFlash(
  13554.                     'success',
  13555.                     'Transferred Transactions '
  13556.                 );
  13557.             }
  13558.             if ($request->request->has('deleteHeadFlag')) {
  13559.                 if (!AccountHeadPermissionService::canDelete($head_data_qry)) {
  13560.                     $this->addFlash('error''Could not Delete Head. This head is protected and cannot be deleted.');
  13561.                 } else {
  13562.                     $query "SELECT accounts_head_id  from  acc_accounts_head  where parent_id=" $id;
  13563.                     $stmt $em->getConnection()->fetchAllAssociative($query);
  13564.                     $results1 $stmt;
  13565.                     if (!empty($results1)) {
  13566.                         $this->addFlash(
  13567.                             'error',
  13568.                             'Could not Delete Head. Child Heads Found'
  13569.                         );
  13570.                     } else {
  13571.                         $query "SELECT * from acc_transaction_details where accounts_head_id =" $id;
  13572.                         $stmt $em->getConnection()->fetchAllAssociative($query);
  13573.                         $results2 $stmt;
  13574.                         if (!empty($results2)) {
  13575.                             $this->addFlash(
  13576.                                 'error',
  13577.                                 'Could not Delete Head. Transactions Entry Found'
  13578.                             );
  13579.                         } else {
  13580.                             $headExists 0;
  13581.                             if ($head_data_qry) {
  13582.                                 AccountHeadExternalMappingService::deleteMappingsForHead($em, (int)$id);
  13583.                                 $em->remove($head_data_qry);
  13584.                                 $em->flush();
  13585.                             }
  13586.                             $this->addFlash(
  13587.                                 'success',
  13588.                                 'Deleted Head'
  13589.                             );
  13590.                         }
  13591.                     }
  13592.                 }
  13593.             } else {
  13594.                 $devAdmin $request->getSession()->get('devAdminMode'0) == 1;
  13595.                 if (!$devAdmin && !AccountHeadPermissionService::canEdit($head_data_qry)) {
  13596.                     $this->addFlash('error''Could not Edit Head. This head is protected and cannot be modified.');
  13597.                 } else {
  13598.                     //            $change_in_opening= $request->request->get('opening_balance')-$head_data_qry->setOpeningBalance();
  13599.                     $head_data_qry->setParentId($request->request->get('parent_id'));
  13600.                     $head_data_qry->setName($request->request->get('name'));
  13601.                     if ($request->request->has('markerHash') && !$head_data_qry->getIsSystem())
  13602.                         $head_data_qry->setMarkerHash($request->request->get('markerHash'));
  13603.                     if ($request->request->has('costCentreTypes'))
  13604.                         $head_data_qry->setCostCentreTypes($request->request->get('costCentreTypes'));
  13605.                     if ($request->request->has('narrationOnCheck'))
  13606.                         $head_data_qry->setNarrationOnCheck($request->request->get('narrationOnCheck'));
  13607.                     $head_data_qry->setLedgerHeadCode($request->request->get('code'));
  13608.                     $head_data_qry->setOpeningBalance($request->request->get('opening_balance'));
  13609.                     $head_nature $request->request->get('head_nature');
  13610.                     $parentHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
  13611.                         "accountsHeadId" => $request->request->get('parent_id')
  13612.                     ));
  13613.                     //                if ($head_nature == '' || $head_nature == '0')
  13614.                     if (1// ovverride ,from now the nature will be asiigned by parent only
  13615.                     {
  13616.                         //            $accountsHead->setHeadnature(in_array($TheType, $credit_type) ? AccountsConstant::CREDIT : AccountsConstant::DEBIT);
  13617.                         $head_data_qry->setHeadnature($parentHead->getHeadNature());
  13618.                     } else
  13619.                         $head_data_qry->setHeadNature($head_nature);
  13620.                     $head_data_qry->setCcEnabled($request->request->get('cc_enabled'));
  13621.                     // Dev admin: allow overriding control flags directly from the form
  13622.                     if ($devAdmin) {
  13623.                         if ($request->request->has('flag_is_system'))
  13624.                             $head_data_qry->setIsSystem((bool)$request->request->get('flag_is_system'));
  13625.                         if ($request->request->has('flag_is_editable'))
  13626.                             $head_data_qry->setIsEditable((bool)$request->request->get('flag_is_editable'));
  13627.                         if ($request->request->has('flag_is_deletable'))
  13628.                             $head_data_qry->setIsDeletable((bool)$request->request->get('flag_is_deletable'));
  13629.                         if ($request->request->has('flag_is_child_allowed'))
  13630.                             $head_data_qry->setIsChildAllowed((bool)$request->request->get('flag_is_child_allowed'));
  13631.                     }
  13632.                     // Optional DATEV mapping update
  13633.                     if ($request->request->has('datev_code') && $request->request->get('datev_code') != '') {
  13634.                         AccountHeadExternalMappingService::setDatevMapping(
  13635.                             $em,
  13636.                             $head_data_qry,
  13637.                             $this->getLoggedUserCompanyId($request),
  13638.                             $request->request->get('datev_code'),
  13639.                             $request->request->has('datev_name') ? $request->request->get('datev_name') : null
  13640.                         );
  13641.                     }
  13642.                     //            if($head_data_qry->getLockFlag()!=1&&$change_in_opening!=0) {
  13643.                     //                $first_closing_date= $em->getRepository('ApplicationBundle\\Entity\\AccClosingBalance')->findOneBy(array(
  13644.                     ////                    'date' => new \DateTime($trans_date),
  13645.                     //                    'accountsHeadId'=>$id
  13646.                     //                ),array('date'=>'ASC'));
  13647.                     //                Accounts::SetClosingBalance($em,$id, $change_in_opening, $head_data_qry->getHeadNature(), $first_closing_date->format('Y-m-d'), $request->getSession()->get(UserConstants::USER_LOGIN_ID), true);
  13648.                     //                Accounts::SetActualClosingBalance($em,$id, $change_in_opening, $head_data_qry->getHeadNature(), $first_closing_date->format('Y-m-d'), $request->getSession()->get(UserConstants::USER_LOGIN_ID), true);
  13649.                     //                Accounts::HitLedger($em, $id, $change_in_opening, $head_data_qry->getHeadNature(), $change_in_opening);
  13650.                     //            }
  13651.                     Accounts::AddHeadPath($em$id);
  13652.                     $em->flush();
  13653.                 }
  13654.             }
  13655.         }
  13656.         $head_data = [];
  13657.         if ($id != '' && $id != && $headExists == 1) {
  13658.             $head_data_qry $this->getDoctrine()
  13659.                 ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  13660.                 ->findOneBy(
  13661.                     array(
  13662.                         'accountsHeadId' => $id,
  13663.                     )
  13664.                 );
  13665.             $head_data['id'] = $head_data_qry->getAccountsHeadId();
  13666.             $head_data['name'] = $head_data_qry->getName();
  13667.             $head_data['narrationOnCheck'] = $head_data_qry->getNarrationOnCheck();
  13668.             $head_data['parent_id'] = $head_data_qry->getParentId();
  13669.             $head_data['marker_hash'] = $head_data_qry->getMarkerHash();
  13670.             $head_data['cost_centre_types'] = $head_data_qry->getCostCentreTypes();
  13671.             $head_data['head_nature'] = $head_data_qry->getHeadNature();
  13672.             $head_data['cc_enabled'] = $head_data_qry->getCcEnabled();
  13673.             $head_data['ledger_head_code'] = $head_data_qry->getLedgerHeadCode();
  13674.             $head_data['opening_balance'] = $head_data_qry->getOpeningBalance();
  13675.             $head_data['is_system'] = $head_data_qry->getIsSystem() ? 0;
  13676.             $head_data['is_editable'] = $head_data_qry->getIsEditable() ? 0;
  13677.             $head_data['is_deletable'] = $head_data_qry->getIsDeletable() ? 0;
  13678.             $head_data['is_child_allowed'] = $head_data_qry->getIsChildAllowed() ? 0;
  13679.             return $this->render(
  13680.                 '@Accounts/pages/input_forms/edit_ledger_head.html.twig',
  13681.                 array(
  13682.                     'page_title' => 'Edit Ledger Head',
  13683.                     'head_data' => $head_data,
  13684.                     'headMarkers' => AccountsConstant::$HEAD_MARKER_ARRAY,
  13685.                     'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
  13686.                 )
  13687.             );
  13688.         } else {
  13689.             return $this->render(
  13690.                 '@Accounts/pages/input_forms/add_ledger_heads.html.twig',
  13691.                 array(
  13692.                     'page_title' => 'Create Ledger Head',
  13693.                     'headMarkers' => AccountsConstant::$HEAD_MARKER_ARRAY,
  13694.                     'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
  13695.                 )
  13696.             );
  13697.         }
  13698.     }
  13699.     public function GetCostCentres(Request $request$headId 0$costCentreTypesStr '')
  13700.     {
  13701.         $cc_id '';
  13702.         $cc_name '';
  13703.         $cc_type '';
  13704.         $cost_centre_types_array_this = [];
  13705.         $em $this->getDoctrine()->getManager();
  13706.         if ($headId != 0) {
  13707.             $queryStr "select * from acc_accounts_head where
  13708.             accounts_head_id=$headId  limit 1";
  13709.             $stmt $em->getConnection()->fetchAllAssociative($queryStr);
  13710.             
  13711.             $results $stmt;
  13712.             $parentIdList = [];
  13713.             if (!empty($results)) {
  13714.                 $headData $results[0];
  13715.                 $parentIdList array_filter(explode(","$headData['path_tree']));
  13716.                 $cost_centre_types_array_this array_filter(explode(","$headData['cost_centre_types']));
  13717.                 $costCentreTypesStr $headData['cost_centre_types'];
  13718.                 if ($costCentreTypesStr == "" || $costCentreTypesStr == null) {
  13719.                     $queryStr "select * from acc_accounts_head where
  13720.             accounts_head_id in ( " implode(','$parentIdList) . " )";
  13721.                     $stmt $em->getConnection()->fetchAllAssociative($queryStr);
  13722.                     
  13723.                     $results $stmt;
  13724.                     if (!empty($results)) {
  13725.                         foreach ($results as $result) {
  13726.                             $headData $result;
  13727.                             $cost_centre_types_array_this_only array_filter(explode(","$headData['cost_centre_types']));
  13728.                             $cost_centre_types_array_this array_merge($cost_centre_types_array_thisarray_diff($cost_centre_types_array_this$cost_centre_types_array_this_only));
  13729.                         }
  13730.                     }
  13731.                 }
  13732.             }
  13733.         }
  13734.         if (empty($cost_centre_types_array_this)) {
  13735.             if ($costCentreTypesStr == "" || $costCentreTypesStr == null) {
  13736.             } else {
  13737.                 $cost_centre_types_array_this array_filter(explode(","$costCentreTypesStr));
  13738.             }
  13739.         }
  13740.         $queryStr "select * from acc_cost_centre where
  13741.             company_id=" $this->getLoggedUserCompanyId($request);
  13742.         if (empty($cost_centre_types_array_this)) {
  13743.             foreach ($cost_centre_types_array_this as $typ)
  13744.                 $queryStr .= " and cost_centre_type like '%" $typ "%' ";
  13745.         }
  13746.         $stmt $em->getConnection()->fetchAllAssociative($queryStr);
  13747.         
  13748.         $cc_data $stmt;
  13749.         $cc_data_list = [];
  13750.         foreach ($cc_data as $value) {
  13751.             $cc_data_list[$value['cost_centre_id']]['id'] = $value['cost_centre_id'];
  13752.             $cc_data_list[$value['cost_centre_id']]['name'] = $value['name'];
  13753.             $cc_data_list[$value['cost_centre_id']]['type'] = $value['cost_centre_type'];
  13754.         }
  13755.         if (!empty($cc_data_list))
  13756.             return new JsonResponse(array(
  13757.                 'success' => true,
  13758.                 'data' => $cc_data_list
  13759.             ));
  13760.         else
  13761.             return new JsonResponse(array(
  13762.                 'success' => false,
  13763.                 'data' => $cc_data_list
  13764.             ));
  13765.     }
  13766.     public function CreateCostCentre(Request $request$id)
  13767.     {
  13768.         $em $this->getDoctrine()->getManager();
  13769.         $cc_id '';
  13770.         $cc_name '';
  13771.         $cc_type '';
  13772.         if ($request->isMethod('POST')) {
  13773.             $em $this->getDoctrine()->getManager();
  13774.             //            $submittedToken = $request->request->get('token');
  13775.             //
  13776.             //            // 'delete-item' is the same value used in the template to generate the token
  13777.             //            if ($this->isCsrfTokenValid('delete-item', $submittedToken)) {
  13778.             //                // ... do something, like deleting an object
  13779.             //            }
  13780.             //            return new Response(1);
  13781.             if ($request->request->get('cc_id') != '' && $request->request->get('cc_id') != 0) {
  13782.                 $em $this->getDoctrine()->getManager();
  13783.                 $new_cc $this->getDoctrine()
  13784.                     ->getRepository('ApplicationBundle\\Entity\\AccCostCentre')
  13785.                     ->findOneBy(
  13786.                         array(
  13787.                             'costCentreId' => $id,
  13788.                         )
  13789.                     );
  13790.                 $new_cc->setName($request->request->get('name'));
  13791.                 $new_cc->setCostCentreType($request->request->get('costCentreType'));
  13792.                 $new_cc->setCompanyId($this->getLoggedUserCompanyId($request));
  13793.                 $em->flush();
  13794.             } else {
  13795.                 $new_cc = new AccCostCentre();
  13796.                 $new_cc->setName($request->request->get('name'));
  13797.                 $new_cc->setCostCentreType($request->request->get('costCentreType'));
  13798.                 $new_cc->setCompanyId($this->getLoggedUserCompanyId($request));
  13799.                 $em->persist($new_cc);
  13800.                 $em->flush();
  13801.                 $new_cc->getCostCentreId();
  13802.             }
  13803.         }
  13804.         $cc_data $this->getDoctrine()
  13805.             ->getRepository('ApplicationBundle\\Entity\\AccCostCentre')
  13806.             ->findAll();
  13807.         $cc_data_list = [];
  13808.         foreach ($cc_data as $value) {
  13809.             $cc_data_list[$value->getCostCentreId()]['id'] = $value->getCostCentreId();
  13810.             $cc_data_list[$value->getCostCentreId()]['name'] = $value->getName();
  13811.             $cc_data_list[$value->getCostCentreId()]['type'] = $value->getCostCentreType();
  13812.             if ($value->getCostCentreId() == $id) {
  13813.                 $cc_id $value->getCostCentreId();
  13814.                 $cc_name $value->getName();
  13815.                 $cc_type $value->getCostCentreType();
  13816.             }
  13817.         }
  13818.         return $this->render(
  13819.             '@Accounts/pages/input_forms/add_cost_centre.html.twig',
  13820.             array(
  13821.                 'page_title' => 'Cost Centre',
  13822.                 'cc_data' => $cc_data_list,
  13823.                 'cc_id' => $cc_id,
  13824.                 'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
  13825.                 'costCentreTypes' => AccountsConstant::$costCentreTypes,
  13826.                 'cc_name' => $cc_name,
  13827.                 'cc_type' => $cc_type
  13828.             )
  13829.         );
  13830.     }
  13831.     public function index(Request $request)
  13832.     {
  13833.         return $this->render(
  13834.             '@Application/pages/dashboard/index.html.twig',
  13835.             array(
  13836.                 'page_title' => 'Dashboard'
  13837.             )
  13838.         );
  13839.     }
  13840.     public function TestPixInvent(Request $request)
  13841.     {
  13842.         $em $this->getDoctrine()->getManager();
  13843.         $allowed_ids = [];
  13844.         $companyId $this->getLoggedUserCompanyId($request);
  13845.         //        return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  13846.         return $this->render(
  13847.             '@Application/pages/dashboard/codecovers_test.html.twig',
  13848.             array(
  13849.                 'page_title' => 'Client List',
  13850.                 'data' => SalesOrderM::GetClientList($em, [], $companyId),
  13851.                 'client_types' => Client::GetClientType($em$companyId),
  13852.                 'region_list' => Client::RegionList($em$companyId),
  13853.                 'geographical_region_list' => Client::GeographicalRegionList($em$companyId)
  13854.             )
  13855.         );
  13856.     }
  13857.     public function GetDocumentHash(Request $request$t$p$a)
  13858.     {
  13859.         $em $this->getDoctrine()->getManager();
  13860.         $companyId $this->getLoggedUserCompanyId($request);
  13861.         $timestamp $request->request->get('timeStampOfForm'$request->query->get('timeStampOfForm'''));
  13862.         $documentId $request->request->get('documentId'$request->query->get('documentId'0));
  13863.         if ($request->query->has('returnJson'))
  13864.             return new JsonResponse(array(
  13865.                 'success' => true,
  13866.                 'numberHash' => MiscActions::GetNumberHash($em$t$p$a$timestamp$documentId$companyId)
  13867.             ));
  13868.         else
  13869.             return new Response(MiscActions::GetNumberHash($em$t$p$a$timestamp$documentId$companyId));
  13870.     }
  13871.     public function CreatePrefix(Request $request)
  13872.     {
  13873.         if ($request->isMethod('POST')) {
  13874.             //            Generic::debugMessage($_POST);
  13875.             //
  13876.             $ledgerHeads = [];
  13877.             $costCenters = [];
  13878.             $prefix_name $request->request->get('pref_name');
  13879.             $prefix_usages $request->request->get('pref_usages');
  13880.             $prefix_entry_types $request->request->get('entryTypes');
  13881.             if ($prefix_name != 'GN' || $prefix_name != 'gn') {
  13882.                 $ledgerHeads $request->request->get('ledgerHeads');
  13883.                 $costCenters $request->request->get('costCenters');
  13884.                 $prefix_name $request->request->get('pref_name');
  13885.                 $prefix_usages $request->request->get('pref_usages');
  13886.                 $prefix_entry_types $request->request->get('entryTypes');
  13887.             }
  13888.             // Form arrays may be absent on a POST (e.g. a GN prefix with no ledger
  13889.             // heads) → coalesce to arrays so count()/indexing don't fatal (PHP 7.2+).
  13890.             $ledgerHeads is_array($ledgerHeads) ? $ledgerHeads : [];
  13891.             $costCenters is_array($costCenters) ? $costCenters : [];
  13892.             $prefix_usages is_array($prefix_usages) ? $prefix_usages : [];
  13893.             $prefix_entry_types is_array($prefix_entry_types) ? $prefix_entry_types : [];
  13894.             //            $crAmount=$request->request->get('crAmount');
  13895.             $prefix_details = array();
  13896.             for ($i 0$i count($ledgerHeads); $i++) {
  13897.                 array_push($prefix_details, array(
  13898.                     'head_id' => $ledgerHeads[$i],
  13899.                     'cost_centre' => isset($costCenters[$i]) ? $costCenters[$i] : 0,
  13900.                     'type' => $prefix_entry_types[$i],
  13901.                 ));
  13902.             }
  13903.             for ($i 0$i count($prefix_usages); $i++) {
  13904.                 Accounts::CreateNewPrefix(
  13905.                     $this->getDoctrine()->getManager(),
  13906.                     $prefix_usages[$i],
  13907.                     $prefix_name,
  13908.                     $prefix_details
  13909.                 );
  13910.             }
  13911.             $this->addFlash(
  13912.                 'success',
  13913.                 'New Prefix Added.'
  13914.             );
  13915.         }
  13916.         return $this->render(
  13917.             '@Accounts/pages/input_forms/add_prefix.html.twig',
  13918.             array(
  13919.                 'page_title' => 'Prefix'
  13920.             )
  13921.         );
  13922.     }
  13923.     public function BankRecon(Request $request$id 0)
  13924.     {
  13925.         $em $this->getDoctrine()->getManager();
  13926.         $bank_settings $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  13927.             'name' => 'bank_parents'
  13928.         ));
  13929.         $bank_id_list = [];
  13930.         if ($bank_settings)
  13931.             $bank_id_list json_decode($bank_settings->getData());
  13932.         $head_list Accounts::HeadListFullPath($em);
  13933.         $bank_head_list = [];
  13934.         foreach ($head_list as $k => $v) {
  13935.             foreach ($bank_id_list as $bid) {
  13936.                 $q_str '/' $bid '/';
  13937.                 $path_string $v['path'];
  13938.                 $debug_it[] = [$q_str$path_stringstrpos($path_string$q_str)];
  13939.                 if (strpos($path_string$q_str) !== false) {
  13940.                     $bank_head_list[$k] = $v;
  13941.                 } else {
  13942.                 }
  13943.             }
  13944.         }
  13945.         //        if($request->isMethod('POST')){
  13946.         //            //it will be used on the approval page start
  13947.         //                      //it will be used on the approval page start
  13948.         //        }
  13949.         if ($request->isMethod('POST')) {
  13950.             $em $this->getDoctrine()->getManager();
  13951.             $entity_id array_flip(GeneralConstant::$Entity_list)['Brs'];
  13952.             $typeHash "BRS-" $request->request->get('bank_head');
  13953.             $brsDate = new \DateTime($request->request->get('statement_date'));
  13954.             $prefixHash $brsDate->format('Y');
  13955.             $assocHash $brsDate->format('m');
  13956.             $numberHash $brsDate->format('d');
  13957.             //            $dochash=$request->request->get('docHash');
  13958.             $dochash $typeHash '/' $prefixHash '/' $assocHash '/' $numberHash;
  13959.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13960.             $approveRole $request->request->get('approvalRole') ? $request->request->get('approvalRole') : 1;
  13961.             $approveHash $request->request->has('approvalHash') ? $request->request->get('approvalHash') : '';
  13962.             $skipApprove 0;
  13963.             //            if($approveHash=='') {
  13964.             //                $skipApprove = 1;//temp
  13965.             //            }
  13966.             if (!DocValidation::isInsertable(
  13967.                 $em,
  13968.                 $entity_id,
  13969.                 $dochash,
  13970.                 $loginId,
  13971.                 $approveRole,
  13972.                 $approveHash,
  13973.                 $id,
  13974.                 $skipApprove
  13975.             )) {
  13976.                 $this->addFlash(
  13977.                     'error',
  13978.                     'Sorry Could not insert Data.'
  13979.                 );
  13980.             } else {
  13981.                 //construct the files
  13982.                 $post_data $request->request;
  13983.                 $brs $em
  13984.                     ->getRepository('ApplicationBundle\\Entity\\Brs')
  13985.                     ->findOneby(array(
  13986.                         'brsId' => $id
  13987.                     ));
  13988.                 if ($brs)
  13989.                     $new $brs;
  13990.                 else
  13991.                     $new = new Brs();
  13992.                 $LoginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  13993.                 $companyId $this->getLoggedUserCompanyId($request);
  13994.                 $data = array();
  13995.                 $exception_key_list = [
  13996.                     'approvalRole',
  13997.                     'approvalHash',
  13998.                     'assocHash',
  13999.                     'numberHash',
  14000.                     'typeHash',
  14001.                     'prefixHash',
  14002.                     'pending_cn',
  14003.                     'pending_vn',
  14004.                     'cleared_cn',
  14005.                     'cleared_vn',
  14006.                     'pending_check_amount_old',
  14007.                     'pending_check_amount_add_old',
  14008.                     'nsf_cn',
  14009.                     'nsf_vn',
  14010.                 ];
  14011.                 $prTypeList = array(
  14012.                     => 'Document',
  14013.                     => 'Ind. Check',
  14014.                     => 'Cons. Check',
  14015.                     => 'Adv. Letter',
  14016.                     => 'O/L Trans',
  14017.                 );
  14018.                 //adding vn and cn
  14019.                 $pending_cn = [];
  14020.                 $pending_vn = [];
  14021.                 foreach (json_decode($post_data->get('pending_check_id'), true) as $v) {
  14022.                     $check $em
  14023.                         ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  14024.                         ->findOneby(array(
  14025.                             'CheckId' => $v
  14026.                         ));
  14027.                     if ($check) {
  14028.                         $pending_cn[] = $check->getCheckNumber();
  14029.                         $vchr $em
  14030.                             ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  14031.                             ->findOneby(array(
  14032.                                 'transactionId' => $check->getVoucherId()
  14033.                             ));
  14034.                         if ($vchr) {
  14035.                             $pending_vn[] = $vchr->getDocumentHash();
  14036.                         } else
  14037.                             $pending_vn[] = '';
  14038.                     } else {
  14039.                         $vid explode('_'explode('v'$v)[1])[0];
  14040.                         $vchr $em
  14041.                             ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  14042.                             ->findOneby(array(
  14043.                                 'transactionId' => $vid
  14044.                             ));
  14045.                         if ($vchr) {
  14046.                             $prRef $vchr->getPrReference();
  14047.                             if ($prRef == '0') {
  14048.                                 $prRef $prTypeList[$vchr->getPrMethod()] . " on " $vchr->getDocumentHash();
  14049.                             }
  14050.                             if ($vchr->getDocumentType() == 6) {
  14051.                                 $prRef "Cash Received on " $vchr->getDocumentHash();
  14052.                             }
  14053.                             $pending_cn[] = $prRef;
  14054.                             $pending_vn[] = $vchr->getDocumentHash();
  14055.                         }
  14056.                     }
  14057.                 }
  14058.                 $data['pending_cn'] = $pending_cn;
  14059.                 $data['pending_vn'] = $pending_vn;
  14060.                 $cleared_cn = [];
  14061.                 $cleared_vn = [];
  14062.                 foreach (json_decode($post_data->get('cleared_check_id'), true) as $v) {
  14063.                     $check $em
  14064.                         ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  14065.                         ->findOneby(array(
  14066.                             'CheckId' => $v
  14067.                         ));
  14068.                     if ($check) {
  14069.                         $cleared_cn[] = $check->getCheckNumber();
  14070.                         $vchr $em
  14071.                             ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  14072.                             ->findOneby(array(
  14073.                                 'transactionId' => $check->getVoucherId()
  14074.                             ));
  14075.                         if ($vchr) {
  14076.                             $cleared_vn[] = $vchr->getDocumentHash();
  14077.                         } else
  14078.                             $cleared_vn[] = '';
  14079.                     } else {
  14080.                         $vid explode('_'explode('v'$v)[1])[0];
  14081.                         $vchr $em
  14082.                             ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  14083.                             ->findOneby(array(
  14084.                                 'transactionId' => $vid
  14085.                             ));
  14086.                         if ($vchr) {
  14087.                             $prRef $vchr->getPrReference();
  14088.                             if ($prRef == '0') {
  14089.                                 $prRef $prTypeList[$vchr->getPrMethod()] . " on " $vchr->getDocumentHash();
  14090.                             }
  14091.                             if ($vchr->getDocumentType() == 6) {
  14092.                                 $prRef "Cash Received on " $vchr->getDocumentHash();
  14093.                             }
  14094.                             $cleared_cn[] = $prRef;
  14095.                             $cleared_vn[] = $vchr->getDocumentHash();
  14096.                         }
  14097.                     }
  14098.                 }
  14099.                 $data['cleared_cn'] = $cleared_cn;
  14100.                 $data['cleared_vn'] = $cleared_vn;
  14101.                 $nsf_cn = [];
  14102.                 $nsf_vn = [];
  14103.                 foreach (json_decode($post_data->get('nsf_check_id'), true) as $v) {
  14104.                     $check $em
  14105.                         ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  14106.                         ->findOneby(array(
  14107.                             'CheckId' => $v
  14108.                         ));
  14109.                     if ($check) {
  14110.                         $nsf_cn[] = $check->getCheckNumber();
  14111.                         $vchr $em
  14112.                             ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  14113.                             ->findOneby(array(
  14114.                                 'transactionId' => $check->getVoucherId()
  14115.                             ));
  14116.                         if ($vchr) {
  14117.                             $nsf_vn[] = $vchr->getDocumentHash();
  14118.                         } else
  14119.                             $nsf_vn[] = '';
  14120.                     } else {
  14121.                         $vid explode('_'explode('v'$v)[1])[0];
  14122.                         $vchr $em
  14123.                             ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  14124.                             ->findOneby(array(
  14125.                                 'transactionId' => $vid
  14126.                             ));
  14127.                         if ($vchr) {
  14128.                             $prRef $vchr->getPrReference();
  14129.                             if ($prRef == '0') {
  14130.                                 $prRef $prTypeList[$vchr->getPrMethod()] . " on " $vchr->getDocumentHash();
  14131.                             }
  14132.                             if ($vchr->getDocumentType() == 6) {
  14133.                                 $prRef "Cash Received on " $vchr->getDocumentHash();
  14134.                             }
  14135.                             $nsf_cn[] = $prRef;
  14136.                             $nsf_vn[] = $vchr->getDocumentHash();
  14137.                         }
  14138.                     }
  14139.                 }
  14140.                 $data['nsf_cn'] = $nsf_cn;
  14141.                 $data['nsf_vn'] = $nsf_vn;
  14142.                 foreach ($post_data->keys() as $req_key) {
  14143.                     if (!in_array($req_key$exception_key_list)) {
  14144.                         if (in_array($req_key, ['pending_check_amount''pending_check_amount_add''pending_check_id''cleared_check_id''nsf_check_id''pending_head_id''pending_rec_id_list''cleared_cn''cleared_vn''cleared_cd''pending_cn''pending_vn''pending_cd''nsf_cn''nsf_vn''nsf_cd'])) {
  14145.                             $data[$req_key] = json_decode($post_data->get($req_key), true);
  14146.                         } else
  14147.                             $data[$req_key] = $post_data->get($req_key);
  14148.                     }
  14149.                 }
  14150.                 $new->setBrsDate($brsDate);
  14151.                 $new->setDocumentHash($dochash);
  14152.                 $new->setTypeHash($typeHash);
  14153.                 $new->setPrefixHash($prefixHash);
  14154.                 $new->setNumberHash($numberHash);
  14155.                 $new->setAssocHash($assocHash);
  14156.                 $new->setAccountsHeadId($request->request->get('bank_head'));
  14157.                 $new->setCompanyId($companyId);
  14158.                 $new->setData(json_encode($data));
  14159.                 $new->setStatus(GeneralConstant::ACTIVE);
  14160.                 //                if($auto_created==1)
  14161.                 //                    $new->setApproved(GeneralConstant::APPROVED);
  14162.                 //                else
  14163.                 $new->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  14164.                 $new->setAutoCreated(0);
  14165.                 $new->setEditFlag(0);
  14166.                 $new->setDeleteFlag(0);
  14167.                 $new->setLockFlag(0);
  14168.                 $new->setDisabledFlag(0);
  14169.                 if (!$brs) {
  14170.                     $new->setCreatedLoginId($LoginId);
  14171.                 } else
  14172.                     $new->setEditedLoginId($LoginId);
  14173.                 $em->persist($new);
  14174.                 $em->flush();
  14175.                 $docId $new->getBrsId();
  14176.                 //now add Approval info
  14177.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14178.                 $approveRole $request->request->get('approvalRole');  //created
  14179.                 System::setApprovalInfo(
  14180.                     $this->getDoctrine()->getManager(),
  14181.                     [],
  14182.                     array_flip(GeneralConstant::$Entity_list)['Brs'],
  14183.                     $docId,
  14184.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  14185.                 );
  14186.                 System::createEditSignatureHash(
  14187.                     $this->getDoctrine()->getManager(),
  14188.                     array_flip(GeneralConstant::$Entity_list)['Brs'],
  14189.                     $docId,
  14190.                     $loginId,
  14191.                     $approveRole,
  14192.                     $request->request->get('approvalHash')
  14193.                 );
  14194.                 $this->addFlash(
  14195.                     'success',
  14196.                     'Bank Reconciliation Created'
  14197.                 );
  14198.                 $url $this->generateUrl(
  14199.                     'view_brs'
  14200.                 );
  14201.                 System::AddNewNotification(
  14202.                     $this->container->getParameter('notification_enabled'),
  14203.                     $this->container->getParameter('notification_server'),
  14204.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  14205.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  14206.                     "Bank Reconciliation : " $dochash " Has Been Created And is Under Processing",
  14207.                     'pos',
  14208.                     System::getPositionIdsByDepartment($emGeneralConstant::SALES_DEPARTMENT),
  14209.                     'success',
  14210.                     $url "/" $docId,
  14211.                     "BRS"
  14212.                 );
  14213.                 return $this->redirect($url "/" $docId);
  14214.             }
  14215.         }
  14216.         $check_query $this->getDoctrine()
  14217.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  14218.             ->findBy(
  14219.                 array(
  14220.                     'assigned' => 1,
  14221.                     'status' => 3//pending
  14222.                     'active' => 1,
  14223.                     'destroyed' => [0null],
  14224.                     'securityCheck' => [0null],
  14225.                 ),
  14226.                 array(
  14227.                     'checkNumber' => 'ASC'
  14228.                 )
  14229.             );
  14230.         $check_data = [];
  14231.         $voucher_list Accounts::VoucherList($em);
  14232.         foreach ($check_query as $check_here) {
  14233.             $new_check_data = array(
  14234.                 'checkId' => $check_here->getCheckId(),
  14235.                 'checkNumber' => $check_here->getCheckNumber(),
  14236.                 'voucherId' => $check_here->getVoucherId(),
  14237.                 'voucherNumber' => isset($voucher_list[$check_here->getVoucherId()]) ? $voucher_list[$check_here->getVoucherId()]['doc_hash'] : '',
  14238.                 'checkDate' => $check_here->getCheckDate() ? $check_here->getCheckDate()->format('Y-m-d') : '',
  14239.                 'transactionDate' => isset($voucher_list[$check_here->getVoucherId()]) ? ($voucher_list[$check_here->getVoucherId()]['date'] ? $voucher_list[$check_here->getVoucherId()]['date']->format('Y-m-d') : '') : ($check_here->getCheckDate() ? $check_here->getCheckDate()->format('Y-m-d') : ''),
  14240.                 //                'reconDate'=>$recondatestr,
  14241.             );
  14242.             $check_data[$check_here->getCheckId()] = $new_check_data;
  14243.         }
  14244.         return $this->render(
  14245.             '@Accounts/pages/input_forms/bank_recon.html.twig',
  14246.             array(
  14247.                 'page_title' => 'Bank ',
  14248.                 'check_list' => $check_data,
  14249.                 'bank_head_list' => $bank_head_list,
  14250.                 'bank_id_list' => $bank_id_list,
  14251.             )
  14252.         );
  14253.     }
  14254.     public function CheckRecon(Request $request)
  14255.     {
  14256.         $em $this->getDoctrine()->getManager();
  14257.         if ($request->isMethod('POST')) {
  14258.             $check_ids $request->request->get('check_id');
  14259.             $recon_dates $request->request->get('recon_date');
  14260.             if (!empty($check_ids)) {
  14261.                 foreach ($check_ids as $key => $c) {
  14262.                     $check $this->getDoctrine()
  14263.                         ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  14264.                         ->findOneBy(
  14265.                             array(
  14266.                                 'CheckId' => $c
  14267.                             )
  14268.                         );
  14269.                     if ($check) {
  14270.                         $check->setStatus(1); //transaction confirmed
  14271.                         $check->setReconDate(new \DateTime($recon_dates[$key]));
  14272.                         $em->flush();
  14273.                         Accounts::ActionAfterNonProvisionalVoucher($em$check->getVoucherId());
  14274.                     }
  14275.                 }
  14276.             }
  14277.         }
  14278.         $check_query $this->getDoctrine()
  14279.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  14280.             ->findBy(
  14281.                 array(
  14282.                     'assigned' => 1,
  14283.                     'status' => 3//pending
  14284.                     'active' => 1
  14285.                 ),
  14286.                 array(
  14287.                     'checkNumber' => 'ASC'
  14288.                 )
  14289.             );
  14290.         $check_data = [];
  14291.         $voucher_list Accounts::VoucherList($em);
  14292.         foreach ($check_query as $check_here) {
  14293.             $new_check_data = array(
  14294.                 'checkId' => $check_here->getCheckId(),
  14295.                 'checkNumber' => $check_here->getCheckNumber(),
  14296.                 'voucherId' => $check_here->getVoucherId(),
  14297.                 'voucherNumber' => $voucher_list[$check_here->getVoucherId()]['doc_hash'],
  14298.                 'checkDate' => $check_here->getCheckDate()->format('Y-m-d'),
  14299.                 'transactionDate' => $voucher_list[$check_here->getVoucherId()]['date']->format('Y-m-d'),
  14300.                 //                'reconDate'=>$recondatestr,
  14301.             );
  14302.             $check_data[$check_here->getCheckId()] = $new_check_data;
  14303.         }
  14304.         return $this->render(
  14305.             '@Accounts/pages/input_forms/check_recon.html.twig',
  14306.             array(
  14307.                 'page_title' => 'Bank Reconciliation',
  14308.                 'check_list' => $check_data
  14309.             )
  14310.         );
  14311.     }
  14312.     public function ExcelTest(Request $request)
  14313.     {
  14314.         // ask the service for a Excel5
  14315.         $phpExcelObject $this->get('phpexcel')->createPHPExcelObject();
  14316.         $phpExcelObject->getProperties()->setCreator("liuggio")
  14317.             ->setLastModifiedBy("Giulio De Donato")
  14318.             ->setTitle("Office 2005 XLSX Test Document")
  14319.             ->setSubject("Office 2005 XLSX Test Document")
  14320.             ->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.")
  14321.             ->setKeywords("office 2005 openxml php")
  14322.             ->setCategory("Test result file");
  14323.         $phpExcelObject->setActiveSheetIndex(0)
  14324.             ->setCellValue('A1''Hello')
  14325.             ->setCellValue('B2''world!');
  14326.         $phpExcelObject->getActiveSheet()->setTitle('Simple');
  14327.         // Set active sheet index to the first sheet, so Excel opens this as the first sheet
  14328.         $phpExcelObject->setActiveSheetIndex(0);
  14329.         // create the writer
  14330.         $writer $this->get('phpexcel')->createWriter($phpExcelObject'Excel5');
  14331.         // create the response
  14332.         $response $this->get('phpexcel')->createStreamedResponse($writer);
  14333.         // adding headers
  14334.         $dispositionHeader $response->headers->makeDisposition(
  14335.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  14336.             'stream-file.xls'
  14337.         );
  14338.         $response->headers->set('Content-Type''text/vnd.ms-excel; charset=utf-8');
  14339.         $response->headers->set('Pragma''public');
  14340.         $response->headers->set('Cache-Control''maxage=1');
  14341.         $response->headers->set('Content-Disposition'$dispositionHeader);
  14342.         return $response;
  14343.     }
  14344.     public function ImageUpload(Request $request)
  14345.     {
  14346.         $post_data $request->request;
  14347.         $file $post_data->get('file');
  14348.         $fileName "";
  14349.         if ($file) {
  14350.             if ($post_data->has('isBase64')) {
  14351.                 $data base64_decode(preg_replace('#^data:image/\w+;base64,#i'''$file));
  14352.                 $fileName md5(uniqid()) . '.png';
  14353.                 $path $fileName;
  14354.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/';
  14355.                 if (!file_exists($upl_dir)) {
  14356.                     mkdir($upl_dir0777true);
  14357.                 }
  14358.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/' $path;
  14359.                 file_put_contents($upl_dir$data);
  14360.             } else {
  14361.                 $fileName md5(uniqid()) . '.' $file->guessExtension();
  14362.                 $path $fileName;
  14363.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/';
  14364.                 if (!file_exists($upl_dir)) {
  14365.                     mkdir($upl_dir0777true);
  14366.                 }
  14367.                 $file $file->move($upl_dir$path);
  14368.             }
  14369.         }
  14370.         return new JsonResponse(array('file_name' => $fileName));
  14371.     }
  14372.     public function ExportPagePdf(Request $request)
  14373.     {
  14374.         //        $l= $this->get('knp_snappy.pdf')->generateFromHtml($html
  14375.         //            ,
  14376.         //            $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/myfile.pdf'
  14377.         //        );
  14378.         //        $chk=$this->get('knp_snappy.pdf');
  14379.         if ($request->getMethod() == 'POST') {
  14380.             $data $request->request->has('exportable_data') ? $request->request->get('exportable_data') : '';
  14381.             $doc_title $request->request->has('doc_title') ? $request->request->get('doc_title') : 'Exported_data';
  14382.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($data, array(
  14383.                 //                'orientation' => 'landscape',
  14384.                 //                'enable-javascript' => true,
  14385.                 //                'javascript-delay' => 1000,
  14386.                 'no-stop-slow-scripts' => true,
  14387.                 'no-background' => false,
  14388.                 'lowquality' => false,
  14389.                 'encoding' => 'utf-8',
  14390.                 //            'images' => true,
  14391.                 //            'cookie' => array(),
  14392.                 'dpi' => 300,
  14393.                 'image-dpi' => 300,
  14394.                 //                'enable-external-links' => true,
  14395.                 //                'enable-internal-links' => true
  14396.             ));
  14397.             return new Response(
  14398.                 $pdf_response,
  14399.                 200,
  14400.                 array(
  14401.                     'Content-Type' => 'application/pdf',
  14402.                     'Content-Disposition' => 'attachment; filename="' $doc_title '.pdf"'
  14403.                 )
  14404.             );
  14405.         }
  14406.     }
  14407.     public function ExportTableDataExcel(Request $request)
  14408.     {
  14409.         // ask the service for a Excel5
  14410.         $em $this->getDoctrine()->getManager();
  14411.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  14412.         $company_name $company_data->getName();
  14413.         $company_address $company_data->getAddress();
  14414.         $company_invoice_footer $company_data->getInvoiceFooter();
  14415.         $replace_list = array(
  14416.             '%companyName%' => $company_name,
  14417.             '%companyAddress%' => $company_address,
  14418.         );
  14419.         if ($request->isMethod('POST')) {
  14420.             //            $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
  14421.             //            $spreadsheet = new Spreadsheet();
  14422.             //
  14423.             //            $sheet = $spreadsheet->getActiveSheet();
  14424.             //            $sheet->setCellValue('A1', 'Hello World !');
  14425.             //
  14426.             //            $writer = new Xlsx($spreadsheet);
  14427.             //            $writer->save('hello world.xlsx');
  14428.             if (version_compare(PHP_VERSION'7.3.0''>=')) {
  14429.                 $phpExcelObject = new Spreadsheet();
  14430.             } else {
  14431.                 $phpExcelObject $this->get('phpexcel')->createPHPExcelObject();
  14432.             }
  14433.             $phpExcelObject->getProperties()->setCreator("HoneyBee IoT Ltd.")
  14434.                 ->setLastModifiedBy("Honeybee Ecosystem")
  14435.                 ->setTitle("Office 2005 XLSX Test Document")
  14436.                 ->setSubject("Office 2005 XLSX Test Document")
  14437.                 ->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.")
  14438.                 ->setKeywords("office 2005 openxml php")
  14439.                 ->setCategory("Test result file");
  14440.             $data $request->request->has('exportable_data') ? json_decode($request->request->get('exportable_data'), true) : [];
  14441.             $sheet_title_data $request->request->has('sheet_title') ? json_decode($request->request->get('sheet_title'), true) : [];
  14442.             $doc_title $request->request->has('doc_title') ? $request->request->get('doc_title') : 'Exported_data';
  14443.             $sheet_id 0;
  14444.             foreach ($data as $list_index => $sheet) {
  14445.                 $phpExcelObject->createSheet($sheet_id);
  14446.                 $celldata = isset($sheet['data']) ? ($sheet['data']) : [];
  14447.                 $mergedata = isset($sheet['merge_data']) ? ($sheet['merge_data']) : [];
  14448.                 $styleArray = array(
  14449.                     'font' => array(
  14450.                         'bold' => false,
  14451.                         'color' => array('rgb' => '000000'),
  14452.                         'size' => 12,
  14453.                         'name' => 'Verdana',
  14454.                     ),
  14455.                     'alignment' => array(
  14456.                         'horizontal' => 'left',
  14457.                         'vertical' => 'middle',
  14458.                     )
  14459.                 );
  14460.                 $phpExcelObject->getDefaultStyle()
  14461.                     ->applyFromArray(
  14462.                         $styleArray
  14463.                     );
  14464.                 //
  14465.                 //                $phpExcelObject->getDefaultStyle()
  14466.                 //                    ->getAlignment()
  14467.                 //                    ->applyFromArray(
  14468.                 //                        array('horizontal' => 'left',));
  14469.                 foreach ($celldata as $cell_info) {
  14470.                     $cell_text = isset($replace_list[$cell_info['cell_data']]) ? $replace_list[$cell_info['cell_data']] : $cell_info['cell_data'];
  14471.                     $phpExcelObject->setActiveSheetIndex($sheet_id)->setCellValue($cell_info['cell_no'], $cell_text);
  14472.                     //                    $phpExcelObject->setActiveSheetIndex($sheet_id)->setCellValue($cell_info['cell_no'], json_encode($cell_info));
  14473.                     //                    $phpExcelObject->getActiveSheet()->getStyle($cell_info['cell_no'])->applyFromArray(array(           'alignment'=>['horizontal='=>$cell_info['align'] ]));
  14474.                     if (isset($cell_info['align']))
  14475.                         $phpExcelObject->getActiveSheet()->getStyle($cell_info['cell_no'])->getAlignment()->applyFromArray(
  14476.                             array('horizontal' => $cell_info['align'], 'vertical' => 'middle',)
  14477.                         );
  14478.                 }
  14479.                 foreach ($mergedata as $merge_info) {
  14480.                     if ($merge_info['enabled'] == 1)
  14481.                         $phpExcelObject->setActiveSheetIndex($sheet_id)->mergeCells($merge_info['merge_str']);
  14482.                 }
  14483.                 //now the sheet title
  14484.                 $sheet_name $sheet_title_data[$list_index];
  14485.                 $sheet_name str_ireplace('/'''$sheet_name);
  14486.                 $sheet_name str_ireplace(':'' '$sheet_name);
  14487.                 //                $sheet_name=str_ireplace('\n','',$sheet_name);
  14488.                 $sheet_name trim(preg_replace('/\s\s+/'' '$sheet_name));;
  14489.                 //                            System::log_it($this->container->getParameter('kernel.root_dir'),$sheet_name,'sheet_test');
  14490.                 if (strlen($sheet_name) > 31) {
  14491.                     //have to truncate
  14492.                     //first find if it has 'of and only take later part'
  14493.                     while (count(explode("of"$sheet_name)) > && strlen($sheet_name) > 31) {
  14494.                         $pieces explode("of"$sheet_name);
  14495.                         $sheet_name str_replace($pieces[0], ""$sheet_name);
  14496.                         $sheet_name str_replace($pieces[0], ""$sheet_name);
  14497.                     }
  14498.                     //now remove 1 word form start until length matches
  14499.                     //                    while(count(explode(" ", $sheet_name))>1&&strlen($sheet_name)>31) {
  14500.                     //                        $pieces = explode(" ", $sheet_name);
  14501.                     //                        if(count($pieces)<=1)
  14502.                     //                            break;
  14503.                     //                        $sheet_name=str_replace($pieces[0], "", $sheet_name);
  14504.                     ////                        str_replace()
  14505.                     ////                        $sheet_name = str_replace($pieces[0], "", $sheet_name);
  14506.                     //                    }
  14507.                     if (strlen($sheet_name) > 31//now just chop
  14508.                     {
  14509.                         $sheet_name substr($sheet_name030);
  14510.                     }
  14511.                 }
  14512.                 $phpExcelObject->getActiveSheet()->setTitle($sheet_name);
  14513.                 $sheet $phpExcelObject->getActiveSheet();
  14514.                 $cellIterator $sheet->getRowIterator()->current()->getCellIterator();
  14515.                 $cellIterator->setIterateOnlyExistingCells(true);
  14516.                 /** @var PHPExcel_Cell $cell */
  14517.                 foreach ($cellIterator as $cell) {
  14518.                     $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
  14519.                 }
  14520.                 $sheet_id++;
  14521.             }
  14522.             // Auto size columns for each worksheet
  14523.             //            foreach ($phpExcelObject->getWorksheetIterator() as $worksheet) {
  14524.             //
  14525.             //                $phpExcelObject->setActiveSheetIndex($phpExcelObject->getIndex($worksheet));
  14526.             //
  14527.             //                $sheet = $phpExcelObject->getActiveSheet();
  14528.             //                $cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
  14529.             //                $cellIterator->setIterateOnlyExistingCells(true);
  14530.             //                /** @var PHPExcel_Cell $cell */
  14531.             //                foreach ($cellIterator as $cell) {
  14532.             //                    $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
  14533.             //                }
  14534.             //            }
  14535.             //
  14536.             // Set active sheet index to the first sheet, so Excel opens this as the first sheet
  14537.             if (version_compare(PHP_VERSION'7.3.0''>=')) {
  14538.                 $writer = new Xlsx($phpExcelObject);
  14539.                 $response = new StreamedResponse(
  14540.                     function () use ($writer) {
  14541.                         $writer->save('php://output');
  14542.                     }
  14543.                 );
  14544.             } else {
  14545.                 $writer $this->get('phpexcel')->createWriter($phpExcelObject'Excel5');
  14546.                 // create the response
  14547.                 $response $this->get('phpexcel')->createStreamedResponse($writer);
  14548.             }
  14549.             $phpExcelObject->setActiveSheetIndex(0);
  14550.             // adding headers
  14551.             //            $writer->save('hello world.xlsx');
  14552.             // create the writer
  14553.             //            $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
  14554.             // create the response
  14555.             //            $response = $this->get('phpexcel')->createStreamedResponse($writer);
  14556.             // adding headers
  14557.             $dispositionHeader $response->headers->makeDisposition(
  14558.                 ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  14559.                 $doc_title '.xls'
  14560.             );
  14561.             $response->headers->set('Content-Type''text/vnd.ms-excel; charset=utf-8');
  14562.             $response->headers->set('Pragma''public');
  14563.             $response->headers->set('Cache-Control''maxage=1');
  14564.             $response->headers->set('Content-Disposition'$dispositionHeader);
  14565.             return $response;
  14566.         } else {
  14567.             $phpExcelObject $this->get('phpexcel')->createPHPExcelObject();
  14568.             $phpExcelObject->getProperties()->setCreator("liuggio")
  14569.                 ->setLastModifiedBy("Giulio De Donato")
  14570.                 ->setTitle("Office 2005 XLSX Test Document")
  14571.                 ->setSubject("Office 2005 XLSX Test Document")
  14572.                 ->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.")
  14573.                 ->setKeywords("office 2005 openxml php")
  14574.                 ->setCategory("Test result file");
  14575.             $phpExcelObject->createSheet(0);
  14576.             $phpExcelObject->setActiveSheetIndex(0);
  14577.             $phpExcelObject->setActiveSheetIndex(0)->setCellValue('A1''Hello');
  14578.             $phpExcelObject->setActiveSheetIndex(0)->setCellValue('B2''world!');
  14579.             $phpExcelObject->getActiveSheet()->setTitle('Simple');
  14580.             $phpExcelObject->createSheet(1);
  14581.             $phpExcelObject->setActiveSheetIndex(1)
  14582.                 ->setCellValue('A1''Hello')
  14583.                 ->setCellValue('B2''world!');
  14584.             $phpExcelObject->getActiveSheet()->setTitle('complex');
  14585.             // Set active sheet index to the first sheet, so Excel opens this as the first sheet
  14586.             $phpExcelObject->setActiveSheetIndex(0);
  14587.             // create the writer
  14588.             $writer $this->get('phpexcel')->createWriter($phpExcelObject'Excel5');
  14589.             // create the response
  14590.             $response $this->get('phpexcel')->createStreamedResponse($writer);
  14591.             // adding headers
  14592.             $dispositionHeader $response->headers->makeDisposition(
  14593.                 ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  14594.                 'stream-file.xls'
  14595.             );
  14596.             $response->headers->set('Content-Type''text/vnd.ms-excel; charset=utf-8');
  14597.             $response->headers->set('Pragma''public');
  14598.             $response->headers->set('Cache-Control''maxage=1');
  14599.             $response->headers->set('Content-Disposition'$dispositionHeader);
  14600.             return $response;
  14601.         }
  14602.     }
  14603.     public function AnalyzeTableDataExcel(Request $request)
  14604.     {
  14605.         // ask the service for a Excel5
  14606.         $em $this->getDoctrine()->getManager();
  14607.         $extractedData = array();
  14608.         if ($request->isMethod('POST')) {
  14609.             foreach ($request->files as $uploadedFileGG) {
  14610.                 //            if($uploadedFile->getImage())
  14611.                 //                var_dump($uploadedFile->getFile());
  14612.                 //                var_dump($uploadedFile);
  14613.                 $tempD $uploadedFileGG;
  14614.                 if (!is_array($uploadedFileGG)) {
  14615.                     $uploadedFileGG = array();
  14616.                     $uploadedFileGG[] = $tempD;
  14617.                 }
  14618.                 foreach ($uploadedFileGG as $uploadedFile) {
  14619.                     if ($uploadedFile != null) {
  14620.                         $extension $uploadedFile->guessExtension();
  14621.                         $size $uploadedFile->getSize();
  14622.                         $fileName 'TEMP_FILE_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  14623.                         $path $fileName;
  14624.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/temp';
  14625.                         if (!file_exists($upl_dir)) {
  14626.                             mkdir($upl_dir0777true);
  14627.                         }
  14628.                         if (file_exists($upl_dir '' $path)) {
  14629.                             chmod($upl_dir '' $path0755);
  14630.                             unlink($upl_dir '' $path);
  14631.                         }
  14632.                         $file $uploadedFile->move($upl_dir$path);
  14633.                         if (version_compare(PHP_VERSION'7.3.0''>=')) {
  14634.                             $phpExcelObject = new Spreadsheet($upl_dir '' $path);
  14635.                         } else {
  14636.                             $phpExcelObject $this->get('phpexcel')->createPHPExcelObject($upl_dir '' $path);
  14637.                         }
  14638.                         $extractedData $phpExcelObject;
  14639.                         if (file_exists($upl_dir '' $path)) {
  14640.                             chmod($upl_dir '' $path0755);
  14641.                             unlink($upl_dir '' $path);
  14642.                         }
  14643.                     }
  14644.                 }
  14645.             }
  14646.             //            $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
  14647.             //            $spreadsheet = new Spreadsheet();
  14648.             //
  14649.             //            $sheet = $spreadsheet->getActiveSheet();
  14650.             //            $sheet->setCellValue('A1', 'Hello World !');
  14651.             //
  14652.             //            $writer = new Xlsx($spreadsheet);
  14653.             //            $writer->save('hello world.xlsx');
  14654.             if (version_compare(PHP_VERSION'7.3.0''>=')) {
  14655.                 $phpExcelObject = new Spreadsheet();
  14656.             } else {
  14657.                 $phpExcelObject $this->get('phpexcel')->createPHPExcelObject();
  14658.             }
  14659.         }
  14660.         return new JsonResponse($extractedData);
  14661.     }
  14662.     public function ViewVoucher(Request $request$id)
  14663.     {
  14664.         $voucher_id $id;
  14665.         $em $this->getDoctrine()->getManager();
  14666.         $dt Accounts::GetVoucherDetails($em$voucher_id);
  14667.         if ($request->get('returnJson')==1) {
  14668.             return new \Symfony\Component\HttpFoundation\JsonResponse([
  14669.                 'success' => true,
  14670.                 'data' => $dt
  14671.             ]);
  14672.         }
  14673.         return $this->render(
  14674. //            '@Accounts/pages/views/view_journal_voucher.html.twig',
  14675.             '@Accounts/pages/views/view_journal_voucher_demo.html.twig',
  14676.             array(
  14677.                 'page_title' => 'View',
  14678.                 'data' => $dt,
  14679.                 'auto_created' => $dt['auto_created'],
  14680.                 'approval_data' => System::checkIfApprovalExists(
  14681.                     $em,
  14682.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  14683.                     $voucher_id,
  14684.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  14685.                 ),
  14686.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  14687.                     $this->getDoctrine()->getManager(),
  14688.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  14689.                     $voucher_id,
  14690.                     $dt['created_by'],
  14691.                     $dt['edited_by']
  14692.                 ) : []
  14693.             )
  14694.         );
  14695.     }
  14696.     public function ViewPurchaseInvoice(Request $request$id)
  14697.     {
  14698.         $em $this->getDoctrine()->getManager();
  14699.         $dt Accounts::GetInvoiceDetails($em$id);
  14700.         return $this->render(
  14701. //            '@Accounts/pages/views/view_purchase_invoice.html.twig',
  14702.             '@Accounts/pages/views/view_purchase_invoice_demo.html.twig',
  14703.             array(
  14704.                 'page_title' => 'View Purchase Invoice',
  14705.                 'data' => $dt,
  14706.                 'approval_data' => System::checkIfApprovalExists(
  14707.                     $em,
  14708.                     array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
  14709.                     $id,
  14710.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  14711.                 ),
  14712.                 'document_log' => System::getDocumentLog(
  14713.                     $this->getDoctrine()->getManager(),
  14714.                     array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
  14715.                     $id,
  14716.                     $dt['created_by'],
  14717.                     $dt['edited_by']
  14718.                 )
  14719.             )
  14720.         );
  14721.     }
  14722.     public function PrintPurchaseInvoice(Request $request$id)
  14723.     {
  14724.         $em $this->getDoctrine()->getManager();
  14725.         $invoice_id $id;
  14726.         $data Accounts::GetInvoiceDetails($em$invoice_id);
  14727.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  14728.         $document_mark = array(
  14729.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  14730.             'pending' => '/images/pending.jpg',
  14731.             'copy' => ''
  14732.         );
  14733.         $printTemplate CountryTemplateResolver::resolve(
  14734.             $this->get('twig'),
  14735.             $em,
  14736.             $this->getLoggedUserCompanyId($request),
  14737.             '@Accounts/pages/print/pi_print.html.twig'
  14738.         );
  14739.         $taxMarkers TaxMarkerLookup::forCompany($em$this->getLoggedUserCompanyId($request));
  14740.          if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  14741.             $html $this->renderView(
  14742.                  $printTemplate,
  14743.                 array(
  14744.                     //full array here
  14745.                 'pdf' => true,
  14746.                 'page_title' => 'Purchase Invoice',
  14747.                 'data' => $data,
  14748.                 'document_mark_image' => $document_mark['original'],
  14749.                 'company_name' => $company_data->getName(),
  14750.                 'company_data' => $company_data,
  14751.                 'company_address' => $company_data->getAddress(),
  14752.                 'company_image' => $company_data->getImage(),
  14753.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  14754.         
  14755.                 'export' => 'pdf,print',
  14756.                 'document_mark_image' => $document_mark['original'],
  14757.                 'company_name' => $company_data->getName(),
  14758.                 'company_data' => $company_data,
  14759.                 'company_address' => $company_data->getAddress(),
  14760.                 'company_image' => $company_data->getImage(),
  14761.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  14762.                 'page_header' => 'New Product',
  14763.                     'document_type' => 'Purchase Invoice',
  14764.                     'page_header_sub' => 'Add',
  14765.                     //                'type_list'=>$type_list,
  14766.                     //                'mis_data'=>$mis_data,
  14767.                     //                'mis_print'=>$mis_print,
  14768.                     'item_data' => [],
  14769.                     'received' => 2,
  14770.                     'return' => 1,
  14771.                     'total_w_vat' => 1,
  14772.                     'total_vat' => 1,
  14773.                     'total_wo_vat' => 1,
  14774.                     'invoice_id' => 'abcd1234',
  14775.                     'created_by' => 'created by',
  14776.                     'created_at' => '',
  14777.                     'red' => 0,
  14778.                     'taxMarkers' => $taxMarkers,
  14779.                 )
  14780.             );
  14781.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  14782.                 //                'orientation' => 'landscape',
  14783.                 //                'enable-javascript' => true,
  14784.                 //                'javascript-delay' => 1000,
  14785.                 'no-stop-slow-scripts' => false,
  14786.                 'no-background' => false,
  14787.                 'lowquality' => false,
  14788.                 'encoding' => 'utf-8',
  14789.                 //            'images' => true,
  14790.                 //            'cookie' => array(),
  14791.                 'dpi' => 300,
  14792.                 'image-dpi' => 300,
  14793.                 //                'enable-external-links' => true,
  14794.                 //                'enable-internal-links' => true
  14795.             ));
  14796.             return new Response(
  14797.                 $pdf_response,
  14798.                 200,
  14799.                 array(
  14800.                     'Content-Type' => 'application/pdf',
  14801.                     'Content-Disposition' => 'attachment; filename="sales_invoice_' $id '.pdf"'
  14802.                 )
  14803.             );
  14804.         }
  14805.         return $this->render(
  14806.             $printTemplate,
  14807.             array(
  14808.                 // 'page_title' => 'Purchase Invoice',
  14809.                 // 'data' => $data,
  14810.                 // 'document_mark_image' => $document_mark['original'],
  14811.                 // 'company_name' => $company_data->getName(),
  14812.                 // 'company_data' => $company_data,
  14813.                 // 'company_address' => $company_data->getAddress(),
  14814.                 // 'company_image' => $company_data->getImage(),
  14815.                 // 'invoice_footer' => $company_data->getInvoiceFooter(),
  14816.                 // 'red' => 0
  14817.                 'page_title' => 'Purchase Invoice',
  14818.                 'data' => $data,
  14819.                 'document_mark_image' => $document_mark['original'],
  14820.                 'company_name' => $company_data->getName(),
  14821.                 'company_data' => $company_data,
  14822.                 'company_address' => $company_data->getAddress(),
  14823.                 'company_image' => $company_data->getImage(),
  14824.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  14825.         
  14826.                 'export' => 'pdf,print',
  14827.                 'document_mark_image' => $document_mark['original'],
  14828.                 'company_name' => $company_data->getName(),
  14829.                 'company_data' => $company_data,
  14830.                 'company_address' => $company_data->getAddress(),
  14831.                 'company_image' => $company_data->getImage(),
  14832.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  14833.                 'page_header' => 'New Product',
  14834.                     'document_type' => 'Purchase Invoice',
  14835.                     'page_header_sub' => 'Add',
  14836.                     //                'type_list'=>$type_list,
  14837.                     //                'mis_data'=>$mis_data,
  14838.                     //                'mis_print'=>$mis_print,
  14839.                     'item_data' => [],
  14840.                     'received' => 2,
  14841.                     'return' => 1,
  14842.                     'total_w_vat' => 1,
  14843.                     'total_vat' => 1,
  14844.                     'total_wo_vat' => 1,
  14845.                     'invoice_id' => 'abcd1234',
  14846.                     'created_by' => 'created by',
  14847.                     'created_at' => '',
  14848.                     'red' => 0,
  14849.                     'taxMarkers' => $taxMarkers,
  14850.             )
  14851.         );
  14852.     }
  14853.     public function ExpenseInvoiceList(Request $request)
  14854.     {
  14855.         $q $this->getDoctrine()
  14856.             ->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')
  14857.             ->findBy(
  14858.                 array(
  14859.                     'status' => GeneralConstant::ACTIVE,
  14860.                 ),
  14861.                 array(
  14862.                     'expenseInvoiceDate' => 'DESC'
  14863.                 )
  14864.             );
  14865.         $stage_list = array(
  14866.             => 'Pending',
  14867.             => 'Complete',
  14868.             => 'Pending Payment',
  14869.         );
  14870.         $data = [];
  14871.         foreach ($q as $entry) {
  14872.             $data[] = array(
  14873.                 'doc_date' => $entry->getExpenseInvoiceDate(),
  14874.                 'id' => $entry->getExpenseInvoiceId(),
  14875.                 'doc_hash' => $entry->getDocumentHash(),
  14876.                 'invoice_amount' => $entry->getInvoiceAmount(),
  14877.                 'stage' => $stage_list[$entry->getStage()]
  14878.             );
  14879.         }
  14880.         return $this->render(
  14881.             '@Accounts/pages/list/expense_invoices.html.twig',
  14882.             array(
  14883.                 'page_title' => 'Expense Invoices',
  14884.                 'data' => $data
  14885.             )
  14886.         );
  14887.     }
  14888.     public function ExpenseInvoiceApprovalQueue(Request $request)
  14889.     {
  14890.         $em $this->getDoctrine()->getManager();
  14891.         $expenseInvoiceEntityId array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'];
  14892.         if ($request->isMethod('POST')) {
  14893.             $selectedIds $request->request->all('selected_ids');
  14894.             if (!is_array($selectedIds)) {
  14895.                 $selectedIds = [];
  14896.             }
  14897.             $selectedIds array_values(array_filter(array_map('intval'$selectedIds)));
  14898.             $bulkAction $request->request->get('bulk_action''');
  14899.             if (empty($selectedIds)) {
  14900.                 $this->addFlash('error''Please select at least one expense invoice.');
  14901.             } elseif (!in_array($bulkAction, ['approve''decline'], true)) {
  14902.                 $this->addFlash('error''Please choose a valid bulk action.');
  14903.             } else {
  14904.                 $processed 0;
  14905.                 foreach ($selectedIds as $selectedId) {
  14906.                     if ($bulkAction === 'approve') {
  14907.                         System::takeFullApproveActions(
  14908.                             $em,
  14909.                             $expenseInvoiceEntityId,
  14910.                             $selectedId,
  14911.                             $this->get('mail_module')
  14912.                         );
  14913.                     } else {
  14914.                         System::takeFullDeclineActions(
  14915.                             $em,
  14916.                             $expenseInvoiceEntityId,
  14917.                             $selectedId,
  14918.                             $this->get('mail_module')
  14919.                         );
  14920.                     }
  14921.                     $processed++;
  14922.                 }
  14923.                 $this->addFlash(
  14924.                     'success',
  14925.                     sprintf(
  14926.                         '%d expense invoice%s %s successfully.',
  14927.                         $processed,
  14928.                         $processed === '' 's',
  14929.                         $bulkAction === 'approve' 'approved' 'declined'
  14930.                     )
  14931.                 );
  14932.             }
  14933.             $redirectParams array_filter([
  14934.                 'date_from' => $request->request->get('date_from'''),
  14935.                 'date_to' => $request->request->get('date_to'''),
  14936.                 'created_user_id' => $request->request->get('created_user_id'''),
  14937.                 'approved' => $request->request->get('approved'''),
  14938.                 'search' => $request->request->get('search'''),
  14939.             ], static function ($value) {
  14940.                 return $value !== '' && $value !== null;
  14941.             });
  14942.             return $this->redirectToRoute('expense_invoice_approval_queue'$redirectParams);
  14943.         }
  14944.         $dateFrom trim((string)$request->query->get('date_from'''));
  14945.         $dateTo trim((string)$request->query->get('date_to'''));
  14946.         $createdUserId trim((string)$request->query->get('created_user_id'''));
  14947.         $approved trim((string)$request->query->get('approved''3'));
  14948.         $search trim((string)$request->query->get('search'''));
  14949.         $qb $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->createQueryBuilder('ei');
  14950.         $qb->where('ei.status = :status')
  14951.             ->setParameter('status'GeneralConstant::ACTIVE)
  14952.             ->orderBy('ei.expenseInvoiceDate''DESC')
  14953.             ->addOrderBy('ei.expenseInvoiceId''DESC');
  14954.         if ($dateFrom !== '') {
  14955.             $qb->andWhere('ei.expenseInvoiceDate >= :dateFrom')
  14956.                 ->setParameter('dateFrom', new \DateTime($dateFrom ' 00:00:00'));
  14957.         }
  14958.         if ($dateTo !== '') {
  14959.             $qb->andWhere('ei.expenseInvoiceDate <= :dateTo')
  14960.                 ->setParameter('dateTo', new \DateTime($dateTo ' 23:59:59'));
  14961.         }
  14962.         if ($createdUserId !== '') {
  14963.             $qb->andWhere(
  14964.                 $qb->expr()->orX(
  14965.                     'ei.createdUserId = :createdUserId',
  14966.                     'ei.createdUserId IS NULL AND ei.createdLoginId = :createdUserLoginId'
  14967.                 )
  14968.             )
  14969.                 ->setParameter('createdUserId', (int)$createdUserId)
  14970.                 ->setParameter('createdUserLoginId', (int)$createdUserId);
  14971.         }
  14972.         if ($approved !== '') {
  14973.             $qb->andWhere('ei.approved = :approved')
  14974.                 ->setParameter('approved', (int)$approved);
  14975.         }
  14976.         if ($search !== '') {
  14977.             $qb->andWhere(
  14978.                 $qb->expr()->orX(
  14979.                     $qb->expr()->like('ei.documentHash'':searchTerm'),
  14980.                     $qb->expr()->like('ei.description'':searchTerm')
  14981.                 )
  14982.             )->setParameter('searchTerm''%' $search '%');
  14983.         }
  14984.         $invoices $qb->getQuery()->getResult();
  14985.         $currencyList Inventory::CurrencyList($em);
  14986.         $approvalStatusMap = [
  14987.             => ['label' => 'Declined''class' => 'danger'],
  14988.             => ['label' => 'Approved''class' => 'success'],
  14989.             => ['label' => 'Reverted''class' => 'warning'],
  14990.             => ['label' => 'Pending''class' => 'warning'],
  14991.         ];
  14992.         $expenseInvoiceTypeList = [
  14993.             => 'General Expense',
  14994.             => 'Against Purchase',
  14995.             => 'Against Project/Sales',
  14996.             => 'Against Lead/Tender',
  14997.         ];
  14998.         $groupedInvoices = [];
  14999.         $userOptions = [];
  15000.         $userCache = [];
  15001.         $summary = [
  15002.             'count' => 0,
  15003.             'approved' => 0,
  15004.             'pending' => 0,
  15005.             'declined' => 0,
  15006.             'reverted' => 0,
  15007.             'amount_by_currency' => [],
  15008.         ];
  15009.         foreach ($invoices as $invoice) {
  15010.             $createdUserIdValue = (int)$invoice->getCreatedUserId();
  15011.             $loginId = (int)$invoice->getCreatedLoginId();
  15012.             $cacheKey $createdUserIdValue $createdUserIdValue $loginId;
  15013.             if (!isset($userCache[$cacheKey])) {
  15014.                 if ($createdUserIdValue 0) {
  15015.                     $userCache[$cacheKey] = Users::getUserInfoByUserId($em$createdUserIdValue);
  15016.                 } else {
  15017.                     $resolvedUser Users::getUserInfoByLoginId($em$loginId);
  15018.                     $userCache[$cacheKey] = $resolvedUser;
  15019.                     if (!empty($resolvedUser['id'])) {
  15020.                         $createdUserIdValue = (int)$resolvedUser['id'];
  15021.                         $cacheKey $createdUserIdValue;
  15022.                         $userCache[$cacheKey] = $resolvedUser;
  15023.                     }
  15024.                 }
  15025.             }
  15026.             $userInfo $userCache[$cacheKey] ?? [];
  15027.             $userId = (int)($userInfo['id'] ?? $createdUserIdValue);
  15028.             $userName $userInfo['name'] ?? ('User #' $userId);
  15029.             $invoiceDate $invoice->getExpenseInvoiceDate();
  15030.             $dateKey $invoiceDate $invoiceDate->format('Y-m-d') : 'unknown';
  15031.             $dateLabel $invoiceDate $invoiceDate->format('M d, Y') : 'Unknown date';
  15032.             $amount = (float)$invoice->getInvoiceAmount();
  15033.             $currencyId $invoice->getCurrency();
  15034.             $currencyName = isset($currencyList[$currencyId]) ? ($currencyList[$currencyId]['nameOnly'] ?? '') : '';
  15035.             $approvalState = (int)$invoice->getApproved();
  15036.             $approvalMeta $approvalStatusMap[$approvalState] ?? ['label' => 'Unknown''class' => 'default'];
  15037.             $summary['count']++;
  15038.             if ($approvalState === 1) {
  15039.                 $summary['approved']++;
  15040.             } elseif ($approvalState === 0) {
  15041.                 $summary['declined']++;
  15042.             } elseif ($approvalState === 2) {
  15043.                 $summary['reverted']++;
  15044.             } else {
  15045.                 $summary['pending']++;
  15046.             }
  15047.             if (!isset($summary['amount_by_currency'][$currencyId])) {
  15048.                 $summary['amount_by_currency'][$currencyId] = [
  15049.                     'currency' => $currencyName,
  15050.                     'amount' => 0,
  15051.                 ];
  15052.             }
  15053.             $summary['amount_by_currency'][$currencyId]['amount'] += $amount;
  15054.             $userOptions[$userId] = $userName;
  15055.             if (!isset($groupedInvoices[$userId])) {
  15056.                 $groupedInvoices[$userId] = [
  15057.                     'userId' => $userId,
  15058.                     'userName' => $userName,
  15059.                     'totalCount' => 0,
  15060.                     'totalAmount' => 0,
  15061.                     'amountByCurrency' => [],
  15062.                     'dates' => [],
  15063.                 ];
  15064.             }
  15065.             if (!isset($groupedInvoices[$userId]['amountByCurrency'][$currencyId])) {
  15066.                 $groupedInvoices[$userId]['amountByCurrency'][$currencyId] = [
  15067.                     'currency' => $currencyName,
  15068.                     'amount' => 0,
  15069.                 ];
  15070.             }
  15071.             $groupedInvoices[$userId]['amountByCurrency'][$currencyId]['amount'] += $amount;
  15072.             $groupedInvoices[$userId]['totalCount']++;
  15073.             $groupedInvoices[$userId]['totalAmount'] += $amount;
  15074.             if (!isset($groupedInvoices[$userId]['dates'][$dateKey])) {
  15075.                 $groupedInvoices[$userId]['dates'][$dateKey] = [
  15076.                     'key' => $dateKey,
  15077.                     'label' => $dateLabel,
  15078.                     'count' => 0,
  15079.                     'amount' => 0,
  15080.                     'rows' => [],
  15081.                 ];
  15082.             }
  15083.             $groupedInvoices[$userId]['dates'][$dateKey]['count']++;
  15084.             $groupedInvoices[$userId]['dates'][$dateKey]['amount'] += $amount;
  15085.             $groupedInvoices[$userId]['dates'][$dateKey]['rows'][] = [
  15086.                 'expenseInvoiceId' => $invoice->getExpenseInvoiceId(),
  15087.                 'documentHash' => $invoice->getDocumentHash(),
  15088.                 'expenseInvoiceDate' => $dateLabel,
  15089.                 'expenseInvoiceTypeId' => $invoice->getExpenseInvoiceTypeId(),
  15090.                 'expenseInvoiceTypeLabel' => $expenseInvoiceTypeList[$invoice->getExpenseInvoiceTypeId()] ?? 'N/A',
  15091.                 'invoiceAmount' => $amount,
  15092.                 'currencyId' => $currencyId,
  15093.                 'currencyName' => $currencyName,
  15094.                 'approved' => $approvalState,
  15095.                 'approvedLabel' => $approvalMeta['label'],
  15096.                 'approvedClass' => $approvalMeta['class'],
  15097.                 'description' => $invoice->getDescription(),
  15098.                 'partyHeadId' => $invoice->getPartyHeadId(),
  15099.                 'expenseTypeId' => $invoice->getExpenseTypeId(),
  15100.                 'createdUserId' => $userId,
  15101.                 'viewUrl' => $this->generateUrl('view_expense_invoice', ['id' => $invoice->getExpenseInvoiceId()]),
  15102.                 'printUrl' => $this->generateUrl('print_expense_invoice', ['id' => $invoice->getExpenseInvoiceId()]),
  15103.             ];
  15104.         }
  15105.         krsort($groupedInvoices);
  15106.         foreach ($groupedInvoices as &$group) {
  15107.             krsort($group['dates']);
  15108.         }
  15109.         unset($group);
  15110.         $amountBreakdown = [];
  15111.         foreach ($summary['amount_by_currency'] as $currencyData) {
  15112.             $amountBreakdown[] = trim(
  15113.                 ($currencyData['currency'] !== '' $currencyData['currency'] . ' ' '') .
  15114.                 number_format((float)$currencyData['amount'], 2'.'',')
  15115.             );
  15116.         }
  15117.         return $this->render(
  15118.             '@Accounts/pages/views/view_expense_invoice_approval_queue.html.twig',
  15119.             [
  15120.                 'page_title' => 'Expense Invoice Approval Queue',
  15121.                 'groupedInvoices' => $groupedInvoices,
  15122.                 'userOptions' => $userOptions,
  15123.                 'summary' => $summary,
  15124.                 'amountBreakdown' => $amountBreakdown,
  15125.                 'filters' => [
  15126.                     'date_from' => $dateFrom,
  15127.                     'date_to' => $dateTo,
  15128.                     'created_user_id' => $createdUserId,
  15129.                     'approved' => $approved,
  15130.                     'search' => $search,
  15131.                 ],
  15132.                 'approvalStatusMap' => $approvalStatusMap,
  15133.                 'expenseInvoiceTypeList' => $expenseInvoiceTypeList,
  15134.                 'currencyList' => $currencyList,
  15135.             ]
  15136.         );
  15137.     }
  15138.     public function BrsList(Request $request)
  15139.     {
  15140.         $q $this->getDoctrine()
  15141.             ->getRepository('ApplicationBundle\\Entity\\Brs')
  15142.             ->findBy(
  15143.                 array(
  15144.                     'status' => GeneralConstant::ACTIVE,
  15145.                 ),
  15146.                 array(
  15147.                     'brsDate' => 'DESC'
  15148.                 )
  15149.             );
  15150.         $stage_list = array(
  15151.             => 'Pending',
  15152.             => 'Complete',
  15153.             => 'Pending Payment',
  15154.         );
  15155.         $data = [];
  15156.         foreach ($q as $entry) {
  15157.             $data[] = array(
  15158.                 'doc_date' => $entry->getBrsDate(),
  15159.                 'id' => $entry->getBrsId(),
  15160.                 'doc_hash' => $entry->getDocumentHash(),
  15161.                 'accountsHeadId' => $entry->getAccountsHeadId(),
  15162.                 //                'stage'=>$stage_list[$entry->getStage()]
  15163.             );
  15164.         }
  15165.         return $this->render(
  15166.             '@Accounts/pages/list/brs_list.html.twig',
  15167.             array(
  15168.                 'page_title' => 'BRS Statements',
  15169.                 'data' => $data,
  15170.                 'head_list' => Accounts::HeadList($this->getDoctrine()->getManager())
  15171.             )
  15172.         );
  15173.     }
  15174.     public function FinancialBudgetList(Request $request)
  15175.     {
  15176.         $q $this->getDoctrine()
  15177.             ->getRepository('ApplicationBundle\\Entity\\FinancialBudget')
  15178.             ->findBy(
  15179.                 array( //                    'status' =>  GeneralConstant::ACTIVE,
  15180.                 ),
  15181.                 array( //                    'brsDate'=>'DESC'
  15182.                 )
  15183.             );
  15184.         $stage_list = array(
  15185.             => 'Pending',
  15186.             => 'Complete',
  15187.             => 'Pending Payment',
  15188.         );
  15189.         $data = [];
  15190.         foreach ($q as $entry) {
  15191.             $data[] = array(
  15192.                 'doc_start_date' => $entry->getBudgetStartDate(),
  15193.                 'doc_end_date' => $entry->getBudgetEndDate(),
  15194.                 'id' => $entry->getBudgetId(),
  15195.                 'doc_hash' => $entry->getBudgetTitle(),
  15196.                 //                'accountsHeadId'=>$entry->getAccountsHeadId(),
  15197.                 //                'stage'=>$stage_list[$entry->getStage()]
  15198.             );
  15199.         }
  15200.         return $this->render(
  15201.             '@Accounts/pages/list/financial_budget_list.html.twig',
  15202.             array(
  15203.                 'page_title' => 'Financial Budgets',
  15204.                 'data' => $data,
  15205.                 'head_list' => Accounts::HeadList($this->getDoctrine()->getManager())
  15206.             )
  15207.         );
  15208.     }
  15209.     public function ViewExpenseInvoice(Request $request$id)
  15210.     {
  15211.         $invoice_id $id;
  15212.         $em $this->getDoctrine()->getManager();
  15213.         $dt Accounts::GetExpenseInvoiceDetails($em$invoice_id);
  15214.         if ($request->get('returnJson')==1) {
  15215.             $ei $dt['ei_data'];
  15216.             return new \Symfony\Component\HttpFoundation\JsonResponse([
  15217.                 'success' => true,
  15218.                 'data' => [
  15219.                     'supplier_data' => $dt['supplier_data'] ? [
  15220.                         'supplierName'    => $dt['supplier_data']->getSupplierName(),
  15221.                         'supplierAddress' => $dt['supplier_data']->getSupplierAddress(),
  15222.                         'contactNumber'   => $dt['supplier_data']->getContactNumber(),
  15223.                     ] : null,
  15224.                     'party_head_data' => isset($dt['party_head_data']) && $dt['party_head_data'] ? [
  15225.                         'name' => $dt['party_head_data']->getName(),
  15226.                     ] : null,
  15227.                     'ei_data' => [
  15228.                         'expenseInvoiceId'      => $ei->getExpenseInvoiceId(),
  15229.                         'documentHash'          => $ei->getDocumentHash(),
  15230.                         'expenseInvoiceDate'    => $ei->getExpenseInvoiceDate()
  15231.                             ? $ei->getExpenseInvoiceDate()->format('Y-m-d') : null,
  15232.                         'invoiceAmount'         => $ei->getInvoiceAmount(),
  15233.                         'advanceAmount'         => $ei->getAdvanceAmount(),
  15234.                         'dueAmount'             => $ei->getDueAmount(),
  15235.                         'currency'              => $ei->getCurrency(),
  15236.                         'currencyMultiplyRate'  => $ei->getCurrencyMultiplyRate(),
  15237.                         'expenseInvoiceTypeId'  => $ei->getExpenseInvoiceTypeId(),
  15238.                         'expenseTypeId'         => $ei->getExpenseTypeId(),
  15239.                         'expenseFromNote'       => $ei->getExpenseFromNote(),
  15240.                         'expenseToNote'         => $ei->getExpenseToNote(),
  15241.                         'description'           => $ei->getDescription(),
  15242.                         'approved'              => $ei->getApproved(),
  15243.                         'editFlag'              => $ei->getEditFlag(),
  15244.                     ],
  15245.                     'supplier_data'             => $dt['supplier_data'] ? [
  15246.                         'supplierName'          => $dt['supplier_data']->getSupplierName(),
  15247.                         'supplierAddress'       => $dt['supplier_data']->getSupplierAddress(),
  15248.                         'contactNumber'         => $dt['supplier_data']->getContactNumber(),
  15249.                     ] : null,
  15250.                     'currency_list'             => $dt['currency_list'],
  15251.                     'head_list'                 => $dt['head_list'],
  15252.                     'expenseInvoiceTypeList'    => $dt['expenseInvoiceTypeList'] ?? [],
  15253.                     'voucher_data'              => $dt['voucher_data'],
  15254.                     'probable_transaction_data' => $dt['probable_transaction_data'] ?? [],
  15255.                 ]
  15256.             ]);
  15257.         }
  15258.         return $this->render(
  15259. //            '@Accounts/pages/views/view_expense_invoice.html.twig',
  15260.             '@Accounts/pages/views/view_expense_invoice_demo.html.twig',
  15261.             array(
  15262.                 'page_title' => 'View Expense Invoice',
  15263.                 'data' => $dt,
  15264.                 'auto_created' => $dt['ei_data']->getAutoCreated(),
  15265.                 'approval_data' => System::checkIfApprovalExists(
  15266.                     $em,
  15267.                     array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  15268.                     $invoice_id,
  15269.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  15270.                 ),
  15271.                 'document_log' => System::getDocumentLog(
  15272.                     $this->getDoctrine()->getManager(),
  15273.                     array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  15274.                     $invoice_id,
  15275.                     $dt['created_by'],
  15276.                     $dt['edited_by']
  15277.                 )
  15278.             )
  15279.         );
  15280.     }
  15281.     public function PrintExpenseInvoice(Request $request$id)
  15282.     {
  15283.         $em $this->getDoctrine()->getManager();
  15284.         $invoice_id $id;
  15285.         $data Accounts::GetExpenseInvoiceDetails($em$invoice_id);
  15286.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  15287.         $document_mark = array(
  15288.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  15289.             'copy' => ''
  15290.         );
  15291.         return $this->render(
  15292.             '@Accounts/pages/print/ei_print.html.twig',
  15293.             array(
  15294.                 'page_title' => 'Expense Invoice',
  15295.                 'data' => $data,
  15296.                 'export' => 'pdf,print,sendForward',
  15297.                 'document_mark_image' => $document_mark['original'],
  15298.                 'company_name' => $company_data->getName(),
  15299.                 'company_data' => $company_data,
  15300.                 'company_address' => $company_data->getAddress(),
  15301.                 'company_image' => $company_data->getImage(),
  15302.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  15303.                 'red' => 0
  15304.             )
  15305.         );
  15306.     }
  15307.     public function strtohex($x)
  15308.     {
  15309.         $s '';
  15310.         foreach (str_split($x) as $c$s .= sprintf("%02X"ord($c));
  15311.         return ($s);
  15312.     }
  15313.     public function PrintVoucher(Request $request$id$mis_start_date ''$mis_end_date '')
  15314.     {
  15315.         $voucher_id $id;
  15316.         $p '';
  15317. //        if ($this->container->has('profiler')) {
  15318. //            $this->container->get('profiler')->disable();
  15319. //        }
  15320.         $mis_print 0;
  15321.         if ($request->query->has('mis_print'))
  15322.             $mis_print $request->query->get('mis_print');
  15323.         $em $this->getDoctrine()->getManager();
  15324.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  15325.         $start_date "";
  15326.         $end_date "";
  15327.         $em $this->getDoctrine()->getManager();
  15328.         if ($mis_start_date != '' && $mis_start_date != 0)
  15329.             $start_date $mis_start_date;
  15330.         if ($mis_end_date != '' && $mis_start_date != 0)
  15331.             $end_date $mis_end_date;
  15332.         $document_mark = array(
  15333.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  15334.             'pending' => '/images/pending.jpg',
  15335.             'copy' => ''
  15336.         );
  15337.         $data Accounts::GetVoucherDetails($em$voucher_id);
  15338.         if (!empty($data))
  15339.             $mis_data Accounts::GetVoucherMisDetails($em$data['head_id_list'], $start_date$end_date);
  15340.         $templates = [
  15341.             '3' => '@Accounts/pages/print/voucher_print.html.twig',
  15342.             '4' => '@Accounts/pages/print/contra_voucher_print.html.twig',
  15343.             '5' => '@Accounts/pages/print/payment_voucher_print.html.twig',
  15344.             '6' => '@Accounts/pages/print/receipt_voucher_print.html.twig',
  15345.         ];
  15346.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  15347.             $html $this->renderView(
  15348.                 $templates[$data['type_id']],
  15349.                 array(
  15350.                     //full array here
  15351.                     'pdf' => true,
  15352.                     'page_title' => 'Voucher ' $data['doc_hash'],
  15353.                     'data' => $data,
  15354.                     'page_header' => 'New Product',
  15355.                     'document_type' => 'Journal voucher',
  15356.                     'document_mark_image' => $document_mark['original'],
  15357.                     'page_header_sub' => 'Add',
  15358.                     //                'type_list'=>$type_list,
  15359.                     'mis_data' => $mis_data,
  15360.                     'mis_print' => $mis_print,
  15361.                     'item_data' => [],
  15362.                     'received' => 2,
  15363.                     'return' => 1,
  15364.                     'total_w_vat' => 1,
  15365.                     'total_vat' => 1,
  15366.                     'total_wo_vat' => 1,
  15367.                     'invoice_id' => 'abcd1234',
  15368.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  15369.                     'created_by' => 'created by',
  15370.                     'created_at' => '',
  15371.                     'red' => 0,
  15372.                     'company_name' => $company_data->getName(),
  15373.                     'company_data' => $company_data,
  15374.                     'company_address' => $company_data->getAddress(),
  15375.                     'company_image' => $company_data->getImage(),
  15376.                     'p' => $p
  15377.                 )
  15378.             );
  15379.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  15380.                 //                'orientation' => 'landscape',
  15381.                 //                'enable-javascript' => true,
  15382.                 //                'javascript-delay' => 1000,
  15383.                 'no-stop-slow-scripts' => false,
  15384.                 'no-background' => false,
  15385.                 'lowquality' => false,
  15386.                 'encoding' => 'utf-8',
  15387.                 //            'images' => true,
  15388.                 //            'cookie' => array(),
  15389.                 'dpi' => 300,
  15390.                 'image-dpi' => 300,
  15391.                 //                'enable-external-links' => true,
  15392.                 //                'enable-internal-links' => true
  15393.             ));
  15394.             return new Response(
  15395.                 $pdf_response,
  15396.                 200,
  15397.                 array(
  15398.                     'Content-Type' => 'application/pdf',
  15399.                     'Content-Disposition' => 'attachment; filename="' $data['doc_hash'] . '.pdf"'
  15400.                 )
  15401.             );
  15402.         }
  15403.         return $this->render(
  15404.             $templates[$data['type_id']],
  15405.             array(
  15406.                 'page_title' => 'Voucher ' $data['doc_hash'],
  15407.                 'export' => 'pdf,print',
  15408.                 'data' => $data,
  15409.                 'page_header' => 'New Product',
  15410.                 'document_type' => 'Journal voucher',
  15411.                 'document_mark_image' => $document_mark['original'],
  15412.                 'page_header_sub' => 'Add',
  15413.                 //                'type_list'=>$type_list,
  15414.                 'mis_data' => $mis_data,
  15415.                 'mis_print' => $mis_print,
  15416.                 'item_data' => [],
  15417.                 'received' => 2,
  15418.                 'return' => 1,
  15419.                 'total_w_vat' => 1,
  15420.                 'total_vat' => 1,
  15421.                 'total_wo_vat' => 1,
  15422.                 'invoice_id' => 'abcd1234',
  15423.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  15424.                 'created_by' => 'created by',
  15425.                 'created_at' => '',
  15426.                 'red' => 0,
  15427.                 'company_name' => $company_data->getName(),
  15428.                 'company_data' => $company_data,
  15429.                 'company_address' => $company_data->getAddress(),
  15430.                 'company_image' => $company_data->getImage(),
  15431.                 'p' => $p
  15432.             )
  15433.         );
  15434.     }
  15435.     public function PrintVoucherPdf(Request $request$voucher_id$mis_start_date ''$mis_end_date '')
  15436.     {
  15437.         if ($this->container->has('profiler')) {
  15438.             $this->container->get('profiler')->disable();
  15439.         }
  15440.         $p '';
  15441.         $mis_print 0;
  15442.         if ($request->query->has('mis_print'))
  15443.             $mis_print $request->query->get('mis_print');
  15444.         $em $this->getDoctrine()->getManager();
  15445.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  15446.         $start_date "";
  15447.         $end_date "";
  15448.         $em $this->getDoctrine()->getManager();
  15449.         if ($mis_start_date != '' && $mis_start_date != 0)
  15450.             $start_date $mis_start_date;
  15451.         if ($mis_end_date != '' && $mis_start_date != 0)
  15452.             $end_date $mis_end_date;
  15453.         $document_mark = array(
  15454.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  15455.             'pending' => '/images/pending.jpg',
  15456.             'copy' => ''
  15457.         );
  15458.         $data Accounts::GetVoucherDetails($em$voucher_id);
  15459.         if (!empty($data))
  15460.             $mis_data Accounts::GetVoucherMisDetails($em$data['head_id_list'], $start_date$end_date);
  15461.         $format $request->get('_format');
  15462.         $this->get('knp_snappy.pdf');
  15463.         //        $format = 'pdf';
  15464.         //        $response = $this->render(sprintf('ApplicationBundle:pages/accounts/pdf:helloAction.%s.twig', $format), array(
  15465.         //            'name' => 'Ecobeco',
  15466.         //        ));
  15467.         ////        $response->headers->set('Content-Type', 'application/pdf');
  15468.         //
  15469.         //        return $response;
  15470.         $templates = [
  15471.             '3' => '@Accounts/pages/print/voucher_print.html.twig',
  15472.             '4' => '@Accounts/pages/print/contra_voucher_print.html.twig',
  15473.             '5' => '@Accounts/pages/print/payment_voucher_print.html.twig',
  15474.         ];
  15475.         //        return $this->render($templates[$data['type_id']],
  15476.         $html $this->renderView(
  15477.             $templates[$data['type_id']],
  15478.             array(
  15479.                 'page_title' => 'Voucher ' $data['doc_hash'],
  15480.                 'data' => $data,
  15481.                 'page_header' => 'New Product',
  15482.                 'document_type' => 'Journal voucher',
  15483.                 'document_mark_image' => $document_mark['original'],
  15484.                 'page_header_sub' => 'Add',
  15485.                 //                'type_list'=>$type_list,
  15486.                 'mis_data' => $mis_data,
  15487.                 'mis_print' => $mis_print,
  15488.                 'item_data' => [],
  15489.                 'received' => 2,
  15490.                 'return' => 1,
  15491.                 'total_w_vat' => 1,
  15492.                 'total_vat' => 1,
  15493.                 'total_wo_vat' => 1,
  15494.                 'invoice_id' => 'abcd1234',
  15495.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  15496.                 'created_by' => 'created by',
  15497.                 'created_at' => '',
  15498.                 'red' => 0,
  15499.                 'company_name' => $company_data->getName(),
  15500.                 'company_data' => $company_data,
  15501.                 'company_address' => $company_data->getAddress(),
  15502.                 'company_image' => $company_data->getImage(),
  15503.                 'p' => $p
  15504.             )
  15505.         );
  15506.         $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  15507.             //                'orientation' => 'landscape',
  15508.             //                'enable-javascript' => true,
  15509.             //                'javascript-delay' => 1000,
  15510.             'no-stop-slow-scripts' => true,
  15511.             'no-background' => false,
  15512.             'lowquality' => false,
  15513.             'encoding' => 'utf-8',
  15514.             //            'images' => true,
  15515.             //            'cookie' => array(),
  15516.             'dpi' => 300,
  15517.             'image-dpi' => 300,
  15518.             //                'enable-external-links' => true,
  15519.             //                'enable-internal-links' => true
  15520.         ));
  15521.         return new Response(
  15522.             $pdf_response,
  15523.             200,
  15524.             array(
  15525.                 'Content-Type' => 'application/pdf',
  15526.                 //                'Content-Disposition'   => 'attachment; filename="file.pdf"'
  15527.             )
  15528.         );
  15529.     }
  15530.     public function VoucherList(Request $request)
  15531.     {
  15532.         $em $this->getDoctrine()->getManager();
  15533.         //        $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findAllOrderedByName();
  15534.         $voucherListData Accounts::GetVoucherList($em$request->isMethod('POST') ? 'POST' 'GET'$request->request);
  15535.         if ($request->isMethod('POST')) {
  15536.             if ($request->query->has('dataTableQry')) {
  15537.                 return new JsonResponse(
  15538.                     $voucherListData
  15539.                 );
  15540.             }
  15541.         }
  15542.         return $this->render(
  15543.             '@Accounts/pages/list/voucher_list.html.twig',
  15544.             array(
  15545.                 'page_title' => 'Transactions',
  15546.                 'data' => $voucherListData['data']
  15547.             )
  15548.         );
  15549.     }
  15550.     /**
  15551.      * @Pdf()
  15552.      */
  15553.     public function TestPdf(Request $request$slug)
  15554.     {
  15555.         $format $request->get('_format');
  15556.         //        $format = 'pdf';
  15557.         $response $this->render(sprintf('@Application/pages/accounts/pdf/helloAction.%s.twig'$format), array(
  15558.             'name' => 'Ecobeco',
  15559.         ));
  15560.         //        $response->headers->set('Content-Type', 'application/pdf');
  15561.         return $response;
  15562.     }
  15563.     public function ViewLedger(Request $request$id)
  15564.     {
  15565.         //        $format = $request->get('_format');
  15566.         //        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);
  15567.         $start_date "";
  15568.         $end_date "";
  15569.         $em $this->getDoctrine()->getManager();
  15570.         if ($request->query->has('start_date'))
  15571.             $start_date $request->query->get('start_date');
  15572.         if ($request->query->has('end_date'))
  15573.             $end_date $request->query->get('end_date');
  15574.         $balance_view_method 0;
  15575.         $bal_set $em
  15576.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  15577.             ->findOneBy(
  15578.                 array(
  15579.                     'name' => 'ledger_balance_display_method',
  15580.                 )
  15581.             );
  15582.         if ($bal_set) {
  15583.             $balance_view_method $bal_set->getdata();
  15584.         }
  15585.         // now lets get its tree for the description
  15586.         $id_list_for_ledger = [];
  15587.         $parent_id_list_for_ledger = [];
  15588.         if ($request->query->has('HeadId'))
  15589.             $id_list_for_ledger $request->query->get('HeadId');
  15590.         if ($request->query->has('parentHeadId'))
  15591.             $parent_id_list_for_ledger $request->query->get('parentHeadId');
  15592.         $provisional_option 1//include
  15593.         if ($request->query->has('provisional')) {
  15594.             $provisional_option $request->query->get('provisional'); //include
  15595.         }
  15596.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  15597.         $allocationFilters $allocationSupportData['allocation_filters'];
  15598.         if (empty($id_list_for_ledger))
  15599.             if ($id != 0)
  15600.                 $id_list_for_ledger = [$id];
  15601.         $ledger_det = [];
  15602.         foreach ($id_list_for_ledger as $ind_head_id) {
  15603.             //            $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
  15604.             $ledger_data Accounts::LedgerDetailsTransMethod($em$ind_head_id$start_date$end_date$provisional_option$allocationFilters);
  15605.             $ledger_det[$ind_head_id] = $ledger_data;
  15606.         }
  15607.         $grouped_heads Accounts::getLedgerHeadsWithParents($em);
  15608.         return $this->render(
  15609.             '@Accounts/pages/views/view_head_ledger.html.twig',
  15610.             array(
  15611.                 'page_title' => 'Ledger',
  15612.                 'id_list' => $id_list_for_ledger,
  15613.                 'parent_id_list' => $parent_id_list_for_ledger,
  15614.                 //                'products'=>Inventory::ProductList($this->getDoctrine()->getManager()),
  15615.                 //                'categories'=>Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  15616.                 //                'itemgroup'=>Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  15617.                 //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager())
  15618.                 'products' => [],
  15619.                 'provisional' => $provisional_option,
  15620.                 'ledger_data' => $ledger_det,
  15621.                 'balance_view_method' => $balance_view_method,
  15622.                 'categories' => [],
  15623.                 'heads' => $grouped_heads,
  15624.                 'itemgroup' => [],
  15625.                 'data' => [],
  15626.                 'start_date' => $start_date,
  15627.                 'end_date' => $end_date,
  15628.                 'allocation_filters' => $allocationFilters,
  15629.                 'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  15630.                 'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  15631.                 'project_list' => $allocationSupportData['project_list'],
  15632.                 'branch_list' => $allocationSupportData['branch_list'],
  15633.                 'cost_centers' => $allocationSupportData['cost_centers'],
  15634.                 //                'desc_head_list'=>$desc_tree_list,
  15635.             )
  15636.         );
  15637.     }
  15638.     public function ViewLedgerForApp(Request $request$id 0)
  15639.     {
  15640.         $start_date "";
  15641.         $end_date "";
  15642.         $em $this->getDoctrine()->getManager();
  15643.         if ($request->query->has('start_date'))
  15644.             $start_date $request->query->get('start_date');
  15645.         if ($request->query->has('end_date'))
  15646.             $end_date $request->query->get('end_date');
  15647.         $balance_view_method 0;
  15648.         $bal_set $em
  15649.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  15650.             ->findOneBy(['name' => 'ledger_balance_display_method']);
  15651.         if ($bal_set) {
  15652.             $balance_view_method $bal_set->getdata();
  15653.         }
  15654.         $id_list_for_ledger = [];
  15655.         if ($request->query->has('acc_heads_id')) {
  15656.             $raw_head_id $request->query->get('acc_heads_id');
  15657.             if (is_array($raw_head_id)) {
  15658.                 $id_list_for_ledger $raw_head_id;
  15659.             } elseif (is_string($raw_head_id)) {
  15660.                 $id_list_for_ledger array_filter(explode(','$raw_head_id));
  15661.             }
  15662.         }
  15663.         $parent_id_list_for_ledger = [];
  15664.         if ($request->query->has('acc_parent_head_id')) {
  15665.             $parent_id_list_for_ledger $request->query->get('acc_parent_head_id');
  15666.         }
  15667.         $provisional_option $request->query->get('provisional'1);
  15668.         $allocationFilters $this->getAllocationReportFilters($request);
  15669.         // ✅ Fallback if HeadId not passed
  15670.         if (empty($id_list_for_ledger) && $id != 0) {
  15671.             $id_list_for_ledger = [$id];
  15672.         }
  15673.         $ledger_det = [];
  15674.         foreach ($id_list_for_ledger as $ind_head_id) {
  15675.             $ledger_data Accounts::LedgerDetailsTransMethodForApp(
  15676.                 $em,
  15677.                 $ind_head_id,
  15678.                 $start_date,
  15679.                 $end_date,
  15680.                 $provisional_option,
  15681.                 23232323,
  15682.                 0,
  15683.                 'DATE_RANGE',
  15684.                 $allocationFilters
  15685.             );
  15686.             if (isset($ledger_data['error']) && $ledger_data['error'] === true) {
  15687.                 continue;
  15688.             }
  15689.             $head $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(['accountsHeadId' => $ind_head_id]);
  15690.             $head_name $head $head->getName() : 'Unknown_' $ind_head_id;
  15691.             $ledger_det[$head_name] = Accounts::formatLedgerSummary($ledger_data);
  15692.         }
  15693.         $grouped_heads Accounts::getLedgerHeadsWithParents($em);
  15694.         return new JsonResponse([
  15695.             'success' => true,
  15696.             'response' => $ledger_det,
  15697.         ]);
  15698.     }
  15699.     public function ListOfProvisional()
  15700.     {
  15701.         return new JsonResponse([
  15702.             ['id' => 0'label' => "Don't Include Provisional Transaction"],
  15703.             ['id' => 1'label' => 'Include Provisional Transaction'],
  15704.             ['id' => 2'label' => 'Only Provisional Transaction'],
  15705.         ]);
  15706.     }
  15707.     // public function dashboardCashFlow(Request $request, $id)
  15708.     // {
  15709.     //     $em = $this->getDoctrine()->getManager();
  15710.     //     $end_date = new \DateTime();
  15711.     //     $end_date = $end_date->format('Y-m-d'); 
  15712.     //     $start_date = new \DateTime();
  15713.     //     $start_date->modify('-1 month');
  15714.     //     $start_date = $start_date->format('Y-m-d'); 
  15715.     //     // Get the date for the last 7 days
  15716.     //     $seven_days_ago = new \DateTime();
  15717.     //     $seven_days_ago->modify('-7 days');
  15718.     //     $seven_days_ago = $seven_days_ago->format('Y-m-d'); 
  15719.     //     $balance_view_method = 0;
  15720.     //     $bal_set = $em
  15721.     //         ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  15722.     //         ->findOneBy(array(
  15723.     //             'name' => 'ledger_balance_display_method',
  15724.     //         ));
  15725.     //     if ($bal_set) {
  15726.     //         $balance_view_method = $bal_set->getdata();
  15727.     //     }
  15728.     //     // Now lets get its tree for the description
  15729.     //     $id_list_for_ledger = [];
  15730.     //     $parent_id_list_for_ledger = [];
  15731.     //     $candceq = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  15732.     //         'name' => 'cash_and_cash_equivalent_parents'
  15733.     //     ));
  15734.     //     if ($candceq)
  15735.     //         $id_list_for_ledger = json_decode($candceq->getData(), true);
  15736.     //     $provisional_option = 1; //include
  15737.     //     if ($request->query->has('provisional')) {
  15738.     //         $provisional_option = $request->query->get('provisional'); //include
  15739.     //     }
  15740.     //     if (empty($id_list_for_ledger))
  15741.     //         if ($id != 0)
  15742.     //             $id_list_for_ledger = [$id];
  15743.     //     $ledger_det = [];
  15744.     //     foreach ($id_list_for_ledger as $ind_head_id) {
  15745.     //         $ledger_data = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $start_date, $end_date, $provisional_option);
  15746.     //         $ledger_det[$ind_head_id] = $ledger_data;
  15747.     //     }
  15748.     //     $last_7_days_ledger_det = [];
  15749.     //     foreach ($id_list_for_ledger as $ind_head_id) {
  15750.     //         $ledger_data_7_days = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $seven_days_ago, $end_date, $provisional_option);
  15751.     //         $last_7_days_ledger_det[$ind_head_id] = $ledger_data_7_days;
  15752.     //     }
  15753.     //     $grouped_heads = Accounts::getLedgerHeadsWithParents($em);
  15754.     //     $debitCreditData = [];
  15755.     //     foreach ($ledger_det as $key => $entry) {
  15756.     //         if (isset($entry['imidiate_child']) && is_array($entry['imidiate_child'])) {
  15757.     //             foreach ($entry['imidiate_child'] as $child) {
  15758.     //                 $debitCreditData[] = [
  15759.     //                     'debit'  => $child['debit'] ?? 0,
  15760.     //                     'credit' => $child['credit'] ?? 0,
  15761.     //                     'balance' => $child['balance'] ?? 0
  15762.     //                 ];
  15763.     //             }
  15764.     //         }
  15765.     //     }
  15766.     //     $total = [
  15767.     //         'debit' => 0,
  15768.     //         'credit' => 0,
  15769.     //         'balance' => 0,
  15770.     //         'closing_balance_last_7_days' => 0, 
  15771.     //     ];
  15772.     //     foreach ($debitCreditData as $entry) {
  15773.     //         $total['debit'] += $entry['debit'];
  15774.     //         $total['credit'] += $entry['credit'];
  15775.     //         $total['balance'] += $entry['balance'];
  15776.     //     }
  15777.     //     $closing_balance_details_last_7_days = [];
  15778.     //     foreach ($last_7_days_ledger_det as $key => $entry) {
  15779.     //         if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  15780.     //             foreach ($entry['closing_data'] as $closing_entry) {
  15781.     //                 $closing_balance_details_last_7_days[] = [
  15782.     //                     'date' => $closing_entry['date'] ?? null,
  15783.     //                     //'opening' => $closing_entry['opening'] ?? 0,
  15784.     //                     //'balance' => $closing_entry['balance'] ?? 0,
  15785.     //                     'difference' => ($closing_entry['balance'] ?? 0) - ($closing_entry['opening'] ?? 0) // Calculate balance - opening
  15786.     //                 ];
  15787.     //             }
  15788.     //         }
  15789.     //     }
  15790.     //     // Add to total response
  15791.     //     $total['closing_balance_details_last_7_days'] = $closing_balance_details_last_7_days;
  15792.     //     return new JsonResponse($total);
  15793.     // }
  15794.     // public function dashboardCashFlow(Request $request, $id)
  15795.     // {
  15796.     //     $em = $this->getDoctrine()->getManager();
  15797.     //     $end_date = new \DateTime();
  15798.     //     $end_date = $end_date->format('Y-m-d');
  15799.     //     $start_date = new \DateTime();
  15800.     //     $start_date->modify('-1 month');
  15801.     //     $start_date = $start_date->format('Y-m-d');
  15802.     //     $seven_days_ago = new \DateTime();
  15803.     //     $seven_days_ago->modify('-7 days');
  15804.     //     $seven_days_ago = $seven_days_ago->format('Y-m-d');
  15805.     //     $balance_view_method = 0;
  15806.     //     $bal_set = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'ledger_balance_display_method']);
  15807.     //     if ($bal_set) {
  15808.     //         $balance_view_method = $bal_set->getdata();
  15809.     //     }
  15810.     //     $id_list_for_ledger = [];
  15811.     //     $candceq = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'cash_and_cash_equivalent_parents']);
  15812.     //     if ($candceq) {
  15813.     //         $id_list_for_ledger = json_decode($candceq->getData(), true);
  15814.     //     }
  15815.     //     $provisional_option = $request->query->get('provisional', 1);
  15816.     //     if (empty($id_list_for_ledger) && $id != 0) {
  15817.     //         $id_list_for_ledger = [$id];
  15818.     //     }
  15819.     //     $ledger_det = [];
  15820.     //     foreach ($id_list_for_ledger as $ind_head_id) {
  15821.     //         $ledger_det[$ind_head_id] = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $start_date, $end_date, $provisional_option);
  15822.     //     }
  15823.     //     $last_7_days_ledger_det = [];
  15824.     //     foreach ($id_list_for_ledger as $ind_head_id) {
  15825.     //         $last_7_days_ledger_det[$ind_head_id] = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $seven_days_ago, $end_date, $provisional_option);
  15826.     //     }
  15827.     //     $total = ['debit' => 0, 'credit' => 0, 'balance' => 0, 'past_week' => 0, 'vs_past_period' => 0];
  15828.     //     $first_day_opening_7_days = 0;
  15829.     //     $first_day_opening_30_days = 0;
  15830.     //     $first_day_set_7_days = false;
  15831.     //     $first_day_set_30_days = false;
  15832.     //     foreach ($ledger_det as $entry) {
  15833.     //         if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  15834.     //             foreach ($entry['closing_data'] as $closing_entry) {
  15835.     //                 if (!$first_day_set_30_days) {
  15836.     //                     $first_day_opening_30_days = $closing_entry['opening'] ?? 0;
  15837.     //                     $first_day_set_30_days = true;
  15838.     //                 }
  15839.     //             }
  15840.     //         }
  15841.     //     }
  15842.     //     foreach ($last_7_days_ledger_det as $entry) {
  15843.     //         if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  15844.     //             foreach ($entry['closing_data'] as $closing_entry) {
  15845.     //                 if (!$first_day_set_7_days) {
  15846.     //                     $first_day_opening_7_days = $closing_entry['opening'] ?? 0;
  15847.     //                     $first_day_set_7_days = true;
  15848.     //                 }
  15849.     //             }
  15850.     //         }
  15851.     //     }
  15852.     //     foreach ($ledger_det as $entry) {
  15853.     //         if (isset($entry['imidiate_child']) && is_array($entry['imidiate_child'])) {
  15854.     //             foreach ($entry['imidiate_child'] as $child) {
  15855.     //                 $total['debit'] += $child['debit'] ?? 0;
  15856.     //                 $total['credit'] += $child['credit'] ?? 0;
  15857.     //                 $total['balance'] += $child['balance'] ?? 0;
  15858.     //             }
  15859.     //         }
  15860.     //     }
  15861.     //     $closing_balance_details_last_7_days = [];
  15862.     //     foreach ($last_7_days_ledger_det as $key => $entry) {
  15863.     //         if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  15864.     //             foreach ($entry['closing_data'] as $closing_entry) {
  15865.     //                 $closing_balance_details_last_7_days[] = [
  15866.     //                     'date' => $closing_entry['date'] ?? null,
  15867.     //                     //'opening' => $closing_entry['opening'] ?? 0,
  15868.     //                     //'balance' => $closing_entry['balance'] ?? 0,
  15869.     //                     'difference' => ($closing_entry['balance'] ?? 0) - ($closing_entry['opening'] ?? 0) // Calculate balance - opening
  15870.     //                 ];
  15871.     //             }
  15872.     //         }
  15873.     //     }
  15874.     //     $total['closing_balance_details_last_7_days'] = $closing_balance_details_last_7_days;
  15875.     //     $total['past_week'] = $total['balance'] - $first_day_opening_7_days;
  15876.     //     $total['past_period'] = $total['balance'] - $first_day_opening_30_days;
  15877.     //     $total['vs_past_period'] = ($total['balance'] - $total['past_period'])/100;
  15878.     //     return new JsonResponse($total);
  15879.     // } 
  15880.     public function dashboardCashFlow(Request $request$id)
  15881.     {
  15882.         $em $this->getDoctrine()->getManager();
  15883.         $end_date = new \DateTime();
  15884.         $end_date $end_date->format('Y-m-d');
  15885.         $start_date = new \DateTime();
  15886.         $start_date->modify('-1 month');
  15887.         $start_date $start_date->format('Y-m-d');
  15888.         $seven_days_ago = new \DateTime();
  15889.         $seven_days_ago->modify('-7 days');
  15890.         $seven_days_ago $seven_days_ago->format('Y-m-d');
  15891.         $balance_view_method 0;
  15892.         $bal_set $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'ledger_balance_display_method']);
  15893.         if ($bal_set) {
  15894.             $balance_view_method $bal_set->getdata();
  15895.         }
  15896.         $id_list_for_ledger = [];
  15897.         $candceq $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'cash_and_cash_equivalent_parents']);
  15898.         if ($candceq) {
  15899.             $id_list_for_ledger json_decode($candceq->getData(), true);
  15900.         }
  15901.         $provisional_option $request->query->get('provisional'1);
  15902.         if (empty($id_list_for_ledger) && $id != 0) {
  15903.             $id_list_for_ledger = [$id];
  15904.         }
  15905.         $ledger_det = [];
  15906.         foreach ($id_list_for_ledger as $ind_head_id) {
  15907.             $ledger_det[$ind_head_id] = Accounts::LedgerDetailsTransMethod($em$ind_head_id$start_date$end_date$provisional_option);
  15908.         }
  15909.         $last_7_days_ledger_det = [];
  15910.         foreach ($id_list_for_ledger as $ind_head_id) {
  15911.             $last_7_days_ledger_det[$ind_head_id] = Accounts::LedgerDetailsTransMethod($em$ind_head_id$seven_days_ago$end_date$provisional_option);
  15912.         }
  15913.         $total = ['debit' => 0'credit' => 0'balance' => 0'closing_balance_last_7_days' => 0'past_week' => 0'vs_past_period' => 0];
  15914.         $first_day_opening_7_days 0;
  15915.         $first_day_opening_30_days 0;
  15916.         $first_day_set_7_days false;
  15917.         $first_day_set_30_days false;
  15918.         foreach ($ledger_det as $entry) {
  15919.             if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  15920.                 foreach ($entry['closing_data'] as $closing_entry) {
  15921.                     if (!$first_day_set_30_days) {
  15922.                         $first_day_opening_30_days $closing_entry['opening'] ?? 0;
  15923.                         $first_day_set_30_days true;
  15924.                     }
  15925.                 }
  15926.             }
  15927.         }
  15928.         foreach ($last_7_days_ledger_det as $entry) {
  15929.             if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  15930.                 foreach ($entry['closing_data'] as $closing_entry) {
  15931.                     if (!$first_day_set_7_days) {
  15932.                         $first_day_opening_7_days $closing_entry['opening'] ?? 0;
  15933.                         $first_day_set_7_days true;
  15934.                     }
  15935.                 }
  15936.             }
  15937.         }
  15938.         foreach ($ledger_det as $entry) {
  15939.             if (isset($entry['imidiate_child']) && is_array($entry['imidiate_child'])) {
  15940.                 foreach ($entry['imidiate_child'] as $child) {
  15941.                     $total['debit'] += $child['debit'] ?? 0;
  15942.                     $total['credit'] += $child['credit'] ?? 0;
  15943.                     $total['balance'] += $child['balance'] ?? 0;
  15944.                 }
  15945.             }
  15946.         }
  15947.         $closing_balance_details_last_7_days = [];
  15948.         $closing_balance_last_7_days_total 0;
  15949.         foreach ($last_7_days_ledger_det as $key => $entry) {
  15950.             if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  15951.                 foreach ($entry['closing_data'] as $closing_entry) {
  15952.                     $difference = ($closing_entry['balance'] ?? 0) - ($closing_entry['opening'] ?? 0);
  15953.                     $closing_balance_details_last_7_days[] = [
  15954.                         'date' => $closing_entry['date'] ?? null,
  15955.                         'difference' => $difference
  15956.                     ];
  15957.                     $closing_balance_last_7_days_total += $difference;
  15958.                 }
  15959.             }
  15960.         }
  15961.         $total['closing_balance_details_last_7_days'] = $closing_balance_details_last_7_days;
  15962.         $total['closing_balance_last_7_days'] = $closing_balance_last_7_days_total;
  15963.         $total['past_week'] = $total['balance'] - $first_day_opening_7_days;
  15964.         $total['past_period'] = $total['balance'] - $first_day_opening_30_days;
  15965.         $total['vs_past_period'] = ($total['balance'] - $total['past_period']) / 100;
  15966.         return new JsonResponse($total);
  15967.     }
  15968.     public function LedgerReportForApp(Request $request$id)
  15969.     {
  15970.         //        $format = $request->get('_format');
  15971.         //        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);
  15972.         $start_date "";
  15973.         $end_date "";
  15974.         $em $this->getDoctrine()->getManager();
  15975.         $start_date $request->request->get('start_date'$request->query->get('start_date'''));
  15976.         $end_date $request->request->get('end_date'$request->query->get('end_date'''));
  15977.         $limit $request->request->get('limit'$request->query->get('limit'2511165651));
  15978.         $offset $request->request->get('offset'$request->query->get('offset'0));
  15979.         $indexType $request->request->get('indexType'$request->query->get('indexType''DATE_RANGE'));
  15980.         $balance_view_method 0;
  15981.         $bal_set $em
  15982.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  15983.             ->findOneBy(
  15984.                 array(
  15985.                     'name' => 'ledger_balance_display_method',
  15986.                 )
  15987.             );
  15988.         if ($bal_set) {
  15989.             $balance_view_method $bal_set->getdata();
  15990.         }
  15991.         // now lets get its tree for the description
  15992.         $id_list_for_ledger = [];
  15993.         $parent_id_list_for_ledger = [];
  15994.         $id_list_for_ledger $request->request->get('HeadId'$request->query->get('HeadId', []));
  15995.         if (is_string($id_list_for_ledger))
  15996.             $id_list_for_ledger json_decode($id_list_for_ledgertrue);
  15997.         if ($id_list_for_ledger == null)
  15998.             $id_list_for_ledger = [];
  15999.         $parent_id_list_for_ledger $request->request->get('parentHeadId'$request->query->get('parentHeadId', []));
  16000.         $provisional_option 1//include
  16001.         $provisional_option $request->request->get('provisional'$request->query->get('provisional'1));
  16002.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  16003.         $allocationFilters $allocationSupportData['allocation_filters'];
  16004.         if (empty($id_list_for_ledger))
  16005.             if ($id != 0)
  16006.                 $id_list_for_ledger = [$id];
  16007.         $ledger_det = [];
  16008.         foreach ($id_list_for_ledger as $ind_head_id) {
  16009.             //            $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
  16010.             $ledger_data Accounts::LedgerDetailsTransMethodForApp($em$ind_head_id$start_date$end_date$provisional_option$limit$offset$indexType$allocationFilters);
  16011.             //            $ledger_det[$ind_head_id] = $ledger_data;
  16012.             $ledger_det $ledger_data;
  16013.         }
  16014.         $grouped_heads Accounts::getLedgerHeadsWithParents($em);
  16015.         if (!empty($ledger_det)) {
  16016.             return new JsonResponse(
  16017.                 array(
  16018.                     'success' => true,
  16019.                     //                'id_list' => $id_list_for_ledger,
  16020.                     //                'parent_id_list' => $parent_id_list_for_ledger,
  16021.                     //                'products' => [],
  16022.                     //                'provisional' => $provisional_option,
  16023.                     'ledger_data' => $ledger_det,
  16024.                     //                'balance_view_method' => $balance_view_method,
  16025.                     //                'categories' => [],
  16026.                     //                'heads' => $grouped_heads,
  16027.                     'itemgroup' => [],
  16028.                     'data' => [],
  16029.                     'start_date' => $start_date,
  16030.                     'end_date' => $end_date,
  16031.                 )
  16032.             );
  16033.         } else {
  16034.             return new JsonResponse(
  16035.                 array(
  16036.                     'message' => "data not found"
  16037.                 )
  16038.             );
  16039.         }
  16040.     }
  16041.     public function PrintLedger(Request $request$id)
  16042.     {
  16043.         $start_date "";
  16044.         $end_date "";
  16045.         $em $this->getDoctrine()->getManager();
  16046.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  16047.         if ($request->query->has('start_date'))
  16048.             $start_date $request->query->get('start_date');
  16049.         if ($request->query->has('end_date'))
  16050.             $end_date $request->query->get('end_date');
  16051.         $provisional_option 1//include
  16052.         if ($request->query->has('provisional')) {
  16053.             $provisional_option $request->query->get('provisional'); //include
  16054.         }
  16055.         $balance_view_method 0;
  16056.         $bal_set $em
  16057.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  16058.             ->findOneBy(
  16059.                 array(
  16060.                     'name' => 'ledger_balance_display_method',
  16061.                 )
  16062.             );
  16063.         if ($bal_set) {
  16064.             $balance_view_method $bal_set->getdata();
  16065.         }
  16066.         // now lets get its tree for the description
  16067.         $id_list_for_ledger = [];
  16068.         if ($request->query->has('id_list'))
  16069.             $id_list_for_ledger explode(','$request->query->get('id_list'));
  16070.         if ($id && empty($id_list))
  16071.             $id_list_for_ledger = [0];
  16072.         $ledger_det = [];
  16073.         $head_name_list = [];
  16074.         // Build the allocation filters (tag/project/branch/cost-center) from the request — same as the
  16075.         // ledger view; the print URL carries these query params and LedgerDetailsTransMethod requires them.
  16076.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  16077.         $allocationFilters $allocationSupportData['allocation_filters'];
  16078.         foreach ($id_list_for_ledger as $ind_head_id) {
  16079.             $ledger_data Accounts::LedgerDetailsTransMethod($em$ind_head_id$start_date$end_date$provisional_option$allocationFilters);
  16080.             $ledger_det[$ind_head_id] = $ledger_data;
  16081.             $head_name_list[] = $ledger_data['basic_data']['name'];
  16082.         }
  16083.         $grouped_heads Accounts::GroupedHeads($em);
  16084.         $document_mark = array(
  16085.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  16086.             'copy' => ''
  16087.         );
  16088.         $html "";
  16089.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  16090.             $html $this->renderView(
  16091.                 '@Accounts/pages/print/ledger_print.html.twig',
  16092.                 array(
  16093.                     'pdf' => true,
  16094.                     'page_title' => 'Ledger ',
  16095.                     'ledger_data' => $ledger_det,
  16096.                     'balance_view_method' => $balance_view_method,
  16097.                     'page_header' => 'Ledger',
  16098.                     'document_type' => implode(', '$head_name_list),
  16099.                     'document_mark_image' => $document_mark['original'],
  16100.                     'page_header_sub' => 'Add',
  16101.                     'start_date' => $start_date,
  16102.                     'end_date' => $end_date,
  16103.                     'head_list' => Accounts::HeadListFullPath($em),
  16104.                     'provisional' => $provisional_option,
  16105.                     //                'type_list'=>$type_list,
  16106.                     //            'child_list'=>$child_list,
  16107.                     //                'trans_data_by_closing'=>$trans_data_by_closing,
  16108.                     'item_data' => [],
  16109.                     'received' => 2,
  16110.                     'return' => 1,
  16111.                     'total_w_vat' => 1,
  16112.                     'total_vat' => 1,
  16113.                     'total_wo_vat' => 1,
  16114.                     'invoice_id' => 'abcd1234',
  16115.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  16116.                     'created_by' => 'created by',
  16117.                     'created_at' => '',
  16118.                     'red' => 0,
  16119.                     //                'desc_head_list'=>$desc_tree_list,
  16120.                     'company_name' => $company_data->getName(),
  16121.                     'company_data' => $company_data,
  16122.                     'company_address' => $company_data->getAddress(),
  16123.                     'company_image' => $company_data->getImage(),
  16124.                     //                'p'=>$p
  16125.                 )
  16126.             );
  16127.             if ($request->query->has('sendMail')) {
  16128.                 if ($request->query->get('sendMail') == 1) {
  16129.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' 'ledger' '.pdf';
  16130.                     $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  16131.                         'no-stop-slow-scripts' => true,
  16132.                         'no-background' => false,
  16133.                         'lowquality' => false,
  16134.                         'encoding' => 'utf-8',
  16135.                         'dpi' => 300,
  16136.                         'image-dpi' => 300,
  16137.                     ));
  16138.                     $new_mail $this->get('mail_module');
  16139.                     $new_mail->sendMyMail(array(
  16140.                         'attachment' => $pdf_response
  16141.                     ));
  16142.                     return $this->render(
  16143.                         '@Accounts/pages/print/ledger_print.html.twig',
  16144.                         array(
  16145.                             'page_title' => 'Ledger ',
  16146.                             'ledger_data' => $ledger_det,
  16147.                             'page_header' => 'Ledger',
  16148.                             'document_type' => implode(', '$head_name_list),
  16149.                             'document_mark_image' => $document_mark['original'],
  16150.                             'page_header_sub' => 'Add',
  16151.                             'start_date' => $start_date,
  16152.                             'end_date' => $end_date,
  16153.                             'head_list' => Accounts::HeadListFullPath($em),
  16154.                             'provisional' => $provisional_option,
  16155.                             'balance_view_method' => $balance_view_method,
  16156.                             //                'type_list'=>$type_list,
  16157.                             //            'child_list'=>$child_list,
  16158.                             //                'trans_data_by_closing'=>$trans_data_by_closing,
  16159.                             'item_data' => [],
  16160.                             'received' => 2,
  16161.                             'return' => 1,
  16162.                             'total_w_vat' => 1,
  16163.                             'total_vat' => 1,
  16164.                             'total_wo_vat' => 1,
  16165.                             'invoice_id' => 'abcd1234',
  16166.                             'invoice_footer' => $company_data->getInvoiceFooter(),
  16167.                             'created_by' => 'created by',
  16168.                             'created_at' => '',
  16169.                             'red' => 0,
  16170.                             //                'desc_head_list'=>$desc_tree_list,
  16171.                             'company_name' => $company_data->getName(),
  16172.                             'company_data' => $company_data,
  16173.                             'company_address' => $company_data->getAddress(),
  16174.                             'company_image' => $company_data->getImage(),
  16175.                             'allocation_filters' => $allocationFilters,
  16176.                             'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  16177.                             'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  16178.                             'project_list' => $allocationSupportData['project_list'],
  16179.                             'branch_list' => $allocationSupportData['branch_list'],
  16180.                             'cost_centers' => $allocationSupportData['cost_centers'],
  16181.                             'export' => 'all'
  16182.                             //                'p'=>$p
  16183.                         )
  16184.                     );
  16185.                 }
  16186.             } else {
  16187.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  16188.                     'no-stop-slow-scripts' => true,
  16189.                     'no-background' => false,
  16190.                     'lowquality' => false,
  16191.                     'encoding' => 'utf-8',
  16192.                     'dpi' => 300,
  16193.                     'image-dpi' => 300,
  16194.                 ));
  16195.                 return new Response(
  16196.                     $pdf_response,
  16197.                     200,
  16198.                     array(
  16199.                         'Content-Type' => 'application/pdf',
  16200.                         'Content-Disposition' => 'attachment; filename="Ledger.pdf"'
  16201.                     )
  16202.                 );
  16203.             }
  16204.         }
  16205.         return $this->render(
  16206.             '@Accounts/pages/print/ledger_print.html.twig',
  16207.             array(
  16208.                 'page_title' => 'Ledger ',
  16209.                 'ledger_data' => $ledger_det,
  16210.                 'page_header' => 'Ledger',
  16211.                 'document_type' => implode(', '$head_name_list),
  16212.                 'document_mark_image' => $document_mark['original'],
  16213.                 'page_header_sub' => 'Add',
  16214.                 'start_date' => $start_date,
  16215.                 'end_date' => $end_date,
  16216.                 'head_list' => Accounts::HeadListFullPath($em),
  16217.                 'provisional' => $provisional_option,
  16218.                 'balance_view_method' => $balance_view_method,
  16219.                 //                'type_list'=>$type_list,
  16220.                 //            'child_list'=>$child_list,
  16221.                 //                'trans_data_by_closing'=>$trans_data_by_closing,
  16222.                 'item_data' => [],
  16223.                 'received' => 2,
  16224.                 'return' => 1,
  16225.                 'total_w_vat' => 1,
  16226.                 'total_vat' => 1,
  16227.                 'total_wo_vat' => 1,
  16228.                 'invoice_id' => 'abcd1234',
  16229.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  16230.                 'created_by' => 'created by',
  16231.                 'created_at' => '',
  16232.                 'red' => 0,
  16233.                 //                'desc_head_list'=>$desc_tree_list,
  16234.                 'company_name' => $company_data->getName(),
  16235.                 'company_data' => $company_data,
  16236.                 'company_address' => $company_data->getAddress(),
  16237.                 'company_image' => $company_data->getImage(),
  16238.                 'export' => 'all'
  16239.                 //                'p'=>$p
  16240.             )
  16241.         );
  16242.     }
  16243.     public function PrintLedgerPdf(Request $request$id)
  16244.     {
  16245.         $start_date "";
  16246.         $end_date "";
  16247.         if ($this->container->has('profiler')) {
  16248.             $this->container->get('profiler')->disable();
  16249.         }
  16250.         $em $this->getDoctrine()->getManager();
  16251.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  16252.         if ($request->query->has('start_date'))
  16253.             $start_date $request->query->get('start_date');
  16254.         if ($request->query->has('end_date'))
  16255.             $end_date $request->query->get('end_date');
  16256.         $provisional_option 1//include
  16257.         if ($request->query->has('provisional')) {
  16258.             $provisional_option $request->query->get('provisional'); //include
  16259.         }
  16260.         // now lets get its tree for the description
  16261.         $id_list_for_ledger = [];
  16262.         if ($request->query->has('id_list'))
  16263.             $id_list_for_ledger explode(','$request->query->get('id_list'));
  16264.         if ($id && empty($id_list))
  16265.             $id_list_for_ledger = [0];
  16266.         $ledger_det = [];
  16267.         $head_name_list = [];
  16268.         foreach ($id_list_for_ledger as $ind_head_id) {
  16269.             $ledger_data Accounts::LedgerDetailsTransMethod($em$ind_head_id$start_date$end_date$provisional_option);
  16270.             $ledger_det[$ind_head_id] = $ledger_data;
  16271.             $head_name_list[] = $ledger_data['basic_data']['name'];
  16272.         }
  16273.         $grouped_heads Accounts::GroupedHeads($em);
  16274.         $document_mark = array(
  16275.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  16276.             'copy' => ''
  16277.         );
  16278.         // now lets get its tree for the description
  16279.         //        $id_list=explode('/',$em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
  16280.         //            'accountsHeadId'=>$id
  16281.         //        ))->getPathTree());
  16282.         //        $desc_tree_list=$em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findBy(array(
  16283.         //            'accountsHeadId'=>$id_list
  16284.         //        ),
  16285.         //            array(
  16286.         //                'accountsHeadId'=>'ASC',
  16287.         //            ));
  16288.         //
  16289.         //        //now assigning transactions to closing_data_list
  16290.         //        $trans_data_by_closing=[];
  16291.         //
  16292.         //        foreach($child_list['transaction_list'] as $g=>$entry)
  16293.         //        {
  16294.         //            $my_time = strtotime($entry['transaction_date']);
  16295.         //            $tr_date = date("m/d/Y", $my_time);
  16296.         ////                if($entry['transaction_date'] instanceof \DateTime)
  16297.         //            $trans_data_by_closing[$tr_date][]=$entry;
  16298.         //        }
  16299.         $html $this->renderView(
  16300.             '@Accounts/pages/print/ledger_print.html.twig',
  16301.             array(
  16302.                 'page_title' => 'Ledger ',
  16303.                 'ledger_data' => $ledger_det,
  16304.                 'page_header' => 'Ledger',
  16305.                 'document_type' => implode(', '$head_name_list),
  16306.                 'document_mark_image' => $document_mark['original'],
  16307.                 'page_header_sub' => 'Add',
  16308.                 'start_date' => $start_date,
  16309.                 'end_date' => $end_date,
  16310.                 'provisional' => $provisional_option,
  16311.                 'head_list' => Accounts::HeadList($em),
  16312.                 //                'type_list'=>$type_list,
  16313.                 //            'child_list'=>$child_list,
  16314.                 //                'trans_data_by_closing'=>$trans_data_by_closing,
  16315.                 'item_data' => [],
  16316.                 'received' => 2,
  16317.                 'return' => 1,
  16318.                 'total_w_vat' => 1,
  16319.                 'total_vat' => 1,
  16320.                 'total_wo_vat' => 1,
  16321.                 'invoice_id' => 'abcd1234',
  16322.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  16323.                 'created_by' => 'created by',
  16324.                 'created_at' => '',
  16325.                 'red' => 0,
  16326.                 //                'desc_head_list'=>$desc_tree_list,
  16327.                 'company_name' => $company_data->getName(),
  16328.                 'company_data' => $company_data,
  16329.                 'company_address' => $company_data->getAddress(),
  16330.                 'company_image' => $company_data->getImage(),
  16331.                 'allocation_filters' => $allocationFilters,
  16332.                 'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  16333.                 'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  16334.                 'project_list' => $allocationSupportData['project_list'],
  16335.                 'branch_list' => $allocationSupportData['branch_list'],
  16336.                 'cost_centers' => $allocationSupportData['cost_centers'],
  16337.                 //                'p'=>$p
  16338.             )
  16339.         );
  16340.         //        $l= $this->get('knp_snappy.pdf')->generateFromHtml($html
  16341.         //            ,
  16342.         //            $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/myfile.pdf'
  16343.         //        );
  16344.         //        $chk=$this->get('knp_snappy.pdf');
  16345.         $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  16346.             //                'orientation' => 'landscape',
  16347.             'enable-javascript' => true,
  16348.             'javascript-delay' => 1000,
  16349.             'no-stop-slow-scripts' => true,
  16350.             'no-background' => false,
  16351.             //            'lowquality' => false,
  16352.             'encoding' => 'utf-8',
  16353.             'images' => true,
  16354.             'cookie' => array(),
  16355.             'dpi' => 300,
  16356.             'image-dpi' => 300,
  16357.             //            'page-height' =>  '29.7cm',
  16358.             //            'page-width' => '21cm'
  16359.             //                'enable-external-links' => true,
  16360.             //                'enable-internal-links' => true
  16361.         ));
  16362.         return new Response(
  16363.             $pdf_response,
  16364.             200,
  16365.             array(
  16366.                 'Content-Type' => 'application/pdf',
  16367.                 //                'Content-Disposition'   => 'attachment; filename="file.pdf"'
  16368.             )
  16369.         );
  16370.     }
  16371.     public function AccountsSettings(Request $request)
  16372.     {
  16373.         $id 0;
  16374.         $cc_id '';
  16375.         $cc_name '';
  16376.         $em $this->getDoctrine()->getManager();
  16377.         if ($request->isMethod('POST')) {
  16378.             foreach ($request->request->keys() as $req_key) {
  16379.                 //first check if it exists so we can update
  16380.                 $new_cc $this->getDoctrine()
  16381.                     ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  16382.                     ->findOneBy(
  16383.                         array(
  16384.                             'name' => $req_key,
  16385.                         )
  16386.                     );
  16387.                 if (empty($new_cc)) //doesnot exists  make new
  16388.                 {
  16389.                     $new = new AccSettings();
  16390.                     $new->setName($req_key);
  16391.                     if ($req_key == 'accounting_year_start' || $req_key == 'accounting_year_end')
  16392.                         $new->setData($request->request->get($req_key)); //might look as array so setting as string
  16393.                     else if (is_array($request->request->get($req_key)))
  16394.                         $new->setData(json_encode($request->request->get($req_key)));
  16395.                     else
  16396.                         $new->setData($request->request->get($req_key));
  16397.                     $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  16398.                     $em->persist($new);
  16399.                     $em->flush();
  16400.                 } else {
  16401.                     if ($req_key == 'accounting_year_start' || $req_key == 'accounting_year_end')
  16402.                         $new_cc->setData($request->request->get($req_key));
  16403.                     else if (is_array($request->request->get($req_key)))
  16404.                         $new_cc->setData(json_encode($request->request->get($req_key)));
  16405.                     else
  16406.                         $new_cc->setData($request->request->get($req_key));
  16407.                     $new_cc->setEditLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  16408.                 }
  16409.             }
  16410.             $em->flush();
  16411.         }
  16412.         $data $this->getDoctrine()
  16413.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  16414.             ->findAll();
  16415.         $supplier_type_data $this->getDoctrine()
  16416.             ->getRepository('ApplicationBundle\\Entity\\SupplierType')
  16417.             ->findAll();
  16418.         $client_type_data $this->getDoctrine()
  16419.             ->getRepository('ApplicationBundle\\Entity\\ClientType')
  16420.             ->findAll();
  16421.         $action_type_data = [
  16422.             => 'general',
  16423.             => 'advance',
  16424.         ];
  16425.         $settings_list = [];
  16426.         $supplier_type_data_list = [];
  16427.         $client_type_data_list = [];
  16428.         foreach ($supplier_type_data as $value) {
  16429.             $supplier_type_data_list[$value->getSupplierTypeId()]['id'] = $value->getSupplierTypeId();
  16430.             $supplier_type_data_list[$value->getSupplierTypeId()]['name'] = $value->getName();
  16431.         }
  16432.         foreach ($client_type_data as $value) {
  16433.             $client_type_data_list[$value->getClientTypeId()]['id'] = $value->getClientTypeId();
  16434.             $client_type_data_list[$value->getClientTypeId()]['name'] = $value->getName();
  16435.         }
  16436.         foreach ($data as $value) {
  16437.             $settings_list[$value->getName()]['id'] = $value->getId();
  16438.             $settings_list[$value->getName()]['name'] = $value->getName();
  16439.             $settings_list[$value->getName()]['value'] = $value->getData();
  16440.             if ($value->getName() == 'accounting_year_start' || $value->getName() == 'accounting_year_end')
  16441.                 $settings_list[$value->getName()]['value'] = $value->getData();
  16442.             else if (is_array(json_decode($value->getData())))
  16443.                 $settings_list[$value->getName()]['value'] = json_decode($value->getData());
  16444.             else
  16445.                 $settings_list[$value->getName()]['value'] = $value->getData();
  16446.         }
  16447.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');
  16448.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  16449.         return $this->render(
  16450.             '@Application/pages/accounts/settings/acc_settings.html.twig',
  16451.             array(
  16452.                 'page_title' => 'Settings',
  16453.                 'settings_data' => $settings_list,
  16454.                 'client_type_list' => $client_type_data_list,
  16455.                 'sales_type_list' => array(=> 'Package'=> 'Project'=> 'Item/Spare'),
  16456.                 'sales_sub_type_list' => array(=> 'Cash Sales'=> 'Credit Sale'),
  16457.                 'supplier_type_list' => $supplier_type_data_list,
  16458.                 'payment_action_type_list' => $action_type_data,
  16459.                 'warehouse_action_list' => $warehouse_action_list,
  16460.                 'head_list' => Accounts::HeadListFullPath($em),
  16461.                 'expense_list' => InventoryConstant::$Expense_list_details,
  16462.                 'payroll_segregation_settings' => HumanResourceConstant::$segregationSettings
  16463.             )
  16464.         );
  16465.     }
  16466.     public function BankAccount(Request $request$id 0)
  16467.     {
  16468.         $em $this->getDoctrine()->getManager();
  16469.         $AccounDetails $em->getRepository(BankAccounts::class)->findAll();
  16470.         $childAccount Accounts::getChildLedgerHeads($em"""");
  16471.         $accountType AccountsConstant::$AccountType;
  16472.         $interestCategory AccountsConstant::$InterestCategory;
  16473.         $bankLists $em->getRepository(BankList::class)->findAll();
  16474.         $bankAccount $id $em->getRepository(BankAccounts::class)->find($id) : new BankAccounts();
  16475.         $availableHeads $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findAll();
  16476.         if ($id && !$bankAccount) {
  16477.             return new JsonResponse(['success' => false'message' => 'Bank account not found'], 404);
  16478.         }
  16479.         if ($request->isMethod('POST')) {
  16480.             $accountHolderName $request->request->get('account_holder_name');
  16481.             $accountNumber $request->request->get('account_number');
  16482.             $accountTypeVal $request->request->get('account_type');
  16483.             $interestRate $request->request->get('interest_rate');
  16484.             $bankName $request->request->get('bank_name');
  16485.             $branchName $request->request->get('branch_name');
  16486.             $swiftCode $request->request->get('swift_code');
  16487.             $routingNumber $request->request->get('routing_number');
  16488.             $numlength strlen((string)$accountNumber);
  16489.             if ($numlength || $accountNumber <= 0) {
  16490.                 return new JsonResponse(['message' => 'Account number must be at least 8 digits and positive!']);
  16491.             }
  16492.             if (!$accountHolderName || !$accountNumber || !$accountTypeVal || $interestRate <= 0) {
  16493.                 return new JsonResponse(['message' => 'Missing or invalid required fields.']);
  16494.             }
  16495.             // Save main bank
  16496.             $bank $em->getRepository(BankList::class)->findOneBy(['name' => $bankName'type' => 0]);
  16497.             if (!$bank) {
  16498.                 $bank = new BankList();
  16499.                 $bank->setName($bankName);
  16500.                 $bank->setType(0); // Type 0 for Bank
  16501.                 $bank->setSwiftCode($swiftCode);
  16502.                 $bank->setRoutingNumber($routingNumber);
  16503.                 $em->persist($bank);
  16504.                 $em->flush();
  16505.             }
  16506.             // Save or find branch under this bank
  16507.             $branch $em->getRepository(BankList::class)->findOneBy([
  16508.                 'name' => $branchName,
  16509.                 'type' => 2,
  16510.                 'parentId' => $bank->getBankId()
  16511.             ]);
  16512.             if (!$branch) {
  16513.                 $branch = new BankList();
  16514.                 $branch->setName($branchName);
  16515.                 $branch->setType(2);
  16516.                 $branch->setParentId($bank->getBankId());
  16517.                 $branch->setBank($bankName);
  16518.                 $branch->setSwiftCode($swiftCode);
  16519.                 $branch->setRoutingNumber($routingNumber);
  16520.                 $em->persist($branch);
  16521.                 $em->flush();
  16522.             }
  16523.             // Set BankAccount info
  16524.             $bankAccount->setAccountHolderName($accountHolderName);
  16525.             $bankAccount->setAccountNumber($accountNumber);
  16526.             $bankAccount->setAccountType($accountTypeVal);
  16527.             $bankAccount->setInterestRate($interestRate);
  16528.             $bankAccount->setInterestCategory($request->request->get('interest_category'));
  16529.             $bankAccount->setSwiftCode($swiftCode);
  16530.             $bankAccount->setRoutingNumber($routingNumber);
  16531.             $bankAccount->setBranchName($branchName);
  16532.             $accountsHeadId $request->request->get('accounts_head_id');
  16533.             if (!$accountsHeadId) {
  16534.                 $branchBankParentData $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'branch_bank_parent']);
  16535.                 if (!$branchBankParentData) {
  16536.                     return new JsonResponse(['success' => false'message' => 'Parent not found']);
  16537.                 }
  16538.                 $branchBankParent $branchBankParentData->getData();
  16539.                 $accHead Accounts::CreateNewHead(
  16540.                     $em,
  16541.                     GeneralConstant::OPENING_YEAR,
  16542.                     $branchBankParent,
  16543.                     $bankAccount->getAccountHolderName() . ' # ' $bankAccount->getAccountNumber(),
  16544.                     '',
  16545.                     0,
  16546.                     0,
  16547.                     'dr',
  16548.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  16549.                 );
  16550.                 $em->flush();
  16551.                 $bankAccount->setAccountsHeadId($accHead);
  16552.             } else {
  16553.                 $bankAccount->setAccountsHeadId($accountsHeadId);
  16554.             }
  16555.             $em->persist($bankAccount);
  16556.             $em->flush();
  16557.             return new JsonResponse(['success' => true]);
  16558.         }
  16559.         return $this->render('@Accounts/pages/input_forms/bank_account.html.twig', [
  16560.             'page_title' => $id 'Update Bank Account' 'Bank Account',
  16561.             'account_type' => $accountType,
  16562.             'childAccounts' => $childAccount,
  16563.             'interestCategory' => $interestCategory,
  16564.             'bankLists' => $bankLists,
  16565.             'bankaccount' => $bankAccount,
  16566.             'AccounDetails' => $AccounDetails,
  16567.             'available_heads' => $availableHeads,
  16568.             'id' => $id
  16569.         ]);
  16570.     }
  16571.     public function DeleteBankAccount(Request $request$id)
  16572.     {
  16573.         $em $this->getDoctrine()->getManager();
  16574.         $account $em->getRepository('ApplicationBundle\\Entity\\BankAccounts')->find($id);
  16575.         if (!$account) {
  16576.             return new JsonResponse(['success' => false'message' => 'Bank account not found'], 404);
  16577.         }
  16578.         $currentHeadId $account->getAccountsHeadId();
  16579.         $currentHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->find($currentHeadId);
  16580.         if ($request->isXmlHttpRequest() && $request->isMethod('POST')) {
  16581.             $newHeadId $request->request->get('new_head');
  16582.             if (!$newHeadId) {
  16583.                 return new JsonResponse(['success' => false'message' => 'Please select a new head before deletion'], 400);
  16584.             }
  16585.             $transactions $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
  16586.                 ->findBy(['accountsHeadId' => $account->getAccountsHeadId()]);
  16587.             $newHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->find($newHeadId);
  16588.             if ($newHead) {
  16589.                 foreach ($transactions as $transaction) {
  16590.                     $transaction->setAccountsHead($newHead);
  16591.                     $em->persist($transaction);
  16592.                 }
  16593.                 $em->flush();
  16594.             }
  16595.             $accountId $account->getId();
  16596.             $em->remove($account);
  16597.             $em->flush();
  16598.             if ($currentHead) {
  16599.                 $em->remove($currentHead);
  16600.                 $em->flush();
  16601.             }
  16602.             return new JsonResponse([
  16603.                 'success' => true,
  16604.                 'message' => 'Bank account deleted successfully',
  16605.                 'accountId' => $accountId
  16606.             ]);
  16607.         }
  16608.         return new JsonResponse(['success' => false'message' => 'Invalid request'], 400);
  16609.     }
  16610.     public function BankAccountList()
  16611.     {
  16612.         $em $this->getDoctrine()->getManager();
  16613.         $AccounDetails $em->getRepository(BankAccounts::class)->findAll();
  16614.         $childAccount Accounts:: getChildLedgerHeads($em$doc_type ""$Type "");
  16615.         $accountType AccountsConstant::$AccountType;
  16616.         return $this->render('@Accounts/pages/list/bank_account_list.html.twig', array(
  16617.             'page_title' => 'Bank Account List',
  16618.             'AccounDetails' => $AccounDetails,
  16619.             'childAccounts' => $childAccount,
  16620.             'accountType' => $accountType,
  16621.         ));
  16622.     }
  16623.     public function createBank(Request $request)
  16624.     {
  16625.         $em $this->getDoctrine()->getManager();
  16626.         $BankList $em->getRepository('ApplicationBundle\\Entity\\BankList')->findAll();
  16627.         if ($request->isMethod('POST')) {
  16628.             $bank = new BankList();
  16629.             $name $request->request->get('name');
  16630.             $branchName $request->request->get('branch_name');
  16631.             $swiftCode $request->request->get('swift_code');
  16632.             $routingNumber $request->request->get('routing_number');
  16633.             $address $request->request->get('address');
  16634.             $mapPosition $request->request->get('map_position');
  16635.             $countryId $request->request->get('country_id');
  16636.             $type $request->request->get('type');
  16637.             $parentId $request->request->get('parent_id');
  16638.             $status $request->request->get('status');
  16639.             $createdLoginId $request->getSession()->get('user_login_id');
  16640.             $bank->setName($name);
  16641.             $bank->setBranchName($branchName);
  16642.             $bank->setSwiftCode($swiftCode);
  16643.             $bank->setRoutingNumber($routingNumber);
  16644.             $bank->setAddress($address);
  16645.             $bank->setMapPosition($mapPosition);
  16646.             $bank->setCountryId($countryId);
  16647.             $bank->setType($type);
  16648.             $bank->setParentId($parentId);
  16649.             $bank->setStatus($status);
  16650.             $bank->setCreatedLoginId($createdLoginId);
  16651.             $bank->setCreatedAt(new \DateTime());
  16652.             $em->persist($bank);
  16653.             $em->flush();
  16654. //            return new JsonResponse(['success' => true, 'message' => 'Bank created successfully']);
  16655.             return $this->redirectToRoute('create_bank_account');
  16656.         }
  16657.         return $this->render('@Accounts/pages/input_forms/create_bank.html.twig', [
  16658.             'page_title' => 'Create Bank Account',
  16659.             'bankList' => $BankList
  16660.         ]);
  16661.     }
  16662.     public function ViewAccountDetail($id)
  16663.     {
  16664.         $em $this->getDoctrine()->getManager();
  16665.         $AccounDetails $em->getRepository(BankAccounts::class)->find($id);
  16666.         $bankLists $em->getRepository(BankList::class)->findAll();
  16667.         $childAccount Accounts::getChildLedgerHeads($em$doc_type ""$Type "");
  16668.         $accountType AccountsConstant::$AccountType;
  16669.         $interestCategory AccountsConstant::$InterestCategory;
  16670.         return $this->render('@Accounts/pages/views/view_bank_account_details.html.twig', array(
  16671.             'page_title' => ' View Bank Account Details',
  16672.             'AccounDetails' => $AccounDetails,
  16673.             'childAccounts' => $childAccount,
  16674.             'account_Type' => $accountType,
  16675.             'bankLists' => $bankLists,
  16676.             'interestCategory' => $interestCategory,
  16677.             'id' => $id,
  16678.         ));
  16679.     }
  16680.     public function PrintBankAccount(Request $request$id)
  16681.     {
  16682.         $em $this->getDoctrine()->getManager();
  16683.         $company_data Company::getCompanyData($em1);
  16684.         $AccounDetails $em->getRepository(BankAccounts::class)->find($id);
  16685.         $bankLists $em->getRepository(BankList::class)->findAll();
  16686.         $childAccount Accounts::getChildLedgerHeads($em$doc_type ""$Type "");
  16687.         $accountType AccountsConstant::$AccountType;
  16688.         $interestCategory AccountsConstant::$InterestCategory;
  16689.         return $this->render('@Accounts/pages/print/bank_account_print.html.twig', array(
  16690.             'page_title' => ' Print Bank Account Details',
  16691.             'AccounDetails' => $AccounDetails,
  16692.             'company_name' => $company_data->getName(),
  16693.             'company_data' => $company_data,
  16694.             'company_address' => $company_data->getAddress(),
  16695.             'company_image' => $company_data->getImage(),
  16696.             'bankLists' => $bankLists,
  16697.             'childAccounts' => $childAccount,
  16698.             'account_Type' => $accountType,
  16699.             'interestCategory' => $interestCategory,
  16700.         ));
  16701.     }
  16702.     public function SingleBank($id)
  16703.     {
  16704.         $em $this->getDoctrine()->getManager();
  16705.         $bankLists $em->getRepository(BankList::class)->find($id);
  16706.         return new JsonResponse(
  16707.             array(
  16708.                 'success' => true,
  16709.                 'routing_code' => $bankLists->getRoutingNumber(),
  16710.                 'swift_code' => $bankLists->getSwiftCode(),
  16711.             )
  16712.         );
  16713.     }
  16714.     public function createTaxConfig(Request $request$id 0)
  16715.     {
  16716.         $em $this->getDoctrine()->getManager();
  16717.         $companyId $this->getLoggedUserCompanyId($request);
  16718.         $taxConfig null;
  16719.         if ($request->isMethod('POST')) {
  16720.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  16721.             if ($id != 0)
  16722.                 $taxConfig $em->getRepository(TaxConfig::class)->find($id);
  16723.             if (!$taxConfig)
  16724.                 $taxConfig = new TaxConfig();
  16725.             $taxConfig->setName($request->request->get('name'));
  16726.             $taxConfig->setAmount($request->request->get('amount'));
  16727.             $taxConfig->setAmountType($request->request->get('amountType'));
  16728.             $taxConfig->setInvocationType($request->request->get('invocationType'));
  16729.             $taxConfig->setMinimumAmountToinvoke($request->request->get('minimumInvokeAmount'));
  16730.             $taxConfig->setOutgoingHeadId($request->request->get('outgoingHeadId'));
  16731.             $taxConfig->setIncomingHeadId($request->request->get('incomingHeadId'));
  16732.             $taxConfig->setPayableHeadId($request->request->get('payableHeadId'));
  16733.             $taxConfig->setCurrency($request->request->get('currency'));
  16734.             $markerPost $request->request->get('marker'null);
  16735.             $markerNorm = ($markerPost === null) ? null trim((string) $markerPost);
  16736.             $taxConfig->setMarker(($markerNorm === '' || $markerNorm === null) ? null $markerNorm);
  16737.             $taxConfig->setStatus(1);
  16738.             $em->persist($taxConfig);
  16739.             $em->flush();
  16740.             $this->addFlash(
  16741.                 'success',
  16742.                 'Data added successfully'
  16743.             );
  16744.         }
  16745.         $taxConfigDetails $em->getRepository(TaxConfig::class)->findAll();
  16746.         $taxConfigData = [];
  16747.         if ($id != 0)
  16748.             $taxConfigData $em->getRepository(TaxConfig::class)->find($id);
  16749.         return $this->render('@Accounts/pages/input_forms/create_tax_config.html.twig', array(
  16750.             'page_title' => 'Tax Config ',
  16751.             'taxconfigDetails' => $taxConfigDetails,
  16752.             'data' => $taxConfigData
  16753.         ));
  16754.     }
  16755.     public function expenseCategory()
  16756.     {
  16757.         $expenseCategory GeneralConstant::$expenseCategory;
  16758.         return new JsonResponse($expenseCategory);
  16759.     }
  16760.     public function packageDetails()
  16761.     {
  16762.         $packageDetails GeneralConstant::$packageDetails;
  16763.         return new JsonResponse($packageDetails);
  16764.     }
  16765.     public function employeerange()
  16766.     {
  16767.         $employeerange GeneralConstant::$employeerange;
  16768.         return new JsonResponse($employeerange);
  16769.     }
  16770. //    public function getExpenseByCurrentDate(Request $request)
  16771. //    {
  16772. //        $em = $this->getDoctrine()->getManager();
  16773. //        $session = $request->getSession();
  16774. //        $currentTime = new \Datetime();
  16775. //        $currDate = $currentTime->format('Y-m-d');
  16776. //        $partyId = 1313;
  16777. //
  16778. //
  16779. //
  16780. //        $absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  16781. //
  16782. //
  16783. //        $expDetails = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->createQueryBuilder('E')
  16784. //            ->leftJoin('ApplicationBundle:Currencies', 'C', 'WITH', 'E.currency = C.currencyId')
  16785. //            ->select('E, C.code as currencyName') // Selecting currency name
  16786. //            ->where('E.partyHeadId = :partyId')
  16787. //            ->andWhere('E.createdAt >= :currentDate')
  16788. //            ->setParameter('currentDate', $currDate)
  16789. //            ->setParameter('partyId', $partyId)
  16790. //            ->getQuery()
  16791. //            ->getResult();
  16792. //
  16793. //
  16794. //        $expenseCategories = GeneralConstant::$expenseCategory;
  16795. //
  16796. //        function getExpenseCategoryByMarker($markerHash, $categories)
  16797. //        {
  16798. //            foreach ($categories as $category) {
  16799. //                if ($category['markerHash'] === $markerHash) {
  16800. //                    return $category; // Return full category array
  16801. //                }
  16802. //            }
  16803. //            return null;
  16804. //        }
  16805. //
  16806. //        function getSubcategoryName($category, $subcategoryId)
  16807. //        {
  16808. //            if (!$category || !isset($category['expenseSubcategory'])) {
  16809. //                return null;
  16810. //            }
  16811. //
  16812. //            foreach ($category['expenseSubcategory'] as $subcategory) {
  16813. //                if ($subcategory['id'] == $subcategoryId) {
  16814. //                    return $subcategory;
  16815. //                }
  16816. //            }
  16817. //            return null;
  16818. //        }
  16819. //
  16820. //        function getSubcategoryOptionName($subcategory, $optionId)
  16821. //        {
  16822. //            if (!$subcategory || !isset($subcategory['option'])) {
  16823. //                return null;
  16824. //            }
  16825. //
  16826. //            foreach ($subcategory['option'] as $option) {
  16827. //                if ($option['id'] == $optionId) {
  16828. //                    return $option;
  16829. //                }
  16830. //            }
  16831. //            return null;
  16832. //        }
  16833. //
  16834. //        $expList = [];
  16835. //
  16836. //        foreach ($expDetails as $data) {
  16837. //            $expenseCategory = getExpenseCategoryByMarker($data[0]->getMarkerHash(), $expenseCategories);
  16838. //            $subcategory = getSubcategoryName($expenseCategory, $data[0]->getExpenseSubCategory());
  16839. //            $subcategoryOption = getSubcategoryOptionName($subcategory, $data[0]->getExpenseSubCategoryOption());
  16840. //
  16841. //            $list = [
  16842. //                'id' => $data[0]->getExpenseInvoiceId(),
  16843. //                'amount' => $data[0]->getInvoiceAmount(),
  16844. //                'editFlag' => $data[0]->getEditFlag(),
  16845. //                'deleteFlag' => $data[0]->getDeleteFlag(),
  16846. //                'markerHash' => $data[0]->getMarkerHash(),
  16847. //                'expenseDate' => 1 * $data[0]->getExpenseInvoiceDate()->format('U'),
  16848. //                'expenseDescription' => $data[0]->getDescription(),
  16849. //                'currency' => $data[0]->getCurrency(),
  16850. //                'currencyName' => $data['currencyName'] ?? "Unknown Currency", // Fetching currency name
  16851. //                'currencyMultiplyRate' => $data[0]->getCurrencyMultiply(),
  16852. //                'file' =>  $absoluteUrl.''.'uploads/ExpenseInvoice/'.$data[0]->getFiles(),
  16853. //                'expenseName' => $expenseCategory ? $expenseCategory['name'] : "Unknown Expense",
  16854. //                'child' => [
  16855. //                    'expenseSubCategoryId' => $data[0]->getExpenseSubCategory(),
  16856. //                    'expenseSubcategoryName' => $subcategory ? $subcategory['name'] : "Unknown Subcategory",
  16857. //                    'option' => [
  16858. //                        'expenseSubCategoryOptionId' => $data[0]->getExpenseSubCategoryOption(),
  16859. //                        'expenseSubcategoryOptionName' => $subcategoryOption ? $subcategoryOption['name'] : "Unknown Option"
  16860. //                    ]
  16861. //                ]
  16862. //            ];
  16863. //            $expList[] = $list;
  16864. //        }
  16865. //
  16866. //        return new JsonResponse($expList);
  16867. //    }
  16868.     public function getExpenseByCurrentDate(Request $request)
  16869.     {
  16870.         $em $this->getDoctrine()->getManager();
  16871.         $session $request->getSession();
  16872.         $currentTime = new \Datetime();
  16873.         $currDate $currentTime->format('Y-m-d');
  16874.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  16875.         $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\Employee')->createQueryBuilder('E')
  16876.             ->select('E.employeeId, E.accountsHeadId')  // Selecting currency name
  16877.             ->where('E.employeeId = :employeeId')
  16878.             ->setParameter('employeeId'$employeeId)
  16879.             ->getQuery()
  16880.             ->getResult();
  16881. //        $partyId = 1313;
  16882.         $partyId $employeeDetails[0]['accountsHeadId'];
  16883.         $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  16884.         $expDetails $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->createQueryBuilder('E')
  16885.             ->leftJoin('ApplicationBundle:Currencies''C''WITH''E.currency = C.currencyId')
  16886.             ->select('E, C.code as currencyName'// Selecting currency name
  16887.             ->where('E.partyHeadId = :partyId')
  16888.             ->andWhere('E.createdAt >= :currentDate')
  16889.             ->setParameter('currentDate'$currDate)
  16890.             ->setParameter('partyId'$partyId)
  16891.             ->getQuery()
  16892.             ->getResult();
  16893.         $expenseCategories GeneralConstant::$expenseCategory;
  16894.         function getExpenseCategoryByMarker($markerHash$categories)
  16895.         {
  16896.             foreach ($categories as $category) {
  16897.                 if ($category['markerHash'] === $markerHash) {
  16898.                     return $category;
  16899.                 }
  16900.             }
  16901.             return null;
  16902.         }
  16903.         function getSubcategoryName($category$subcategoryId)
  16904.         {
  16905.             if (!$category || !isset($category['expenseSubcategory'])) {
  16906.                 return null;
  16907.             }
  16908.             foreach ($category['expenseSubcategory'] as $subcategory) {
  16909.                 if ($subcategory['id'] == $subcategoryId) {
  16910.                     return $subcategory;
  16911.                 }
  16912.             }
  16913.             return null;
  16914.         }
  16915.         function getSubcategoryOptionName($subcategory$optionId)
  16916.         {
  16917.             if (!$subcategory || !isset($subcategory['option'])) {
  16918.                 return null;
  16919.             }
  16920.             foreach ($subcategory['option'] as $option) {
  16921.                 if ($option['id'] == $optionId) {
  16922.                     return $option;
  16923.                 }
  16924.             }
  16925.             return null;
  16926.         }
  16927.         $expList = [];
  16928.         $totalAmount 0;
  16929.         foreach ($expDetails as $data) {
  16930.             $expenseCategory getExpenseCategoryByMarker($data[0]->getMarkerHash(), $expenseCategories);
  16931.             $subcategory getSubcategoryName($expenseCategory$data[0]->getExpenseSubCategory());
  16932.             $subcategoryOption getSubcategoryOptionName($subcategory$data[0]->getExpenseSubCategoryOption());
  16933.             $amount floatval($data[0]->getInvoiceAmount());
  16934.             $totalAmount += $amount;
  16935.             $list = [
  16936.                 'id' => $data[0]->getExpenseInvoiceId(),
  16937.                 'amount' => number_format($amount2'.'''),
  16938.                 'editFlag' => $data[0]->getEditFlag(),
  16939.                 'deleteFlag' => $data[0]->getDeleteFlag(),
  16940.                 'markerHash' => $data[0]->getMarkerHash(),
  16941.                 'expenseDate' => $data[0]->getExpenseInvoiceDate()->format('U'),
  16942.                 'expenseDescription' => $data[0]->getDescription(),
  16943.                 'currency' => $data[0]->getCurrency(),
  16944.                 'currencyName' => $data['currencyName'] ?? "Unknown Currency",
  16945.                 'currencyMultiplyRate' => $data[0]->getCurrencyMultiply(),
  16946.                 'filePath' => $absoluteUrl '' 'uploads/ExpenseInvoice/' $data[0]->getFiles(),
  16947.                 'file' => $data[0]->getFiles(),
  16948.                 'expenseName' => $expenseCategory $expenseCategory['name'] : "Unknown Expense",
  16949.                 'child' => [
  16950.                     'expenseSubCategoryId' => $data[0]->getExpenseSubCategory(),
  16951.                     'expenseSubcategoryName' => $subcategory $subcategory['name'] : "Unknown Subcategory",
  16952.                     'option' => [
  16953.                         'expenseSubCategoryOptionId' => $data[0]->getExpenseSubCategoryOption(),
  16954.                         'expenseSubcategoryOptionName' => $subcategoryOption $subcategoryOption['name'] : "Unknown Option"
  16955.                     ]
  16956.                 ]
  16957.             ];
  16958.             $expList[] = $list;
  16959.         }
  16960.         $response = [
  16961.             'totalAmount' => number_format($totalAmount2'.'''),
  16962.             'expenses' => $expList
  16963. //        $employeeId,$partyId
  16964. //            $employeeDetails[0]['accountsHeadId']
  16965.         ];
  16966.         return new JsonResponse($response);
  16967.     }
  16968.     public function currentBalance(Request $request)
  16969.     {
  16970.         $em $this->getDoctrine()->getManager();
  16971.         $ind_head_id = [];
  16972.         $start_date $request->query->get('start_date'"");
  16973.         $end_date $request->query->get('end_date'"");
  16974.         if($end_date=='')
  16975.             $end_date=(new \DateTime())->format('Y-m-d');
  16976. //       return new JsonResponse( Accounts::GetBalanceOnDateByMarkerHash($em,$end_date,[],[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],1));
  16977.         $dataType '_OWN_';
  16978. //        $dataType='_COMPANY_';//_OWN_
  16979.         $session $request->getSession();
  16980.         $userId=$session->get(UserConstants::USER_TYPE);
  16981.         if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_SYSTEM)
  16982.         $dataType '_COMPANY_';
  16983.         $allowedCards=[];
  16984.         if($dataType=='_OWN_')
  16985.         {
  16986.             $allowedCards=[1,2,3];
  16987.             $get_kids_sql "SELECT accounts_head_id, advance_head_id,advance_wages_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  16988.             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  16989.             
  16990.             $query_output $stmt;
  16991.             if (empty($query_output)) {
  16992.                 $ind_head_id=[0];
  16993.             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  16994.                 $ind_head_id=[0];
  16995.             else {
  16996.                 if($query_output[0]['accounts_head_id'] !='' && $query_output[0]['accounts_head_id'] != && $query_output[0]['accounts_head_id'] !=null)$ind_head_id[] = $query_output[0]['accounts_head_id'];
  16997.                 if($query_output[0]['advance_head_id'] !='' && $query_output[0]['advance_head_id'] != && $query_output[0]['advance_head_id'] !=null)$ind_head_id[] = $query_output[0]['advance_head_id'];
  16998.                 if($query_output[0]['advance_wages_head_id'] !='' && $query_output[0]['advance_wages_head_id'] != && $query_output[0]['advance_wages_head_id'] !=null)$ind_head_id[] = $query_output[0]['advance_wages_head_id'];
  16999.             }
  17000.         }
  17001.         else
  17002.         {
  17003.             $setting_qry $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  17004.                 'name' => 'cash_and_cash_equivalent_parents'
  17005.             ));
  17006.             $cace_parents=[];
  17007.             if ($setting_qry)
  17008.                 $cace_parents json_decode($setting_qry->getData(), true);
  17009.             $ind_head_id=$cace_parents;
  17010.         }
  17011.         $query_head_balance=0;
  17012.         if($dataType=='_COMPANY_')
  17013.         {
  17014.             $ledger_data=Accounts::GetBalanceOnDateByMarkerHash($em,$end_date,[],[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],1);
  17015.             $query_head_balance += $ledger_data[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['closingBalance'] ?? 0;
  17016.         }
  17017.         else {
  17018.             foreach ($ind_head_id as $ind_head) {
  17019.                 $ledger_data Accounts::LedgerDetailsTransMethod($em$ind_head$start_date$end_date);
  17020.                     $mult $ledger_data['basic_data']['head_nature'] ? ($ledger_data['basic_data']['head_nature'] == 'cr' : -1) : 0;
  17021.                     $query_head_balance += ($mult $ledger_data['query_head_balance'] ?? 0);
  17022.             }
  17023.         }
  17024.         $today_date = new \DateTime();
  17025.         $today_date $today_date->format('Y-m-d');
  17026.         $s_date_obj = \DateTime::createFromFormat('Y-m-d'$today_date);
  17027.         $start_of_month $s_date_obj->format('Y-m-01');  // First day of the month
  17028.         $end_of_month $s_date_obj->format('Y-m-t');  // Last day of the month
  17029.         $expense_date $today_date;
  17030.         $start_of_day = new \DateTime($expense_date ' 00:00:00');
  17031.         $end_of_day = new \DateTime($expense_date ' 23:59:59');
  17032.         $query $em->createQueryBuilder()
  17033.             ->select('b.accountsHeadId''a.current_balance')
  17034.             ->from('ApplicationBundle:BankAccounts''b')
  17035.             ->join('ApplicationBundle:AccAccountsHead''a''WITH''b.accountsHeadId = a.accountsHeadId')
  17036.             ->getQuery();
  17037.         $results $query->getResult();
  17038.         $acc_account_head_data = [];
  17039.         foreach ($results as $result) {
  17040.             $acc_account_head_data[] = [
  17041.                 'current_balance' => $result['current_balance'],
  17042.             ];
  17043.         }
  17044.         $monthly_summary_data $em->getRepository('ApplicationBundle\\Entity\\MonthlySummary')
  17045.             ->createQueryBuilder('m')
  17046.             ->where('m.date >= :start_of_month')
  17047.             ->andWhere('m.date <= :end_of_month')
  17048.             ->setParameter('start_of_month'$start_of_month)
  17049.             ->setParameter('end_of_month'$end_of_month)
  17050.             ->orderBy('m.date''ASC')
  17051.             ->getQuery()
  17052.             ->getResult();
  17053.         $monthly_summary = [];
  17054.         foreach ($monthly_summary_data as $summary) {
  17055.             if ($summary instanceof \ApplicationBundle\Entity\MonthlySummary) {
  17056.                 $monthly_summary[] = [
  17057.                     'date' => $summary->getDate()->format('Y-m-d'),
  17058.                     'cash' => $summary->getCash(),
  17059.                     'revenue' => $summary->getRevenue(),
  17060.                     'expense' => $summary->getExpense(),
  17061.                     'receivable' => $summary->getReceivable(),
  17062.                     'payable' => $summary->getPayable(),
  17063.                     'asset' => $summary->getAsset(),
  17064.                     'liability' => $summary->getLiability()
  17065.                 ];
  17066.             }
  17067.         }
  17068.         $qb $em->createQueryBuilder()
  17069.             ->select('SUM(e.invoiceAmount)')
  17070.             ->from('ApplicationBundle:ExpenseInvoice''e')
  17071.             ->where('e.createdAt BETWEEN :start_of_day AND :end_of_day')
  17072.             ->setParameter('start_of_day'$start_of_day)
  17073.             ->setParameter('end_of_day'$end_of_day);
  17074.         if($dataType=='_OWN_')
  17075.             $qb->andWhere("e.createdUserId = $userId");
  17076.         $total_invoice_amount $qb->getQuery()->getSingleScalarResult();
  17077.         $total_invoice_amount $total_invoice_amount !== null ? (float)$total_invoice_amount 0.00;
  17078.         $acc_account_head_data = isset($acc_account_head_data[0]['current_balance'])
  17079.             ? $acc_account_head_data[0]['current_balance'] : 0.00;
  17080.         $response = [
  17081.             'query_head_balance' => $query_head_balance,
  17082.             'total_today_expense_amount' => number_format($total_invoice_amount2'.'''),
  17083.             'primary_account_balance' => $acc_account_head_data,
  17084.             'allowed_cards' => $allowedCards
  17085.         ];
  17086.         if (!empty($monthly_summary)) {
  17087.             $response array_merge($response$monthly_summary[0]);
  17088.         }
  17089.         return new JsonResponse($response);
  17090.     }
  17091.     public function editExpense(Request $request$id 0)
  17092.     {
  17093.         $em $this->getDoctrine()->getManager();
  17094.         $expenseInvoice $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->find($id);
  17095.         if (!$expenseInvoice) {
  17096.             return new JsonResponse(['success' => false'message' => 'Expense invoice not found'], 404);
  17097.         }
  17098.         if ($request->isMethod('POST')) {
  17099.             $expenseInvoice->setExpenseInvoiceDate(new \DateTime($request->request->get('expense_date')));
  17100.             $expenseInvoice->setInvoiceAmount($request->request->get('expense_amount'));
  17101.             $expenseInvoice->setPartyId(1313);
  17102.             $expenseInvoice->setExpenseInvoiceTypeId($request->request->get('expense_type'));
  17103.             $expenseInvoice->setMarkerHash($request->request->get('markerHash'));
  17104.             $expenseInvoice->setCurrency($request->request->get('expense_currency_id'));
  17105.             $expenseInvoice->setCurrencyMultiply($request->request->get('expense_currency_multiply'));
  17106.             $expenseInvoice->setExpenseSubcategory($request->request->get('expense_sub_category'));
  17107.             $expenseInvoice->setExpenseSubcategoryOption($request->request->get('expense_sub_category_option'));
  17108.             $expenseInvoice->setWbsCode($request->request->get('wbsCode'''));
  17109.             $expenseInvoice->setWbsActivityName($request->request->get('wbsActivityName'''));
  17110.             if (!empty($request->files->get('file'))) {
  17111.                 $file $request->files->get('file');
  17112.                 $fileName md5(uniqid()) . '.' $file->guessExtension();
  17113.                 $path $fileName;
  17114.                 $upl_dir $_SERVER["DOCUMENT_ROOT"] . '/../web/uploads/ExpenseInvoice/';
  17115.                 if (!file_exists($upl_dir)) {
  17116.                     mkdir($upl_dir0777true);
  17117.                 }
  17118.                 $file $file->move($upl_dir$path);
  17119.                 $expenseInvoice->setFiles($fileName);
  17120.             } else {
  17121.             }
  17122.             $expenseInvoice->setDescription($request->request->get('description'));
  17123.             $em->flush(); //
  17124.             return new JsonResponse(['success' => true]);
  17125.         }
  17126.         return new JsonResponse(['success' => false'message' => 'Invalid request'], 400);
  17127.     }
  17128.     public function deleteExpenseInvoice(Request $request$id 0)
  17129.     {
  17130.         $em $this->getDoctrine()->getManager();
  17131.         //        $id = $request->query->get('id');
  17132.         $expenseInvoice $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->find($id);
  17133.         if (!$expenseInvoice) {
  17134.             return new JsonResponse(['message' => 'Expense invoice not found'], 404);
  17135.         }
  17136.         $em->remove($expenseInvoice);
  17137.         $em->flush();
  17138.         return new JsonResponse(['message' => 'Expense invoice deleted successfully'], 200);
  17139.     }
  17140. //    public function getChequeListForApp(Request $request)
  17141. //    {
  17142. //        $em = $this->getDoctrine()->getManager();
  17143. //
  17144. //
  17145. //        $qb = $em->getRepository('ApplicationBundle\\Entity\\AccCheck')->createQueryBuilder('C')
  17146. //            ->select(
  17147. //                'c.checkDate',
  17148. //                'c.checkNumber',
  17149. //                'c.checkAmount',
  17150. //                'c.CheckId',
  17151. //                't.documentHash',
  17152. //                't.transactionDate'
  17153. ////                'a.name AS accountsHeadName'
  17154. //            )
  17155. //            ->from('ApplicationBundle:AccCheck', 'c')
  17156. //            ->leftJoin('ApplicationBundle:AccTransactions', 't', 'WITH', 'c.voucherId = t.transactionId')
  17157. //            ->leftJoin('ApplicationBundle:AccTransactionDetails', 'd', 'WITH', 'd.transactionId = c.voucherId')
  17158. //            ->leftJoin('ApplicationBundle:AccAccountsHead', 'a', 'WITH', 'a.accountsHeadId = d.accountsHeadId');
  17159. //
  17160. //
  17161. //        $inventoryData = $qb->getQuery()->getResult();
  17162. //
  17163. //        return $this->json([
  17164. //
  17165. //            'data' => $inventoryData,
  17166. //        ]);
  17167. //    }
  17168.     public function getChequeListForApp(Request $request)
  17169.     {
  17170.         $em $this->getDoctrine()->getManager();
  17171.         $accountsHeadId $request->query->get('accountsHeadId');
  17172.         if (!$accountsHeadId) {
  17173.             return new JsonResponse(['error' => 'accountsHeadId parameter is required'], 400);
  17174.         }
  17175.         $page = (int)$request->query->get('page'1);
  17176.         $limit = (int)$request->query->get('limit'10);
  17177.         $offset = ($page 1) * $limit;
  17178.         $qb $em->createQueryBuilder();
  17179.         $qb->select(
  17180.             'c.checkDate',
  17181.             'c.checkNumber',
  17182.             'c.checkAmount',
  17183.             'c.CheckId',
  17184.             't.documentHash',
  17185.             't.transactionDate',
  17186.             'a.name AS accountsHeadName'
  17187.         )
  17188.             ->from('ApplicationBundle:AccCheck''c')
  17189.             ->leftJoin('ApplicationBundle:AccTransactions''t''WITH''c.voucherId = t.transactionId')
  17190.             ->leftJoin('ApplicationBundle:AccTransactionDetails''d''WITH''d.transactionId = c.voucherId')
  17191.             ->leftJoin('ApplicationBundle:AccAccountsHead''a''WITH''a.accountsHeadId = d.accountsHeadId')
  17192.             ->where('c.accountsHeadId = :accountsHeadId')
  17193.             ->setParameter('accountsHeadId'$accountsHeadId)
  17194.             ->setFirstResult($offset)
  17195.             ->setMaxResults($limit);
  17196.         $results $qb->getQuery()->getArrayResult();
  17197.         // Get total count
  17198.         $countQb $em->createQueryBuilder();
  17199.         $countQb->select('COUNT(c.CheckId)')
  17200.             ->from('ApplicationBundle:AccCheck''c')
  17201.             ->where('c.accountsHeadId = :accountsHeadId')
  17202.             ->setParameter('accountsHeadId'$accountsHeadId);
  17203.         $total $countQb->getQuery()->getSingleScalarResult();
  17204.         // Format dates as timestamp
  17205.         foreach ($results as &$row) {
  17206.             $row['checkDate'] = isset($row['checkDate']) && $row['checkDate'] instanceof \DateTime
  17207.                 $row['checkDate']->getTimestamp()
  17208.                 : '';
  17209.             $row['transactionDate'] = isset($row['transactionDate']) && $row['transactionDate'] instanceof \DateTime
  17210.                 $row['transactionDate']->getTimestamp()
  17211.                 : '';
  17212.             $row['checkNumber'] = $row['checkNumber'] ?? '';
  17213.             $row['checkAmount'] = $row['checkAmount'] ?? '';
  17214.             $row['CheckId'] = $row['CheckId'] ?? '';
  17215.             $row['documentHash'] = !empty($row['documentHash']) ? $row['documentHash'] : '';
  17216.             $row['accountsHeadName'] = !empty($row['accountsHeadName']) ? $row['accountsHeadName'] : '';
  17217.         }
  17218.         return new JsonResponse([
  17219.             'currentPage' => $page,
  17220.             'limit' => $limit,
  17221.             'total' => (int)$total,
  17222.             'data' => $results,
  17223.         ]);
  17224.     }
  17225.     public function MarkerHashCostCenterData()
  17226.     {
  17227.         $data AccountsConstant::$COMBINED_ARRAY;
  17228.         return new JsonResponse([
  17229.             'markerHash' => $data['markerHash'],
  17230.             'costCenter' => $data['costCenter'],
  17231.         ]);
  17232.     }
  17233.     public function agingReportApi(Request $request)
  17234.     {
  17235.         $em $this->getDoctrine()->getManager();
  17236.         $entity 18;
  17237.         $projectCategories $em->getRepository('ApplicationBundle\\Entity\\ProjectCategory')
  17238.             ->findBy(['status' => GeneralConstant::ACTIVE]);
  17239.         $categoryDetails = [];
  17240.         foreach ($projectCategories as $category) {
  17241.             $categoryDetails[] = [
  17242.                 'categoryName' => $category->getCategoryName(),
  17243.                 'categoryId' => $category->getProjectCategoryId(),
  17244.             ];
  17245.         }
  17246.         $reportData = [];
  17247.         $periodType 1;
  17248.         $divide 1;
  17249.         $categoryIds = [];
  17250.         if ($request->isMethod('POST')) {
  17251.             $categoryInput $request->request->get('projectCategoryId');
  17252.             if ($categoryInput) {
  17253.                 $categoryIds is_array($categoryInput) ? $categoryInput explode(','$categoryInput);
  17254.                 $categoryIds array_map('intval'$categoryIds);
  17255.             }
  17256.             $periodType = (int)$request->request->get('period_type'1);
  17257.             $divide = (int)$request->request->get('divide'1);
  17258.         }
  17259.         $monthsPerInterval = ($periodType 12) / $divide;
  17260.         $intervals = [];
  17261.         $startMonth 1;
  17262.         for ($i 0$i $divide$i++) {
  17263.             $endMonth $startMonth $monthsPerInterval 1;
  17264.             $intervals[] = [
  17265.                 'label' => "$startMonth-$endMonth month",
  17266.                 'start' => $startMonth,
  17267.                 'end' => $endMonth
  17268.             ];
  17269.             $startMonth += $monthsPerInterval;
  17270.         }
  17271.         foreach ($intervals as $interval) {
  17272.             $reportData[$interval['label']] = [];
  17273.         }
  17274.         if ($request->isMethod('POST')) {
  17275.             $qb $em->createQueryBuilder()
  17276.                 ->select([
  17277.                     'cf.entity',
  17278.                     'cf.entityId',
  17279.                     'cf.cashFlowAmount',
  17280.                     'cf.cashFlowDate',
  17281.                     'si.salesInvoiceNumber',
  17282.                     'so.salesOrderId',
  17283.                     'so.salesOrderNumber',
  17284.                     'p.projectId',
  17285.                     'p.projectName',
  17286.                     'pc.projectCategoryId',
  17287.                     'pc.categoryName',
  17288.                     'c.clientName',
  17289.                     'c.clientShortCode',
  17290. //                    'e.name',
  17291. //                    'ed.lastname',
  17292.                 ])
  17293.                 ->from('ApplicationBundle:CashFlowProjection''cf')
  17294.                 ->innerJoin('ApplicationBundle:SalesInvoice''si''WITH''si.salesInvoiceId = cf.entityId')
  17295.                 ->innerJoin('ApplicationBundle:SalesOrder''so''WITH''so.salesOrderId = si.salesOrderId')
  17296.                 ->innerJoin('ApplicationBundle:Project''p''WITH''p.projectId = so.projectId')
  17297.                 ->innerJoin('ApplicationBundle:ProjectCategory''pc''WITH''pc.projectCategoryId = p.projectCategoryId')
  17298.                 ->innerJoin('ApplicationBundle:AccClients''c''WITH''c.clientId = so.clientId')
  17299. //                ->innerJoin('ApplicationBundle:Employee', 'e', 'WITH', 'e.employeeId = so.salesPersonId')
  17300.                 ->where('cf.entity = :entity')
  17301.                 ->setParameter('entity'$entity);
  17302.             if (!empty($categoryIds)) {
  17303.                 $qb->andWhere('pc.projectCategoryId IN (:categoryIds)')
  17304.                     ->setParameter('categoryIds'$categoryIds);
  17305.             }
  17306.             $results $qb->getQuery()->getArrayResult();
  17307.             foreach ($results as $item) {
  17308.                 $month = (int)$item['cashFlowDate']->format('m');
  17309.                 // Find the interval label
  17310.                 $intervalLabel null;
  17311.                 foreach ($intervals as $interval) {
  17312.                     if ($month >= $interval['start'] && $month <= $interval['end']) {
  17313.                         $intervalLabel $interval['label'];
  17314.                         break;
  17315.                     }
  17316.                 }
  17317.                 if (!$intervalLabel) continue;
  17318.                 $projectId $item['projectId'];
  17319.                 $salesOrderId $item['salesOrderId'];
  17320.                 if (!isset($reportData[$intervalLabel][$projectId])) {
  17321.                     $reportData[$intervalLabel][$projectId] = [
  17322.                         'projectName' => $item['projectName'],
  17323.                         'projectCategory' => $item['projectCategoryId'],
  17324.                         'projectCategoryName' => $item['categoryName'],
  17325.                         'TotalAmount' => 0,
  17326.                         'salesOrders' => []
  17327.                     ];
  17328.                 }
  17329.                 if (!isset($reportData[$intervalLabel][$projectId]['salesOrders'][$salesOrderId])) {
  17330.                     $reportData[$intervalLabel][$projectId]['salesOrders'][$salesOrderId] = [
  17331.                         'salesOrderNumber' => $item['salesOrderNumber'],
  17332.                         'clientName' => $item['clientName'],
  17333.                         'clientShortCode' => $item['clientShortCode'],
  17334. //                        'firstName' => $item['name'],
  17335. //                        'lastName' => $item['lastname'],
  17336.                         'TotalAmount' => 0,
  17337.                         'invoices' => []
  17338.                     ];
  17339.                 }
  17340.                 $invoice = [
  17341.                     'entity' => $item['entity'],
  17342.                     'entityId' => $item['entityId'],
  17343.                     'amount' => $item['cashFlowAmount'],
  17344.                     'date' => $item['cashFlowDate'] ? $item['cashFlowDate']->format('Y-m-d') : null,
  17345.                     'salesInvoiceNumber' => $item['salesInvoiceNumber']
  17346.                 ];
  17347.                 $reportData[$intervalLabel][$projectId]['salesOrders'][$salesOrderId]['invoices'][] = $invoice;
  17348.                 $reportData[$intervalLabel][$projectId]['salesOrders'][$salesOrderId]['TotalAmount'] += $item['cashFlowAmount'];
  17349.                 $reportData[$intervalLabel][$projectId]['TotalAmount'] += $item['cashFlowAmount'];
  17350.             }
  17351.         }
  17352. //        return new JsonResponse([
  17353. //            'reportData' => $reportData,
  17354. //
  17355. //        ]);
  17356.         return $this->render('@Accounts/pages/report/aging_report.html.twig', [
  17357.             'page_title' => 'Aging Report',
  17358.             'reportData' => $reportData,
  17359.             'periodType' => $periodType,
  17360.             'divide' => $divide,
  17361.             'selectedCategoryIds' => $categoryIds,
  17362.             'category' => $categoryDetails,
  17363.         ]);
  17364.     }
  17365.     public function getParentHead(Request $request)
  17366.     {
  17367.         $em $this->getDoctrine()->getManager();
  17368.         $response Accounts::getParentLedgerHeadsForApi($request$em);
  17369.         if (!$response) {
  17370.             return new JsonResponse([
  17371.                 'status' => 'False',
  17372.                 'message' => 'Something went wrong'
  17373.             ], 500);
  17374.         }
  17375.         return new JsonResponse($response200);
  17376.     }
  17377.     public function getChildHead(Request $request)
  17378.     {
  17379.         $em $this->getDoctrine()->getManager();
  17380.         $parentId $request->query->get('parent_id');
  17381.         if (!$parentId) {
  17382.             return new JsonResponse([
  17383.                 'status' => 'error',
  17384.                 'message' => 'parent_id is required'
  17385.             ], 400);
  17386.         }
  17387.         $response Accounts::getChildHeadData($em$parentId);
  17388.         if (!$response) {
  17389.             return new JsonResponse([
  17390.                 'status' => 'False',
  17391.                 'message' => 'Something went wrong'
  17392.             ], 500);
  17393.         }
  17394.         return new JsonResponse($response200);
  17395.     }
  17396. //    public function getSalesInvoiceDetails(Request $request, $id)
  17397. //    {
  17398. //        $em = $this->getDoctrine()->getManager();
  17399. //
  17400. //        $salesInvoiceDetails = $em
  17401. //            ->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
  17402. //            ->find($id);
  17403. //
  17404. //        if (!$salesInvoiceDetails) {
  17405. //            return new JsonResponse(['data' => null], 200);
  17406. //        }
  17407. //        $salesInvoiceItems = $em
  17408. //            ->getRepository('ApplicationBundle\\Entity\\SalesInvoiceItem')
  17409. //            ->findBy([
  17410. //                'salesInvoiceId' => $salesInvoiceDetails->getSalesInvoiceId()
  17411. //            ]);
  17412. //        $items = [];
  17413. //
  17414. //        foreach ($salesInvoiceItems as $item) {
  17415. //
  17416. //            $product = $em
  17417. //                ->getRepository('ApplicationBundle\\Entity\\InvProducts')
  17418. //                ->findOneBy([
  17419. //                    'id' => $item->getProductId()
  17420. //                ]);
  17421. //            $service = $em
  17422. //                ->getRepository('ApplicationBundle\\Entity\\AccService')
  17423. //                ->findOneBy([
  17424. //                    'serviceId' => $item->getServiceid()
  17425. //                ]);
  17426. //
  17427. //            $items[] = [
  17428. //                'productId' => $item->getProductId(),
  17429. //                'productName' => $product ? $product->getName() : '',
  17430. //                'serviceId' => $item->getServiceId(),
  17431. //                'servceName' => $service ? $service->getServiceName() : '',
  17432. //                'qty' => $item->getQty(),
  17433. //                'unitPrice' => $item->getAmount(),
  17434. //                'total' => $item->getPrice()
  17435. //            ];
  17436. //        }
  17437. //
  17438. //        $accClient = $em
  17439. //            ->getRepository('ApplicationBundle\\Entity\\AccClients')
  17440. //            ->findOneBy([
  17441. //                'clientId' => $salesInvoiceDetails->getClientId()
  17442. //            ]);
  17443. //
  17444. //        $currency = $em
  17445. //            ->getRepository('ApplicationBundle\\Entity\\Currencies')
  17446. //            ->findOneBy([
  17447. //                'currencyId' => $salesInvoiceDetails->getCurrency()
  17448. //            ]);
  17449. //
  17450. //        $data = [
  17451. //            'invoiceNumber' => $salesInvoiceDetails->getSalesInvoiceId(),
  17452. //            'documentNumber' => $salesInvoiceDetails->getDocumentHash(),
  17453. //            'date' => $salesInvoiceDetails->getSalesInvoiceDate()
  17454. //                ? $salesInvoiceDetails->getSalesInvoiceDate()->format('Y-m-d')
  17455. //                : null,
  17456. //            'currencyName' => $currency ? $currency->getName() : null,
  17457. //            'clientName' => $accClient ? $accClient->getClientName() : null,
  17458. //            'clientAddress' => $accClient ? $accClient->getAddressContact() : null,
  17459. //            'taxAmount' => $salesInvoiceDetails ? $salesInvoiceDetails->getTaxDeductionAmount() : 0,
  17460. //            'items' => $items
  17461. //        ];
  17462. //
  17463. //        return new JsonResponse(['data' => $data]);
  17464. //    }
  17465.     public function getSalesInvoiceDetails(Request $request$id)
  17466.     {
  17467.         $em $this->getDoctrine()->getManager();
  17468.         $salesInvoice $em
  17469.             ->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
  17470.             ->find($id);
  17471.         if (!$salesInvoice) {
  17472.             return new Response('Invoice not found'404);
  17473.         }
  17474.         $accClient $em->getRepository('ApplicationBundle\\Entity\\AccClients')
  17475.             ->findOneBy(['clientId' => $salesInvoice->getClientId()]);
  17476.         $currency $em->getRepository('ApplicationBundle\\Entity\\Currencies')
  17477.             ->findOneBy(['currencyId' => $salesInvoice->getCurrency()]);
  17478.         $itemsData $em->getRepository('ApplicationBundle\\Entity\\SalesInvoiceItem')
  17479.             ->findBy(['salesInvoiceId' => $salesInvoice->getSalesInvoiceId()]);
  17480.         $xml = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><Invoice></Invoice>');
  17481.         $xml->addChild('ID'$salesInvoice->getSalesInvoiceId());
  17482.         $xml->addChild('IssueDate'$salesInvoice->getSalesInvoiceDate()->format('Y-m-d'));
  17483.         $xml->addChild('DocumentNumber'$salesInvoice->getDocumentHash());
  17484.         $clientNode $xml->addChild('Customer');
  17485.         $clientNode->addChild('Name'$accClient $accClient->getClientName() : '');
  17486.         $clientNode->addChild('Address'$accClient $accClient->getAddressContact() : '');
  17487.         $xml->addChild('TaxAmount'$salesInvoice->getTaxDeductionAmount() ?? 0);
  17488.         $itemsNode $xml->addChild('Items');
  17489.         foreach ($itemsData as $item) {
  17490.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  17491.                 ->find($item->getProductId());
  17492.             $itemNode $itemsNode->addChild('Item');
  17493.             $itemNode->addChild('ProductName'$product $product->getName() : '');
  17494.             $itemNode->addChild('Quantity'$item->getQty());
  17495.             $itemNode->addChild('UnitPrice'$item->getAmount());
  17496.             $itemNode->addChild('Total'$item->getPrice());
  17497.         }
  17498.         $xmlContent $xml->asXML();
  17499.         $response = new Response($xmlContent);
  17500.         $response->headers->set('Content-Type''application/xml');
  17501.         $response->headers->set(
  17502.             'Content-Disposition',
  17503.             'attachment; filename="invoice_'.$salesInvoice->getSalesInvoiceId().'.xml"'
  17504.         );
  17505.         return $response;
  17506.     }
  17507.     private function validateAddExpenseRequest(Request $request)
  17508.     {
  17509.         $expenseType = (int) $request->request->get('expense_type'0);
  17510.         $expenseAmount = (float) $request->request->get('expense_amount'0);
  17511.         $previousAdvanceAmount = (float) $request->request->get('prev_advance_amount'0);
  17512.         $expenseId = (int) $request->request->get('expense_id'0);
  17513.         $expenseToBePaidTo $request->request->get('expense_to_be_paid_to''');
  17514.         $checkId = (int) $request->request->get('check_id'0);
  17515.         $expenseDate $this->parseAddExpenseDate($request->request->get('expense_date'''));
  17516.         $supportedExpenseTypes = array(01235);
  17517.         if (!in_array($expenseType$supportedExpenseTypestrue)) {
  17518.             return 'Invalid expense type selected.';
  17519.         }
  17520.         if (!$expenseDate) {
  17521.             return 'Please select a valid expense date.';
  17522.         }
  17523.         if ($expenseId <= 0) {
  17524.             return 'Please select expense name/head.';
  17525.         }
  17526.         if ($expenseToBePaidTo === '' || (string) $expenseToBePaidTo === '0') {
  17527.             return 'Please select balance against head.';
  17528.         }
  17529.         if ($expenseAmount <= 0) {
  17530.             return 'Expense amount must be greater than zero.';
  17531.         }
  17532.         if ($previousAdvanceAmount 0) {
  17533.             return 'Advance amount cannot be negative.';
  17534.         }
  17535.         if ($previousAdvanceAmount $expenseAmount) {
  17536.             return 'Advance amount cannot be greater than expense amount.';
  17537.         }
  17538.         if ($expenseType === && (int) $request->request->get('poId'0) <= 0) {
  17539.             return 'Please select a purchase order.';
  17540.         }
  17541.         if ($expenseType === && (int) $request->request->get('soId'0) <= 0) {
  17542.             return 'Please select a sales order/project.';
  17543.         }
  17544.         if ($expenseType === && (int) $request->request->get('opportunityId'$request->request->get('leadId'0)) <= 0) {
  17545.             return 'Please select a lead/bid.';
  17546.         }
  17547.         if ($expenseType === && (int) $request->request->get('tour_id'0) <= 0) {
  17548.             return 'Please select a tour.';
  17549.         }
  17550.         if ($checkId && !$this->parseAddExpenseDate($request->request->get('check_date'''))) {
  17551.             return 'Please select a valid cheque date.';
  17552.         }
  17553.         if ((int) $request->request->get('exp_check_expense_distribution_on_product'0) === 1) {
  17554.             if ($expenseType !== 1) {
  17555.                 return 'Product cost distribution is only available for purchase expenses.';
  17556.             }
  17557.             $distributionPoItemIds $request->request->get('exp_distribution_poitemId', array());
  17558.             $distributionAmounts $request->request->get('exp_distribution_amount', array());
  17559.             if (empty($distributionPoItemIds) || empty($distributionAmounts)) {
  17560.                 return 'No purchase items found for product cost distribution.';
  17561.             }
  17562.             $distributedAmount 0;
  17563.             foreach ($distributionAmounts as $distributionAmount) {
  17564.                 $distributedAmount += (float) $distributionAmount;
  17565.             }
  17566.             if (abs($distributedAmount $expenseAmount) > 0.01) {
  17567.                 return 'Distributed product cost must equal the expense amount.';
  17568.             }
  17569.         }
  17570.         $fileValidationError $this->validateAddExpenseFiles($request->files->get('file', array()));
  17571.         if ($fileValidationError !== null) {
  17572.             return $fileValidationError;
  17573.         }
  17574.         return null;
  17575.     }
  17576.     private function parseAddExpenseDate($value)
  17577.     {
  17578.         $value trim((string) $value);
  17579.         if ($value === '') {
  17580.             return null;
  17581.         }
  17582.         $formats = array('F d, Y''Y-m-d''d-m-Y');
  17583.         foreach ($formats as $format) {
  17584.             $date = \DateTime::createFromFormat($format$value);
  17585.             $errors = \DateTime::getLastErrors();
  17586.             if ($date instanceof \DateTime && ($errors === false || ($errors['warning_count'] === && $errors['error_count'] === 0))) {
  17587.                 $date->setTime(000);
  17588.                 return $date;
  17589.             }
  17590.         }
  17591.         return null;
  17592.     }
  17593.     private function validateAddExpenseFiles($files)
  17594.     {
  17595.         $allowedExtensions = array('pdf''jpg''jpeg''png''doc''docx');
  17596.         $maxFileSize 1024 1024;
  17597.         if (!is_array($files)) {
  17598.             $files $files ? array($files) : array();
  17599.         }
  17600.         foreach ($files as $file) {
  17601.             if ($file === null) {
  17602.                 continue;
  17603.             }
  17604.             $extension strtolower((string) $file->guessExtension());
  17605.             if ($extension === '') {
  17606.                 $extension strtolower((string) $file->getClientOriginalExtension());
  17607.             }
  17608.             if (!in_array($extension$allowedExtensionstrue)) {
  17609.                 return 'Only PDF, JPG, JPEG, PNG, DOC, and DOCX files are allowed.';
  17610.             }
  17611.             if ((int) $file->getSize() > $maxFileSize) {
  17612.                 return 'Each attachment must be 5 MB or smaller.';
  17613.             }
  17614.         }
  17615.         return null;
  17616.     }
  17617.     public function exportDxso(Request $request): Response
  17618.     {
  17619.         $data json_decode($request->getContent(), true);
  17620.         $formattedDate = (new \DateTime($data['date']))->format('Ymd');
  17621.         $csvContent Accounts::generateDxsoCsv($data,$formattedDate);
  17622.         return new Response(
  17623.             $csvContent,
  17624.             Response::HTTP_OK,
  17625.             [
  17626.                 'Content-Type' => 'text/csv',
  17627.                 'Content-Disposition' => 'attachment; filename="dxso_file.csv"',
  17628.             ]
  17629.         );
  17630.     }
  17631.     // =========================================================================
  17632.     // S2.6 — Invoice Variant Print Action
  17633.     // =========================================================================
  17634.     /**
  17635.      * Print a specific invoice variant (commercial / customs / lc / import / credit_note).
  17636.      *
  17637.      * Loads the same invoice data as PrintSalesInvoice but renders the
  17638.      * variant-specific template and registers in DocumentRegistry.
  17639.      *
  17640.      * Routes: print_invoice_commercial, print_invoice_customs, print_invoice_lc,
  17641.      *         print_invoice_import, print_credit_note
  17642.      */
  17643.     public function PrintInvoiceVariantAction(Request $request$id 0$invoiceVariant 'commercial')
  17644.     {
  17645.         $em   $this->getDoctrine()->getManager();
  17646.         $data SalesOrderM::GetSalesInvoiceDetails($em$id);
  17647.         // Ensure variant is valid
  17648.         $validVariants = ['commercial''customs''lc''import''credit_note'];
  17649.         if (!in_array($invoiceVariant$validVariants)) {
  17650.             $invoiceVariant 'commercial';
  17651.         }
  17652.         // Register in DocumentRegistry (S2.3) — non-blocking
  17653.         if (!empty($data['si_data'])) {
  17654.             try {
  17655.                 DocumentRegistry::register($em$invoiceVariant'SalesInvoice', (int)$id, [
  17656.                     'tenantId'       => $data['si_data']->getCompanyId(),
  17657.                     'customerId'     => $data['si_data']->getClientId(),
  17658.                     'projectId'      => $data['si_data']->getProjectId(),
  17659.                     'documentNumber' => isset($data['doc_hash']) ? $data['doc_hash'] : null,
  17660.                     'currency'       => $data['si_data']->getCurrency(),
  17661.                     'documentVariant'=> $invoiceVariant,
  17662.                     'createdBy'      => $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  17663.                 ]);
  17664.             } catch (\Exception $e) { /* non-blocking */ }
  17665.         }
  17666.         $company_data Company::getCompanyData($em$data['si_data']->getCompanyId());
  17667.         // Variant labels for print header
  17668.         $variantLabels = [
  17669.             'commercial' => 'Commercial Invoice',
  17670.             'customs'    => 'Customs Invoice',
  17671.             'lc'         => 'Letter of Credit Invoice',
  17672.             'import'     => 'Import Invoice',
  17673.             'credit_note'=> 'Credit Note',
  17674.         ];
  17675.         return $this->render('@Accounts/pages/print/print_invoice_variant.html.twig', [
  17676.             'page_title'      => $variantLabels[$invoiceVariant] . ' — ' . (isset($data['doc_hash']) ? $data['doc_hash'] : ''),
  17677.             'data'            => $data,
  17678.             'invoice_variant' => $invoiceVariant,
  17679.             'variant_label'   => $variantLabels[$invoiceVariant],
  17680.             'company_name'    => $company_data->getName(),
  17681.             'company_data'    => $company_data,
  17682.             'company_address' => $company_data->getAddress(),
  17683.             'company_image'   => $company_data->getImage(),
  17684.             'invoice_footer'  => $company_data->getInvoiceFooter(),
  17685.             'export'          => 'pdf,print',
  17686.         ]);
  17687.     }
  17688. }